title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
BigData/Streaming: Amazon S3 Data Lake | Storing & Analyzing the Streaming Data on the go (in near real-time) | A Serverless Approach | by Burhanuddin Bhopalwala | Towards Data Science | What is streaming data and its main challenges (3V’s)?What is the serverless approach and Why should we use a serverless approach?Prerequisites — AWS + AWS Kinesis Firehose Delivery Stream+ AWS Kinesis Producer/Consumer + AWS Lambda + AWS S3 Storage + AWS Athena — Bird’s-eye viewAWS Kinesis Delivery Stream Setup — Step by StepBONUS — Pro Tips!
What is streaming data and its main challenges (3V’s)?
What is the serverless approach and Why should we use a serverless approach?
Prerequisites — AWS + AWS Kinesis Firehose Delivery Stream+ AWS Kinesis Producer/Consumer + AWS Lambda + AWS S3 Storage + AWS Athena — Bird’s-eye view
AWS Kinesis Delivery Stream Setup — Step by Step
BONUS — Pro Tips!
Streaming data is simply meant a continuous flow of data. And today in the age of the Internet, Devices like Smart Phones, Watches, GPS Sensors are popular sources for streaming data.
Note: An ecosystem created by all of these Devices by connecting each other over the Internet is what we called as Internet of Things (IoT).
3 main challenges with streaming data (3V’s):
1: Velocity (Throughput/min): From Gigabytes/min (GB/min) to Terabytes/min (TB/min). Consuming streaming data at this velocity without any loss of information is always not an easy task and is non-trivial.
2: Variety (Types): If the data is unstructured(JSON/audio/video format), then it becomes more difficult to analyze such data especially when the data is in flight (will cover in future articles) as compared to when the data in rest!
3: Volume (DB Size): From Terabytes (TBs) to Petabytes(PBs) to Exabytes (EBs), storing streaming data requires lots of space and again scanning such raw data to query over it also becomes a challenging task.
Tip: These 3V’s are the key parameters that decide the data category (small, medium or big data) and hence also play a key role in deciding the type of Database storage solution we need to store the data. Confused? See below:
Let me start by clearing the common myth & confusion after reading the word “serverless” — serverless does not mean performing computation without servers. Simply means delegating the responsibility for managing the Servers to the Cloud Service Providers (AWS/Google Cloud Platform (GCP)/Microsoft Azure), so that we can always focus on business logic!
So, why should we use a serverless approach?
I have already mentioned the 3 main challenges with the streaming data. It requires not only lots of Team effort but constant maintenance. Auto Scaling/Elasticity is also not very trivial. Eventually more cost!
But, In serverless, it’s the opposite, We require minimal maintenance. Cloud Service Providers will auto-scale for us and eventually way less maintenance & cost!
Note: In BONUS — Pro Tips: I will also share, how to configure the delivery streams so it cost as minimum as possible.
AWS: Amazon Web Services (AWS) is the cloud provider we are using. One can use Google Cloud Platform (GCP) or MS Azure for respective services.
AWS Kinesis Firehose Delivery Stream: Kinesis is nothing but a managed (serverless) Apache Kafka. AWS usually has 2 options for using Kinesis. Kinesis Data Stream (for real-time) & Kinesis Firehose Delivery Stream which is a near-real-time (~60-sec delay) service. This blog, will use AWS Firehose Kinesis delivery streams going ahead.
AWS Kinesis Producer: AWS Kinesis Producer SDK (prefer for high performance) or AWS Kinesis Agent are 2 popular ways for shipping the data to AWS Kinesis.
AWS Kinesis Consumer: If You want to consume the data apart from storing the data, You can do that using AWS Kinesis Consumer SDK / AWS Kinesis Client Library (KCL uses AWS DynamoDB under the hood) or even AWS Kinesis Connector Library if you are JAVA lover.
AWS Lambda: We will transform our data streams to record in-flight using AWS Lambda. A virtual function from AWS that we will use as a service a.k.a `function-as-a-service`. It’s easy to use and cost-efficient. https://aws.amazon.com/lambda/
AWS S3: We will use AWS S3 Service for our data lake. It’s one of the most simple, reliable, and cost-efficient AWS services.
AWS Athena: For analyzing the data stored in AWS S3, it will use AWS Athena which is generally used for AWS S3 analytical and ad-hoc queries.
Step 1: AWS Kinesis Producer: I am using here AWS Kinesis Agent, as in my example the data is consuming directly onto the file. AWS Kinesis Agent will directly transfer these file Objects to S3 via AWS Kinesis Delivery Streams.
Kinesis Agent needs to be installed where you are receiving the streaming data or generating the log data.
$ sudo yum install -y aws-kinesis-agent...1081 packages excluded due to repository priority protectionsPackage aws-kinesis-agent-1.1.3-1.amzn1.noarch installed and on latest version$ cd /etc/aws-kinesis$ sudo vim agent.json
Go to agent.json from the above command and place Your IAM credentials, & the location of the server where you are receiving the streaming or generating the log data. Below you can find the agent.json file:
You can also do the same using AWS Kinesis SDK Library and the code for the same using Python you can find it here:
Note: I have used JavaScript for Kinesis Producer Library example using npm aws-kinesis-producer
Step 2: Let’s set up AWS S3 now. We just need to create an AWS S3 Bucket. While you can AWS S3 Bucket, you can choose default S3 Server Side Encryption (S3-SSE) also for Encryption at rest.
Step 3: Now we are setting up AWS Kinesis Delivery Streams. You can find the options below. Partitioning is a must so that Athena can be able to SCAN the data faster. I am partitioning the data below hours-wise.
If you want to use AWS Lambda for records transformation in flight, You can do that also. You can find the manual transformation code below:
Note: Standard records transformation to JSON is also available. You can find it here: https://github.com/aws/aws-lambda-java-libs
Step 4: Finally, AWS Athena for querying over our AWS S3 data lake, excited! Below attaching both the query for making a Database in Athena over S3 data and select a query for reading the data.
If your data is already partitioned inside S3, You can also use existing S3 partition inside Athena, by typing the following ALTER command in Athena console.
Final Results:
$ aws s3 cp s3://<bucket-key-name>/<sub-bucket-key-name>/dt=2020–01–20–08/ . — recursive | xargs -rn 1 gzip -d *data-1–2020–01–20–08–10–00–04453c-3e98–47a3-b28d-521ae9ff9b3d.logdata-1–2020–01–20–08–10–15–04453c-3e98–47a3-b28d-521ae9ff9b3d.logdata-1–2020–01–20–08–10–30–04453c-3e98–47a3-b28d-521ae9ff9b3d.logdata-1–2020–01–20–08–10–45–04453c-3e98–47a3-b28d-521ae9ff9b3d.log
Note: You might be thinking, How AWS Athena crawls & scan the S3 Data? It uses AWS Glue Data Crawler (similar to Extract Transform Load ( ETL) job). It does all the heavy lifting under the hood. https://docs.aws.amazon.com/glue/latest/dg/populate-data-catalog.html
That’s it. It’s too easy...
Mention: Athena also allows to invoking Machine Learning using SQL Queries. RANDOM_CUT_FOREST (for outliers), HOTSPOTS (for finding the dense area) are popular for that. That’s easy too...
Performance: Always prefer to use AWS Kinesis SDK libraries for high performance & throughput. It supports batching also.
Performance: If you want to consume the data with AWS Kinesis Delivery Stream, You can use “Kinesis-Enhanced Fanout Streams” which will allow consuming the data with just double the capacity of a shard i.e. from 1 MB/s to 2 MB/s.
Cost: Use GZIP compression for reducing the size of the Object. While restoring just use the “gzip -d <s3-file-keyname>” command to get the data in the raw format again. GZIP will help you to compress the size by 75% and hence You will end up saving up to 75% of the S3 cost. Usually, AWS S3 Costs about 0.03$/GB.
Note: GZIP is known for large compression ratios, but poor decompression speeds and high CPU usage as compared to ZIP format. GZIP usually preferred!
Cost: Use AWS S3 Life Cycle Rules — AWS S3 stores each object by default on a Standard Zone (means frequent-access zone). AWS S3 Life Cycle Rules will move the Objects to Standard-IA (Infrequent Access) over time which are again 30% cheaper than the Standard S3 Zone.
Security: Always enable S3-Server Side Encryption (SSE) for security. For even more sensitive data, You can also use S3-Client (SSE-C), In which, you can pass your encryption key over HTTPS.
Thanks for reading. I hope you will find this blog helpful. Please stay tuned for more such upcoming blogs on cutting-edge Big Data, Machine Learning & Deep Learning. Stay tuned! The best is yet to come :)
That’s pretty much of it!
I hope you will find this blog helpful. Thanks for reading :)Connect: [email protected]
For more such blogs:
Cloud & Big Data Engineering:
Towards Data Science Publication: https://medium.com/@burhanuddinbhopalwala
Software Engineering/Backend Engineering Blogs: | [
{
"code": null,
"e": 517,
"s": 171,
"text": "What is streaming data and its main challenges (3V’s)?What is the serverless approach and Why should we use a serverless approach?Prerequisites — AWS + AWS Kinesis Firehose Delivery Stream+ AWS Kinesis Producer/Consumer + AWS Lambda + AWS S3 Storage + AWS Athena — Bird’s-eye viewAWS Kinesis Delivery Stream Setup — Step by StepBONUS — Pro Tips!"
},
{
"code": null,
"e": 572,
"s": 517,
"text": "What is streaming data and its main challenges (3V’s)?"
},
{
"code": null,
"e": 649,
"s": 572,
"text": "What is the serverless approach and Why should we use a serverless approach?"
},
{
"code": null,
"e": 800,
"s": 649,
"text": "Prerequisites — AWS + AWS Kinesis Firehose Delivery Stream+ AWS Kinesis Producer/Consumer + AWS Lambda + AWS S3 Storage + AWS Athena — Bird’s-eye view"
},
{
"code": null,
"e": 849,
"s": 800,
"text": "AWS Kinesis Delivery Stream Setup — Step by Step"
},
{
"code": null,
"e": 867,
"s": 849,
"text": "BONUS — Pro Tips!"
},
{
"code": null,
"e": 1051,
"s": 867,
"text": "Streaming data is simply meant a continuous flow of data. And today in the age of the Internet, Devices like Smart Phones, Watches, GPS Sensors are popular sources for streaming data."
},
{
"code": null,
"e": 1192,
"s": 1051,
"text": "Note: An ecosystem created by all of these Devices by connecting each other over the Internet is what we called as Internet of Things (IoT)."
},
{
"code": null,
"e": 1238,
"s": 1192,
"text": "3 main challenges with streaming data (3V’s):"
},
{
"code": null,
"e": 1444,
"s": 1238,
"text": "1: Velocity (Throughput/min): From Gigabytes/min (GB/min) to Terabytes/min (TB/min). Consuming streaming data at this velocity without any loss of information is always not an easy task and is non-trivial."
},
{
"code": null,
"e": 1678,
"s": 1444,
"text": "2: Variety (Types): If the data is unstructured(JSON/audio/video format), then it becomes more difficult to analyze such data especially when the data is in flight (will cover in future articles) as compared to when the data in rest!"
},
{
"code": null,
"e": 1886,
"s": 1678,
"text": "3: Volume (DB Size): From Terabytes (TBs) to Petabytes(PBs) to Exabytes (EBs), storing streaming data requires lots of space and again scanning such raw data to query over it also becomes a challenging task."
},
{
"code": null,
"e": 2112,
"s": 1886,
"text": "Tip: These 3V’s are the key parameters that decide the data category (small, medium or big data) and hence also play a key role in deciding the type of Database storage solution we need to store the data. Confused? See below:"
},
{
"code": null,
"e": 2465,
"s": 2112,
"text": "Let me start by clearing the common myth & confusion after reading the word “serverless” — serverless does not mean performing computation without servers. Simply means delegating the responsibility for managing the Servers to the Cloud Service Providers (AWS/Google Cloud Platform (GCP)/Microsoft Azure), so that we can always focus on business logic!"
},
{
"code": null,
"e": 2510,
"s": 2465,
"text": "So, why should we use a serverless approach?"
},
{
"code": null,
"e": 2721,
"s": 2510,
"text": "I have already mentioned the 3 main challenges with the streaming data. It requires not only lots of Team effort but constant maintenance. Auto Scaling/Elasticity is also not very trivial. Eventually more cost!"
},
{
"code": null,
"e": 2883,
"s": 2721,
"text": "But, In serverless, it’s the opposite, We require minimal maintenance. Cloud Service Providers will auto-scale for us and eventually way less maintenance & cost!"
},
{
"code": null,
"e": 3002,
"s": 2883,
"text": "Note: In BONUS — Pro Tips: I will also share, how to configure the delivery streams so it cost as minimum as possible."
},
{
"code": null,
"e": 3146,
"s": 3002,
"text": "AWS: Amazon Web Services (AWS) is the cloud provider we are using. One can use Google Cloud Platform (GCP) or MS Azure for respective services."
},
{
"code": null,
"e": 3482,
"s": 3146,
"text": "AWS Kinesis Firehose Delivery Stream: Kinesis is nothing but a managed (serverless) Apache Kafka. AWS usually has 2 options for using Kinesis. Kinesis Data Stream (for real-time) & Kinesis Firehose Delivery Stream which is a near-real-time (~60-sec delay) service. This blog, will use AWS Firehose Kinesis delivery streams going ahead."
},
{
"code": null,
"e": 3637,
"s": 3482,
"text": "AWS Kinesis Producer: AWS Kinesis Producer SDK (prefer for high performance) or AWS Kinesis Agent are 2 popular ways for shipping the data to AWS Kinesis."
},
{
"code": null,
"e": 3896,
"s": 3637,
"text": "AWS Kinesis Consumer: If You want to consume the data apart from storing the data, You can do that using AWS Kinesis Consumer SDK / AWS Kinesis Client Library (KCL uses AWS DynamoDB under the hood) or even AWS Kinesis Connector Library if you are JAVA lover."
},
{
"code": null,
"e": 4138,
"s": 3896,
"text": "AWS Lambda: We will transform our data streams to record in-flight using AWS Lambda. A virtual function from AWS that we will use as a service a.k.a `function-as-a-service`. It’s easy to use and cost-efficient. https://aws.amazon.com/lambda/"
},
{
"code": null,
"e": 4264,
"s": 4138,
"text": "AWS S3: We will use AWS S3 Service for our data lake. It’s one of the most simple, reliable, and cost-efficient AWS services."
},
{
"code": null,
"e": 4406,
"s": 4264,
"text": "AWS Athena: For analyzing the data stored in AWS S3, it will use AWS Athena which is generally used for AWS S3 analytical and ad-hoc queries."
},
{
"code": null,
"e": 4634,
"s": 4406,
"text": "Step 1: AWS Kinesis Producer: I am using here AWS Kinesis Agent, as in my example the data is consuming directly onto the file. AWS Kinesis Agent will directly transfer these file Objects to S3 via AWS Kinesis Delivery Streams."
},
{
"code": null,
"e": 4741,
"s": 4634,
"text": "Kinesis Agent needs to be installed where you are receiving the streaming data or generating the log data."
},
{
"code": null,
"e": 4965,
"s": 4741,
"text": "$ sudo yum install -y aws-kinesis-agent...1081 packages excluded due to repository priority protectionsPackage aws-kinesis-agent-1.1.3-1.amzn1.noarch installed and on latest version$ cd /etc/aws-kinesis$ sudo vim agent.json"
},
{
"code": null,
"e": 5172,
"s": 4965,
"text": "Go to agent.json from the above command and place Your IAM credentials, & the location of the server where you are receiving the streaming or generating the log data. Below you can find the agent.json file:"
},
{
"code": null,
"e": 5288,
"s": 5172,
"text": "You can also do the same using AWS Kinesis SDK Library and the code for the same using Python you can find it here:"
},
{
"code": null,
"e": 5385,
"s": 5288,
"text": "Note: I have used JavaScript for Kinesis Producer Library example using npm aws-kinesis-producer"
},
{
"code": null,
"e": 5575,
"s": 5385,
"text": "Step 2: Let’s set up AWS S3 now. We just need to create an AWS S3 Bucket. While you can AWS S3 Bucket, you can choose default S3 Server Side Encryption (S3-SSE) also for Encryption at rest."
},
{
"code": null,
"e": 5787,
"s": 5575,
"text": "Step 3: Now we are setting up AWS Kinesis Delivery Streams. You can find the options below. Partitioning is a must so that Athena can be able to SCAN the data faster. I am partitioning the data below hours-wise."
},
{
"code": null,
"e": 5928,
"s": 5787,
"text": "If you want to use AWS Lambda for records transformation in flight, You can do that also. You can find the manual transformation code below:"
},
{
"code": null,
"e": 6059,
"s": 5928,
"text": "Note: Standard records transformation to JSON is also available. You can find it here: https://github.com/aws/aws-lambda-java-libs"
},
{
"code": null,
"e": 6253,
"s": 6059,
"text": "Step 4: Finally, AWS Athena for querying over our AWS S3 data lake, excited! Below attaching both the query for making a Database in Athena over S3 data and select a query for reading the data."
},
{
"code": null,
"e": 6411,
"s": 6253,
"text": "If your data is already partitioned inside S3, You can also use existing S3 partition inside Athena, by typing the following ALTER command in Athena console."
},
{
"code": null,
"e": 6426,
"s": 6411,
"text": "Final Results:"
},
{
"code": null,
"e": 6799,
"s": 6426,
"text": "$ aws s3 cp s3://<bucket-key-name>/<sub-bucket-key-name>/dt=2020–01–20–08/ . — recursive | xargs -rn 1 gzip -d *data-1–2020–01–20–08–10–00–04453c-3e98–47a3-b28d-521ae9ff9b3d.logdata-1–2020–01–20–08–10–15–04453c-3e98–47a3-b28d-521ae9ff9b3d.logdata-1–2020–01–20–08–10–30–04453c-3e98–47a3-b28d-521ae9ff9b3d.logdata-1–2020–01–20–08–10–45–04453c-3e98–47a3-b28d-521ae9ff9b3d.log"
},
{
"code": null,
"e": 7064,
"s": 6799,
"text": "Note: You might be thinking, How AWS Athena crawls & scan the S3 Data? It uses AWS Glue Data Crawler (similar to Extract Transform Load ( ETL) job). It does all the heavy lifting under the hood. https://docs.aws.amazon.com/glue/latest/dg/populate-data-catalog.html"
},
{
"code": null,
"e": 7092,
"s": 7064,
"text": "That’s it. It’s too easy..."
},
{
"code": null,
"e": 7281,
"s": 7092,
"text": "Mention: Athena also allows to invoking Machine Learning using SQL Queries. RANDOM_CUT_FOREST (for outliers), HOTSPOTS (for finding the dense area) are popular for that. That’s easy too..."
},
{
"code": null,
"e": 7403,
"s": 7281,
"text": "Performance: Always prefer to use AWS Kinesis SDK libraries for high performance & throughput. It supports batching also."
},
{
"code": null,
"e": 7633,
"s": 7403,
"text": "Performance: If you want to consume the data with AWS Kinesis Delivery Stream, You can use “Kinesis-Enhanced Fanout Streams” which will allow consuming the data with just double the capacity of a shard i.e. from 1 MB/s to 2 MB/s."
},
{
"code": null,
"e": 7947,
"s": 7633,
"text": "Cost: Use GZIP compression for reducing the size of the Object. While restoring just use the “gzip -d <s3-file-keyname>” command to get the data in the raw format again. GZIP will help you to compress the size by 75% and hence You will end up saving up to 75% of the S3 cost. Usually, AWS S3 Costs about 0.03$/GB."
},
{
"code": null,
"e": 8097,
"s": 7947,
"text": "Note: GZIP is known for large compression ratios, but poor decompression speeds and high CPU usage as compared to ZIP format. GZIP usually preferred!"
},
{
"code": null,
"e": 8365,
"s": 8097,
"text": "Cost: Use AWS S3 Life Cycle Rules — AWS S3 stores each object by default on a Standard Zone (means frequent-access zone). AWS S3 Life Cycle Rules will move the Objects to Standard-IA (Infrequent Access) over time which are again 30% cheaper than the Standard S3 Zone."
},
{
"code": null,
"e": 8556,
"s": 8365,
"text": "Security: Always enable S3-Server Side Encryption (SSE) for security. For even more sensitive data, You can also use S3-Client (SSE-C), In which, you can pass your encryption key over HTTPS."
},
{
"code": null,
"e": 8762,
"s": 8556,
"text": "Thanks for reading. I hope you will find this blog helpful. Please stay tuned for more such upcoming blogs on cutting-edge Big Data, Machine Learning & Deep Learning. Stay tuned! The best is yet to come :)"
},
{
"code": null,
"e": 8788,
"s": 8762,
"text": "That’s pretty much of it!"
},
{
"code": null,
"e": 8877,
"s": 8788,
"text": "I hope you will find this blog helpful. Thanks for reading :)Connect: [email protected]"
},
{
"code": null,
"e": 8898,
"s": 8877,
"text": "For more such blogs:"
},
{
"code": null,
"e": 8928,
"s": 8898,
"text": "Cloud & Big Data Engineering:"
},
{
"code": null,
"e": 9004,
"s": 8928,
"text": "Towards Data Science Publication: https://medium.com/@burhanuddinbhopalwala"
}
]
|
Random Effects in Linear Models. An end-to-end analysis example in R... | by Yufeng | Towards Data Science | The simple linear model has an important assumption, the independence of the observations. This assumption holds in most carefully designed experiments but seldom does in real-life datasets.
One of the biggest risks of assuming correlated data as independent is that your linear model will always give you a beautiful p-value due to a large number of “independent” observations.
The “correlation” of observations usually comes from some shared features by the data points within the same group. For example, if you are interested in how family income affects children’s exam grades, you need to consider that the students’ grades from the same school or class are more similar to each other than those from different schools or classes.
In such cases, using random effects is an efficient way to improve the estimates in the linear models. Generally speaking, if you have some grouping structures in the investigating dataset that are not directly related to your keen question to answer, it’s better to include them as random effects in your linear model. (To note, random effects cannot be used on continuous variables and it’s better to have more than 5 levels.)
In this article, I’ll go through a mini-project to show how to use random effects in the linear modeling with R. I will avoid complicated math equations and make the idea and implementation code as simple as possible. Hope you can learn something from it!
My project question is “How does the number of field goal attempts affect the field goal percentage?”
During the timeouts of NBA games, we can always hear the coach shouting at the players, “Keep shooting!”
It’s believed by most NBA professionals that one can finally find his rhythm if he keeps shooting the ball to the basket even though he's freezing cold now. Actually, the underlying assumption is that the increase in the number of field goal attempts can positively affect the field goal made (and finally increase the field goal percentage).
Some players even complain that they are not performing well in terms of the field goal percentage just because they are not allowed to shoot as many as the superstars do on court.
The question of this mini-project is to address the aforementioned phenomenon with statistical modeling.
The dataset is the NBA players’ stats per game in the 2020–2021 NBA season, which is downloaded from the website basketball reference.
Here are the codes in R for data cleaning.
my_tab = read_excel("sportsref_download.xlsx")dup_players = my_tab[with(my_tab, Tm == "TOT"),]$Playermy_tab_filtered = my_tab[with(my_tab,((Player %in% dup_players) & Tm == "TOT")| !(Player %in% dup_players)),] %>% mutate(Pos = replace(Pos, Pos == "SG-PG", "SG"))%>% mutate(Pos = replace(Pos, Pos == "SF-SG", "SF"))%>% mutate(Pos = replace(Pos, Pos == "PF-SF", "PF"))%>% mutate(Pos = replace(Pos, Pos == "C-PF", "C"))%>% mutate(Pos = replace(Pos, Pos == "PG-SG", "PG"))%>% mutate(Pos = replace(Pos, Pos == "SG-SF", "SG"))%>% mutate(Pos = replace(Pos, Pos == "SF-PF", "SF"))%>% mutate(Pos = replace(Pos, Pos == "PF-C", "PF"))my_tab_filtered = my_tab_filtered[complete.cases(my_tab_filtered),]
First, I removed the duplicated players who have been traded between teams within the season from the data. Then, I modified the players’ positions to their primary positions if they can play multiple positions. Finally, I removed the NA values from the data.
To check whether the player names are unique inside the data, I used the following code.
length(unique(my_tab_filtered$Player)) == nrow(my_tab_filtered)
It gives me “TRUE”, which means the players are unique.
Since I’m trying to comment on the field goal attempts’ effects on the field goal percentage, I plotted them against each other in the following scatter plot.
There seems to be some linear relationship between the field goal attempts number and the field goal percentage from the plot. Next, I will use statistical methods to check the observation.
If we don’t consider any possible grouping structures inside the data, we can simply apply the linear regression model to it, which is to fit everything into one linear model.
null.lm = lm(`FG%` ~ FGA, data = my_tab_filtered)summary(null.lm)
it gives us,
## ## Call:## lm(formula = `FG%` ~ FGA, data = my_tab_filtered)## ## Residuals:## Min 1Q Median 3Q Max ## -0.42711 -0.04531 -0.00926 0.03243 0.32324 ## ## Coefficients:## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 0.4254855 0.0084259 50.497 < 2e-16 ***## FGA 0.0032440 0.0009531 3.404 0.000741 ***## ---## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1## ## Residual standard error: 0.08477 on 358 degrees of freedom## Multiple R-squared: 0.03134, Adjusted R-squared: 0.02864 ## F-statistic: 11.58 on 1 and 358 DF, p-value: 0.0007406
The p-value of FGA (field goal attempts) looks good, isn’t it?
I also checked the residuals,
plot(null.lm, which = 1)
plot(null.lm, which = 2)
These diagnoses plots do show some abnormal patterns, but the majority of data looks OK. Please refer to this article for more about diagnosing linear models.
If I stop here, I could have drawn the conclusion that the field goal attempts do positively affect the field goal percentage significantly. However, I have assumed independence between observations in the linear model, which is totally wrong.
Let’s look at the players’ FG% in different positions,
boxplot(`FG%` ~ Pos, data = my_tab_filtered, las=2,xlab = "")
We can see from the boxplot that different positions do have different levels of field goal percentage. For example, the centers have much higher FG% than the other positions, which makes sense because they are closer to the basket.
If we plot again the scatter plot with positions of players as the color, we can see the patterns of grouping (clustering) as well,
Therefore, I cannot ignore the “position” variable even though it is not my interest in modeling.
In such a case, it’s necessary to induce the concepts of fixed effects and random effects in linear models. Simply speaking, a fixed effect is an unknown constant that we are trying to estimate from the data, whereas a random effect is a random variable that we try to estimate the distribution parameters of (Faraway, Julian J. , 2016).
For fixed effects, we aim to estimate their coefficients in the linear model in order to comment on the relationship with the dependent variable. However, we are not interested in the effect of each specific level in the random effect variable, and we just want to test whether the variation of the random effect is larger than zero.
Since I am interested in the FGA’s effects on the FG% in a general way instead of how it looks like in each individual position, I used the position as random effects instead of fixed effects in the linear model. The more conceptual differences between fixed effects and random effects can be found here.
To perform the mixed (fixed effects + random effects) linear model in R, the package lme4 is needed.
Then, I extended the previous linear model with the position as the random effects.
library(lme4)mixed.lm = lmer(`FG%` ~ FGA + (1|Pos), data = my_tab_filtered)summary(mixed.lm)
which gives me,
## Linear mixed model fit by REML ['lmerMod']## Formula: `FG%` ~ FGA + (1 | Pos)## Data: my_tab_filtered## ## REML criterion at convergence: -859.3## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -5.2524 -0.5565 0.0096 0.5838 3.5555 ## ## Random effects:## Groups Name Variance Std.Dev.## Pos (Intercept) 0.003318 0.05760 ## Residual 0.004878 0.06984 ## Number of obs: 360, groups: Pos, 5## ## Fixed effects:## Estimate Std. Error t value## (Intercept) 0.4178439 0.0266955 15.65## FGA 0.0048149 0.0007998 6.02## ## Correlation of Fixed Effects:## (Intr)## FGA -0.223
In the report above, the Random effects part tells us how much variance we found among the grouping factor (here are players’ positions) as well as the residual variance.
And the part of the Fixed effect is very similar to that of the simple linear model report, which shows the estimate of coefficients as well as the standard error of the coefficient.
If we first look at the random effects part of the report above, we can see that the variance from “Pos” is very similar to that from “Residual”. After calculating the proportion,
0.003318/(0.003318 + 0.004878)
I got 40.4% of the variance is not explained by the fixed effects. These results again confirm the necessity of including “Pos” as the random effects.
If we look at the estimate and standard error of the FGA coefficient in the fixed effects part, we can see that the standard error is much smaller than the estimate, which indicates the coefficient of FGA is different from zero.
You may already notice that there is no “p-value” in the report of the mixed linear model by package lme4.
“No p-value provided” is a major disadvantage of using random effects in the linear model. There are actually a lot of ways to calculate the approximate p-value, but none of them is that precise theoretically because of the complicated calculation of the degree of freedom. The discussion of this specific topic can be very complicated and long, so we are not going through the details here.
A practical workaround to calculate the p-value for random effects is to use the likelihood ratio test statistics in bootstrap. The basic idea of the likelihood ratio test is to compare two models’ likelihood to the observed data by including a different number of variables. If the ratio of likelihood is significantly different from 1, the inclusion of the extra variable is useful then.
To test whether the likelihood ratio is significantly different from one is the same as to test whether the difference between the log-likelihood ratio is different from zero.
The test statistic can be calculated as the following,
my_stat = 2*(logLik(mixed.lm) - logLik(null.lm,REML = TRUE))
Then, we create a bootstrap method to simulate the data under the null hypothesis (the simple linear model) and then generate a large number of likelihood ratio test statistics.
LRT_stat = numeric(1000)for(i in 1:1000){ y = simulate(null.lm)$sim_1 null_md = lm(y ~ FGA, data = my_tab_filtered) mixed_md = lmer(y ~ FGA + (1|Pos), data = my_tab_filtered) LRT_stat[i] = as.numeric(2*(logLik(mixed_md) - logLik(null_md,REML = TRUE)))}
Then, we test how many simulated cases exceed the observed statistics in our data,
sum(LRT_stat > my_stat)
In our case, the number is close to zero, which indicates the significance of the random effects.
The same likelihood ratio test could be applied to testing the fixed effects in the linear model. I will not repeat the process again in this article since it’s very similar to that of the test of random effects. The only difference is to set REML to FALSE when you calculate the likelihood ratio statistics between two models that differ in the fixed effects. The code is as below:
my_stat = 2*(logLik(mixed.lm) - logLik(null.lm,REML = FALSE))LRT_stat = numeric(1000)for(i in 1:1000){ y = simulate(null.lm)$sim_1 null_md = lmer(y ~ 1 + (1|Pos), data = my_tab_filtered, method = "ML") mixed_md = lmer(y ~ FGA + (1|Pos), data = my_tab_filtered, method = "ML") LRT_stat[i] = as.numeric(2*(logLik(mixed_md) - logLik(null_md,REML = FALSE)))}sum(LRT_stat > my_stat)
In summary, we found that field goal attempts significantly affect the field goal percentage of a player after considering the random effects from the players’ positions.
The real-life problems could be more complicated than the ones I showed above. For example, if you have more than 1 grouping factor in your random effects, you need to consider the type of the random effects. There are mainly two types of random effects, crossed effects and nested effects. If the subjects in one level of the random effects do not appear in any other levels, then it’s nested effects, otherwise, it’s crossed effects.
For example, in the aforementioned question about the relationship between family income and student grades, you have both school and class as the random effects. The school and class variables are nested effects because one class could only belong to one specific school. The sudo code for such a case could be:
nested_mod = lmer(grades ~ income + (1|school) + (1|school:class), data = school_grades)
or,
nested_mod = lmer(grades ~ income + (1|school/class), data = school_grades)
For another example, if you are trying to measure the relationship between the body size and bodyweight of birds in a large range of mountain areas, you may need to consider two random effects, the season and the mountain location.
Both the season when and the location where the bird is captured can affect the relationship between the body size and weight of birds. Since each mountain will of course have all four seasons, these two random effects are crossed effects. The sudo code is like,
crossed_mod = lmer(grades ~ income + (1|season) + (1|mountain_id), data = birds_data)
These aforementioned usages of random effects in the linear models have covered most possible situations. Hope these are helpful to you.
If you are puzzling about when to use random effects or not, there are a lot of debates and criteria about that. If you are interested, you can read more here. However, my suggestion is that as long as you notice the effects from any grouping factors in the dataset, go ahead with random effects, which is also recommended by Gelman, Andrew (2005).
Cheers!
dynamicecology.wordpress.com
stats.stackexchange.com
Faraway, Julian J. Extending the linear model with R: generalized linear, mixed effects and nonparametric regression models. CRC press, 2016
Gelman, Andrew. “Analysis of variance — why it is more important than ever.” The annals of statistics 33.1 (2005): 1–53. | [
{
"code": null,
"e": 363,
"s": 172,
"text": "The simple linear model has an important assumption, the independence of the observations. This assumption holds in most carefully designed experiments but seldom does in real-life datasets."
},
{
"code": null,
"e": 551,
"s": 363,
"text": "One of the biggest risks of assuming correlated data as independent is that your linear model will always give you a beautiful p-value due to a large number of “independent” observations."
},
{
"code": null,
"e": 909,
"s": 551,
"text": "The “correlation” of observations usually comes from some shared features by the data points within the same group. For example, if you are interested in how family income affects children’s exam grades, you need to consider that the students’ grades from the same school or class are more similar to each other than those from different schools or classes."
},
{
"code": null,
"e": 1338,
"s": 909,
"text": "In such cases, using random effects is an efficient way to improve the estimates in the linear models. Generally speaking, if you have some grouping structures in the investigating dataset that are not directly related to your keen question to answer, it’s better to include them as random effects in your linear model. (To note, random effects cannot be used on continuous variables and it’s better to have more than 5 levels.)"
},
{
"code": null,
"e": 1594,
"s": 1338,
"text": "In this article, I’ll go through a mini-project to show how to use random effects in the linear modeling with R. I will avoid complicated math equations and make the idea and implementation code as simple as possible. Hope you can learn something from it!"
},
{
"code": null,
"e": 1696,
"s": 1594,
"text": "My project question is “How does the number of field goal attempts affect the field goal percentage?”"
},
{
"code": null,
"e": 1801,
"s": 1696,
"text": "During the timeouts of NBA games, we can always hear the coach shouting at the players, “Keep shooting!”"
},
{
"code": null,
"e": 2144,
"s": 1801,
"text": "It’s believed by most NBA professionals that one can finally find his rhythm if he keeps shooting the ball to the basket even though he's freezing cold now. Actually, the underlying assumption is that the increase in the number of field goal attempts can positively affect the field goal made (and finally increase the field goal percentage)."
},
{
"code": null,
"e": 2325,
"s": 2144,
"text": "Some players even complain that they are not performing well in terms of the field goal percentage just because they are not allowed to shoot as many as the superstars do on court."
},
{
"code": null,
"e": 2430,
"s": 2325,
"text": "The question of this mini-project is to address the aforementioned phenomenon with statistical modeling."
},
{
"code": null,
"e": 2565,
"s": 2430,
"text": "The dataset is the NBA players’ stats per game in the 2020–2021 NBA season, which is downloaded from the website basketball reference."
},
{
"code": null,
"e": 2608,
"s": 2565,
"text": "Here are the codes in R for data cleaning."
},
{
"code": null,
"e": 3308,
"s": 2608,
"text": "my_tab = read_excel(\"sportsref_download.xlsx\")dup_players = my_tab[with(my_tab, Tm == \"TOT\"),]$Playermy_tab_filtered = my_tab[with(my_tab,((Player %in% dup_players) & Tm == \"TOT\")| !(Player %in% dup_players)),] %>% mutate(Pos = replace(Pos, Pos == \"SG-PG\", \"SG\"))%>% mutate(Pos = replace(Pos, Pos == \"SF-SG\", \"SF\"))%>% mutate(Pos = replace(Pos, Pos == \"PF-SF\", \"PF\"))%>% mutate(Pos = replace(Pos, Pos == \"C-PF\", \"C\"))%>% mutate(Pos = replace(Pos, Pos == \"PG-SG\", \"PG\"))%>% mutate(Pos = replace(Pos, Pos == \"SG-SF\", \"SG\"))%>% mutate(Pos = replace(Pos, Pos == \"SF-PF\", \"SF\"))%>% mutate(Pos = replace(Pos, Pos == \"PF-C\", \"PF\"))my_tab_filtered = my_tab_filtered[complete.cases(my_tab_filtered),]"
},
{
"code": null,
"e": 3568,
"s": 3308,
"text": "First, I removed the duplicated players who have been traded between teams within the season from the data. Then, I modified the players’ positions to their primary positions if they can play multiple positions. Finally, I removed the NA values from the data."
},
{
"code": null,
"e": 3657,
"s": 3568,
"text": "To check whether the player names are unique inside the data, I used the following code."
},
{
"code": null,
"e": 3721,
"s": 3657,
"text": "length(unique(my_tab_filtered$Player)) == nrow(my_tab_filtered)"
},
{
"code": null,
"e": 3777,
"s": 3721,
"text": "It gives me “TRUE”, which means the players are unique."
},
{
"code": null,
"e": 3936,
"s": 3777,
"text": "Since I’m trying to comment on the field goal attempts’ effects on the field goal percentage, I plotted them against each other in the following scatter plot."
},
{
"code": null,
"e": 4126,
"s": 3936,
"text": "There seems to be some linear relationship between the field goal attempts number and the field goal percentage from the plot. Next, I will use statistical methods to check the observation."
},
{
"code": null,
"e": 4302,
"s": 4126,
"text": "If we don’t consider any possible grouping structures inside the data, we can simply apply the linear regression model to it, which is to fit everything into one linear model."
},
{
"code": null,
"e": 4368,
"s": 4302,
"text": "null.lm = lm(`FG%` ~ FGA, data = my_tab_filtered)summary(null.lm)"
},
{
"code": null,
"e": 4381,
"s": 4368,
"text": "it gives us,"
},
{
"code": null,
"e": 5002,
"s": 4381,
"text": "## ## Call:## lm(formula = `FG%` ~ FGA, data = my_tab_filtered)## ## Residuals:## Min 1Q Median 3Q Max ## -0.42711 -0.04531 -0.00926 0.03243 0.32324 ## ## Coefficients:## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 0.4254855 0.0084259 50.497 < 2e-16 ***## FGA 0.0032440 0.0009531 3.404 0.000741 ***## ---## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1## ## Residual standard error: 0.08477 on 358 degrees of freedom## Multiple R-squared: 0.03134, Adjusted R-squared: 0.02864 ## F-statistic: 11.58 on 1 and 358 DF, p-value: 0.0007406"
},
{
"code": null,
"e": 5065,
"s": 5002,
"text": "The p-value of FGA (field goal attempts) looks good, isn’t it?"
},
{
"code": null,
"e": 5095,
"s": 5065,
"text": "I also checked the residuals,"
},
{
"code": null,
"e": 5120,
"s": 5095,
"text": "plot(null.lm, which = 1)"
},
{
"code": null,
"e": 5145,
"s": 5120,
"text": "plot(null.lm, which = 2)"
},
{
"code": null,
"e": 5304,
"s": 5145,
"text": "These diagnoses plots do show some abnormal patterns, but the majority of data looks OK. Please refer to this article for more about diagnosing linear models."
},
{
"code": null,
"e": 5548,
"s": 5304,
"text": "If I stop here, I could have drawn the conclusion that the field goal attempts do positively affect the field goal percentage significantly. However, I have assumed independence between observations in the linear model, which is totally wrong."
},
{
"code": null,
"e": 5603,
"s": 5548,
"text": "Let’s look at the players’ FG% in different positions,"
},
{
"code": null,
"e": 5665,
"s": 5603,
"text": "boxplot(`FG%` ~ Pos, data = my_tab_filtered, las=2,xlab = \"\")"
},
{
"code": null,
"e": 5898,
"s": 5665,
"text": "We can see from the boxplot that different positions do have different levels of field goal percentage. For example, the centers have much higher FG% than the other positions, which makes sense because they are closer to the basket."
},
{
"code": null,
"e": 6030,
"s": 5898,
"text": "If we plot again the scatter plot with positions of players as the color, we can see the patterns of grouping (clustering) as well,"
},
{
"code": null,
"e": 6128,
"s": 6030,
"text": "Therefore, I cannot ignore the “position” variable even though it is not my interest in modeling."
},
{
"code": null,
"e": 6466,
"s": 6128,
"text": "In such a case, it’s necessary to induce the concepts of fixed effects and random effects in linear models. Simply speaking, a fixed effect is an unknown constant that we are trying to estimate from the data, whereas a random effect is a random variable that we try to estimate the distribution parameters of (Faraway, Julian J. , 2016)."
},
{
"code": null,
"e": 6800,
"s": 6466,
"text": "For fixed effects, we aim to estimate their coefficients in the linear model in order to comment on the relationship with the dependent variable. However, we are not interested in the effect of each specific level in the random effect variable, and we just want to test whether the variation of the random effect is larger than zero."
},
{
"code": null,
"e": 7105,
"s": 6800,
"text": "Since I am interested in the FGA’s effects on the FG% in a general way instead of how it looks like in each individual position, I used the position as random effects instead of fixed effects in the linear model. The more conceptual differences between fixed effects and random effects can be found here."
},
{
"code": null,
"e": 7206,
"s": 7105,
"text": "To perform the mixed (fixed effects + random effects) linear model in R, the package lme4 is needed."
},
{
"code": null,
"e": 7290,
"s": 7206,
"text": "Then, I extended the previous linear model with the position as the random effects."
},
{
"code": null,
"e": 7383,
"s": 7290,
"text": "library(lme4)mixed.lm = lmer(`FG%` ~ FGA + (1|Pos), data = my_tab_filtered)summary(mixed.lm)"
},
{
"code": null,
"e": 7399,
"s": 7383,
"text": "which gives me,"
},
{
"code": null,
"e": 8055,
"s": 7399,
"text": "## Linear mixed model fit by REML ['lmerMod']## Formula: `FG%` ~ FGA + (1 | Pos)## Data: my_tab_filtered## ## REML criterion at convergence: -859.3## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -5.2524 -0.5565 0.0096 0.5838 3.5555 ## ## Random effects:## Groups Name Variance Std.Dev.## Pos (Intercept) 0.003318 0.05760 ## Residual 0.004878 0.06984 ## Number of obs: 360, groups: Pos, 5## ## Fixed effects:## Estimate Std. Error t value## (Intercept) 0.4178439 0.0266955 15.65## FGA 0.0048149 0.0007998 6.02## ## Correlation of Fixed Effects:## (Intr)## FGA -0.223"
},
{
"code": null,
"e": 8226,
"s": 8055,
"text": "In the report above, the Random effects part tells us how much variance we found among the grouping factor (here are players’ positions) as well as the residual variance."
},
{
"code": null,
"e": 8409,
"s": 8226,
"text": "And the part of the Fixed effect is very similar to that of the simple linear model report, which shows the estimate of coefficients as well as the standard error of the coefficient."
},
{
"code": null,
"e": 8589,
"s": 8409,
"text": "If we first look at the random effects part of the report above, we can see that the variance from “Pos” is very similar to that from “Residual”. After calculating the proportion,"
},
{
"code": null,
"e": 8620,
"s": 8589,
"text": "0.003318/(0.003318 + 0.004878)"
},
{
"code": null,
"e": 8771,
"s": 8620,
"text": "I got 40.4% of the variance is not explained by the fixed effects. These results again confirm the necessity of including “Pos” as the random effects."
},
{
"code": null,
"e": 9000,
"s": 8771,
"text": "If we look at the estimate and standard error of the FGA coefficient in the fixed effects part, we can see that the standard error is much smaller than the estimate, which indicates the coefficient of FGA is different from zero."
},
{
"code": null,
"e": 9107,
"s": 9000,
"text": "You may already notice that there is no “p-value” in the report of the mixed linear model by package lme4."
},
{
"code": null,
"e": 9499,
"s": 9107,
"text": "“No p-value provided” is a major disadvantage of using random effects in the linear model. There are actually a lot of ways to calculate the approximate p-value, but none of them is that precise theoretically because of the complicated calculation of the degree of freedom. The discussion of this specific topic can be very complicated and long, so we are not going through the details here."
},
{
"code": null,
"e": 9889,
"s": 9499,
"text": "A practical workaround to calculate the p-value for random effects is to use the likelihood ratio test statistics in bootstrap. The basic idea of the likelihood ratio test is to compare two models’ likelihood to the observed data by including a different number of variables. If the ratio of likelihood is significantly different from 1, the inclusion of the extra variable is useful then."
},
{
"code": null,
"e": 10065,
"s": 9889,
"text": "To test whether the likelihood ratio is significantly different from one is the same as to test whether the difference between the log-likelihood ratio is different from zero."
},
{
"code": null,
"e": 10120,
"s": 10065,
"text": "The test statistic can be calculated as the following,"
},
{
"code": null,
"e": 10181,
"s": 10120,
"text": "my_stat = 2*(logLik(mixed.lm) - logLik(null.lm,REML = TRUE))"
},
{
"code": null,
"e": 10359,
"s": 10181,
"text": "Then, we create a bootstrap method to simulate the data under the null hypothesis (the simple linear model) and then generate a large number of likelihood ratio test statistics."
},
{
"code": null,
"e": 10616,
"s": 10359,
"text": "LRT_stat = numeric(1000)for(i in 1:1000){ y = simulate(null.lm)$sim_1 null_md = lm(y ~ FGA, data = my_tab_filtered) mixed_md = lmer(y ~ FGA + (1|Pos), data = my_tab_filtered) LRT_stat[i] = as.numeric(2*(logLik(mixed_md) - logLik(null_md,REML = TRUE)))}"
},
{
"code": null,
"e": 10699,
"s": 10616,
"text": "Then, we test how many simulated cases exceed the observed statistics in our data,"
},
{
"code": null,
"e": 10723,
"s": 10699,
"text": "sum(LRT_stat > my_stat)"
},
{
"code": null,
"e": 10821,
"s": 10723,
"text": "In our case, the number is close to zero, which indicates the significance of the random effects."
},
{
"code": null,
"e": 11204,
"s": 10821,
"text": "The same likelihood ratio test could be applied to testing the fixed effects in the linear model. I will not repeat the process again in this article since it’s very similar to that of the test of random effects. The only difference is to set REML to FALSE when you calculate the likelihood ratio statistics between two models that differ in the fixed effects. The code is as below:"
},
{
"code": null,
"e": 11586,
"s": 11204,
"text": "my_stat = 2*(logLik(mixed.lm) - logLik(null.lm,REML = FALSE))LRT_stat = numeric(1000)for(i in 1:1000){ y = simulate(null.lm)$sim_1 null_md = lmer(y ~ 1 + (1|Pos), data = my_tab_filtered, method = \"ML\") mixed_md = lmer(y ~ FGA + (1|Pos), data = my_tab_filtered, method = \"ML\") LRT_stat[i] = as.numeric(2*(logLik(mixed_md) - logLik(null_md,REML = FALSE)))}sum(LRT_stat > my_stat)"
},
{
"code": null,
"e": 11757,
"s": 11586,
"text": "In summary, we found that field goal attempts significantly affect the field goal percentage of a player after considering the random effects from the players’ positions."
},
{
"code": null,
"e": 12193,
"s": 11757,
"text": "The real-life problems could be more complicated than the ones I showed above. For example, if you have more than 1 grouping factor in your random effects, you need to consider the type of the random effects. There are mainly two types of random effects, crossed effects and nested effects. If the subjects in one level of the random effects do not appear in any other levels, then it’s nested effects, otherwise, it’s crossed effects."
},
{
"code": null,
"e": 12506,
"s": 12193,
"text": "For example, in the aforementioned question about the relationship between family income and student grades, you have both school and class as the random effects. The school and class variables are nested effects because one class could only belong to one specific school. The sudo code for such a case could be:"
},
{
"code": null,
"e": 12595,
"s": 12506,
"text": "nested_mod = lmer(grades ~ income + (1|school) + (1|school:class), data = school_grades)"
},
{
"code": null,
"e": 12599,
"s": 12595,
"text": "or,"
},
{
"code": null,
"e": 12675,
"s": 12599,
"text": "nested_mod = lmer(grades ~ income + (1|school/class), data = school_grades)"
},
{
"code": null,
"e": 12907,
"s": 12675,
"text": "For another example, if you are trying to measure the relationship between the body size and bodyweight of birds in a large range of mountain areas, you may need to consider two random effects, the season and the mountain location."
},
{
"code": null,
"e": 13170,
"s": 12907,
"text": "Both the season when and the location where the bird is captured can affect the relationship between the body size and weight of birds. Since each mountain will of course have all four seasons, these two random effects are crossed effects. The sudo code is like,"
},
{
"code": null,
"e": 13256,
"s": 13170,
"text": "crossed_mod = lmer(grades ~ income + (1|season) + (1|mountain_id), data = birds_data)"
},
{
"code": null,
"e": 13393,
"s": 13256,
"text": "These aforementioned usages of random effects in the linear models have covered most possible situations. Hope these are helpful to you."
},
{
"code": null,
"e": 13742,
"s": 13393,
"text": "If you are puzzling about when to use random effects or not, there are a lot of debates and criteria about that. If you are interested, you can read more here. However, my suggestion is that as long as you notice the effects from any grouping factors in the dataset, go ahead with random effects, which is also recommended by Gelman, Andrew (2005)."
},
{
"code": null,
"e": 13750,
"s": 13742,
"text": "Cheers!"
},
{
"code": null,
"e": 13779,
"s": 13750,
"text": "dynamicecology.wordpress.com"
},
{
"code": null,
"e": 13803,
"s": 13779,
"text": "stats.stackexchange.com"
},
{
"code": null,
"e": 13944,
"s": 13803,
"text": "Faraway, Julian J. Extending the linear model with R: generalized linear, mixed effects and nonparametric regression models. CRC press, 2016"
}
]
|
C/C++ Program for nth Catalan Number? | Catalan numbers are a sequence of numbers. Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursively-defined objects.
Cn is the number of Dyck words of length 2n. A Dyck word is a string consisting of n X's and n Y's such that no initial segment of the string has more Y's than X's. For example, the following are the Dyck words of length 6
Cn is the number of Dyck words of length 2n. A Dyck word is a string consisting of n X's and n Y's such that no initial segment of the string has more Y's than X's. For example, the following are the Dyck words of length 6
XXXYYY XYXXYY XYXYXY XXYYXY XXYXYY.
Re-interpreting the symbol X as an open parenthesis and Y as a close parenthesis, Cn counts the number of expressions containing n pairs of parentheses which are correctly matched
Re-interpreting the symbol X as an open parenthesis and Y as a close parenthesis, Cn counts the number of expressions containing n pairs of parentheses which are correctly matched
((())) ()(()) ()()() (())() (()())
Cn is the number of different ways n + 1 factors can be completely parenthesized (or the number of ways of associating n applications of a binary operator). For n = 3, for example, we have the following five different parenthesizations of four factors:
Cn is the number of different ways n + 1 factors can be completely parenthesized (or the number of ways of associating n applications of a binary operator). For n = 3, for example, we have the following five different parenthesizations of four factors:
((ab)c)d (a(bc))d (ab)(cd) a((bc)d) a(b(cd))
Successive applications of a binary operator can be represented in terms of a full binary tree. (A rooted binary tree is full if every vertex has either two children or no children.) It follows that Cn is the number of full binary trees with n + 1 leaves:
Successive applications of a binary operator can be represented in terms of a full binary tree. (A rooted binary tree is full if every vertex has either two children or no children.) It follows that Cn is the number of full binary trees with n + 1 leaves:
Input - 6Output - 1 1 2 5 14 42
Explanation
The first Catalan numbers for n = 0, 1, 2, 3,4,5,6,7,8,9,10, ... are1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862,
#include<iostream>
using namespace std;
long int catalan( int n) {
if (n <= 1){
return 1;
}
long int result = 0;
for (int i=0; i<n; i++){
result += catalan(i)*catalan(n-i-1);
}
return result;
}
int main(){
for (int i=0; i<6; i++)
cout << catalan(i) << " ";
return 0;
}
1 1 2 5 14 42 | [
{
"code": null,
"e": 1242,
"s": 1062,
"text": "Catalan numbers are a sequence of numbers. Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursively-defined objects."
},
{
"code": null,
"e": 1465,
"s": 1242,
"text": "Cn is the number of Dyck words of length 2n. A Dyck word is a string consisting of n X's and n Y's such that no initial segment of the string has more Y's than X's. For example, the following are the Dyck words of length 6"
},
{
"code": null,
"e": 1688,
"s": 1465,
"text": "Cn is the number of Dyck words of length 2n. A Dyck word is a string consisting of n X's and n Y's such that no initial segment of the string has more Y's than X's. For example, the following are the Dyck words of length 6"
},
{
"code": null,
"e": 1724,
"s": 1688,
"text": "XXXYYY XYXXYY XYXYXY XXYYXY XXYXYY."
},
{
"code": null,
"e": 1904,
"s": 1724,
"text": "Re-interpreting the symbol X as an open parenthesis and Y as a close parenthesis, Cn counts the number of expressions containing n pairs of parentheses which are correctly matched"
},
{
"code": null,
"e": 2084,
"s": 1904,
"text": "Re-interpreting the symbol X as an open parenthesis and Y as a close parenthesis, Cn counts the number of expressions containing n pairs of parentheses which are correctly matched"
},
{
"code": null,
"e": 2119,
"s": 2084,
"text": "((())) ()(()) ()()() (())() (()())"
},
{
"code": null,
"e": 2372,
"s": 2119,
"text": "Cn is the number of different ways n + 1 factors can be completely parenthesized (or the number of ways of associating n applications of a binary operator). For n = 3, for example, we have the following five different parenthesizations of four factors:"
},
{
"code": null,
"e": 2625,
"s": 2372,
"text": "Cn is the number of different ways n + 1 factors can be completely parenthesized (or the number of ways of associating n applications of a binary operator). For n = 3, for example, we have the following five different parenthesizations of four factors:"
},
{
"code": null,
"e": 2670,
"s": 2625,
"text": "((ab)c)d (a(bc))d (ab)(cd) a((bc)d) a(b(cd))"
},
{
"code": null,
"e": 2926,
"s": 2670,
"text": "Successive applications of a binary operator can be represented in terms of a full binary tree. (A rooted binary tree is full if every vertex has either two children or no children.) It follows that Cn is the number of full binary trees with n + 1 leaves:"
},
{
"code": null,
"e": 3182,
"s": 2926,
"text": "Successive applications of a binary operator can be represented in terms of a full binary tree. (A rooted binary tree is full if every vertex has either two children or no children.) It follows that Cn is the number of full binary trees with n + 1 leaves:"
},
{
"code": null,
"e": 3214,
"s": 3182,
"text": "Input - 6Output - 1 1 2 5 14 42"
},
{
"code": null,
"e": 3226,
"s": 3214,
"text": "Explanation"
},
{
"code": null,
"e": 3336,
"s": 3226,
"text": "The first Catalan numbers for n = 0, 1, 2, 3,4,5,6,7,8,9,10, ... are1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862,"
},
{
"code": null,
"e": 3644,
"s": 3336,
"text": "#include<iostream>\nusing namespace std;\nlong int catalan( int n) {\n if (n <= 1){\n return 1;\n }\n long int result = 0;\n for (int i=0; i<n; i++){\n result += catalan(i)*catalan(n-i-1);\n }\n return result;\n}\nint main(){\n for (int i=0; i<6; i++)\n cout << catalan(i) << \" \";\n return 0;\n}"
},
{
"code": null,
"e": 3658,
"s": 3644,
"text": "1 1 2 5 14 42"
}
]
|
file command in Linux with examples - GeeksforGeeks | 19 Feb, 2021
file command is used to determine the type of a file. .file type may be of human-readable(e.g. ‘ASCII text’) or MIME type(e.g. ‘text/plain; charset=us-ascii’). This command tests each argument in an attempt to categorize it.
It has three sets of tests as follows:
filesystem test: This test is based on the result which returns from a stat system call. The program verifies that if the file is empty, or if it’s some sort of special file. This test causes the file type to be printed.
magic test: These tests are used to check for files with data in particular fixed formats.
language test: This test search for particular strings which can appear anywhere in the first few blocks of a file.
Syntax:
file [option] [filename]
Example: Command displays the file type
file email.py
file name.jpeg
file Invoice.pdf
file exam.ods
file videosong.mp4
Options:
-b, –brief : This is used to display just file type in brief mode.Syntax:file -b filename
Example:file -b email.py
file -b input.txt
file -b os.pdf
Here, we can see that file type without filename.
Syntax:
file -b filename
Example:
file -b email.py
file -b input.txt
file -b os.pdf
Here, we can see that file type without filename.
* option : Command displays the all files’s file type.file *
The output shows all files in the home directory
file *
The output shows all files in the home directory
directoryname/* option : This is used to display all files filetypes in particular directory.Syntax:file directoryname/*
Example:file work/*
The output shows all files in a particular directory.
Syntax:
file directoryname/*
Example:
file work/*
The output shows all files in a particular directory.
[range]* option: To display the file type of files in specific range.Syntax:file [range]*
Example:file [a-z]*
file [a-e]*
The output shows the range of files.
Syntax:
file [range]*
Example:
file [a-z]*
file [a-e]*
The output shows the range of files.
-c option: Cause a checking printout of the parsed form of the magic file. This option is usually used in conjunction with the -m flag to debug a new magic file before installing it.file -c
Example:file -c
file -c
Example:
file -c
-f option: Read the names of the files to be examined from namefile (one per line) before the argument list. Either namefile or atleast one filename argument must be present; to test the standard input, use ‘-’ as a filename argument.Syntax:file -f -
Syntax:
file -f -
-F option : File and file type are separated by :. But we can change separator using -F optionSyntax:file -F "-" filename
Example:file -F - input.txt
file -F + os.pdf
The output shows file and file types are separated by – and +.
Syntax:
file -F "-" filename
Example:
file -F - input.txt
file -F + os.pdf
The output shows file and file types are separated by – and +.
-i option: To view mime type of file.Syntax:file -i filename
Example:file -i input.txt
file -i os.pdf
Syntax:
file -i filename
Example:
file -i input.txt
file -i os.pdf
-N option: Don’t pad filenames so that they align in the output.file -N *
Example:file -N *
file -N *
Example:
file -N *
-s option: For special filesSyntax:file -s filename
Example:file /dev/sda
file -s /dev/sda
file /dev/sda5
file -s /dev/sda5
Syntax:
file -s filename
Example:
file /dev/sda
file -s /dev/sda
file /dev/sda5
file -s /dev/sda5
filenames: Displays file types of multiple filesSyntax:file filenames
Example:file input.txt .local Desktop
Syntax:
file filenames
Example:
file input.txt .local Desktop
-z option: Try to look inside compressed files.Example:file -z flash.tar.gz
Example:
file -z flash.tar.gz
–help option: Print a help message and exit.
YouTubeGeeksforGeeks500K subscribersLinux Tutorials | file and wc commands | GeeksforGeeksWatch laterShareCopy link18/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:35•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=A9411dSJYRk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
shubham_singh
linux-command
Linux-file-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++ | [
{
"code": null,
"e": 23664,
"s": 23636,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 23889,
"s": 23664,
"text": "file command is used to determine the type of a file. .file type may be of human-readable(e.g. ‘ASCII text’) or MIME type(e.g. ‘text/plain; charset=us-ascii’). This command tests each argument in an attempt to categorize it."
},
{
"code": null,
"e": 23928,
"s": 23889,
"text": "It has three sets of tests as follows:"
},
{
"code": null,
"e": 24149,
"s": 23928,
"text": "filesystem test: This test is based on the result which returns from a stat system call. The program verifies that if the file is empty, or if it’s some sort of special file. This test causes the file type to be printed."
},
{
"code": null,
"e": 24240,
"s": 24149,
"text": "magic test: These tests are used to check for files with data in particular fixed formats."
},
{
"code": null,
"e": 24356,
"s": 24240,
"text": "language test: This test search for particular strings which can appear anywhere in the first few blocks of a file."
},
{
"code": null,
"e": 24364,
"s": 24356,
"text": "Syntax:"
},
{
"code": null,
"e": 24390,
"s": 24364,
"text": "file [option] [filename]\n"
},
{
"code": null,
"e": 24430,
"s": 24390,
"text": "Example: Command displays the file type"
},
{
"code": null,
"e": 24510,
"s": 24430,
"text": "file email.py\nfile name.jpeg\nfile Invoice.pdf\nfile exam.ods\nfile videosong.mp4\n"
},
{
"code": null,
"e": 24519,
"s": 24510,
"text": "Options:"
},
{
"code": null,
"e": 24717,
"s": 24519,
"text": "-b, –brief : This is used to display just file type in brief mode.Syntax:file -b filename\nExample:file -b email.py\nfile -b input.txt\nfile -b os.pdf\nHere, we can see that file type without filename."
},
{
"code": null,
"e": 24725,
"s": 24717,
"text": "Syntax:"
},
{
"code": null,
"e": 24743,
"s": 24725,
"text": "file -b filename\n"
},
{
"code": null,
"e": 24752,
"s": 24743,
"text": "Example:"
},
{
"code": null,
"e": 24803,
"s": 24752,
"text": "file -b email.py\nfile -b input.txt\nfile -b os.pdf\n"
},
{
"code": null,
"e": 24853,
"s": 24803,
"text": "Here, we can see that file type without filename."
},
{
"code": null,
"e": 24963,
"s": 24853,
"text": "* option : Command displays the all files’s file type.file *\nThe output shows all files in the home directory"
},
{
"code": null,
"e": 24971,
"s": 24963,
"text": "file *\n"
},
{
"code": null,
"e": 25020,
"s": 24971,
"text": "The output shows all files in the home directory"
},
{
"code": null,
"e": 25215,
"s": 25020,
"text": "directoryname/* option : This is used to display all files filetypes in particular directory.Syntax:file directoryname/*\nExample:file work/*\nThe output shows all files in a particular directory."
},
{
"code": null,
"e": 25223,
"s": 25215,
"text": "Syntax:"
},
{
"code": null,
"e": 25245,
"s": 25223,
"text": "file directoryname/*\n"
},
{
"code": null,
"e": 25254,
"s": 25245,
"text": "Example:"
},
{
"code": null,
"e": 25267,
"s": 25254,
"text": "file work/*\n"
},
{
"code": null,
"e": 25321,
"s": 25267,
"text": "The output shows all files in a particular directory."
},
{
"code": null,
"e": 25480,
"s": 25321,
"text": "[range]* option: To display the file type of files in specific range.Syntax:file [range]*\nExample:file [a-z]*\nfile [a-e]*\nThe output shows the range of files."
},
{
"code": null,
"e": 25488,
"s": 25480,
"text": "Syntax:"
},
{
"code": null,
"e": 25503,
"s": 25488,
"text": "file [range]*\n"
},
{
"code": null,
"e": 25512,
"s": 25503,
"text": "Example:"
},
{
"code": null,
"e": 25537,
"s": 25512,
"text": "file [a-z]*\nfile [a-e]*\n"
},
{
"code": null,
"e": 25574,
"s": 25537,
"text": "The output shows the range of files."
},
{
"code": null,
"e": 25781,
"s": 25574,
"text": "-c option: Cause a checking printout of the parsed form of the magic file. This option is usually used in conjunction with the -m flag to debug a new magic file before installing it.file -c\nExample:file -c\n"
},
{
"code": null,
"e": 25790,
"s": 25781,
"text": "file -c\n"
},
{
"code": null,
"e": 25799,
"s": 25790,
"text": "Example:"
},
{
"code": null,
"e": 25808,
"s": 25799,
"text": "file -c\n"
},
{
"code": null,
"e": 26060,
"s": 25808,
"text": "-f option: Read the names of the files to be examined from namefile (one per line) before the argument list. Either namefile or atleast one filename argument must be present; to test the standard input, use ‘-’ as a filename argument.Syntax:file -f -\n"
},
{
"code": null,
"e": 26068,
"s": 26060,
"text": "Syntax:"
},
{
"code": null,
"e": 26079,
"s": 26068,
"text": "file -f -\n"
},
{
"code": null,
"e": 26309,
"s": 26079,
"text": "-F option : File and file type are separated by :. But we can change separator using -F optionSyntax:file -F \"-\" filename\nExample:file -F - input.txt\nfile -F + os.pdf\nThe output shows file and file types are separated by – and +."
},
{
"code": null,
"e": 26317,
"s": 26309,
"text": "Syntax:"
},
{
"code": null,
"e": 26339,
"s": 26317,
"text": "file -F \"-\" filename\n"
},
{
"code": null,
"e": 26348,
"s": 26339,
"text": "Example:"
},
{
"code": null,
"e": 26386,
"s": 26348,
"text": "file -F - input.txt\nfile -F + os.pdf\n"
},
{
"code": null,
"e": 26449,
"s": 26386,
"text": "The output shows file and file types are separated by – and +."
},
{
"code": null,
"e": 26552,
"s": 26449,
"text": "-i option: To view mime type of file.Syntax:file -i filename\nExample:file -i input.txt\nfile -i os.pdf\n"
},
{
"code": null,
"e": 26560,
"s": 26552,
"text": "Syntax:"
},
{
"code": null,
"e": 26578,
"s": 26560,
"text": "file -i filename\n"
},
{
"code": null,
"e": 26587,
"s": 26578,
"text": "Example:"
},
{
"code": null,
"e": 26621,
"s": 26587,
"text": "file -i input.txt\nfile -i os.pdf\n"
},
{
"code": null,
"e": 26714,
"s": 26621,
"text": "-N option: Don’t pad filenames so that they align in the output.file -N *\nExample:file -N *\n"
},
{
"code": null,
"e": 26725,
"s": 26714,
"text": "file -N *\n"
},
{
"code": null,
"e": 26734,
"s": 26725,
"text": "Example:"
},
{
"code": null,
"e": 26745,
"s": 26734,
"text": "file -N *\n"
},
{
"code": null,
"e": 26877,
"s": 26745,
"text": "-s option: For special filesSyntax:file -s filename\nExample:file /dev/sda \nfile -s /dev/sda \nfile /dev/sda5 \nfile -s /dev/sda5 \n"
},
{
"code": null,
"e": 26885,
"s": 26877,
"text": "Syntax:"
},
{
"code": null,
"e": 26903,
"s": 26885,
"text": "file -s filename\n"
},
{
"code": null,
"e": 26912,
"s": 26903,
"text": "Example:"
},
{
"code": null,
"e": 26984,
"s": 26912,
"text": "file /dev/sda \nfile -s /dev/sda \nfile /dev/sda5 \nfile -s /dev/sda5 \n"
},
{
"code": null,
"e": 27093,
"s": 26984,
"text": "filenames: Displays file types of multiple filesSyntax:file filenames\nExample:file input.txt .local Desktop\n"
},
{
"code": null,
"e": 27101,
"s": 27093,
"text": "Syntax:"
},
{
"code": null,
"e": 27117,
"s": 27101,
"text": "file filenames\n"
},
{
"code": null,
"e": 27126,
"s": 27117,
"text": "Example:"
},
{
"code": null,
"e": 27157,
"s": 27126,
"text": "file input.txt .local Desktop\n"
},
{
"code": null,
"e": 27234,
"s": 27157,
"text": "-z option: Try to look inside compressed files.Example:file -z flash.tar.gz\n"
},
{
"code": null,
"e": 27243,
"s": 27234,
"text": "Example:"
},
{
"code": null,
"e": 27265,
"s": 27243,
"text": "file -z flash.tar.gz\n"
},
{
"code": null,
"e": 27310,
"s": 27265,
"text": "–help option: Print a help message and exit."
},
{
"code": null,
"e": 28152,
"s": 27310,
"text": "YouTubeGeeksforGeeks500K subscribersLinux Tutorials | file and wc commands | GeeksforGeeksWatch laterShareCopy link18/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:35•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=A9411dSJYRk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 28166,
"s": 28152,
"text": "shubham_singh"
},
{
"code": null,
"e": 28180,
"s": 28166,
"text": "linux-command"
},
{
"code": null,
"e": 28200,
"s": 28180,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 28207,
"s": 28200,
"text": "Picked"
},
{
"code": null,
"e": 28218,
"s": 28207,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28316,
"s": 28218,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28325,
"s": 28316,
"text": "Comments"
},
{
"code": null,
"e": 28338,
"s": 28325,
"text": "Old Comments"
},
{
"code": null,
"e": 28376,
"s": 28338,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 28411,
"s": 28376,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 28446,
"s": 28411,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 28482,
"s": 28446,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 28520,
"s": 28482,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28558,
"s": 28520,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 28593,
"s": 28558,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 28630,
"s": 28593,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 28666,
"s": 28630,
"text": "echo command in Linux with Examples"
}
]
|
How to center a button element vertically and horizontally with CSS? | To center a button vertically and horizontally with CSS, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.centered {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid rgb(0, 70, 128);
}
button{
font-size: 18px;
border: none;
padding:10px;
background-color: darkblue;
color:white;
}
</style>
</head>
<body>
<h1>Centering Example</h1>
<div class="centered">
<button>This button is centered</button>
</div>
</body>
</html>
The above code will produce the following output − | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "To center a button vertically and horizontally with CSS, the code is as follows −"
},
{
"code": null,
"e": 1155,
"s": 1144,
"text": " Live Demo"
},
{
"code": null,
"e": 1707,
"s": 1155,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .centered {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 200px;\n border: 3px solid rgb(0, 70, 128);\n }\n button{\n font-size: 18px;\n border: none;\n padding:10px;\n background-color: darkblue;\n color:white;\n }\n</style>\n</head>\n<body>\n<h1>Centering Example</h1>\n<div class=\"centered\">\n<button>This button is centered</button>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 1758,
"s": 1707,
"text": "The above code will produce the following output −"
}
]
|
Program to find sum of the given sequence - GeeksforGeeks | 14 Mar, 2022
Given two numbers and . The task is to find the sum of the sequence given below.
(1*2*3*...*k) + (2*3*...*k*(k+1)) + (3*4*..*(k+1)*(k+2)) +.....+((n-k+1)*(n-k+2)*...*(n-k+k)).
Since the output can be large, print the answer under modulo 10^9+7.Examples:
Input : N = 3, K = 2
Output : 8
Input : N = 4, K = 2
Output : 20
Let us take the given example and try to reduce it to a general formula.In the given example for n = 3 and k=2,
Sum = 1*2 + 2*3
We know that: So each term is of the form:
If we multiply and divide by , it becomes
Which is nothing but, Therefore, But since n is so large we can not calculate it directly, we have to simplify the above expression.On Simplifying we get,
Below is the implementation of the above idea:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the sum of the// given sequence #include <bits/stdc++.h>using namespace std; const long long MOD = 1000000007; // function to find modulo inverse// under 10^9+7long long modInv(long long x){ long long n = MOD - 2; long long result = 1; while (n) { if (n & 1) result = result * x % MOD; x = x * x % MOD; n = n / 2; } return result;} // Function to find the sum of the// given sequencelong long getSum(long long n, long long k){ long long ans = 1; for (long long i = n + 1; i > n - k; i--) ans = ans * i % MOD; ans = ans * modInv(k + 1) % MOD; return ans;} // Driver codeint main(){ long long n = 3, k = 2; cout<<getSum(n,k); return 0;}
// Java program to find the sum of the// given sequence class GFG { static long MOD = 1000000007; // function to find modulo inverse// under 10^9+7 static long modInv(long x) { long n = MOD - 2; long result = 1; while (n > 0) { if ((n & 1) > 0) { result = result * x % MOD; } x = x * x % MOD; n = n / 2; } return result; } // Function to find the sum of the// given sequence static long getSum(long n, long k) { long ans = 1; for (long i = n + 1; i > n - k; i--) { ans = ans * i % MOD; } ans = ans * modInv(k + 1) % MOD; return ans; } // Driver code public static void main(String[] args) { long n = 3, k = 2; System.out.println(getSum(n, k)); }}
# Python3 program to find the sum# of the given sequence MOD = 1000000007; # function to find modulo inverse# under 10^9+7def modInv(x): n = MOD - 2; result = 1; while (n): if (n&1): result = result * x % MOD; x = x * x % MOD; n = int(n / 2); return result; # Function to find the sum of# the given sequencedef getSum(n, k): ans = 1; for i in range(n + 1, n - k, -1): ans = ans * i % MOD; ans = ans * modInv(k + 1) % MOD; return ans; # Driver coden = 3;k = 2; print(getSum(n,k)); # This code is contributed by mits
// C# program to find the sum of the// given sequenceusing System; // function to find modulo inverse// under 10^9+7class gfg{ public long MOD = 1000000007; public long modInv(long x) { long n = MOD - 2; long result = 1; while (n >0) { if ((n & 1) > 0) result = result * x % MOD; x = x * x % MOD; n = n / 2; } return result;} // Function to find the sum of the// given sequence public long getSum(long n, long k) { long ans = 1; for (long i = n + 1; i > n - k; i--) ans = ans * i % MOD; ans = ans * modInv(k + 1) % MOD; return ans; }} // Driver codeclass geek{ public static int Main() { gfg g = new gfg(); long n = 3, k = 2; Console.WriteLine(g.getSum(n,k)); return 0; }}//This code is contributed by SoumikMondal
<?php// PHP program to find the sum of// the given sequence // function to find modulo inverse// under 10^9+7function modInv($x){ $MOD = 1000000007; $n = $MOD - 2; $result = 1; while ($n) { if ($n & 1) $result = $result * $x % $MOD; $x = $x * $x % $MOD; $n = $n / 2; } return $result;} // Function to find the sum of the// given sequencefunction getSum($n, $k){ $MOD = 1000000007; $ans = 1; for ($i = $n + 1; $i > $n - $k; $i--) $ans = $ans * $i % $MOD; $ans = $ans * modInv($k + 1) % $MOD; return $ans;} // Driver code$n = 3; $k = 2; echo getSum($n, $k); // This code is contributed// by Akanksha Rai?>
<script> // Javascript program to find the sum of the// given sequence var MOD = 100000007; // function to find modulo inverse// under 10^9+7function modInv(x){ var n = MOD - 2; var result = 1; while (n) { if (n & 1) result = result * x % MOD; x = x * x % MOD; n = n / 2; } return result;} // Function to find the sum of the// given sequencefunction getSum(n, k){ var ans = 1; for (var i = n + 1; i > n - k; i--) ans = ans * i % MOD; ans = ans * modInv(k + 1) % MOD; return ans;} // Driver codevar n = 3, k = 2; document.write( getSum(n,k)); // This code is contributed by noob2000.</script>
8
SoumikMondal
29AjayKumar
Mithun Kumar
Akanksha_Rai
noob2000
varshagumber28
math
Modular Arithmetic
series
C++ Programs
Mathematical
Mathematical
series
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program for QuickSort
Shallow Copy and Deep Copy in C++
delete keyword in C++
Passing a function as a parameter in C++
cin in C++
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26865,
"s": 26837,
"text": "\n14 Mar, 2022"
},
{
"code": null,
"e": 26947,
"s": 26865,
"text": "Given two numbers and . The task is to find the sum of the sequence given below. "
},
{
"code": null,
"e": 27042,
"s": 26947,
"text": "(1*2*3*...*k) + (2*3*...*k*(k+1)) + (3*4*..*(k+1)*(k+2)) +.....+((n-k+1)*(n-k+2)*...*(n-k+k))."
},
{
"code": null,
"e": 27122,
"s": 27042,
"text": "Since the output can be large, print the answer under modulo 10^9+7.Examples: "
},
{
"code": null,
"e": 27188,
"s": 27122,
"text": "Input : N = 3, K = 2\nOutput : 8\n\nInput : N = 4, K = 2\nOutput : 20"
},
{
"code": null,
"e": 27304,
"s": 27190,
"text": "Let us take the given example and try to reduce it to a general formula.In the given example for n = 3 and k=2, "
},
{
"code": null,
"e": 27321,
"s": 27304,
"text": "Sum = 1*2 + 2*3 "
},
{
"code": null,
"e": 27365,
"s": 27321,
"text": "We know that: So each term is of the form: "
},
{
"code": null,
"e": 27413,
"s": 27370,
"text": "If we multiply and divide by , it becomes "
},
{
"code": null,
"e": 27574,
"s": 27418,
"text": "Which is nothing but, Therefore, But since n is so large we can not calculate it directly, we have to simplify the above expression.On Simplifying we get, "
},
{
"code": null,
"e": 27628,
"s": 27579,
"text": "Below is the implementation of the above idea: "
},
{
"code": null,
"e": 27632,
"s": 27628,
"text": "C++"
},
{
"code": null,
"e": 27637,
"s": 27632,
"text": "Java"
},
{
"code": null,
"e": 27645,
"s": 27637,
"text": "Python3"
},
{
"code": null,
"e": 27648,
"s": 27645,
"text": "C#"
},
{
"code": null,
"e": 27652,
"s": 27648,
"text": "PHP"
},
{
"code": null,
"e": 27663,
"s": 27652,
"text": "Javascript"
},
{
"code": "// CPP program to find the sum of the// given sequence #include <bits/stdc++.h>using namespace std; const long long MOD = 1000000007; // function to find modulo inverse// under 10^9+7long long modInv(long long x){ long long n = MOD - 2; long long result = 1; while (n) { if (n & 1) result = result * x % MOD; x = x * x % MOD; n = n / 2; } return result;} // Function to find the sum of the// given sequencelong long getSum(long long n, long long k){ long long ans = 1; for (long long i = n + 1; i > n - k; i--) ans = ans * i % MOD; ans = ans * modInv(k + 1) % MOD; return ans;} // Driver codeint main(){ long long n = 3, k = 2; cout<<getSum(n,k); return 0;}",
"e": 28421,
"s": 27663,
"text": null
},
{
"code": "// Java program to find the sum of the// given sequence class GFG { static long MOD = 1000000007; // function to find modulo inverse// under 10^9+7 static long modInv(long x) { long n = MOD - 2; long result = 1; while (n > 0) { if ((n & 1) > 0) { result = result * x % MOD; } x = x * x % MOD; n = n / 2; } return result; } // Function to find the sum of the// given sequence static long getSum(long n, long k) { long ans = 1; for (long i = n + 1; i > n - k; i--) { ans = ans * i % MOD; } ans = ans * modInv(k + 1) % MOD; return ans; } // Driver code public static void main(String[] args) { long n = 3, k = 2; System.out.println(getSum(n, k)); }}",
"e": 29247,
"s": 28421,
"text": null
},
{
"code": "# Python3 program to find the sum# of the given sequence MOD = 1000000007; # function to find modulo inverse# under 10^9+7def modInv(x): n = MOD - 2; result = 1; while (n): if (n&1): result = result * x % MOD; x = x * x % MOD; n = int(n / 2); return result; # Function to find the sum of# the given sequencedef getSum(n, k): ans = 1; for i in range(n + 1, n - k, -1): ans = ans * i % MOD; ans = ans * modInv(k + 1) % MOD; return ans; # Driver coden = 3;k = 2; print(getSum(n,k)); # This code is contributed by mits",
"e": 29850,
"s": 29247,
"text": null
},
{
"code": "// C# program to find the sum of the// given sequenceusing System; // function to find modulo inverse// under 10^9+7class gfg{ public long MOD = 1000000007; public long modInv(long x) { long n = MOD - 2; long result = 1; while (n >0) { if ((n & 1) > 0) result = result * x % MOD; x = x * x % MOD; n = n / 2; } return result;} // Function to find the sum of the// given sequence public long getSum(long n, long k) { long ans = 1; for (long i = n + 1; i > n - k; i--) ans = ans * i % MOD; ans = ans * modInv(k + 1) % MOD; return ans; }} // Driver codeclass geek{ public static int Main() { gfg g = new gfg(); long n = 3, k = 2; Console.WriteLine(g.getSum(n,k)); return 0; }}//This code is contributed by SoumikMondal",
"e": 30678,
"s": 29850,
"text": null
},
{
"code": "<?php// PHP program to find the sum of// the given sequence // function to find modulo inverse// under 10^9+7function modInv($x){ $MOD = 1000000007; $n = $MOD - 2; $result = 1; while ($n) { if ($n & 1) $result = $result * $x % $MOD; $x = $x * $x % $MOD; $n = $n / 2; } return $result;} // Function to find the sum of the// given sequencefunction getSum($n, $k){ $MOD = 1000000007; $ans = 1; for ($i = $n + 1; $i > $n - $k; $i--) $ans = $ans * $i % $MOD; $ans = $ans * modInv($k + 1) % $MOD; return $ans;} // Driver code$n = 3; $k = 2; echo getSum($n, $k); // This code is contributed// by Akanksha Rai?>",
"e": 31376,
"s": 30678,
"text": null
},
{
"code": "<script> // Javascript program to find the sum of the// given sequence var MOD = 100000007; // function to find modulo inverse// under 10^9+7function modInv(x){ var n = MOD - 2; var result = 1; while (n) { if (n & 1) result = result * x % MOD; x = x * x % MOD; n = n / 2; } return result;} // Function to find the sum of the// given sequencefunction getSum(n, k){ var ans = 1; for (var i = n + 1; i > n - k; i--) ans = ans * i % MOD; ans = ans * modInv(k + 1) % MOD; return ans;} // Driver codevar n = 3, k = 2; document.write( getSum(n,k)); // This code is contributed by noob2000.</script>",
"e": 32049,
"s": 31376,
"text": null
},
{
"code": null,
"e": 32051,
"s": 32049,
"text": "8"
},
{
"code": null,
"e": 32066,
"s": 32053,
"text": "SoumikMondal"
},
{
"code": null,
"e": 32078,
"s": 32066,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32091,
"s": 32078,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 32104,
"s": 32091,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 32113,
"s": 32104,
"text": "noob2000"
},
{
"code": null,
"e": 32128,
"s": 32113,
"text": "varshagumber28"
},
{
"code": null,
"e": 32133,
"s": 32128,
"text": "math"
},
{
"code": null,
"e": 32152,
"s": 32133,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 32159,
"s": 32152,
"text": "series"
},
{
"code": null,
"e": 32172,
"s": 32159,
"text": "C++ Programs"
},
{
"code": null,
"e": 32185,
"s": 32172,
"text": "Mathematical"
},
{
"code": null,
"e": 32198,
"s": 32185,
"text": "Mathematical"
},
{
"code": null,
"e": 32205,
"s": 32198,
"text": "series"
},
{
"code": null,
"e": 32224,
"s": 32205,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 32322,
"s": 32224,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32348,
"s": 32322,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 32382,
"s": 32348,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 32404,
"s": 32382,
"text": "delete keyword in C++"
},
{
"code": null,
"e": 32445,
"s": 32404,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 32456,
"s": 32445,
"text": "cin in C++"
},
{
"code": null,
"e": 32486,
"s": 32456,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32501,
"s": 32486,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32561,
"s": 32501,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32604,
"s": 32561,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
How to create a combined child selector in SASS ? | 15 Oct, 2020
Introduction: Lets first talk about the various types of Combinators available in CSS.
Combinator: A combinator is something that explains the relationship between the selectors. A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.
There are four different combinators in CSS:
Descendant selector (space)
Child selector (>)
Adjacent sibling selector (+)
General sibling selector (~)
Descendant Selector: The descendant selector matches all elements that are descendants of a specified element.The following example selects all <p> elements inside <div> elements:div p {
background-color: red;
}
Child Selector: The child selector selects all elements that are the children of a specified element.The following example selects all <p> elements that are children of a <div> element:div > p {
background-color: red;
}
Adjacent Sibling Selector: The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element. Sibling elements must have the same parent element, and “adjacent” means “immediately following”.The following example selects all <p> elements that are placed immediately after <div> elements:div + p {
background-color: red;
}
General Sibling Selector: The general sibling selector selects all elements that are siblings of a specified element.The following example selects all <p> elements that are siblings of <div> elements:div ~ p {
background-color: red;
}
Descendant Selector: The descendant selector matches all elements that are descendants of a specified element.The following example selects all <p> elements inside <div> elements:div p {
background-color: red;
}
The following example selects all <p> elements inside <div> elements:
div p {
background-color: red;
}
Child Selector: The child selector selects all elements that are the children of a specified element.The following example selects all <p> elements that are children of a <div> element:div > p {
background-color: red;
}
The following example selects all <p> elements that are children of a <div> element:
div > p {
background-color: red;
}
Adjacent Sibling Selector: The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element. Sibling elements must have the same parent element, and “adjacent” means “immediately following”.The following example selects all <p> elements that are placed immediately after <div> elements:div + p {
background-color: red;
}
The following example selects all <p> elements that are placed immediately after <div> elements:
div + p {
background-color: red;
}
General Sibling Selector: The general sibling selector selects all elements that are siblings of a specified element.The following example selects all <p> elements that are siblings of <div> elements:div ~ p {
background-color: red;
}
The following example selects all <p> elements that are siblings of <div> elements:
div ~ p {
background-color: red;
}
Now let’s talk about creating a combined child selector in SASS.
There are several ways to create a combined child selector in SASS.
See the examples given below.
Without the combined child selector you would probably do something like this:
card { outer { inner { color: red; } }}
If you want to produce the same syntax with >, you can do this:
card {
> outer {
> inner {
color: red;
}
}
}
Output:
The above code compiles to the given code in CSS:
card > outer > inner {
color: red;
}
Or in SASS, it compiles to:
card
> outer
> inner
color: red
CSS-Misc
SASS
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 115,
"s": 28,
"text": "Introduction: Lets first talk about the various types of Combinators available in CSS."
},
{
"code": null,
"e": 324,
"s": 115,
"text": "Combinator: A combinator is something that explains the relationship between the selectors. A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator."
},
{
"code": null,
"e": 369,
"s": 324,
"text": "There are four different combinators in CSS:"
},
{
"code": null,
"e": 397,
"s": 369,
"text": "Descendant selector (space)"
},
{
"code": null,
"e": 416,
"s": 397,
"text": "Child selector (>)"
},
{
"code": null,
"e": 446,
"s": 416,
"text": "Adjacent sibling selector (+)"
},
{
"code": null,
"e": 475,
"s": 446,
"text": "General sibling selector (~)"
},
{
"code": null,
"e": 1508,
"s": 475,
"text": "Descendant Selector: The descendant selector matches all elements that are descendants of a specified element.The following example selects all <p> elements inside <div> elements:div p {\n background-color: red;\n}\nChild Selector: The child selector selects all elements that are the children of a specified element.The following example selects all <p> elements that are children of a <div> element:div > p {\n background-color: red;\n}\nAdjacent Sibling Selector: The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element. Sibling elements must have the same parent element, and “adjacent” means “immediately following”.The following example selects all <p> elements that are placed immediately after <div> elements:div + p {\n background-color: red;\n}\nGeneral Sibling Selector: The general sibling selector selects all elements that are siblings of a specified element.The following example selects all <p> elements that are siblings of <div> elements:div ~ p {\n background-color: red;\n}\n"
},
{
"code": null,
"e": 1722,
"s": 1508,
"text": "Descendant Selector: The descendant selector matches all elements that are descendants of a specified element.The following example selects all <p> elements inside <div> elements:div p {\n background-color: red;\n}\n"
},
{
"code": null,
"e": 1792,
"s": 1722,
"text": "The following example selects all <p> elements inside <div> elements:"
},
{
"code": null,
"e": 1827,
"s": 1792,
"text": "div p {\n background-color: red;\n}\n"
},
{
"code": null,
"e": 2049,
"s": 1827,
"text": "Child Selector: The child selector selects all elements that are the children of a specified element.The following example selects all <p> elements that are children of a <div> element:div > p {\n background-color: red;\n}\n"
},
{
"code": null,
"e": 2134,
"s": 2049,
"text": "The following example selects all <p> elements that are children of a <div> element:"
},
{
"code": null,
"e": 2171,
"s": 2134,
"text": "div > p {\n background-color: red;\n}\n"
},
{
"code": null,
"e": 2534,
"s": 2171,
"text": "Adjacent Sibling Selector: The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element. Sibling elements must have the same parent element, and “adjacent” means “immediately following”.The following example selects all <p> elements that are placed immediately after <div> elements:div + p {\n background-color: red;\n}\n"
},
{
"code": null,
"e": 2631,
"s": 2534,
"text": "The following example selects all <p> elements that are placed immediately after <div> elements:"
},
{
"code": null,
"e": 2668,
"s": 2631,
"text": "div + p {\n background-color: red;\n}\n"
},
{
"code": null,
"e": 2905,
"s": 2668,
"text": "General Sibling Selector: The general sibling selector selects all elements that are siblings of a specified element.The following example selects all <p> elements that are siblings of <div> elements:div ~ p {\n background-color: red;\n}\n"
},
{
"code": null,
"e": 2989,
"s": 2905,
"text": "The following example selects all <p> elements that are siblings of <div> elements:"
},
{
"code": null,
"e": 3026,
"s": 2989,
"text": "div ~ p {\n background-color: red;\n}\n"
},
{
"code": null,
"e": 3091,
"s": 3026,
"text": "Now let’s talk about creating a combined child selector in SASS."
},
{
"code": null,
"e": 3159,
"s": 3091,
"text": "There are several ways to create a combined child selector in SASS."
},
{
"code": null,
"e": 3189,
"s": 3159,
"text": "See the examples given below."
},
{
"code": null,
"e": 3268,
"s": 3189,
"text": "Without the combined child selector you would probably do something like this:"
},
{
"code": "card { outer { inner { color: red; } }}",
"e": 3316,
"s": 3268,
"text": null
},
{
"code": null,
"e": 3380,
"s": 3316,
"text": "If you want to produce the same syntax with >, you can do this:"
},
{
"code": null,
"e": 3439,
"s": 3380,
"text": "card {\n > outer {\n > inner {\n color: red;\n }\n }\n}\n"
},
{
"code": null,
"e": 3447,
"s": 3439,
"text": "Output:"
},
{
"code": null,
"e": 3497,
"s": 3447,
"text": "The above code compiles to the given code in CSS:"
},
{
"code": null,
"e": 3536,
"s": 3497,
"text": "card > outer > inner {\n color: red;\n}\n"
},
{
"code": null,
"e": 3564,
"s": 3536,
"text": "Or in SASS, it compiles to:"
},
{
"code": null,
"e": 3606,
"s": 3564,
"text": "card\n > outer\n > inner\n color: red\n"
},
{
"code": null,
"e": 3615,
"s": 3606,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3620,
"s": 3615,
"text": "SASS"
},
{
"code": null,
"e": 3624,
"s": 3620,
"text": "CSS"
},
{
"code": null,
"e": 3641,
"s": 3624,
"text": "Web Technologies"
},
{
"code": null,
"e": 3739,
"s": 3641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3776,
"s": 3739,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3815,
"s": 3776,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3854,
"s": 3815,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 3918,
"s": 3854,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 3979,
"s": 3918,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 4012,
"s": 3979,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4073,
"s": 4012,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4116,
"s": 4073,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 4156,
"s": 4116,
"text": "Remove elements from a JavaScript Array"
}
]
|
Java For loop with Examples | 06 Jun, 2022
Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
Syntax:
for (initialization expr; test expr; update exp)
{
// body of the loop
// statements we want to execute
}
The various parts of the For loop are:
1. Initialization Expression: In this expression, we have to initialize the loop counter to some value.
Example:
int i=1;
2. Test Expression: In this expression, we have to test the condition. If the condition evaluates to true then, we will execute the body of the loop and go to update expression. Otherwise, we will exit from the for loop.
Example:
i <= 10
3. Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value.
Example:
i++;
How does a For loop execute?
Control falls into the for loop. Initialization is doneThe flow jumps to ConditionCondition is tested. If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loopThe statements inside the body of the loop get executed.The flow goes to the UpdationUpdation takes place and the flow goes to Step 3 againThe for loop has ended and the flow has gone outside.
Control falls into the for loop. Initialization is done
The flow jumps to Condition
Condition is tested. If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loop
If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loop
If Condition yields true, the flow goes into the Body
If Condition yields false, the flow goes outside the loop
The statements inside the body of the loop get executed.
The flow goes to the Updation
Updation takes place and the flow goes to Step 3 again
The for loop has ended and the flow has gone outside.
Flow chart for loop (For Control Flow):
Example 1:This program will print 1 to 10
Java
/*package whatever //do not write package name here */// Java program to write a code in for loop from 1 to 10 class GFG { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { System.out.println(i); } }}
1
2
3
4
5
6
7
8
9
10
Example 2: This program will try to print “Hello World” 5 times.
Java
// Java program to illustrate for loopclass forLoopDemo { public static void main(String args[]) { // Writing a for loop // to print Hello World 5 times for (int i = 1; i <= 5; i++) System.out.println("Hello World"); }}
Hello World
Hello World
Hello World
Hello World
Hello World
Time Complexity: O(1), Auxiliary Space : O(1)
Dry-Running Example 1: The program will execute in the following manner.
1. Program starts.
2. i is initialized with value 1.
3. Condition is checked. 1 <= 5 yields true.
3.a) "Hello World" gets printed 1st time.
3.b) Updation is done. Now i = 2.
4. Condition is checked. 2 <= 5 yields true.
4.a) "Hello World" gets printed 2nd time.
4.b) Updation is done. Now i = 3.
5. Condition is checked. 3 <= 5 yields true.
5.a) "Hello World" gets printed 3rd time
5.b) Updation is done. Now i = 4.
6. Condition is checked. 4 <= 5 yields true.
6.a) "Hello World" gets printed 4th time
6.b) Updation is done. Now i = 5.
7. Condition is checked. 5 <= 5 yields true.
7.a) "Hello World" gets printed 5th time
7.b) Updation is done. Now i = 6.
8. Condition is checked. 6 <= 5 yields false.
9. Flow goes outside the loop. Program terminates.
Example 3: The following program prints the sum of x ranging from 1 to 20.
Java
// Java program to illustrate for loop.class forLoopDemo { public static void main(String args[]) { int sum = 0; // for loop begins // and runs till x <= 20 for (int x = 1; x <= 20; x++) { sum = sum + x; } System.out.println("Sum: " + sum); }}
Sum: 210
Enhanced For Loop or Java For-Each loop
Java also includes another version of for loop introduced in Java 5. Enhanced for loop provides a simpler way to iterate through the elements of a collection or array. It is inflexible and should be used only when there is a need to iterate through the elements in a sequential manner without knowing the index of the currently processed element.
Note: The object/variable is immutable when enhanced for loop is used i.e it ensures that the values in the array can not be modified, so it can be said as a read-only loop where you can’t update the values as opposed to other loops where values can be modified.
Syntax:
for (T element:Collection obj/array)
{
// loop body
// statement(s)
}
Let’s take an example to demonstrate how enhanced for loop can be used to simplify the work. Suppose there is an array of names and we want to print all the names in that array. Let’s see the difference between these two examples by this simple implementation:
Java
// Java program to illustrate enhanced for loop public class enhancedforloop { public static void main(String args[]) { String array[] = { "Ron", "Harry", "Hermoine" }; // enhanced for loop for (String x : array) { System.out.println(x); } /* for loop for same function for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } */ }}
Ron
Harry
Hermoine
Time Complexity: O(1), Auxiliary Space : O(1)
Recommendation: Use this form of statement instead of the general form whenever possible. (as per JAVA doc.)
JAVA Infinite for loop:
This is an infinite loop as the condition would never return false. The initialization step is setting up the value of variable i to 1, since we are incrementing the value of i, it would always be greater than 1 so it would never return false. This would eventually lead to the infinite loop condition.
Example:
Java
// Java infinite loopclass GFG { public static void main(String args[]) { for (int i = 1; i >= 1; i++) { System.out.println("Infinite Loop " + i); } }}
There is another method for calling the Infinite for loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax:
for(;;){
//code to be executed
}
Example:
Java
public class GFG { public static void main(String[] args) { for (;;) { System.out.println("infinitive loop"); } }}
https://youtu.be/JkSQ8KtOA14
tttLoops in JavaFor Loop in Java | Important pointsUnderstanding for loops in JavaJava while loop with ExamplesJava do-while loop with ExamplesFor-each loop in JavaDifference between for and while loop in C, C++, JavaDifference between for and do-while loop in C, C++, Java
tttLoops in Java
For Loop in Java | Important points
Understanding for loops in Java
Java while loop with Examples
Java do-while loop with Examples
For-each loop in Java
Difference between for and while loop in C, C++, Java
Difference between for and do-while loop in C, C++, Java
maheshkakde100
rishavnitro
mdfaiz589
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 364,
"s": 52,
"text": "Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping."
},
{
"code": null,
"e": 374,
"s": 364,
"text": "Syntax: "
},
{
"code": null,
"e": 490,
"s": 374,
"text": "for (initialization expr; test expr; update exp)\n{\n // body of the loop\n // statements we want to execute\n}"
},
{
"code": null,
"e": 530,
"s": 490,
"text": "The various parts of the For loop are: "
},
{
"code": null,
"e": 635,
"s": 530,
"text": "1. Initialization Expression: In this expression, we have to initialize the loop counter to some value. "
},
{
"code": null,
"e": 646,
"s": 635,
"text": "Example: "
},
{
"code": null,
"e": 655,
"s": 646,
"text": "int i=1;"
},
{
"code": null,
"e": 876,
"s": 655,
"text": "2. Test Expression: In this expression, we have to test the condition. If the condition evaluates to true then, we will execute the body of the loop and go to update expression. Otherwise, we will exit from the for loop."
},
{
"code": null,
"e": 887,
"s": 876,
"text": "Example: "
},
{
"code": null,
"e": 895,
"s": 887,
"text": "i <= 10"
},
{
"code": null,
"e": 1020,
"s": 895,
"text": "3. Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value. "
},
{
"code": null,
"e": 1031,
"s": 1020,
"text": "Example: "
},
{
"code": null,
"e": 1036,
"s": 1031,
"text": "i++;"
},
{
"code": null,
"e": 1067,
"s": 1036,
"text": "How does a For loop execute? "
},
{
"code": null,
"e": 1473,
"s": 1067,
"text": "Control falls into the for loop. Initialization is doneThe flow jumps to ConditionCondition is tested. If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loopThe statements inside the body of the loop get executed.The flow goes to the UpdationUpdation takes place and the flow goes to Step 3 againThe for loop has ended and the flow has gone outside."
},
{
"code": null,
"e": 1529,
"s": 1473,
"text": "Control falls into the for loop. Initialization is done"
},
{
"code": null,
"e": 1557,
"s": 1529,
"text": "The flow jumps to Condition"
},
{
"code": null,
"e": 1689,
"s": 1557,
"text": "Condition is tested. If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loop"
},
{
"code": null,
"e": 1800,
"s": 1689,
"text": "If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loop"
},
{
"code": null,
"e": 1854,
"s": 1800,
"text": "If Condition yields true, the flow goes into the Body"
},
{
"code": null,
"e": 1912,
"s": 1854,
"text": "If Condition yields false, the flow goes outside the loop"
},
{
"code": null,
"e": 1969,
"s": 1912,
"text": "The statements inside the body of the loop get executed."
},
{
"code": null,
"e": 1999,
"s": 1969,
"text": "The flow goes to the Updation"
},
{
"code": null,
"e": 2054,
"s": 1999,
"text": "Updation takes place and the flow goes to Step 3 again"
},
{
"code": null,
"e": 2108,
"s": 2054,
"text": "The for loop has ended and the flow has gone outside."
},
{
"code": null,
"e": 2150,
"s": 2108,
"text": "Flow chart for loop (For Control Flow): "
},
{
"code": null,
"e": 2192,
"s": 2150,
"text": "Example 1:This program will print 1 to 10"
},
{
"code": null,
"e": 2197,
"s": 2192,
"text": "Java"
},
{
"code": "/*package whatever //do not write package name here */// Java program to write a code in for loop from 1 to 10 class GFG { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { System.out.println(i); } }}",
"e": 2455,
"s": 2197,
"text": null
},
{
"code": null,
"e": 2476,
"s": 2455,
"text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"
},
{
"code": null,
"e": 2543,
"s": 2476,
"text": "Example 2: This program will try to print “Hello World” 5 times. "
},
{
"code": null,
"e": 2548,
"s": 2543,
"text": "Java"
},
{
"code": "// Java program to illustrate for loopclass forLoopDemo { public static void main(String args[]) { // Writing a for loop // to print Hello World 5 times for (int i = 1; i <= 5; i++) System.out.println(\"Hello World\"); }}",
"e": 2809,
"s": 2548,
"text": null
},
{
"code": null,
"e": 2869,
"s": 2809,
"text": "Hello World\nHello World\nHello World\nHello World\nHello World"
},
{
"code": null,
"e": 2915,
"s": 2869,
"text": "Time Complexity: O(1), Auxiliary Space : O(1)"
},
{
"code": null,
"e": 2989,
"s": 2915,
"text": "Dry-Running Example 1: The program will execute in the following manner. "
},
{
"code": null,
"e": 3761,
"s": 2989,
"text": "1. Program starts.\n2. i is initialized with value 1.\n3. Condition is checked. 1 <= 5 yields true.\n 3.a) \"Hello World\" gets printed 1st time.\n 3.b) Updation is done. Now i = 2.\n4. Condition is checked. 2 <= 5 yields true.\n 4.a) \"Hello World\" gets printed 2nd time.\n 4.b) Updation is done. Now i = 3.\n5. Condition is checked. 3 <= 5 yields true.\n 5.a) \"Hello World\" gets printed 3rd time\n 5.b) Updation is done. Now i = 4.\n6. Condition is checked. 4 <= 5 yields true.\n 6.a) \"Hello World\" gets printed 4th time\n 6.b) Updation is done. Now i = 5.\n7. Condition is checked. 5 <= 5 yields true.\n 7.a) \"Hello World\" gets printed 5th time\n 7.b) Updation is done. Now i = 6.\n8. Condition is checked. 6 <= 5 yields false.\n9. Flow goes outside the loop. Program terminates."
},
{
"code": null,
"e": 3838,
"s": 3761,
"text": "Example 3: The following program prints the sum of x ranging from 1 to 20. "
},
{
"code": null,
"e": 3843,
"s": 3838,
"text": "Java"
},
{
"code": "// Java program to illustrate for loop.class forLoopDemo { public static void main(String args[]) { int sum = 0; // for loop begins // and runs till x <= 20 for (int x = 1; x <= 20; x++) { sum = sum + x; } System.out.println(\"Sum: \" + sum); }}",
"e": 4150,
"s": 3843,
"text": null
},
{
"code": null,
"e": 4159,
"s": 4150,
"text": "Sum: 210"
},
{
"code": null,
"e": 4199,
"s": 4159,
"text": "Enhanced For Loop or Java For-Each loop"
},
{
"code": null,
"e": 4546,
"s": 4199,
"text": "Java also includes another version of for loop introduced in Java 5. Enhanced for loop provides a simpler way to iterate through the elements of a collection or array. It is inflexible and should be used only when there is a need to iterate through the elements in a sequential manner without knowing the index of the currently processed element."
},
{
"code": null,
"e": 4810,
"s": 4546,
"text": "Note: The object/variable is immutable when enhanced for loop is used i.e it ensures that the values in the array can not be modified, so it can be said as a read-only loop where you can’t update the values as opposed to other loops where values can be modified. "
},
{
"code": null,
"e": 4819,
"s": 4810,
"text": "Syntax: "
},
{
"code": null,
"e": 4897,
"s": 4819,
"text": "for (T element:Collection obj/array)\n{\n // loop body\n // statement(s)\n}"
},
{
"code": null,
"e": 5159,
"s": 4897,
"text": "Let’s take an example to demonstrate how enhanced for loop can be used to simplify the work. Suppose there is an array of names and we want to print all the names in that array. Let’s see the difference between these two examples by this simple implementation: "
},
{
"code": null,
"e": 5164,
"s": 5159,
"text": "Java"
},
{
"code": "// Java program to illustrate enhanced for loop public class enhancedforloop { public static void main(String args[]) { String array[] = { \"Ron\", \"Harry\", \"Hermoine\" }; // enhanced for loop for (String x : array) { System.out.println(x); } /* for loop for same function for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } */ }}",
"e": 5610,
"s": 5164,
"text": null
},
{
"code": null,
"e": 5629,
"s": 5610,
"text": "Ron\nHarry\nHermoine"
},
{
"code": null,
"e": 5675,
"s": 5629,
"text": "Time Complexity: O(1), Auxiliary Space : O(1)"
},
{
"code": null,
"e": 5785,
"s": 5675,
"text": "Recommendation: Use this form of statement instead of the general form whenever possible. (as per JAVA doc.) "
},
{
"code": null,
"e": 5809,
"s": 5785,
"text": "JAVA Infinite for loop:"
},
{
"code": null,
"e": 6112,
"s": 5809,
"text": "This is an infinite loop as the condition would never return false. The initialization step is setting up the value of variable i to 1, since we are incrementing the value of i, it would always be greater than 1 so it would never return false. This would eventually lead to the infinite loop condition."
},
{
"code": null,
"e": 6122,
"s": 6112,
"text": "Example: "
},
{
"code": null,
"e": 6127,
"s": 6122,
"text": "Java"
},
{
"code": "// Java infinite loopclass GFG { public static void main(String args[]) { for (int i = 1; i >= 1; i++) { System.out.println(\"Infinite Loop \" + i); } }}",
"e": 6313,
"s": 6127,
"text": null
},
{
"code": null,
"e": 6371,
"s": 6313,
"text": "There is another method for calling the Infinite for loop"
},
{
"code": null,
"e": 6449,
"s": 6371,
"text": "If you use two semicolons ;; in the for loop, it will be infinitive for loop."
},
{
"code": null,
"e": 6458,
"s": 6449,
"text": "Syntax: "
},
{
"code": null,
"e": 6497,
"s": 6458,
"text": "for(;;){ \n//code to be executed \n} "
},
{
"code": null,
"e": 6506,
"s": 6497,
"text": "Example:"
},
{
"code": null,
"e": 6511,
"s": 6506,
"text": "Java"
},
{
"code": "public class GFG { public static void main(String[] args) { for (;;) { System.out.println(\"infinitive loop\"); } }}",
"e": 6661,
"s": 6511,
"text": null
},
{
"code": null,
"e": 6690,
"s": 6661,
"text": "https://youtu.be/JkSQ8KtOA14"
},
{
"code": null,
"e": 6964,
"s": 6690,
"text": "tttLoops in JavaFor Loop in Java | Important pointsUnderstanding for loops in JavaJava while loop with ExamplesJava do-while loop with ExamplesFor-each loop in JavaDifference between for and while loop in C, C++, JavaDifference between for and do-while loop in C, C++, Java"
},
{
"code": null,
"e": 6981,
"s": 6964,
"text": "tttLoops in Java"
},
{
"code": null,
"e": 7017,
"s": 6981,
"text": "For Loop in Java | Important points"
},
{
"code": null,
"e": 7049,
"s": 7017,
"text": "Understanding for loops in Java"
},
{
"code": null,
"e": 7079,
"s": 7049,
"text": "Java while loop with Examples"
},
{
"code": null,
"e": 7112,
"s": 7079,
"text": "Java do-while loop with Examples"
},
{
"code": null,
"e": 7134,
"s": 7112,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 7188,
"s": 7134,
"text": "Difference between for and while loop in C, C++, Java"
},
{
"code": null,
"e": 7245,
"s": 7188,
"text": "Difference between for and do-while loop in C, C++, Java"
},
{
"code": null,
"e": 7260,
"s": 7245,
"text": "maheshkakde100"
},
{
"code": null,
"e": 7272,
"s": 7260,
"text": "rishavnitro"
},
{
"code": null,
"e": 7282,
"s": 7272,
"text": "mdfaiz589"
},
{
"code": null,
"e": 7287,
"s": 7282,
"text": "Java"
},
{
"code": null,
"e": 7306,
"s": 7287,
"text": "School Programming"
},
{
"code": null,
"e": 7311,
"s": 7306,
"text": "Java"
}
]
|
Operator overloading in C++ to print contents of vector, map, pair, .. | 03 Sep, 2018
Operator overloading is one of the features of Object oriented programming which gives an extra ability to an operator to act on a User-defined operand(Objects).We can take advantage of that feature while debugging the code specially in competitive programming. All we need to do is to overload the stream insertion operator(See this article to understand more) “<<" for printing the class of vector, map, set, pair etc. For instance,
Vector
// C++ program to print vector objects// by overloading "<<" operator#include <iostream>#include <vector>using namespace std; // C++ template to print vector container elementstemplate <typename T>ostream& operator<<(ostream& os, const vector<T>& v){ os << "["; for (int i = 0; i < v.size(); ++i) { os << v[i]; if (i != v.size() - 1) os << ", "; } os << "]\n"; return os;} // Driver codeint main(){ vector<int> vec{ 4, 2, 17, 11, 15 }; // Printing the elements directly cout << vec; return 0;}
Output
[4, 2, 17, 11, 15]
Set
// C++ program to print set elements// by overloading "<<" operator#include <iostream>#include <set>using namespace std; // C++ template to print set container elementstemplate <typename T>ostream& operator<<(ostream& os, const set<T>& v){ os << "["; for (auto it : v) { os << it; if (it != *v.rbegin()) os << ", "; } os << "]\n"; return os;} // Driver codeint main(){ set<int> st{ 4, 2, 17, 11, 15 }; cout << st; return 0;}
Output
[2, 4, 11, 15, 17]
Map
// C++ program to print map elements// by overloading "<<" operator#include <iostream>#include <map>using namespace std; // C++ template to print map container elementstemplate <typename T, typename S>ostream& operator<<(ostream& os, const map<T, S>& v){ for (auto it : v) os << it.first << " : " << it.second << "\n"; return os;} // Driver codeint main(){ map<char, int> mp; mp['b'] = 3; mp['d'] = 5; mp['a'] = 2; cout << mp;}
Output
a : 2
b : 3
d : 5
Pair
// C++ program to print pair<> class// by overloading "<<" operator#include <iostream>using namespace std; // C++ template to print pair<>// class by using templatetemplate <typename T, typename S>ostream& operator<<(ostream& os, const pair<T, S>& v){ os << "("; os << v.first << ", " << v.second << ")"; return os;} // Driver codeint main(){ pair<int, int> pi{ 45, 7 }; cout << pi; return 0;}
Output
(45, 7)
As we can see from above, printing or debugging would become easier as we don’t need to write down the extra for loop or print statement. All we need to write the specific container name after the insertion operator “<<" of cout.Exercise: Now let’s design your own template with operator overloading for other container class according to your requirement.
This article is contributed by Shubham Bansal. 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.
cpp-operator-overloading
cpp-overloading
cpp-pair
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Sep, 2018"
},
{
"code": null,
"e": 487,
"s": 52,
"text": "Operator overloading is one of the features of Object oriented programming which gives an extra ability to an operator to act on a User-defined operand(Objects).We can take advantage of that feature while debugging the code specially in competitive programming. All we need to do is to overload the stream insertion operator(See this article to understand more) “<<\" for printing the class of vector, map, set, pair etc. For instance,"
},
{
"code": null,
"e": 494,
"s": 487,
"text": "Vector"
},
{
"code": "// C++ program to print vector objects// by overloading \"<<\" operator#include <iostream>#include <vector>using namespace std; // C++ template to print vector container elementstemplate <typename T>ostream& operator<<(ostream& os, const vector<T>& v){ os << \"[\"; for (int i = 0; i < v.size(); ++i) { os << v[i]; if (i != v.size() - 1) os << \", \"; } os << \"]\\n\"; return os;} // Driver codeint main(){ vector<int> vec{ 4, 2, 17, 11, 15 }; // Printing the elements directly cout << vec; return 0;}",
"e": 1049,
"s": 494,
"text": null
},
{
"code": null,
"e": 1076,
"s": 1049,
"text": "Output\n[4, 2, 17, 11, 15]\n"
},
{
"code": null,
"e": 1080,
"s": 1076,
"text": "Set"
},
{
"code": "// C++ program to print set elements// by overloading \"<<\" operator#include <iostream>#include <set>using namespace std; // C++ template to print set container elementstemplate <typename T>ostream& operator<<(ostream& os, const set<T>& v){ os << \"[\"; for (auto it : v) { os << it; if (it != *v.rbegin()) os << \", \"; } os << \"]\\n\"; return os;} // Driver codeint main(){ set<int> st{ 4, 2, 17, 11, 15 }; cout << st; return 0;}",
"e": 1556,
"s": 1080,
"text": null
},
{
"code": null,
"e": 1583,
"s": 1556,
"text": "Output\n[2, 4, 11, 15, 17]\n"
},
{
"code": null,
"e": 1587,
"s": 1583,
"text": "Map"
},
{
"code": "// C++ program to print map elements// by overloading \"<<\" operator#include <iostream>#include <map>using namespace std; // C++ template to print map container elementstemplate <typename T, typename S>ostream& operator<<(ostream& os, const map<T, S>& v){ for (auto it : v) os << it.first << \" : \" << it.second << \"\\n\"; return os;} // Driver codeint main(){ map<char, int> mp; mp['b'] = 3; mp['d'] = 5; mp['a'] = 2; cout << mp;}",
"e": 2065,
"s": 1587,
"text": null
},
{
"code": null,
"e": 2091,
"s": 2065,
"text": "Output\na : 2\nb : 3\nd : 5\n"
},
{
"code": null,
"e": 2096,
"s": 2091,
"text": "Pair"
},
{
"code": "// C++ program to print pair<> class// by overloading \"<<\" operator#include <iostream>using namespace std; // C++ template to print pair<>// class by using templatetemplate <typename T, typename S>ostream& operator<<(ostream& os, const pair<T, S>& v){ os << \"(\"; os << v.first << \", \" << v.second << \")\"; return os;} // Driver codeint main(){ pair<int, int> pi{ 45, 7 }; cout << pi; return 0;}",
"e": 2517,
"s": 2096,
"text": null
},
{
"code": null,
"e": 2533,
"s": 2517,
"text": "Output\n(45, 7)\n"
},
{
"code": null,
"e": 2890,
"s": 2533,
"text": "As we can see from above, printing or debugging would become easier as we don’t need to write down the extra for loop or print statement. All we need to write the specific container name after the insertion operator “<<\" of cout.Exercise: Now let’s design your own template with operator overloading for other container class according to your requirement."
},
{
"code": null,
"e": 3192,
"s": 2890,
"text": "This article is contributed by Shubham Bansal. 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": 3217,
"s": 3192,
"text": "cpp-operator-overloading"
},
{
"code": null,
"e": 3233,
"s": 3217,
"text": "cpp-overloading"
},
{
"code": null,
"e": 3242,
"s": 3233,
"text": "cpp-pair"
},
{
"code": null,
"e": 3246,
"s": 3242,
"text": "STL"
},
{
"code": null,
"e": 3250,
"s": 3246,
"text": "C++"
},
{
"code": null,
"e": 3254,
"s": 3250,
"text": "STL"
},
{
"code": null,
"e": 3258,
"s": 3254,
"text": "CPP"
}
]
|
Convert ArrayList to HashMap in Java | 28 Dec, 2020
Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap.
Basically, there are two different ways to convert ArrayList to Hashmap-
Using ArrayList IterationUsing ArrayList Iteration with LinkedHashMap
Using ArrayList Iteration
Using ArrayList Iteration with LinkedHashMap
Using ArrayList Iteration:
Here, we just need to iterate on each of the elements of the ArrayList and the element can be converted into the key-value pair and store in the HashMap.
Java
// Java program to convert ArrayList// to HashMap import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.Map; public class ArrayListExample { public static void main(String[] args) { // ArrayList of string ArrayList<String> languageList = new ArrayList<>(Arrays.asList("Java", "C++", "Python", "PHP", "NodeJS")); System.out.println( "-------------ArrayList---------------"); // printing the ArrayList for (String language : languageList) { System.out.println(language); } System.out.println( "--------------HashMap----------------"); // convertArrayListToHashMap() method directly // converts ArrayList to Hashmap HashMap<String, Integer> languageMap = convertArrayListToHashMap(languageList); // printing the HashMap for (Map.Entry<String, Integer> entry : languageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } } private static HashMap<String, Integer> convertArrayListToHashMap(ArrayList<String> arrayList) { HashMap<String, Integer> hashMap = new HashMap<>(); for (String str : arrayList) { hashMap.put(str, str.length()); } return hashMap; }}
-------------ArrayList---------------
Java
C++
Python
PHP
NodeJS
--------------HashMap----------------
Java : 4
C++ : 3
PHP : 3
NodeJS : 6
Python : 6
Using ArrayList Iteration with LinkedHashMap :
Here, the Array List is converted into a HashMap but HashMap does not maintain the order of the ArrayList.
To maintain the order, we use LinkedHashMap which is an implementation of HashMap and helps us to maintain the order of the elements, and we can easily convert Arraylist to Hashmap.
Java
// Java program to convert ArrayList// to HashMap import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.*; public class ArrayListExample { public static void main(String[] args) { // ArrayList of string ArrayList<String> languageList = new ArrayList<>(Arrays.asList( "Java", "C++", "Python", "PHP", "NodeJS")); System.out.println( "-------------ArrayList---------------"); // printing the ArrayList for (String language : languageList) { System.out.println(language); } System.out.println( "--------------HashMap----------------"); // convertArrayListToHashMap() method directly // converts ArrayList to HashMap HashMap<String, Integer> languageMap = convertArrayListToHashMap(languageList); // printing the HashMap for (Map.Entry<String, Integer> entry : languageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } } private static HashMap<String, Integer> convertArrayListToHashMap(ArrayList<String> arrayList) { LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>(); for (String str : arrayList) { linkedHashMap.put(str, str.length()); } return linkedHashMap; }}
-------------ArrayList---------------
Java
C++
Python
PHP
NodeJS
--------------HashMap----------------
Java : 4
C++ : 3
Python : 6
PHP : 3
NodeJS : 6
Java-HashMap
Picked
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": "\n28 Dec, 2020"
},
{
"code": null,
"e": 216,
"s": 28,
"text": "Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap."
},
{
"code": null,
"e": 289,
"s": 216,
"text": "Basically, there are two different ways to convert ArrayList to Hashmap-"
},
{
"code": null,
"e": 359,
"s": 289,
"text": "Using ArrayList IterationUsing ArrayList Iteration with LinkedHashMap"
},
{
"code": null,
"e": 385,
"s": 359,
"text": "Using ArrayList Iteration"
},
{
"code": null,
"e": 430,
"s": 385,
"text": "Using ArrayList Iteration with LinkedHashMap"
},
{
"code": null,
"e": 457,
"s": 430,
"text": "Using ArrayList Iteration:"
},
{
"code": null,
"e": 612,
"s": 457,
"text": "Here, we just need to iterate on each of the elements of the ArrayList and the element can be converted into the key-value pair and store in the HashMap. "
},
{
"code": null,
"e": 617,
"s": 612,
"text": "Java"
},
{
"code": "// Java program to convert ArrayList// to HashMap import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.Map; public class ArrayListExample { public static void main(String[] args) { // ArrayList of string ArrayList<String> languageList = new ArrayList<>(Arrays.asList(\"Java\", \"C++\", \"Python\", \"PHP\", \"NodeJS\")); System.out.println( \"-------------ArrayList---------------\"); // printing the ArrayList for (String language : languageList) { System.out.println(language); } System.out.println( \"--------------HashMap----------------\"); // convertArrayListToHashMap() method directly // converts ArrayList to Hashmap HashMap<String, Integer> languageMap = convertArrayListToHashMap(languageList); // printing the HashMap for (Map.Entry<String, Integer> entry : languageMap.entrySet()) { System.out.println(entry.getKey() + \" : \" + entry.getValue()); } } private static HashMap<String, Integer> convertArrayListToHashMap(ArrayList<String> arrayList) { HashMap<String, Integer> hashMap = new HashMap<>(); for (String str : arrayList) { hashMap.put(str, str.length()); } return hashMap; }}",
"e": 2079,
"s": 617,
"text": null
},
{
"code": null,
"e": 2229,
"s": 2079,
"text": "-------------ArrayList---------------\nJava\nC++\nPython\nPHP\nNodeJS\n--------------HashMap----------------\nJava : 4\nC++ : 3\nPHP : 3\nNodeJS : 6\nPython : 6"
},
{
"code": null,
"e": 2276,
"s": 2229,
"text": "Using ArrayList Iteration with LinkedHashMap :"
},
{
"code": null,
"e": 2384,
"s": 2276,
"text": "Here, the Array List is converted into a HashMap but HashMap does not maintain the order of the ArrayList."
},
{
"code": null,
"e": 2566,
"s": 2384,
"text": "To maintain the order, we use LinkedHashMap which is an implementation of HashMap and helps us to maintain the order of the elements, and we can easily convert Arraylist to Hashmap."
},
{
"code": null,
"e": 2571,
"s": 2566,
"text": "Java"
},
{
"code": "// Java program to convert ArrayList// to HashMap import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.*; public class ArrayListExample { public static void main(String[] args) { // ArrayList of string ArrayList<String> languageList = new ArrayList<>(Arrays.asList( \"Java\", \"C++\", \"Python\", \"PHP\", \"NodeJS\")); System.out.println( \"-------------ArrayList---------------\"); // printing the ArrayList for (String language : languageList) { System.out.println(language); } System.out.println( \"--------------HashMap----------------\"); // convertArrayListToHashMap() method directly // converts ArrayList to HashMap HashMap<String, Integer> languageMap = convertArrayListToHashMap(languageList); // printing the HashMap for (Map.Entry<String, Integer> entry : languageMap.entrySet()) { System.out.println(entry.getKey() + \" : \" + entry.getValue()); } } private static HashMap<String, Integer> convertArrayListToHashMap(ArrayList<String> arrayList) { LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>(); for (String str : arrayList) { linkedHashMap.put(str, str.length()); } return linkedHashMap; }}",
"e": 4098,
"s": 2571,
"text": null
},
{
"code": null,
"e": 4248,
"s": 4098,
"text": "-------------ArrayList---------------\nJava\nC++\nPython\nPHP\nNodeJS\n--------------HashMap----------------\nJava : 4\nC++ : 3\nPython : 6\nPHP : 3\nNodeJS : 6"
},
{
"code": null,
"e": 4261,
"s": 4248,
"text": "Java-HashMap"
},
{
"code": null,
"e": 4268,
"s": 4261,
"text": "Picked"
},
{
"code": null,
"e": 4273,
"s": 4268,
"text": "Java"
},
{
"code": null,
"e": 4287,
"s": 4273,
"text": "Java Programs"
},
{
"code": null,
"e": 4292,
"s": 4287,
"text": "Java"
}
]
|
Move all zeroes to end of array | Set-2 (Using single traversal) | 23 Jun, 2022
Given an array of n numbers. The problem is to move all the 0’s to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.Examples:
Input : arr[] = {1, 2, 0, 0, 0, 3, 6}
Output : 1 2 3 6 0 0 0
Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}
Output: 1 9 8 4 2 7 6 9 0 0 0 0 0
Algorithm:
moveZerosToEnd(arr, n)
Initialize count = 0
for i = 0 to n-1
if (arr[i] != 0) then
arr[count++]=arr[i]
for i = count to n-1
arr[i] = 0
Flowchart
CPP
Java
Python3
C#
Javascript
// C++ implementation to move all zeroes at// the end of array#include <iostream>using namespace std; // function to move all zeroes at// the end of arrayvoid moveZerosToEnd(int arr[], int n){ // Count of non-zero elements int count = 0; // Traverse the array. If arr[i] is non-zero, then // update the value of arr at index count to arr[i] for (int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // Update all elements at index >=count with value 0 for (int i = count; i<n;i++) arr[i]=0;} // function to print the array elementsvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Driver program to test aboveint main(){ int arr[] = { 0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Original array: "; printArray(arr, n); moveZerosToEnd(arr, n); cout << "\nModified array: "; printArray(arr, n); return 0;} // This code is contributed by Ashutosh Singh
// Java implementation to move// all zeroes at the end of arrayimport java.io.*; class GFG { // function to move all zeroes at// the end of arraystatic void moveZerosToEnd(int arr[], int n) { // Count of non-zero elements int count = 0; // Traverse the array. If arr[i] is non-zero, then // update the value of arr at index count to arr[i] for (int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // Update all elements at index >=count with value 0 for (int i = count; i<n;i++) arr[i]=0;} // function to print the array elementsstatic void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");} // Driver program to test abovepublic static void main(String args[]) { int arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; int n = arr.length; System.out.print("Original array: "); printArray(arr, n); moveZerosToEnd(arr, n); System.out.print("\nModified array: "); printArray(arr, n);}} // This code is contributed by Ashutosh Singh
# Python implementation to move all zeroes at# the end of array # function to move all zeroes at# the end of arraydef moveZerosToEnd (arr, n): # Count of non-zero elements count = 0; # Traverse the array. If arr[i] is non-zero, then # update the value of arr at index count to arr[i] for i in range(0, n): if (arr[i] != 0): arr[count] = arr[i] count+=1 # Update all elements at index >=count with value 0 for i in range(count, n): arr[i] = 0 # function to print the array elementsdef printArray(arr, n): for i in range(0, n): print(arr[i],end=" ") # Driver program to test abovearr = [ 0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 ]n = len(arr) print("Original array:", end=" ")printArray(arr, n) moveZerosToEnd(arr, n) print("\nModified array: ", end=" ")printArray(arr, n) # This code is contributed by# Ashutosh Singh
// C# implementation to move// all zeroes at the end of arrayusing System; class GFG { // function to move all zeroes at // the end of array static void moveZerosToEnd(int[] arr, int n) { // Count of non-zero elements int count = 0; // Traverse the array. If arr[i] is non-zero, then // update the value of arr at index count to arr[i] for (int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // Update all elements at index >=count with value 0 for (int i = count; i<n;i++) arr[i]=0; } // function to print the array elements static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } // Driver program to test above public static void Main() { int[] arr = { 0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 }; int n = arr.Length; Console.Write("Original array: "); printArray(arr, n); moveZerosToEnd(arr, n); Console.Write("\nModified array: "); printArray(arr, n); }} // This code is contributed by Ashutosh Singh
<script>// JavaScript implementation to move all zeroes at// the end of array // function to move all zeroes at// the end of arrayfunction moveZerosToEnd(arr, n){ // Count of non-zero elements let count = 0; // Traverse the array. If arr[i] is non-zero, then // update the value of arr at index count to arr[i] for (let i = 0; i < n; i++) if (arr[i] != 0) { arr[count] = arr[i]; count = count + 1; } // Update all elements at index >= count with value 0 for (let i = count; i < n; i++) arr[i] = 0 } // function to print the array elementsfunction printArray(arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Driver program to test above let arr = [ 0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 ]; let n = arr.length; document.write("Original array: "); printArray(arr, n); moveZerosToEnd(arr, n); document.write("<br>" + "Modified array: "); printArray(arr, n); //This code is contributed by Ashutosh Singh</script>
Original array: 0 1 9 8 4 0 0 2 7 0 6 0 9
Modified array: 1 9 8 4 2 7 6 9 0 0 0 0 0
Time Complexity: O(n). Auxiliary Space: O(1).
mayanktyagi1709
AmanDeepSingh97
guptavivek0503
array-rearrange
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 250,
"s": 52,
"text": "Given an array of n numbers. The problem is to move all the 0’s to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.Examples: "
},
{
"code": null,
"e": 402,
"s": 250,
"text": "Input : arr[] = {1, 2, 0, 0, 0, 3, 6}\nOutput : 1 2 3 6 0 0 0\n\nInput: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}\nOutput: 1 9 8 4 2 7 6 9 0 0 0 0 0"
},
{
"code": null,
"e": 417,
"s": 404,
"text": "Algorithm: "
},
{
"code": null,
"e": 592,
"s": 417,
"text": "moveZerosToEnd(arr, n)\n Initialize count = 0\n for i = 0 to n-1\n if (arr[i] != 0) then\n arr[count++]=arr[i]\n for i = count to n-1\n arr[i] = 0"
},
{
"code": null,
"e": 602,
"s": 592,
"text": "Flowchart"
},
{
"code": null,
"e": 608,
"s": 604,
"text": "CPP"
},
{
"code": null,
"e": 613,
"s": 608,
"text": "Java"
},
{
"code": null,
"e": 621,
"s": 613,
"text": "Python3"
},
{
"code": null,
"e": 624,
"s": 621,
"text": "C#"
},
{
"code": null,
"e": 635,
"s": 624,
"text": "Javascript"
},
{
"code": "// C++ implementation to move all zeroes at// the end of array#include <iostream>using namespace std; // function to move all zeroes at// the end of arrayvoid moveZerosToEnd(int arr[], int n){ // Count of non-zero elements int count = 0; // Traverse the array. If arr[i] is non-zero, then // update the value of arr at index count to arr[i] for (int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // Update all elements at index >=count with value 0 for (int i = count; i<n;i++) arr[i]=0;} // function to print the array elementsvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver program to test aboveint main(){ int arr[] = { 0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Original array: \"; printArray(arr, n); moveZerosToEnd(arr, n); cout << \"\\nModified array: \"; printArray(arr, n); return 0;} // This code is contributed by Ashutosh Singh",
"e": 1691,
"s": 635,
"text": null
},
{
"code": "// Java implementation to move// all zeroes at the end of arrayimport java.io.*; class GFG { // function to move all zeroes at// the end of arraystatic void moveZerosToEnd(int arr[], int n) { // Count of non-zero elements int count = 0; // Traverse the array. If arr[i] is non-zero, then // update the value of arr at index count to arr[i] for (int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // Update all elements at index >=count with value 0 for (int i = count; i<n;i++) arr[i]=0;} // function to print the array elementsstatic void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \");} // Driver program to test abovepublic static void main(String args[]) { int arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; int n = arr.length; System.out.print(\"Original array: \"); printArray(arr, n); moveZerosToEnd(arr, n); System.out.print(\"\\nModified array: \"); printArray(arr, n);}} // This code is contributed by Ashutosh Singh",
"e": 2780,
"s": 1691,
"text": null
},
{
"code": "# Python implementation to move all zeroes at# the end of array # function to move all zeroes at# the end of arraydef moveZerosToEnd (arr, n): # Count of non-zero elements count = 0; # Traverse the array. If arr[i] is non-zero, then # update the value of arr at index count to arr[i] for i in range(0, n): if (arr[i] != 0): arr[count] = arr[i] count+=1 # Update all elements at index >=count with value 0 for i in range(count, n): arr[i] = 0 # function to print the array elementsdef printArray(arr, n): for i in range(0, n): print(arr[i],end=\" \") # Driver program to test abovearr = [ 0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 ]n = len(arr) print(\"Original array:\", end=\" \")printArray(arr, n) moveZerosToEnd(arr, n) print(\"\\nModified array: \", end=\" \")printArray(arr, n) # This code is contributed by# Ashutosh Singh",
"e": 3675,
"s": 2780,
"text": null
},
{
"code": "// C# implementation to move// all zeroes at the end of arrayusing System; class GFG { // function to move all zeroes at // the end of array static void moveZerosToEnd(int[] arr, int n) { // Count of non-zero elements int count = 0; // Traverse the array. If arr[i] is non-zero, then // update the value of arr at index count to arr[i] for (int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // Update all elements at index >=count with value 0 for (int i = count; i<n;i++) arr[i]=0; } // function to print the array elements static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); } // Driver program to test above public static void Main() { int[] arr = { 0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 }; int n = arr.Length; Console.Write(\"Original array: \"); printArray(arr, n); moveZerosToEnd(arr, n); Console.Write(\"\\nModified array: \"); printArray(arr, n); }} // This code is contributed by Ashutosh Singh",
"e": 4841,
"s": 3675,
"text": null
},
{
"code": "<script>// JavaScript implementation to move all zeroes at// the end of array // function to move all zeroes at// the end of arrayfunction moveZerosToEnd(arr, n){ // Count of non-zero elements let count = 0; // Traverse the array. If arr[i] is non-zero, then // update the value of arr at index count to arr[i] for (let i = 0; i < n; i++) if (arr[i] != 0) { arr[count] = arr[i]; count = count + 1; } // Update all elements at index >= count with value 0 for (let i = count; i < n; i++) arr[i] = 0 } // function to print the array elementsfunction printArray(arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Driver program to test above let arr = [ 0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 ]; let n = arr.length; document.write(\"Original array: \"); printArray(arr, n); moveZerosToEnd(arr, n); document.write(\"<br>\" + \"Modified array: \"); printArray(arr, n); //This code is contributed by Ashutosh Singh</script>",
"e": 5917,
"s": 4841,
"text": null
},
{
"code": null,
"e": 6003,
"s": 5917,
"text": "Original array: 0 1 9 8 4 0 0 2 7 0 6 0 9 \nModified array: 1 9 8 4 2 7 6 9 0 0 0 0 0 "
},
{
"code": null,
"e": 6050,
"s": 6003,
"text": "Time Complexity: O(n). Auxiliary Space: O(1). "
},
{
"code": null,
"e": 6066,
"s": 6050,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 6082,
"s": 6066,
"text": "AmanDeepSingh97"
},
{
"code": null,
"e": 6097,
"s": 6082,
"text": "guptavivek0503"
},
{
"code": null,
"e": 6113,
"s": 6097,
"text": "array-rearrange"
},
{
"code": null,
"e": 6120,
"s": 6113,
"text": "Arrays"
},
{
"code": null,
"e": 6127,
"s": 6120,
"text": "Arrays"
}
]
|
CSS | rotateX() Function | 07 Aug, 2019
The rotateX() function is an inbuilt function which is used to rotate an element around the x-axis.
Syntax:
rotateX( angle )
Parameters: This function accepts single parameter angle which represents the angle of rotations. The positive and negative angles rotate the elements in clockwise and counter-clockwise respectively.
Below examples illustrate the rotateX() function in CSS:Example 1:
<!DOCTYPE html> <html> <head> <title>CSS rotateX() function</title> <style> body { text-align:center; } h1 { color:green; } .rotateX_image { transform: rotateX(60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateX() function</h2> <img class="rotateX_image" src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GeeksforGeeks logo"> </body> </html>
Output:
Example 2:
<!DOCTYPE html> <html> <head> <title>CSS rotateX() function</title> <style> body { text-align:center; } h1 { color:green; } .GFG { font-size:35px; font-weight:bold; color:green; transform: rotateX(60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateX() function</h2> <div class="GFG">Welcome to GeeksforGeeks</div> </body> </html>
Output:
Supported Browsers: The browsers supported by rotateX() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Aug, 2019"
},
{
"code": null,
"e": 128,
"s": 28,
"text": "The rotateX() function is an inbuilt function which is used to rotate an element around the x-axis."
},
{
"code": null,
"e": 136,
"s": 128,
"text": "Syntax:"
},
{
"code": null,
"e": 153,
"s": 136,
"text": "rotateX( angle )"
},
{
"code": null,
"e": 353,
"s": 153,
"text": "Parameters: This function accepts single parameter angle which represents the angle of rotations. The positive and negative angles rotate the elements in clockwise and counter-clockwise respectively."
},
{
"code": null,
"e": 420,
"s": 353,
"text": "Below examples illustrate the rotateX() function in CSS:Example 1:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>CSS rotateX() function</title> <style> body { text-align:center; } h1 { color:green; } .rotateX_image { transform: rotateX(60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateX() function</h2> <img class=\"rotateX_image\" src= \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GeeksforGeeks logo\"> </body> </html>",
"e": 941,
"s": 420,
"text": null
},
{
"code": null,
"e": 949,
"s": 941,
"text": "Output:"
},
{
"code": null,
"e": 960,
"s": 949,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>CSS rotateX() function</title> <style> body { text-align:center; } h1 { color:green; } .GFG { font-size:35px; font-weight:bold; color:green; transform: rotateX(60deg); } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>CSS rotateX() function</h2> <div class=\"GFG\">Welcome to GeeksforGeeks</div> </body> </html>",
"e": 1448,
"s": 960,
"text": null
},
{
"code": null,
"e": 1456,
"s": 1448,
"text": "Output:"
},
{
"code": null,
"e": 1539,
"s": 1456,
"text": "Supported Browsers: The browsers supported by rotateX() function are listed below:"
},
{
"code": null,
"e": 1553,
"s": 1539,
"text": "Google Chrome"
},
{
"code": null,
"e": 1571,
"s": 1553,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1579,
"s": 1571,
"text": "Firefox"
},
{
"code": null,
"e": 1586,
"s": 1579,
"text": "Safari"
},
{
"code": null,
"e": 1592,
"s": 1586,
"text": "Opera"
},
{
"code": null,
"e": 1606,
"s": 1592,
"text": "CSS-Functions"
},
{
"code": null,
"e": 1610,
"s": 1606,
"text": "CSS"
},
{
"code": null,
"e": 1627,
"s": 1610,
"text": "Web Technologies"
}
]
|
Longest Monotonically Increasing Subsequence Size (N log N): Simple implementation | 23 Jun, 2022
Given an array of random numbers, find the longest monotonically increasing subsequence (LIS) in the array. If you want to understand the O(NlogN) approach, it’s explained very clearly here.
In this post, a simple and time-saving implementation of O(NlogN) approach using stl is discussed. Below is the code for LIS O(NlogN):
Implementation:
C++
Java
Python3
C#
Javascript
// C++ implementation// to find LIS#include<iostream>#include<algorithm>#include<set>using namespace std; // Return length of LIS in arr[] of size Nint lis(int arr[], int N){ int i; set<int> s; set<int>::iterator k; for (i=0; i<N; i++) { // Check if the element was actually inserted // An element in set is not inserted if it is // already present. Please see // https://www.geeksforgeeks.org/set-insert-function-in-c-stl/ if (s.insert(arr[i]).second) { // Find the position of inserted element in iterator k k = s.find(arr[i]); k++; // Find the next greater element in set // If the new element is not inserted at the end, then // remove the greater element next to it (This is tricky) if (k!=s.end()) s.erase(k); } } // Note that set s may not contain actual LIS, but its size gives // us the length of LIS return s.size();} int main(){ int arr[] = {8, 9, 12, 10, 11}; int n = sizeof(arr)/sizeof(arr[0]); cout << lis(arr, n)<< endl;}
// Java implementation// to find LISimport java.util.*;class GFG{ // Return length of LIS// in arr[] of size Nstatic int lis(int arr[], int N){ int i; HashSet<Integer> s = new HashSet<>(); for (i = 0; i < N; i++) { // Check if the element // was actually inserted // An element in set is // not inserted if it is // already present. Please see // https://www.geeksforgeeks. // org/set-insert-function-in-c-stl/ int k = 0; int size = s.size(); if (s.add(arr[i])) { // Find the position of // inserted element in iterator k if(s.contains(arr[i])) k++; // Find the next // greater element in set // If the new element is not // inserted at the end, then // remove the greater element // next to it. if (size == s.size()) s.remove(k + 1); } } // Note that set s may not contain // actual LIS, but its size gives // us the length of LIS return s.size();} public static void main(String[] args){ int arr[] = {8, 9, 12, 10, 11}; int n = arr.length; System.out.print(lis(arr, n) + "\n");}} // This code is contributed by gauravrajput1
# Python implementation# to find LIS # Return length of LIS# in arr of size Ndef lis(arr, N): s = set(); for i in range(N): # Check if the element # was actually inserted # An element in set is # not inserted if it is # already present. Please see # https:#www.geeksforgeeks. # org/set-insert-function-in-c-stl/ k = 0; size = len(s); if (s.add(arr[i])): # Find the position of # inserted element in iterator k if arr[i] in s: k += 1; # Find the next # greater element in set # If the new element is not # inserted at the end, then # remove the greater element # next to it. if (size == len(s)): s.remove(k + 1); # Note that set s may not contain # actual LIS, but its size gives # us the length of LIS return len(s); # Driver codeif __name__ == '__main__': arr = [ 8, 9, 12, 10, 11 ]; n = len(arr); print(lis(arr, n) ,""); # This code is contributed by Rajput-Ji
// C# implementation// to find LISusing System;using System.Collections.Generic; class GFG{ // Return length of LIS// in arr[] of size Nstatic int lis(int[] arr, int N){ int i; HashSet<int> s = new HashSet<int>(); for(i = 0; i < N; i++) { // Check if the element was actually inserted // An element in set is not inserted if it is // already present. Please see // https://www.geeksforgeeks.org/set-insert-function-in-c-stl/ int k = 0; int size = s.Count; if (s.Add(arr[i])) { // Find the position of inserted // element in iterator k if (s.Contains(arr[i])) k++; // Find the next greater element in set // If the new element is not inserted at // the end, then remove the greater element // next to it. if (size == s.Count) s.Remove(k + 1); } } // Note that set s may not contain // actual LIS, but its size gives // us the length of LIS return s.Count;} // Driver codestatic public void Main(){ int[] arr = { 8, 9, 12, 10, 11 }; int n = arr.Length; Console.Write(lis(arr, n) + "\n");}} // This code is contributed by avanitrachhadiya2155
<script> // Javascript implementation// to find LIS // Return length of LIS// in arr[] of size Nfunction lis(arr,N){ let i; let s = new Set(); for (i = 0; i < N; i++) { // Check if the element // was actually inserted // An element in set is // not inserted if it is // already present. Please see // https://www.geeksforgeeks. // org/set-insert-function-in-c-stl/ let k = 0; let size = s.size; if (s.add(arr[i])) { // Find the position of // inserted element in iterator k if(s.has(arr[i])) k++; // Find the next // greater element in set // If the new element is not // inserted at the end, then // remove the greater element // next to it. if (size == s.size) s.delete(k + 1); } } // Note that set s may not contain // actual LIS, but its size gives // us the length of LIS return s.size;} let arr=[8, 9, 12, 10, 11];let n = arr.length;document.write(lis(arr, n) + "<br>"); // This code is contributed by unknown2108 </script>
4
warlockx
GauravRajput1
unknown2108
avanitrachhadiya2155
iramkhalid24
Rajput-Ji
hardikkoriintern
LIS
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 245,
"s": 54,
"text": "Given an array of random numbers, find the longest monotonically increasing subsequence (LIS) in the array. If you want to understand the O(NlogN) approach, it’s explained very clearly here."
},
{
"code": null,
"e": 380,
"s": 245,
"text": "In this post, a simple and time-saving implementation of O(NlogN) approach using stl is discussed. Below is the code for LIS O(NlogN):"
},
{
"code": null,
"e": 396,
"s": 380,
"text": "Implementation:"
},
{
"code": null,
"e": 400,
"s": 396,
"text": "C++"
},
{
"code": null,
"e": 405,
"s": 400,
"text": "Java"
},
{
"code": null,
"e": 413,
"s": 405,
"text": "Python3"
},
{
"code": null,
"e": 416,
"s": 413,
"text": "C#"
},
{
"code": null,
"e": 427,
"s": 416,
"text": "Javascript"
},
{
"code": "// C++ implementation// to find LIS#include<iostream>#include<algorithm>#include<set>using namespace std; // Return length of LIS in arr[] of size Nint lis(int arr[], int N){ int i; set<int> s; set<int>::iterator k; for (i=0; i<N; i++) { // Check if the element was actually inserted // An element in set is not inserted if it is // already present. Please see // https://www.geeksforgeeks.org/set-insert-function-in-c-stl/ if (s.insert(arr[i]).second) { // Find the position of inserted element in iterator k k = s.find(arr[i]); k++; // Find the next greater element in set // If the new element is not inserted at the end, then // remove the greater element next to it (This is tricky) if (k!=s.end()) s.erase(k); } } // Note that set s may not contain actual LIS, but its size gives // us the length of LIS return s.size();} int main(){ int arr[] = {8, 9, 12, 10, 11}; int n = sizeof(arr)/sizeof(arr[0]); cout << lis(arr, n)<< endl;}",
"e": 1519,
"s": 427,
"text": null
},
{
"code": "// Java implementation// to find LISimport java.util.*;class GFG{ // Return length of LIS// in arr[] of size Nstatic int lis(int arr[], int N){ int i; HashSet<Integer> s = new HashSet<>(); for (i = 0; i < N; i++) { // Check if the element // was actually inserted // An element in set is // not inserted if it is // already present. Please see // https://www.geeksforgeeks. // org/set-insert-function-in-c-stl/ int k = 0; int size = s.size(); if (s.add(arr[i])) { // Find the position of // inserted element in iterator k if(s.contains(arr[i])) k++; // Find the next // greater element in set // If the new element is not // inserted at the end, then // remove the greater element // next to it. if (size == s.size()) s.remove(k + 1); } } // Note that set s may not contain // actual LIS, but its size gives // us the length of LIS return s.size();} public static void main(String[] args){ int arr[] = {8, 9, 12, 10, 11}; int n = arr.length; System.out.print(lis(arr, n) + \"\\n\");}} // This code is contributed by gauravrajput1",
"e": 2681,
"s": 1519,
"text": null
},
{
"code": "# Python implementation# to find LIS # Return length of LIS# in arr of size Ndef lis(arr, N): s = set(); for i in range(N): # Check if the element # was actually inserted # An element in set is # not inserted if it is # already present. Please see # https:#www.geeksforgeeks. # org/set-insert-function-in-c-stl/ k = 0; size = len(s); if (s.add(arr[i])): # Find the position of # inserted element in iterator k if arr[i] in s: k += 1; # Find the next # greater element in set # If the new element is not # inserted at the end, then # remove the greater element # next to it. if (size == len(s)): s.remove(k + 1); # Note that set s may not contain # actual LIS, but its size gives # us the length of LIS return len(s); # Driver codeif __name__ == '__main__': arr = [ 8, 9, 12, 10, 11 ]; n = len(arr); print(lis(arr, n) ,\"\"); # This code is contributed by Rajput-Ji",
"e": 3809,
"s": 2681,
"text": null
},
{
"code": "// C# implementation// to find LISusing System;using System.Collections.Generic; class GFG{ // Return length of LIS// in arr[] of size Nstatic int lis(int[] arr, int N){ int i; HashSet<int> s = new HashSet<int>(); for(i = 0; i < N; i++) { // Check if the element was actually inserted // An element in set is not inserted if it is // already present. Please see // https://www.geeksforgeeks.org/set-insert-function-in-c-stl/ int k = 0; int size = s.Count; if (s.Add(arr[i])) { // Find the position of inserted // element in iterator k if (s.Contains(arr[i])) k++; // Find the next greater element in set // If the new element is not inserted at // the end, then remove the greater element // next to it. if (size == s.Count) s.Remove(k + 1); } } // Note that set s may not contain // actual LIS, but its size gives // us the length of LIS return s.Count;} // Driver codestatic public void Main(){ int[] arr = { 8, 9, 12, 10, 11 }; int n = arr.Length; Console.Write(lis(arr, n) + \"\\n\");}} // This code is contributed by avanitrachhadiya2155",
"e": 5127,
"s": 3809,
"text": null
},
{
"code": "<script> // Javascript implementation// to find LIS // Return length of LIS// in arr[] of size Nfunction lis(arr,N){ let i; let s = new Set(); for (i = 0; i < N; i++) { // Check if the element // was actually inserted // An element in set is // not inserted if it is // already present. Please see // https://www.geeksforgeeks. // org/set-insert-function-in-c-stl/ let k = 0; let size = s.size; if (s.add(arr[i])) { // Find the position of // inserted element in iterator k if(s.has(arr[i])) k++; // Find the next // greater element in set // If the new element is not // inserted at the end, then // remove the greater element // next to it. if (size == s.size) s.delete(k + 1); } } // Note that set s may not contain // actual LIS, but its size gives // us the length of LIS return s.size;} let arr=[8, 9, 12, 10, 11];let n = arr.length;document.write(lis(arr, n) + \"<br>\"); // This code is contributed by unknown2108 </script>",
"e": 6178,
"s": 5127,
"text": null
},
{
"code": null,
"e": 6180,
"s": 6178,
"text": "4"
},
{
"code": null,
"e": 6189,
"s": 6180,
"text": "warlockx"
},
{
"code": null,
"e": 6203,
"s": 6189,
"text": "GauravRajput1"
},
{
"code": null,
"e": 6215,
"s": 6203,
"text": "unknown2108"
},
{
"code": null,
"e": 6236,
"s": 6215,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 6249,
"s": 6236,
"text": "iramkhalid24"
},
{
"code": null,
"e": 6259,
"s": 6249,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 6276,
"s": 6259,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 6280,
"s": 6276,
"text": "LIS"
},
{
"code": null,
"e": 6287,
"s": 6280,
"text": "Arrays"
},
{
"code": null,
"e": 6294,
"s": 6287,
"text": "Arrays"
}
]
|
unordered_map size() in C++ STL | 31 Dec, 2018
The unordered_multimap::size() is a built-in function in C++ Standard Template Library which return’s the number of element int the unordered map.
Syntax:
unordered_multimap_name.size()
Return Value: It returns the number of the element present in the unordered map.
Time complexity:
Constant i.e. O(1).
Program 1:
// C++ program to demonstrate// unordered_map size() method #include <iostream>#include <unordered_map>using namespace std; int main(){ unordered_map<char, char> n{ { 'A', 'G' }, { 'B', 'E' }, { 'C', 'E' }, { 'D', 'K' }, { 'E', 'S' } }; cout << "size of map = " << n.size() << endl; return 0;}
size of map = 5
Program 2:
// C++ program to demonstrate// unordered_map size() method #include <iostream>#include <string>#include <unordered_map>using namespace std; int main(){ unordered_map<string, double> ra; cout << "Initial size of map = " << ra.size() << endl; ra = { { "Geeks", 1.556 }, { "For", 2.567 }, { "Geeks", 3.345 }, { "GeeksForGeeks", 4.789 }, { "GFG", 5.998 } }; cout << "size of map = " << ra.size() << endl; return 0;}
Initial size of map = 0
size of map = 4
CPP-Functions
cpp-unordered_map
Picked
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Dec, 2018"
},
{
"code": null,
"e": 201,
"s": 54,
"text": "The unordered_multimap::size() is a built-in function in C++ Standard Template Library which return’s the number of element int the unordered map."
},
{
"code": null,
"e": 209,
"s": 201,
"text": "Syntax:"
},
{
"code": null,
"e": 240,
"s": 209,
"text": "unordered_multimap_name.size()"
},
{
"code": null,
"e": 321,
"s": 240,
"text": "Return Value: It returns the number of the element present in the unordered map."
},
{
"code": null,
"e": 338,
"s": 321,
"text": "Time complexity:"
},
{
"code": null,
"e": 358,
"s": 338,
"text": "Constant i.e. O(1)."
},
{
"code": null,
"e": 369,
"s": 358,
"text": "Program 1:"
},
{
"code": "// C++ program to demonstrate// unordered_map size() method #include <iostream>#include <unordered_map>using namespace std; int main(){ unordered_map<char, char> n{ { 'A', 'G' }, { 'B', 'E' }, { 'C', 'E' }, { 'D', 'K' }, { 'E', 'S' } }; cout << \"size of map = \" << n.size() << endl; return 0;}",
"e": 733,
"s": 369,
"text": null
},
{
"code": null,
"e": 750,
"s": 733,
"text": "size of map = 5\n"
},
{
"code": null,
"e": 761,
"s": 750,
"text": "Program 2:"
},
{
"code": "// C++ program to demonstrate// unordered_map size() method #include <iostream>#include <string>#include <unordered_map>using namespace std; int main(){ unordered_map<string, double> ra; cout << \"Initial size of map = \" << ra.size() << endl; ra = { { \"Geeks\", 1.556 }, { \"For\", 2.567 }, { \"Geeks\", 3.345 }, { \"GeeksForGeeks\", 4.789 }, { \"GFG\", 5.998 } }; cout << \"size of map = \" << ra.size() << endl; return 0;}",
"e": 1253,
"s": 761,
"text": null
},
{
"code": null,
"e": 1294,
"s": 1253,
"text": "Initial size of map = 0\nsize of map = 4\n"
},
{
"code": null,
"e": 1308,
"s": 1294,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1326,
"s": 1308,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 1333,
"s": 1326,
"text": "Picked"
},
{
"code": null,
"e": 1337,
"s": 1333,
"text": "STL"
},
{
"code": null,
"e": 1341,
"s": 1337,
"text": "C++"
},
{
"code": null,
"e": 1345,
"s": 1341,
"text": "STL"
},
{
"code": null,
"e": 1349,
"s": 1345,
"text": "CPP"
}
]
|
Thread.CurrentThread Property in C# | 13 May, 2019
A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as CurrentThread to check the current running thread. Or in other words, the value of this property indicates the current running thread.
Syntax: public static Thread CurrentThread { get; }
Return Value: This property returns a thread that represent the current running thread.
Below programs illustrate the use of CurrentThread property:.Example 1:
// C# program to illustrate the // use of CurrentThread propertyusing System;using System.Threading; class GFG { // Main Method static public void Main() { Thread thr; // Get the reference of main Thread // Using CurrentThread property thr = Thread.CurrentThread; thr.Name = "Main thread"; Console.WriteLine("Name of current running "+ "thread: {0}", thr.Name); }}
Output:
Name of current running thread: Main thread
Example 2:
// C# program to illustrate the// use of CurrentThread propertyusing System;using System.Threading; class GFG { // Display the id of each thread // Using CurrentThread and // ManagedThreadId properties public static void Myjob() { Console.WriteLine("Thread Id: {0}", Thread.CurrentThread.ManagedThreadId); } // Main method static public void Main() { // Creating multiple threads ThreadStart value = new ThreadStart(Myjob); for (int q = 1; q <= 7; ++q) { Thread mythread = new Thread(value); mythread.Start(); } }}
Output:
Thread Id: 3
Thread Id: 8
Thread Id: 9
Thread Id: 6
Thread Id: 5
Thread Id: 7
Thread Id: 4
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.currentthread?view=netframework-4.7.2
Akanksha_Rai
CSharp Multithreading
CSharp Thread Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 May, 2019"
},
{
"code": null,
"e": 289,
"s": 28,
"text": "A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as CurrentThread to check the current running thread. Or in other words, the value of this property indicates the current running thread."
},
{
"code": null,
"e": 341,
"s": 289,
"text": "Syntax: public static Thread CurrentThread { get; }"
},
{
"code": null,
"e": 429,
"s": 341,
"text": "Return Value: This property returns a thread that represent the current running thread."
},
{
"code": null,
"e": 501,
"s": 429,
"text": "Below programs illustrate the use of CurrentThread property:.Example 1:"
},
{
"code": "// C# program to illustrate the // use of CurrentThread propertyusing System;using System.Threading; class GFG { // Main Method static public void Main() { Thread thr; // Get the reference of main Thread // Using CurrentThread property thr = Thread.CurrentThread; thr.Name = \"Main thread\"; Console.WriteLine(\"Name of current running \"+ \"thread: {0}\", thr.Name); }}",
"e": 952,
"s": 501,
"text": null
},
{
"code": null,
"e": 960,
"s": 952,
"text": "Output:"
},
{
"code": null,
"e": 1004,
"s": 960,
"text": "Name of current running thread: Main thread"
},
{
"code": null,
"e": 1015,
"s": 1004,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the// use of CurrentThread propertyusing System;using System.Threading; class GFG { // Display the id of each thread // Using CurrentThread and // ManagedThreadId properties public static void Myjob() { Console.WriteLine(\"Thread Id: {0}\", Thread.CurrentThread.ManagedThreadId); } // Main method static public void Main() { // Creating multiple threads ThreadStart value = new ThreadStart(Myjob); for (int q = 1; q <= 7; ++q) { Thread mythread = new Thread(value); mythread.Start(); } }}",
"e": 1644,
"s": 1015,
"text": null
},
{
"code": null,
"e": 1652,
"s": 1644,
"text": "Output:"
},
{
"code": null,
"e": 1744,
"s": 1652,
"text": "Thread Id: 3\nThread Id: 8\nThread Id: 9\nThread Id: 6\nThread Id: 5\nThread Id: 7\nThread Id: 4\n"
},
{
"code": null,
"e": 1755,
"s": 1744,
"text": "Reference:"
},
{
"code": null,
"e": 1861,
"s": 1755,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.currentthread?view=netframework-4.7.2"
},
{
"code": null,
"e": 1874,
"s": 1861,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1896,
"s": 1874,
"text": "CSharp Multithreading"
},
{
"code": null,
"e": 1916,
"s": 1896,
"text": "CSharp Thread Class"
},
{
"code": null,
"e": 1919,
"s": 1916,
"text": "C#"
}
]
|
Python Number random() Method | Python number method random() returns a random float r, such that 0 is less than or equal to r and r is less than 1.
Following is the syntax for random() method −
random ( )
Note − This function is not accessible directly, so we need to import random module and then we need to call this function using random static object.
NA
NA
This method returns a random float r, such that 0 is less than or equal to r and r is less than 1.
The following example shows the usage of random() method.
#!/usr/bin/python
import random
# First random number
print "random() : ", random.random()
# Second random number
print "random() : ", random.random()
When we run above program, it produces following result −
random() : 0.281954791393
random() : 0.309090465205 | [
{
"code": null,
"e": 2495,
"s": 2378,
"text": "Python number method random() returns a random float r, such that 0 is less than or equal to r and r is less than 1."
},
{
"code": null,
"e": 2541,
"s": 2495,
"text": "Following is the syntax for random() method −"
},
{
"code": null,
"e": 2553,
"s": 2541,
"text": "random ( )\n"
},
{
"code": null,
"e": 2704,
"s": 2553,
"text": "Note − This function is not accessible directly, so we need to import random module and then we need to call this function using random static object."
},
{
"code": null,
"e": 2707,
"s": 2704,
"text": "NA"
},
{
"code": null,
"e": 2710,
"s": 2707,
"text": "NA"
},
{
"code": null,
"e": 2809,
"s": 2710,
"text": "This method returns a random float r, such that 0 is less than or equal to r and r is less than 1."
},
{
"code": null,
"e": 2867,
"s": 2809,
"text": "The following example shows the usage of random() method."
},
{
"code": null,
"e": 3020,
"s": 2867,
"text": "#!/usr/bin/python\nimport random\n\n# First random number\nprint \"random() : \", random.random()\n\n# Second random number\nprint \"random() : \", random.random()"
},
{
"code": null,
"e": 3078,
"s": 3020,
"text": "When we run above program, it produces following result −"
}
]
|
JavaScript SyntaxError – Missing = in const declaration | 27 Sep, 2021
This JavaScript exception missing = in const declaration occurs if a const is declared and value is not provided(like const ABC_DEF;). Need to provide the value in same statement (const ABC_DEF = ‘#ee0’).
Message:
SyntaxError: Const must be initialized (Edge)
SyntaxError: missing = in const declaration (Firefox)
SyntaxError: Missing initializer in const declaration (Chrome)
Error Type:
SyntaxError
Cause of Error: A constant value cannot be changed by the program while execution. It cannot be altered through re-assignment also.
Example 1: In this example, a const is declared but not initialized so the error has occurred.
HTML
<!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> const GFG; document.write(GFG); </script></body></html>
Output:
SyntaxError: Const must be initialized
Example 2: In this example, a const is declared and initialized later, so the error has occurred.
HTML
<!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> const INIT_VAL; // invalid statement INIT_VAL = 5; document.write(INIT_VAL); </script></body></html>
Output:
SyntaxError: Const must be initialized
abhishek0719kadiyan
JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 233,
"s": 28,
"text": "This JavaScript exception missing = in const declaration occurs if a const is declared and value is not provided(like const ABC_DEF;). Need to provide the value in same statement (const ABC_DEF = ‘#ee0’)."
},
{
"code": null,
"e": 242,
"s": 233,
"text": "Message:"
},
{
"code": null,
"e": 405,
"s": 242,
"text": "SyntaxError: Const must be initialized (Edge)\nSyntaxError: missing = in const declaration (Firefox)\nSyntaxError: Missing initializer in const declaration (Chrome)"
},
{
"code": null,
"e": 417,
"s": 405,
"text": "Error Type:"
},
{
"code": null,
"e": 429,
"s": 417,
"text": "SyntaxError"
},
{
"code": null,
"e": 561,
"s": 429,
"text": "Cause of Error: A constant value cannot be changed by the program while execution. It cannot be altered through re-assignment also."
},
{
"code": null,
"e": 656,
"s": 561,
"text": "Example 1: In this example, a const is declared but not initialized so the error has occurred."
},
{
"code": null,
"e": 661,
"s": 656,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> const GFG; document.write(GFG); </script></body></html>",
"e": 831,
"s": 661,
"text": null
},
{
"code": null,
"e": 839,
"s": 831,
"text": "Output:"
},
{
"code": null,
"e": 878,
"s": 839,
"text": "SyntaxError: Const must be initialized"
},
{
"code": null,
"e": 977,
"s": 878,
"text": "Example 2: In this example, a const is declared and initialized later, so the error has occurred."
},
{
"code": null,
"e": 982,
"s": 977,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Syntax Error</title></head><body> <script> const INIT_VAL; // invalid statement INIT_VAL = 5; document.write(INIT_VAL); </script></body></html>",
"e": 1207,
"s": 982,
"text": null
},
{
"code": null,
"e": 1215,
"s": 1207,
"text": "Output:"
},
{
"code": null,
"e": 1254,
"s": 1215,
"text": "SyntaxError: Const must be initialized"
},
{
"code": null,
"e": 1274,
"s": 1254,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 1292,
"s": 1274,
"text": "JavaScript-Errors"
},
{
"code": null,
"e": 1303,
"s": 1292,
"text": "JavaScript"
},
{
"code": null,
"e": 1320,
"s": 1303,
"text": "Web Technologies"
}
]
|
unordered_set == operator in C++ STL | 29 Jun, 2022
The ‘==’ is an operator in C++ STL performs equality comparison operation between two unordered sets and unordered_set::operator== is the corresponding operator function for the same. Syntax:
(unordered_set &uset1 == unordered_set &uset2)
Parameters: This operator function takes reference of two unordered sets uset1 and uset2 as parameters which are to be compared.Return Value: This method returns a boolean result value after comparing the two sets. The comparison procedure is as follows:
Firstly their sizes are compared .
Then each element in ust1 is looked for in ust2
If both the conditions are satisfied true value is returned and at any point if a condition is not satisfied, false value is returned.Below program illustrates unordered_set::operator== in C++.Program:
CPP
#include <iostream>#include <unordered_set>using namespace std; int main(){ // Initialize three unordered sets unordered_set<int> sample1 = { 10, 20, 30, 40, 50 }; unordered_set<int> sample2 = { 10, 30, 50, 40, 20 }; unordered_set<int> sample3 = { 10, 20, 30, 50, 60 }; // Compare sample1 and sample2 if (sample1 == sample2) { cout << "sample1 and " << "sample2 are equal." << endl; } else { cout << "sample1 and " << "sample2 are not equal." << endl; } // Compare sample2 and sample3 if (sample2 == sample3) { cout << "sample2 and " << "sample3 are equal." << endl; } else { cout << "sample2 and " << "sample3 are not equal." << endl; } return 0;}
sample1 and sample2 are equal.
sample2 and sample3 are not equal.
Time complexity: O(N2)
arorakashish0911
utkarshgupta110092
cpp-unordered_set
Picked
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
Object Oriented Programming in C++
Inheritance in C++
C++ Classes and Objects
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 247,
"s": 53,
"text": "The ‘==’ is an operator in C++ STL performs equality comparison operation between two unordered sets and unordered_set::operator== is the corresponding operator function for the same. Syntax: "
},
{
"code": null,
"e": 294,
"s": 247,
"text": "(unordered_set &uset1 == unordered_set &uset2)"
},
{
"code": null,
"e": 551,
"s": 294,
"text": "Parameters: This operator function takes reference of two unordered sets uset1 and uset2 as parameters which are to be compared.Return Value: This method returns a boolean result value after comparing the two sets. The comparison procedure is as follows: "
},
{
"code": null,
"e": 586,
"s": 551,
"text": "Firstly their sizes are compared ."
},
{
"code": null,
"e": 634,
"s": 586,
"text": "Then each element in ust1 is looked for in ust2"
},
{
"code": null,
"e": 837,
"s": 634,
"text": "If both the conditions are satisfied true value is returned and at any point if a condition is not satisfied, false value is returned.Below program illustrates unordered_set::operator== in C++.Program: "
},
{
"code": null,
"e": 841,
"s": 837,
"text": "CPP"
},
{
"code": "#include <iostream>#include <unordered_set>using namespace std; int main(){ // Initialize three unordered sets unordered_set<int> sample1 = { 10, 20, 30, 40, 50 }; unordered_set<int> sample2 = { 10, 30, 50, 40, 20 }; unordered_set<int> sample3 = { 10, 20, 30, 50, 60 }; // Compare sample1 and sample2 if (sample1 == sample2) { cout << \"sample1 and \" << \"sample2 are equal.\" << endl; } else { cout << \"sample1 and \" << \"sample2 are not equal.\" << endl; } // Compare sample2 and sample3 if (sample2 == sample3) { cout << \"sample2 and \" << \"sample3 are equal.\" << endl; } else { cout << \"sample2 and \" << \"sample3 are not equal.\" << endl; } return 0;}",
"e": 1687,
"s": 841,
"text": null
},
{
"code": null,
"e": 1753,
"s": 1687,
"text": "sample1 and sample2 are equal.\nsample2 and sample3 are not equal."
},
{
"code": null,
"e": 1778,
"s": 1755,
"text": "Time complexity: O(N2)"
},
{
"code": null,
"e": 1795,
"s": 1778,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1814,
"s": 1795,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 1832,
"s": 1814,
"text": "cpp-unordered_set"
},
{
"code": null,
"e": 1839,
"s": 1832,
"text": "Picked"
},
{
"code": null,
"e": 1843,
"s": 1839,
"text": "STL"
},
{
"code": null,
"e": 1847,
"s": 1843,
"text": "C++"
},
{
"code": null,
"e": 1851,
"s": 1847,
"text": "STL"
},
{
"code": null,
"e": 1855,
"s": 1851,
"text": "CPP"
},
{
"code": null,
"e": 1953,
"s": 1855,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1980,
"s": 1953,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 2034,
"s": 1980,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2068,
"s": 2034,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 2085,
"s": 2068,
"text": "Substring in C++"
},
{
"code": null,
"e": 2120,
"s": 2085,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 2139,
"s": 2120,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 2163,
"s": 2139,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 2187,
"s": 2163,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2227,
"s": 2187,
"text": "2D Vector In C++ With User Defined Size"
}
]
|
How to disable arrows from Number input ? | 16 Feb, 2021
In this article, we will see how to disable arrows from the Number input.
See the Images below, the first image is having the default arrow and the second is without having the arrow.
Default input box (Having arrows)
Input box without having arrows.
To achieve this, we use the following syntax :
Approach 1:
For chrome, Safari, Edge, Opera :
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
For firefox :
input[type=number]{
-moz-appearance: textfield;
}
Example:
HTML
<!DOCTYPE html><html> <head> <style> input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input[type=number] { -moz-appearance: textfield; } </style></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> How to disable arrows from Number input using CSS? </h3> <input type="number" placeholder="Enter number..." /></body> </html>
Output :
Approach 2: This approach is simple yet powerful. Using inputmode=”numeric” attribute you can find an input box without an arrow. The older browsers might not support this feature for example Internet Explorer and Safari but most of the modern browsers like Chrome, Firefox, Edge, Opera support this attribute. The main purpose of this attribute is to provide a numeric input interface in mobile devices.
<input type="text" inputmode="numeric" />
Example :
HTML
<!DOCTYPE html><html> <body> <h1 style="color: green;">GeeksforGeeks</h1> <h3> Disable arrows from number input </h3> <input type="text" inputmode="numeric" placeholder="Enter number..."/></body> </html>
Output :
CSS-Properties
CSS-Questions
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 102,
"s": 28,
"text": "In this article, we will see how to disable arrows from the Number input."
},
{
"code": null,
"e": 212,
"s": 102,
"text": "See the Images below, the first image is having the default arrow and the second is without having the arrow."
},
{
"code": null,
"e": 246,
"s": 212,
"text": "Default input box (Having arrows)"
},
{
"code": null,
"e": 279,
"s": 246,
"text": "Input box without having arrows."
},
{
"code": null,
"e": 326,
"s": 279,
"text": "To achieve this, we use the following syntax :"
},
{
"code": null,
"e": 338,
"s": 326,
"text": "Approach 1:"
},
{
"code": null,
"e": 372,
"s": 338,
"text": "For chrome, Safari, Edge, Opera :"
},
{
"code": null,
"e": 488,
"s": 372,
"text": "input::-webkit-outer-spin-button,\ninput::-webkit-inner-spin-button {\n -webkit-appearance: none;\n margin: 0;\n}"
},
{
"code": null,
"e": 502,
"s": 488,
"text": "For firefox :"
},
{
"code": null,
"e": 556,
"s": 502,
"text": "input[type=number]{\n -moz-appearance: textfield;\n}"
},
{
"code": null,
"e": 565,
"s": 556,
"text": "Example:"
},
{
"code": null,
"e": 570,
"s": 565,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input[type=number] { -moz-appearance: textfield; } </style></head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> How to disable arrows from Number input using CSS? </h3> <input type=\"number\" placeholder=\"Enter number...\" /></body> </html>",
"e": 1095,
"s": 570,
"text": null
},
{
"code": null,
"e": 1104,
"s": 1095,
"text": "Output :"
},
{
"code": null,
"e": 1509,
"s": 1104,
"text": "Approach 2: This approach is simple yet powerful. Using inputmode=”numeric” attribute you can find an input box without an arrow. The older browsers might not support this feature for example Internet Explorer and Safari but most of the modern browsers like Chrome, Firefox, Edge, Opera support this attribute. The main purpose of this attribute is to provide a numeric input interface in mobile devices."
},
{
"code": null,
"e": 1551,
"s": 1509,
"text": "<input type=\"text\" inputmode=\"numeric\" />"
},
{
"code": null,
"e": 1561,
"s": 1551,
"text": "Example :"
},
{
"code": null,
"e": 1566,
"s": 1561,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style=\"color: green;\">GeeksforGeeks</h1> <h3> Disable arrows from number input </h3> <input type=\"text\" inputmode=\"numeric\" placeholder=\"Enter number...\"/></body> </html>",
"e": 1801,
"s": 1566,
"text": null
},
{
"code": null,
"e": 1810,
"s": 1801,
"text": "Output :"
},
{
"code": null,
"e": 1825,
"s": 1810,
"text": "CSS-Properties"
},
{
"code": null,
"e": 1839,
"s": 1825,
"text": "CSS-Questions"
},
{
"code": null,
"e": 1843,
"s": 1839,
"text": "CSS"
},
{
"code": null,
"e": 1848,
"s": 1843,
"text": "HTML"
},
{
"code": null,
"e": 1865,
"s": 1848,
"text": "Web Technologies"
},
{
"code": null,
"e": 1892,
"s": 1865,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1897,
"s": 1892,
"text": "HTML"
},
{
"code": null,
"e": 1995,
"s": 1897,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2034,
"s": 1995,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2073,
"s": 2034,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2112,
"s": 2073,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2149,
"s": 2112,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 2178,
"s": 2149,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2202,
"s": 2178,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2255,
"s": 2202,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2315,
"s": 2255,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2376,
"s": 2315,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
]
|
Stack pop() Method in Java | 12 Dec, 2021
The Java.util.Stack.pop() method in Java is used to pop an element from the stack. The element is popped from the top of the stack and is removed from the same.Syntax:
STACK.pop()
Parameters: The method does not take any parameters.Return Value: This method returns the element present at the top of the stack and then removes it.Exceptions: The method throws EmptyStackException is thrown if the stack is empty.Below programs illustrate the Java.util.Stack.pop() method: Program 1:
Java
// Java code to illustrate pop()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> STACK = new Stack<String>(); // Use add() method to add elements STACK.push("Welcome"); STACK.push("To"); STACK.push("Geeks"); STACK.push("For"); STACK.push("Geeks"); // Displaying the Stack System.out.println("Initial Stack: " + STACK); // Removing elements using pop() method System.out.println("Popped element: " + STACK.pop()); System.out.println("Popped element: " + STACK.pop()); // Displaying the Stack after pop operation System.out.println("Stack after pop operation " + STACK); }}
Program 2:
Java
// Java code to illustrate pop()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> STACK = new Stack<Integer>(); // Use add() method to add elements STACK.push(10); STACK.push(15); STACK.push(30); STACK.push(20); STACK.push(5); // Displaying the Stack System.out.println("Initial Stack: " + STACK); // Removing elements using pop() method System.out.println("Popped element: " + STACK.pop()); System.out.println("Popped element: " + STACK.pop()); // Displaying the Stack after pop operation System.out.println("Stack after pop operation " + STACK); }}
Initial Stack: [10, 15, 30, 20, 5]
Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]
sumitgumber28
Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 222,
"s": 53,
"text": "The Java.util.Stack.pop() method in Java is used to pop an element from the stack. The element is popped from the top of the stack and is removed from the same.Syntax: "
},
{
"code": null,
"e": 234,
"s": 222,
"text": "STACK.pop()"
},
{
"code": null,
"e": 538,
"s": 234,
"text": "Parameters: The method does not take any parameters.Return Value: This method returns the element present at the top of the stack and then removes it.Exceptions: The method throws EmptyStackException is thrown if the stack is empty.Below programs illustrate the Java.util.Stack.pop() method: Program 1: "
},
{
"code": null,
"e": 543,
"s": 538,
"text": "Java"
},
{
"code": "// Java code to illustrate pop()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> STACK = new Stack<String>(); // Use add() method to add elements STACK.push(\"Welcome\"); STACK.push(\"To\"); STACK.push(\"Geeks\"); STACK.push(\"For\"); STACK.push(\"Geeks\"); // Displaying the Stack System.out.println(\"Initial Stack: \" + STACK); // Removing elements using pop() method System.out.println(\"Popped element: \" + STACK.pop()); System.out.println(\"Popped element: \" + STACK.pop()); // Displaying the Stack after pop operation System.out.println(\"Stack after pop operation \" + STACK); }}",
"e": 1435,
"s": 543,
"text": null
},
{
"code": null,
"e": 1447,
"s": 1435,
"text": "Program 2: "
},
{
"code": null,
"e": 1452,
"s": 1447,
"text": "Java"
},
{
"code": "// Java code to illustrate pop()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> STACK = new Stack<Integer>(); // Use add() method to add elements STACK.push(10); STACK.push(15); STACK.push(30); STACK.push(20); STACK.push(5); // Displaying the Stack System.out.println(\"Initial Stack: \" + STACK); // Removing elements using pop() method System.out.println(\"Popped element: \" + STACK.pop()); System.out.println(\"Popped element: \" + STACK.pop()); // Displaying the Stack after pop operation System.out.println(\"Stack after pop operation \" + STACK); }}",
"e": 2323,
"s": 1452,
"text": null
},
{
"code": null,
"e": 2434,
"s": 2323,
"text": "Initial Stack: [10, 15, 30, 20, 5]\nPopped element: 5\nPopped element: 20\nStack after pop operation [10, 15, 30]"
},
{
"code": null,
"e": 2450,
"s": 2436,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2470,
"s": 2450,
"text": "Java - util package"
},
{
"code": null,
"e": 2487,
"s": 2470,
"text": "Java-Collections"
},
{
"code": null,
"e": 2502,
"s": 2487,
"text": "Java-Functions"
},
{
"code": null,
"e": 2513,
"s": 2502,
"text": "Java-Stack"
},
{
"code": null,
"e": 2518,
"s": 2513,
"text": "Java"
},
{
"code": null,
"e": 2523,
"s": 2518,
"text": "Java"
},
{
"code": null,
"e": 2540,
"s": 2523,
"text": "Java-Collections"
},
{
"code": null,
"e": 2638,
"s": 2540,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2653,
"s": 2638,
"text": "Arrays in Java"
},
{
"code": null,
"e": 2697,
"s": 2653,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 2733,
"s": 2697,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 2784,
"s": 2733,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2809,
"s": 2784,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 2831,
"s": 2809,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 2862,
"s": 2831,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2881,
"s": 2862,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2911,
"s": 2881,
"text": "HashMap in Java with Examples"
}
]
|
Storage Classes in C | 05 Apr, 2022
Storage Classes are used to describe the features of a variable/function. These features basically include the scope, visibility and life-time which help us to trace the existence of a particular variable during the runtime of a program.C language uses 4 storage classes, namely:
auto: This is the default storage class for all the variables declared inside a function or a block. Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope). Of course, these can be accessed within nested blocks within the parent block/function in which the auto variable was declared. However, they can be accessed outside their scope as well using the concept of pointers given here by pointing to the very exact memory location where the variables reside. They are assigned a garbage value by default whenever they are declared. extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. For more information on how extern variables work, have a look at this link. static: This storage class is used to declare static variables which are popularly used while writing programs in C language. Static variables have the property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler. register: This storage class declares register variables that have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free registration is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. If a free registration is not available, these are then stored in the memory only. Usually few variables which are to be accessed very frequently in a program are declared with the register keyword which improves the running time of the program. An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers.
auto: This is the default storage class for all the variables declared inside a function or a block. Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope). Of course, these can be accessed within nested blocks within the parent block/function in which the auto variable was declared. However, they can be accessed outside their scope as well using the concept of pointers given here by pointing to the very exact memory location where the variables reside. They are assigned a garbage value by default whenever they are declared.
extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. For more information on how extern variables work, have a look at this link.
static: This storage class is used to declare static variables which are popularly used while writing programs in C language. Static variables have the property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.
register: This storage class declares register variables that have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free registration is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. If a free registration is not available, these are then stored in the memory only. Usually few variables which are to be accessed very frequently in a program are declared with the register keyword which improves the running time of the program. An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers.
To specify the storage class for a variable, the following syntax is to be followed:Syntax:
storage_class var_data_type var_name;
Functions follow the same syntax as given above for variables. Have a look at the following C example for further clarification:
C
// A C program to demonstrate different storage// classes#include <stdio.h> // declaring the variable which is to be made extern// an initial value can also be initialized to xint x; void autoStorageClass(){ printf("\nDemonstrating auto class\n\n"); // declaring an auto variable (simply // writing "int a=32;" works as well) auto int a = 32; // printing the auto variable 'a' printf("Value of the variable 'a'" " declared as auto: %d\n", a); printf("--------------------------------");} void registerStorageClass(){ printf("\nDemonstrating register class\n\n"); // declaring a register variable register char b = 'G'; // printing the register variable 'b' printf("Value of the variable 'b'" " declared as register: %d\n", b); printf("--------------------------------");} void externStorageClass(){ printf("\nDemonstrating extern class\n\n"); // telling the compiler that the variable // x is an extern variable and has been // defined elsewhere (above the main // function) extern int x; // printing the extern variables 'x' printf("Value of the variable 'x'" " declared as extern: %d\n", x); // value of extern variable x modified x = 2; // printing the modified values of // extern variables 'x' printf("Modified value of the variable 'x'" " declared as extern: %d\n", x); printf("--------------------------------");} void staticStorageClass(){ int i = 0; printf("\nDemonstrating static class\n\n"); // using a static variable 'y' printf("Declaring 'y' as static inside the loop.\n" "But this declaration will occur only" " once as 'y' is static.\n" "If not, then every time the value of 'y' " "will be the declared value 5" " as in the case of variable 'p'\n"); printf("\nLoop started:\n"); for (i = 1; i < 5; i++) { // Declaring the static variable 'y' static int y = 5; // Declare a non-static variable 'p' int p = 10; // Incrementing the value of y and p by 1 y++; p++; // printing value of y at each iteration printf("\nThe value of 'y', " "declared as static, in %d " "iteration is %d\n", i, y); // printing value of p at each iteration printf("The value of non-static variable 'p', " "in %d iteration is %d\n", i, p); } printf("\nLoop ended:\n"); printf("--------------------------------");} int main(){ printf("A program to demonstrate" " Storage Classes in C\n\n"); // To demonstrate auto Storage Class autoStorageClass(); // To demonstrate register Storage Class registerStorageClass(); // To demonstrate extern Storage Class externStorageClass(); // To demonstrate static Storage Class staticStorageClass(); // exiting printf("\n\nStorage Classes demonstrated"); return 0;} // This code is improved by RishabhPrabhu
skbarnwal
RishabhPrabhu
harkiran78
simranarora5sos
kowallivikhyath
kcdobariyayt
C Basics
C-Storage Classes and Type Qualifiers
Veritas
C Language
Veritas
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
Enumeration (or enum) in C
What is the purpose of a function prototype?
C Language Introduction
Command line arguments in C/C++
Operators in C / C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 335,
"s": 54,
"text": "Storage Classes are used to describe the features of a variable/function. These features basically include the scope, visibility and life-time which help us to trace the existence of a particular variable during the runtime of a program.C language uses 4 storage classes, namely: "
},
{
"code": null,
"e": 3402,
"s": 337,
"text": "auto: This is the default storage class for all the variables declared inside a function or a block. Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope). Of course, these can be accessed within nested blocks within the parent block/function in which the auto variable was declared. However, they can be accessed outside their scope as well using the concept of pointers given here by pointing to the very exact memory location where the variables reside. They are assigned a garbage value by default whenever they are declared. extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. For more information on how extern variables work, have a look at this link. static: This storage class is used to declare static variables which are popularly used while writing programs in C language. Static variables have the property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler. register: This storage class declares register variables that have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free registration is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. If a free registration is not available, these are then stored in the memory only. Usually few variables which are to be accessed very frequently in a program are declared with the register keyword which improves the running time of the program. An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers. "
},
{
"code": null,
"e": 4092,
"s": 3402,
"text": "auto: This is the default storage class for all the variables declared inside a function or a block. Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope). Of course, these can be accessed within nested blocks within the parent block/function in which the auto variable was declared. However, they can be accessed outside their scope as well using the concept of pointers given here by pointing to the very exact memory location where the variables reside. They are assigned a garbage value by default whenever they are declared. "
},
{
"code": null,
"e": 5025,
"s": 4092,
"text": "extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. For more information on how extern variables work, have a look at this link. "
},
{
"code": null,
"e": 5684,
"s": 5025,
"text": "static: This storage class is used to declare static variables which are popularly used while writing programs in C language. Static variables have the property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler. "
},
{
"code": null,
"e": 6470,
"s": 5684,
"text": "register: This storage class declares register variables that have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free registration is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. If a free registration is not available, these are then stored in the memory only. Usually few variables which are to be accessed very frequently in a program are declared with the register keyword which improves the running time of the program. An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers. "
},
{
"code": null,
"e": 6563,
"s": 6470,
"text": "To specify the storage class for a variable, the following syntax is to be followed:Syntax: "
},
{
"code": null,
"e": 6602,
"s": 6563,
"text": "storage_class var_data_type var_name; "
},
{
"code": null,
"e": 6733,
"s": 6602,
"text": "Functions follow the same syntax as given above for variables. Have a look at the following C example for further clarification: "
},
{
"code": null,
"e": 6735,
"s": 6733,
"text": "C"
},
{
"code": "// A C program to demonstrate different storage// classes#include <stdio.h> // declaring the variable which is to be made extern// an initial value can also be initialized to xint x; void autoStorageClass(){ printf(\"\\nDemonstrating auto class\\n\\n\"); // declaring an auto variable (simply // writing \"int a=32;\" works as well) auto int a = 32; // printing the auto variable 'a' printf(\"Value of the variable 'a'\" \" declared as auto: %d\\n\", a); printf(\"--------------------------------\");} void registerStorageClass(){ printf(\"\\nDemonstrating register class\\n\\n\"); // declaring a register variable register char b = 'G'; // printing the register variable 'b' printf(\"Value of the variable 'b'\" \" declared as register: %d\\n\", b); printf(\"--------------------------------\");} void externStorageClass(){ printf(\"\\nDemonstrating extern class\\n\\n\"); // telling the compiler that the variable // x is an extern variable and has been // defined elsewhere (above the main // function) extern int x; // printing the extern variables 'x' printf(\"Value of the variable 'x'\" \" declared as extern: %d\\n\", x); // value of extern variable x modified x = 2; // printing the modified values of // extern variables 'x' printf(\"Modified value of the variable 'x'\" \" declared as extern: %d\\n\", x); printf(\"--------------------------------\");} void staticStorageClass(){ int i = 0; printf(\"\\nDemonstrating static class\\n\\n\"); // using a static variable 'y' printf(\"Declaring 'y' as static inside the loop.\\n\" \"But this declaration will occur only\" \" once as 'y' is static.\\n\" \"If not, then every time the value of 'y' \" \"will be the declared value 5\" \" as in the case of variable 'p'\\n\"); printf(\"\\nLoop started:\\n\"); for (i = 1; i < 5; i++) { // Declaring the static variable 'y' static int y = 5; // Declare a non-static variable 'p' int p = 10; // Incrementing the value of y and p by 1 y++; p++; // printing value of y at each iteration printf(\"\\nThe value of 'y', \" \"declared as static, in %d \" \"iteration is %d\\n\", i, y); // printing value of p at each iteration printf(\"The value of non-static variable 'p', \" \"in %d iteration is %d\\n\", i, p); } printf(\"\\nLoop ended:\\n\"); printf(\"--------------------------------\");} int main(){ printf(\"A program to demonstrate\" \" Storage Classes in C\\n\\n\"); // To demonstrate auto Storage Class autoStorageClass(); // To demonstrate register Storage Class registerStorageClass(); // To demonstrate extern Storage Class externStorageClass(); // To demonstrate static Storage Class staticStorageClass(); // exiting printf(\"\\n\\nStorage Classes demonstrated\"); return 0;} // This code is improved by RishabhPrabhu",
"e": 9867,
"s": 6735,
"text": null
},
{
"code": null,
"e": 9877,
"s": 9867,
"text": "skbarnwal"
},
{
"code": null,
"e": 9891,
"s": 9877,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 9902,
"s": 9891,
"text": "harkiran78"
},
{
"code": null,
"e": 9918,
"s": 9902,
"text": "simranarora5sos"
},
{
"code": null,
"e": 9934,
"s": 9918,
"text": "kowallivikhyath"
},
{
"code": null,
"e": 9947,
"s": 9934,
"text": "kcdobariyayt"
},
{
"code": null,
"e": 9956,
"s": 9947,
"text": "C Basics"
},
{
"code": null,
"e": 9994,
"s": 9956,
"text": "C-Storage Classes and Type Qualifiers"
},
{
"code": null,
"e": 10002,
"s": 9994,
"text": "Veritas"
},
{
"code": null,
"e": 10013,
"s": 10002,
"text": "C Language"
},
{
"code": null,
"e": 10021,
"s": 10013,
"text": "Veritas"
},
{
"code": null,
"e": 10119,
"s": 10021,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10136,
"s": 10119,
"text": "Substring in C++"
},
{
"code": null,
"e": 10158,
"s": 10136,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 10203,
"s": 10158,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 10228,
"s": 10203,
"text": "std::string class in C++"
},
{
"code": null,
"e": 10276,
"s": 10228,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 10303,
"s": 10276,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 10348,
"s": 10303,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 10372,
"s": 10348,
"text": "C Language Introduction"
},
{
"code": null,
"e": 10404,
"s": 10372,
"text": "Command line arguments in C/C++"
}
]
|
Plotting a trend graph in Python | 21 Apr, 2021
Prerequisites: Matplotlib
A trend Graph is a graph that is used to show the trends data over a period of time. It describes a functional representation of two variables (x , y). In which the x is the time-dependent variable whereas y is the collected data. The graph can be in shown any form that can be via line chart, Histograms, scatter plot, bar chart, and pie-chart. In python, we can plot these trend graphs by using matplotlib.pyplot library. It is used for plotting a figure for the given data.
The task is simple and straightforward, for plotting any graph we must suffice the basic data requirement after this determine the values of x over the period of time and data collected for y. Plot the graphs for the above-given data.
Given below are various implementations to depict the same:
Example 1:
Python3
# import all the librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt # create a dataframeSports = { "medals": [100, 98, 102, 56, 78, 56, 78, 96], "Time_Period": [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]} df = pd.DataFrame(Sports)print(df) # to plot the graphdf.plot(x="Time_Period", y="medals", kind="line")plt.show()
Output:
medals Time_Period
0 100 2010
1 98 2011
2 102 2012
3 56 2013
4 78 2014
5 56 2015
6 78 2016
7 96 2017
Example 2: Using the above data we would plot the scatter and bar graph.
Python3
# import all the librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt # create a dataframeSports = { "medals": [100, 98, 102, 56, 78, 56, 78, 96], "Time_Period": [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]}df = pd.DataFrame(Sports)print(df) # to plot the graph# subplot (rowno,columno,position) is used# to plot in a single frame.# to plot the scatter graph ,write kind= scatterdf.plot(x="Time_Period", y="medals", kind="scatter")plt.title("scatter chart")plt.subplot(1, 1, 1) # to Plot the graph in Bar chartdf.plot(x="Time_Period", y="medals", kind="bar")plt.title("bar")plt.subplot(1, 1, 2) plt.show()
Output:
Example 3: student getting marks in 2010.
Python3
# import the libraryimport matplotlib.pyplot as plt # Creation of Datax1 = ['math', 'english', 'science', 'Hindi', 'social studies']y1 = [92, 54, 63, 75, 53]y2 = [86, 44, 65, 98, 85] # Plotting the Dataplt.plot(x1, y1, label='Semester1')plt.plot(x1, y2, label='semester2') plt.xlabel('subjects')plt.ylabel('marks')plt.title("marks obtained in 2010") plt.plot(y1, 'o:g', linestyle='--', linewidth='8')plt.plot(y2, 'o:g', linestyle=':', linewidth='8') plt.legend()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 54,
"s": 28,
"text": "Prerequisites: Matplotlib"
},
{
"code": null,
"e": 533,
"s": 54,
"text": "A trend Graph is a graph that is used to show the trends data over a period of time. It describes a functional representation of two variables (x , y). In which the x is the time-dependent variable whereas y is the collected data. The graph can be in shown any form that can be via line chart, Histograms, scatter plot, bar chart, and pie-chart. In python, we can plot these trend graphs by using matplotlib.pyplot library. It is used for plotting a figure for the given data. "
},
{
"code": null,
"e": 768,
"s": 533,
"text": "The task is simple and straightforward, for plotting any graph we must suffice the basic data requirement after this determine the values of x over the period of time and data collected for y. Plot the graphs for the above-given data."
},
{
"code": null,
"e": 828,
"s": 768,
"text": "Given below are various implementations to depict the same:"
},
{
"code": null,
"e": 839,
"s": 828,
"text": "Example 1:"
},
{
"code": null,
"e": 847,
"s": 839,
"text": "Python3"
},
{
"code": "# import all the librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt # create a dataframeSports = { \"medals\": [100, 98, 102, 56, 78, 56, 78, 96], \"Time_Period\": [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]} df = pd.DataFrame(Sports)print(df) # to plot the graphdf.plot(x=\"Time_Period\", y=\"medals\", kind=\"line\")plt.show()",
"e": 1207,
"s": 847,
"text": null
},
{
"code": null,
"e": 1215,
"s": 1207,
"text": "Output:"
},
{
"code": null,
"e": 1422,
"s": 1215,
"text": " medals Time_Period\n0 100 2010\n1 98 2011\n2 102 2012\n3 56 2013\n4 78 2014\n5 56 2015\n6 78 2016\n7 96 2017"
},
{
"code": null,
"e": 1572,
"s": 1499,
"text": "Example 2: Using the above data we would plot the scatter and bar graph."
},
{
"code": null,
"e": 1580,
"s": 1572,
"text": "Python3"
},
{
"code": "# import all the librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt # create a dataframeSports = { \"medals\": [100, 98, 102, 56, 78, 56, 78, 96], \"Time_Period\": [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]}df = pd.DataFrame(Sports)print(df) # to plot the graph# subplot (rowno,columno,position) is used# to plot in a single frame.# to plot the scatter graph ,write kind= scatterdf.plot(x=\"Time_Period\", y=\"medals\", kind=\"scatter\")plt.title(\"scatter chart\")plt.subplot(1, 1, 1) # to Plot the graph in Bar chartdf.plot(x=\"Time_Period\", y=\"medals\", kind=\"bar\")plt.title(\"bar\")plt.subplot(1, 1, 2) plt.show()",
"e": 2266,
"s": 1580,
"text": null
},
{
"code": null,
"e": 2274,
"s": 2266,
"text": "Output:"
},
{
"code": null,
"e": 2316,
"s": 2274,
"text": "Example 3: student getting marks in 2010."
},
{
"code": null,
"e": 2324,
"s": 2316,
"text": "Python3"
},
{
"code": "# import the libraryimport matplotlib.pyplot as plt # Creation of Datax1 = ['math', 'english', 'science', 'Hindi', 'social studies']y1 = [92, 54, 63, 75, 53]y2 = [86, 44, 65, 98, 85] # Plotting the Dataplt.plot(x1, y1, label='Semester1')plt.plot(x1, y2, label='semester2') plt.xlabel('subjects')plt.ylabel('marks')plt.title(\"marks obtained in 2010\") plt.plot(y1, 'o:g', linestyle='--', linewidth='8')plt.plot(y2, 'o:g', linestyle=':', linewidth='8') plt.legend()",
"e": 2794,
"s": 2324,
"text": null
},
{
"code": null,
"e": 2802,
"s": 2794,
"text": "Output:"
},
{
"code": null,
"e": 2809,
"s": 2802,
"text": "Picked"
},
{
"code": null,
"e": 2827,
"s": 2809,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2834,
"s": 2827,
"text": "Python"
}
]
|
Tailwind CSS - GeeksforGeeks | 24 Mar, 2022
Tailwind CSS is basically a Utility first CSS framework for building rapid custom UI. It is a highly customizable, low-level CSS framework that gives you all of the building blocks that you need. Also, it is a cool way to write inline styling and achieve an awesome interface without writing a single line of your own CSS.
Why Tailwind CSS ?
As we know there are many CSS frameworks but people always choose the fast and easy framework to learn and use in the project. Tailwind has come with inbuilt a lot of features and styles for users to choose from and is also used to reduce the tendency of writing CSS code and create a beautiful custom UI. It will help you to overcome the complicated task. Tailwind CSS creates small utilities with a defined set of options enabling easy integration of existing classes directly into the HTML code.
Installation of Tailwind CSS:
Basically Tailwind is available on npm and you can install it using following command:
npm install tailwindcss
After that create ad Tailwind configuration file using the following command:
npm tailwind init {name of file}
or
You can install tailwind by using the yarn command:
yarn add tailwindcss
After that create ad Tailwind configuration file using the following command:
yarn tailwind init {name of file}
Example: It is a basic example of Tailwind CSS that describe how to change background color on mouse hover.
Output:
Advantages:
Highly Customizable.
Enables building complex responsive layout.
Responsive and development is easy.
Components creation is easy.
Disadvantages:
There is missing headers, navigation components.
It take time to learn how to implement inbuilt classes.
Learn more about Tailwind CSS:
Tailwind CSS BasicsIntroduction to Tailwind CSS
Tailwind CSS Basics
Introduction to Tailwind CSS
Introduction to Tailwind CSS
Tailwind CSS AccessibilityTailwind CSS Screen Readers
Tailwind CSS Accessibility
Tailwind CSS Screen Readers
Tailwind CSS AlignmentTailwind CSS Justify ContentTailwind CSS Justify ItemsTailwind CSS Justify SelfTailwind CSS Align ContentTailwind CSS Align ItemsTailwind CSS Align SelfTailwind CSS Place ContentTailwind CSS Place ItemsTailwind CSS Place Self
Tailwind CSS Alignment
Tailwind CSS Justify Content
Tailwind CSS Justify Items
Tailwind CSS Justify Self
Tailwind CSS Align Content
Tailwind CSS Align Items
Tailwind CSS Align Self
Tailwind CSS Place Content
Tailwind CSS Place Items
Tailwind CSS Place Self
Tailwind CSS BackgroundsTailwind CSS Background ImageTailwind CSS Background ClipTailwind CSS Background ColorTailwind CSS Background OpacityTailwind CSS Background PositionTailwind CSS Background RepeatTailwind CSS Background SizeTailwind CSS Gradient Color Stops
Tailwind CSS Backgrounds
Tailwind CSS Background Image
Tailwind CSS Background Clip
Tailwind CSS Background Color
Tailwind CSS Background Opacity
Tailwind CSS Background Position
Tailwind CSS Background Repeat
Tailwind CSS Background Size
Tailwind CSS Gradient Color Stops
Tailwind CSS BordersTailwind CSS Border RadiusTailwind CSS Border WidthTailwind CSS Border ColorTailwind CSS Border OpacityTailwind CSS Border StyleTailwind CSS Divide WidthTailwind CSS Divide ColorTailwind CSS Divide OpacityTailwind CSS Divide StyleTailwind CSS Divide WidthTailwind CSS Divide ColorTailwind CSS Divide OpacityTailwind CSS Divide StyleTailwind CSS Ring WidthTailwind CSS Ring ColorTailwind CSS Ring OpacityTailwind CSS Ring Offset WidthTailwind CSS Ring Offset Color
Tailwind CSS Borders
Tailwind CSS Border Radius
Tailwind CSS Border Width
Tailwind CSS Border Color
Tailwind CSS Border Opacity
Tailwind CSS Border Style
Tailwind CSS Divide Width
Tailwind CSS Divide Color
Tailwind CSS Divide Opacity
Tailwind CSS Divide Style
Tailwind CSS Divide Width
Tailwind CSS Divide Color
Tailwind CSS Divide Opacity
Tailwind CSS Divide Style
Tailwind CSS Ring Width
Tailwind CSS Ring Color
Tailwind CSS Ring Opacity
Tailwind CSS Ring Offset Width
Tailwind CSS Ring Offset Color
Tailwind CSS EffectsTailwind CSS Box ShadowTailwind CSS Opacity
Tailwind CSS Effects
Tailwind CSS Box Shadow
Tailwind CSS Opacity
Tailwind FiltersTailwind CSS FilterTailwind CSS BlurTailwind CSS BrightnessTailwind CSS ContrastTailwind CSS Drop ShadowTailwind CSS GrayscaleTailwind CSS Hue RotateTailwind CSS InvertTailwind CSS SaturateTailwind CSS SepiaTailwind CSS Backdrop FilterTailwind CSS Backdrop BlurTailwind CSS Backdrop BrightnessTailwind CSS Backdrop ContrastTailwind CSS Backdrop GrayscaleTailwind CSS Backdrop Hue RotateTailwind CSS Backdrop InvertTailwind CSS Backdrop OpacityTailwind CSS Backdrop SaturateTailwind CSS Backdrop Sepia
Tailwind Filters
Tailwind CSS Filter
Tailwind CSS Blur
Tailwind CSS Brightness
Tailwind CSS Contrast
Tailwind CSS Drop Shadow
Tailwind CSS Grayscale
Tailwind CSS Hue Rotate
Tailwind CSS Invert
Tailwind CSS Saturate
Tailwind CSS Sepia
Tailwind CSS Backdrop Filter
Tailwind CSS Backdrop Blur
Tailwind CSS Backdrop Brightness
Tailwind CSS Backdrop Contrast
Tailwind CSS Backdrop Grayscale
Tailwind CSS Backdrop Hue Rotate
Tailwind CSS Backdrop Invert
Tailwind CSS Backdrop Opacity
Tailwind CSS Backdrop Saturate
Tailwind CSS Backdrop Sepia
Tailwind CSS FlexboxTailwind CSS Flex DirectionTailwind CSS Flex WrapTailwind CSS FlexTailwind CSS Flex GrowTailwind CSS Flex ShrinkTailwind CSS Order
Tailwind CSS Flexbox
Tailwind CSS Flex Direction
Tailwind CSS Flex Wrap
Tailwind CSS Flex
Tailwind CSS Flex Grow
Tailwind CSS Flex Shrink
Tailwind CSS Order
Tailwind CSS GridTailwind CSS Grid Template ColumnsTailwind CSS Grid Column Start / EndTailwind CSS Grid Template RowsTailwind CSS Grid Row Start / EndTailwind CSS Grid Auto FlowTailwind CSS Grid Auto ColumnsTailwind CSS Grid Auto Rows
Tailwind CSS Grid
Tailwind CSS Grid Template Columns
Tailwind CSS Grid Column Start / End
Tailwind CSS Grid Template Rows
Tailwind CSS Grid Row Start / End
Tailwind CSS Grid Auto Flow
Tailwind CSS Grid Auto Columns
Tailwind CSS Grid Auto Rows
Tailwind CSS InteractivityTailwind CSS AppearanceTailwind CSS CursorTailwind CSS OutlineTailwind CSS Pointer EventsTailwind CSS ResizeTailwind CSS User Select
Tailwind CSS Interactivity
Tailwind CSS Appearance
Tailwind CSS Cursor
Tailwind CSS Outline
Tailwind CSS Pointer Events
Tailwind CSS Resize
Tailwind CSS User Select
Tailwind CSS LayoutTailwind CSS Box SizingTailwind CSS DisplayTailwind CSS FloatTailwind CSS ClearTailwind CSS Object FitTailwind CSS Object PositionTailwind CSS OverflowTailwind CSS overscroll BehaviorTailwind CSS PositionTailwind CSS Top/Right/Bottom/LeftTailwind CSS VisibilityTailwind CSS Z-index
Tailwind CSS Layout
Tailwind CSS Box Sizing
Tailwind CSS Display
Tailwind CSS Float
Tailwind CSS Clear
Tailwind CSS Object Fit
Tailwind CSS Object Position
Tailwind CSS Overflow
Tailwind CSS overscroll Behavior
Tailwind CSS Position
Tailwind CSS Top/Right/Bottom/Left
Tailwind CSS Visibility
Tailwind CSS Z-index
Tailwind CSS SizingTailwind CSS WidthTailwind CSS Min-WidthTailwind CSS Max-WidthTailwind CSS HeightTailwind CSS Min-HeightTailwind CSS Max-Height
Tailwind CSS Sizing
Tailwind CSS Width
Tailwind CSS Min-Width
Tailwind CSS Max-Width
Tailwind CSS Height
Tailwind CSS Min-Height
Tailwind CSS Max-Height
Tailwind CSS SpacingTailwind CSS PaddingTailwind CSS MarginTailwind CSS Space Between
Tailwind CSS Spacing
Tailwind CSS Padding
Tailwind CSS Margin
Tailwind CSS Space Between
Tailwind CSS SVGTailwind CSS FillTailwind CSS StrokeTailwind CSS Stroke Width
Tailwind CSS SVG
Tailwind CSS Fill
Tailwind CSS Stroke
Tailwind CSS Stroke Width
Tailwind CSS TypographyTailwind CSS Font FamilyTailwind CSS Font SizeTailwind CSS Font SmoothingTailwind CSS Font StyleTailwind CSS Font WeightTailwind CSS Font Variant NumericTailwind CSS Letter SpacingTailwind CSS Line HeightTailwind CSS List Style TypeTailwind CSS Placeholder ColorTailwind CSS Placeholder OpacityTailwind CSS Text AlignmentTailwind CSS Text AlignmentTailwind CSS Text ColorTailwind CSS Text OpacityTailwind CSS Text DecorationTailwind CSS Text TransformTailwind CSS Text TransformTailwind CSS Vertical AlignmentTailwind CSS WhitespaceTailwind CSS Word Break
Tailwind CSS Typography
Tailwind CSS Font Family
Tailwind CSS Font Size
Tailwind CSS Font Smoothing
Tailwind CSS Font Style
Tailwind CSS Font Weight
Tailwind CSS Font Variant Numeric
Tailwind CSS Letter Spacing
Tailwind CSS Line Height
Tailwind CSS List Style Type
Tailwind CSS Placeholder Color
Tailwind CSS Placeholder Opacity
Tailwind CSS Text Alignment
Tailwind CSS Text Alignment
Tailwind CSS Text Color
Tailwind CSS Text Opacity
Tailwind CSS Text Decoration
Tailwind CSS Text Transform
Tailwind CSS Text Transform
Tailwind CSS Vertical Alignment
Tailwind CSS Whitespace
Tailwind CSS Word Break
Tailwind CSS TablesTailwind CSS Border CollapseTailwind CSS Table Layout
Tailwind CSS Tables
Tailwind CSS Border Collapse
Tailwind CSS Table Layout
Tailwind CSS Transitions and AnimationTailwind CSS Transition PropertyTailwind CSS Transition DurationTailwind CSS Transition Timing FunctionTailwind CSS Transition Delay
Tailwind CSS Transitions and Animation
Tailwind CSS Transition Property
Tailwind CSS Transition Duration
Tailwind CSS Transition Timing Function
Tailwind CSS Transition Delay
Tailwind CSS TransformsTailwind CSS TransformTailwind CSS Transform OriginTailwind CSS ScaleTailwind CSS RotateTailwind CSS Translate
Tailwind CSS Transforms
Tailwind CSS Transform
Tailwind CSS Transform Origin
Tailwind CSS Scale
Tailwind CSS Rotate
Tailwind CSS Translate
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Floyd’s Cycle Finding Algorithm
Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!
Spring Boot - Annotations
How to Add External JAR File to an IntelliJ IDEA Project?
How to navigate on path by button click in react router ?
How to Install Git in VS Code?
Git - Difference Between Git Fetch and Git Pull
Unit Testing in Spring Boot Project using Mockito and Junit | [
{
"code": null,
"e": 24903,
"s": 24875,
"text": "\n24 Mar, 2022"
},
{
"code": null,
"e": 25226,
"s": 24903,
"text": "Tailwind CSS is basically a Utility first CSS framework for building rapid custom UI. It is a highly customizable, low-level CSS framework that gives you all of the building blocks that you need. Also, it is a cool way to write inline styling and achieve an awesome interface without writing a single line of your own CSS."
},
{
"code": null,
"e": 25245,
"s": 25226,
"text": "Why Tailwind CSS ?"
},
{
"code": null,
"e": 25744,
"s": 25245,
"text": "As we know there are many CSS frameworks but people always choose the fast and easy framework to learn and use in the project. Tailwind has come with inbuilt a lot of features and styles for users to choose from and is also used to reduce the tendency of writing CSS code and create a beautiful custom UI. It will help you to overcome the complicated task. Tailwind CSS creates small utilities with a defined set of options enabling easy integration of existing classes directly into the HTML code."
},
{
"code": null,
"e": 25776,
"s": 25746,
"text": "Installation of Tailwind CSS:"
},
{
"code": null,
"e": 25863,
"s": 25776,
"text": "Basically Tailwind is available on npm and you can install it using following command:"
},
{
"code": null,
"e": 25887,
"s": 25863,
"text": "npm install tailwindcss"
},
{
"code": null,
"e": 25965,
"s": 25887,
"text": "After that create ad Tailwind configuration file using the following command:"
},
{
"code": null,
"e": 25998,
"s": 25965,
"text": "npm tailwind init {name of file}"
},
{
"code": null,
"e": 26001,
"s": 25998,
"text": "or"
},
{
"code": null,
"e": 26053,
"s": 26001,
"text": "You can install tailwind by using the yarn command:"
},
{
"code": null,
"e": 26074,
"s": 26053,
"text": "yarn add tailwindcss"
},
{
"code": null,
"e": 26152,
"s": 26074,
"text": "After that create ad Tailwind configuration file using the following command:"
},
{
"code": null,
"e": 26186,
"s": 26152,
"text": "yarn tailwind init {name of file}"
},
{
"code": null,
"e": 26294,
"s": 26186,
"text": "Example: It is a basic example of Tailwind CSS that describe how to change background color on mouse hover."
},
{
"code": null,
"e": 26304,
"s": 26296,
"text": "Output:"
},
{
"code": null,
"e": 26316,
"s": 26304,
"text": "Advantages:"
},
{
"code": null,
"e": 26337,
"s": 26316,
"text": "Highly Customizable."
},
{
"code": null,
"e": 26381,
"s": 26337,
"text": "Enables building complex responsive layout."
},
{
"code": null,
"e": 26417,
"s": 26381,
"text": "Responsive and development is easy."
},
{
"code": null,
"e": 26446,
"s": 26417,
"text": "Components creation is easy."
},
{
"code": null,
"e": 26461,
"s": 26446,
"text": "Disadvantages:"
},
{
"code": null,
"e": 26510,
"s": 26461,
"text": "There is missing headers, navigation components."
},
{
"code": null,
"e": 26566,
"s": 26510,
"text": "It take time to learn how to implement inbuilt classes."
},
{
"code": null,
"e": 26597,
"s": 26566,
"text": "Learn more about Tailwind CSS:"
},
{
"code": null,
"e": 26645,
"s": 26597,
"text": "Tailwind CSS BasicsIntroduction to Tailwind CSS"
},
{
"code": null,
"e": 26665,
"s": 26645,
"text": "Tailwind CSS Basics"
},
{
"code": null,
"e": 26694,
"s": 26665,
"text": "Introduction to Tailwind CSS"
},
{
"code": null,
"e": 26723,
"s": 26694,
"text": "Introduction to Tailwind CSS"
},
{
"code": null,
"e": 26777,
"s": 26723,
"text": "Tailwind CSS AccessibilityTailwind CSS Screen Readers"
},
{
"code": null,
"e": 26804,
"s": 26777,
"text": "Tailwind CSS Accessibility"
},
{
"code": null,
"e": 26832,
"s": 26804,
"text": "Tailwind CSS Screen Readers"
},
{
"code": null,
"e": 27080,
"s": 26832,
"text": "Tailwind CSS AlignmentTailwind CSS Justify ContentTailwind CSS Justify ItemsTailwind CSS Justify SelfTailwind CSS Align ContentTailwind CSS Align ItemsTailwind CSS Align SelfTailwind CSS Place ContentTailwind CSS Place ItemsTailwind CSS Place Self"
},
{
"code": null,
"e": 27103,
"s": 27080,
"text": "Tailwind CSS Alignment"
},
{
"code": null,
"e": 27132,
"s": 27103,
"text": "Tailwind CSS Justify Content"
},
{
"code": null,
"e": 27159,
"s": 27132,
"text": "Tailwind CSS Justify Items"
},
{
"code": null,
"e": 27185,
"s": 27159,
"text": "Tailwind CSS Justify Self"
},
{
"code": null,
"e": 27212,
"s": 27185,
"text": "Tailwind CSS Align Content"
},
{
"code": null,
"e": 27237,
"s": 27212,
"text": "Tailwind CSS Align Items"
},
{
"code": null,
"e": 27261,
"s": 27237,
"text": "Tailwind CSS Align Self"
},
{
"code": null,
"e": 27288,
"s": 27261,
"text": "Tailwind CSS Place Content"
},
{
"code": null,
"e": 27313,
"s": 27288,
"text": "Tailwind CSS Place Items"
},
{
"code": null,
"e": 27337,
"s": 27313,
"text": "Tailwind CSS Place Self"
},
{
"code": null,
"e": 27602,
"s": 27337,
"text": "Tailwind CSS BackgroundsTailwind CSS Background ImageTailwind CSS Background ClipTailwind CSS Background ColorTailwind CSS Background OpacityTailwind CSS Background PositionTailwind CSS Background RepeatTailwind CSS Background SizeTailwind CSS Gradient Color Stops"
},
{
"code": null,
"e": 27627,
"s": 27602,
"text": "Tailwind CSS Backgrounds"
},
{
"code": null,
"e": 27657,
"s": 27627,
"text": "Tailwind CSS Background Image"
},
{
"code": null,
"e": 27686,
"s": 27657,
"text": "Tailwind CSS Background Clip"
},
{
"code": null,
"e": 27716,
"s": 27686,
"text": "Tailwind CSS Background Color"
},
{
"code": null,
"e": 27748,
"s": 27716,
"text": "Tailwind CSS Background Opacity"
},
{
"code": null,
"e": 27781,
"s": 27748,
"text": "Tailwind CSS Background Position"
},
{
"code": null,
"e": 27812,
"s": 27781,
"text": "Tailwind CSS Background Repeat"
},
{
"code": null,
"e": 27841,
"s": 27812,
"text": "Tailwind CSS Background Size"
},
{
"code": null,
"e": 27875,
"s": 27841,
"text": "Tailwind CSS Gradient Color Stops"
},
{
"code": null,
"e": 28361,
"s": 27877,
"text": "Tailwind CSS BordersTailwind CSS Border RadiusTailwind CSS Border WidthTailwind CSS Border ColorTailwind CSS Border OpacityTailwind CSS Border StyleTailwind CSS Divide WidthTailwind CSS Divide ColorTailwind CSS Divide OpacityTailwind CSS Divide StyleTailwind CSS Divide WidthTailwind CSS Divide ColorTailwind CSS Divide OpacityTailwind CSS Divide StyleTailwind CSS Ring WidthTailwind CSS Ring ColorTailwind CSS Ring OpacityTailwind CSS Ring Offset WidthTailwind CSS Ring Offset Color"
},
{
"code": null,
"e": 28382,
"s": 28361,
"text": "Tailwind CSS Borders"
},
{
"code": null,
"e": 28409,
"s": 28382,
"text": "Tailwind CSS Border Radius"
},
{
"code": null,
"e": 28435,
"s": 28409,
"text": "Tailwind CSS Border Width"
},
{
"code": null,
"e": 28461,
"s": 28435,
"text": "Tailwind CSS Border Color"
},
{
"code": null,
"e": 28489,
"s": 28461,
"text": "Tailwind CSS Border Opacity"
},
{
"code": null,
"e": 28515,
"s": 28489,
"text": "Tailwind CSS Border Style"
},
{
"code": null,
"e": 28541,
"s": 28515,
"text": "Tailwind CSS Divide Width"
},
{
"code": null,
"e": 28567,
"s": 28541,
"text": "Tailwind CSS Divide Color"
},
{
"code": null,
"e": 28595,
"s": 28567,
"text": "Tailwind CSS Divide Opacity"
},
{
"code": null,
"e": 28621,
"s": 28595,
"text": "Tailwind CSS Divide Style"
},
{
"code": null,
"e": 28647,
"s": 28621,
"text": "Tailwind CSS Divide Width"
},
{
"code": null,
"e": 28673,
"s": 28647,
"text": "Tailwind CSS Divide Color"
},
{
"code": null,
"e": 28701,
"s": 28673,
"text": "Tailwind CSS Divide Opacity"
},
{
"code": null,
"e": 28727,
"s": 28701,
"text": "Tailwind CSS Divide Style"
},
{
"code": null,
"e": 28751,
"s": 28727,
"text": "Tailwind CSS Ring Width"
},
{
"code": null,
"e": 28775,
"s": 28751,
"text": "Tailwind CSS Ring Color"
},
{
"code": null,
"e": 28801,
"s": 28775,
"text": "Tailwind CSS Ring Opacity"
},
{
"code": null,
"e": 28832,
"s": 28801,
"text": "Tailwind CSS Ring Offset Width"
},
{
"code": null,
"e": 28863,
"s": 28832,
"text": "Tailwind CSS Ring Offset Color"
},
{
"code": null,
"e": 28927,
"s": 28863,
"text": "Tailwind CSS EffectsTailwind CSS Box ShadowTailwind CSS Opacity"
},
{
"code": null,
"e": 28948,
"s": 28927,
"text": "Tailwind CSS Effects"
},
{
"code": null,
"e": 28972,
"s": 28948,
"text": "Tailwind CSS Box Shadow"
},
{
"code": null,
"e": 28993,
"s": 28972,
"text": "Tailwind CSS Opacity"
},
{
"code": null,
"e": 29510,
"s": 28993,
"text": "Tailwind FiltersTailwind CSS FilterTailwind CSS BlurTailwind CSS BrightnessTailwind CSS ContrastTailwind CSS Drop ShadowTailwind CSS GrayscaleTailwind CSS Hue RotateTailwind CSS InvertTailwind CSS SaturateTailwind CSS SepiaTailwind CSS Backdrop FilterTailwind CSS Backdrop BlurTailwind CSS Backdrop BrightnessTailwind CSS Backdrop ContrastTailwind CSS Backdrop GrayscaleTailwind CSS Backdrop Hue RotateTailwind CSS Backdrop InvertTailwind CSS Backdrop OpacityTailwind CSS Backdrop SaturateTailwind CSS Backdrop Sepia"
},
{
"code": null,
"e": 29527,
"s": 29510,
"text": "Tailwind Filters"
},
{
"code": null,
"e": 29547,
"s": 29527,
"text": "Tailwind CSS Filter"
},
{
"code": null,
"e": 29565,
"s": 29547,
"text": "Tailwind CSS Blur"
},
{
"code": null,
"e": 29589,
"s": 29565,
"text": "Tailwind CSS Brightness"
},
{
"code": null,
"e": 29611,
"s": 29589,
"text": "Tailwind CSS Contrast"
},
{
"code": null,
"e": 29636,
"s": 29611,
"text": "Tailwind CSS Drop Shadow"
},
{
"code": null,
"e": 29659,
"s": 29636,
"text": "Tailwind CSS Grayscale"
},
{
"code": null,
"e": 29683,
"s": 29659,
"text": "Tailwind CSS Hue Rotate"
},
{
"code": null,
"e": 29703,
"s": 29683,
"text": "Tailwind CSS Invert"
},
{
"code": null,
"e": 29725,
"s": 29703,
"text": "Tailwind CSS Saturate"
},
{
"code": null,
"e": 29744,
"s": 29725,
"text": "Tailwind CSS Sepia"
},
{
"code": null,
"e": 29773,
"s": 29744,
"text": "Tailwind CSS Backdrop Filter"
},
{
"code": null,
"e": 29800,
"s": 29773,
"text": "Tailwind CSS Backdrop Blur"
},
{
"code": null,
"e": 29833,
"s": 29800,
"text": "Tailwind CSS Backdrop Brightness"
},
{
"code": null,
"e": 29864,
"s": 29833,
"text": "Tailwind CSS Backdrop Contrast"
},
{
"code": null,
"e": 29896,
"s": 29864,
"text": "Tailwind CSS Backdrop Grayscale"
},
{
"code": null,
"e": 29929,
"s": 29896,
"text": "Tailwind CSS Backdrop Hue Rotate"
},
{
"code": null,
"e": 29958,
"s": 29929,
"text": "Tailwind CSS Backdrop Invert"
},
{
"code": null,
"e": 29988,
"s": 29958,
"text": "Tailwind CSS Backdrop Opacity"
},
{
"code": null,
"e": 30019,
"s": 29988,
"text": "Tailwind CSS Backdrop Saturate"
},
{
"code": null,
"e": 30047,
"s": 30019,
"text": "Tailwind CSS Backdrop Sepia"
},
{
"code": null,
"e": 30198,
"s": 30047,
"text": "Tailwind CSS FlexboxTailwind CSS Flex DirectionTailwind CSS Flex WrapTailwind CSS FlexTailwind CSS Flex GrowTailwind CSS Flex ShrinkTailwind CSS Order"
},
{
"code": null,
"e": 30219,
"s": 30198,
"text": "Tailwind CSS Flexbox"
},
{
"code": null,
"e": 30247,
"s": 30219,
"text": "Tailwind CSS Flex Direction"
},
{
"code": null,
"e": 30270,
"s": 30247,
"text": "Tailwind CSS Flex Wrap"
},
{
"code": null,
"e": 30288,
"s": 30270,
"text": "Tailwind CSS Flex"
},
{
"code": null,
"e": 30311,
"s": 30288,
"text": "Tailwind CSS Flex Grow"
},
{
"code": null,
"e": 30336,
"s": 30311,
"text": "Tailwind CSS Flex Shrink"
},
{
"code": null,
"e": 30355,
"s": 30336,
"text": "Tailwind CSS Order"
},
{
"code": null,
"e": 30591,
"s": 30355,
"text": "Tailwind CSS GridTailwind CSS Grid Template ColumnsTailwind CSS Grid Column Start / EndTailwind CSS Grid Template RowsTailwind CSS Grid Row Start / EndTailwind CSS Grid Auto FlowTailwind CSS Grid Auto ColumnsTailwind CSS Grid Auto Rows"
},
{
"code": null,
"e": 30609,
"s": 30591,
"text": "Tailwind CSS Grid"
},
{
"code": null,
"e": 30644,
"s": 30609,
"text": "Tailwind CSS Grid Template Columns"
},
{
"code": null,
"e": 30681,
"s": 30644,
"text": "Tailwind CSS Grid Column Start / End"
},
{
"code": null,
"e": 30713,
"s": 30681,
"text": "Tailwind CSS Grid Template Rows"
},
{
"code": null,
"e": 30747,
"s": 30713,
"text": "Tailwind CSS Grid Row Start / End"
},
{
"code": null,
"e": 30775,
"s": 30747,
"text": "Tailwind CSS Grid Auto Flow"
},
{
"code": null,
"e": 30806,
"s": 30775,
"text": "Tailwind CSS Grid Auto Columns"
},
{
"code": null,
"e": 30834,
"s": 30806,
"text": "Tailwind CSS Grid Auto Rows"
},
{
"code": null,
"e": 30993,
"s": 30834,
"text": "Tailwind CSS InteractivityTailwind CSS AppearanceTailwind CSS CursorTailwind CSS OutlineTailwind CSS Pointer EventsTailwind CSS ResizeTailwind CSS User Select"
},
{
"code": null,
"e": 31020,
"s": 30993,
"text": "Tailwind CSS Interactivity"
},
{
"code": null,
"e": 31044,
"s": 31020,
"text": "Tailwind CSS Appearance"
},
{
"code": null,
"e": 31064,
"s": 31044,
"text": "Tailwind CSS Cursor"
},
{
"code": null,
"e": 31085,
"s": 31064,
"text": "Tailwind CSS Outline"
},
{
"code": null,
"e": 31113,
"s": 31085,
"text": "Tailwind CSS Pointer Events"
},
{
"code": null,
"e": 31133,
"s": 31113,
"text": "Tailwind CSS Resize"
},
{
"code": null,
"e": 31158,
"s": 31133,
"text": "Tailwind CSS User Select"
},
{
"code": null,
"e": 31459,
"s": 31158,
"text": "Tailwind CSS LayoutTailwind CSS Box SizingTailwind CSS DisplayTailwind CSS FloatTailwind CSS ClearTailwind CSS Object FitTailwind CSS Object PositionTailwind CSS OverflowTailwind CSS overscroll BehaviorTailwind CSS PositionTailwind CSS Top/Right/Bottom/LeftTailwind CSS VisibilityTailwind CSS Z-index"
},
{
"code": null,
"e": 31479,
"s": 31459,
"text": "Tailwind CSS Layout"
},
{
"code": null,
"e": 31503,
"s": 31479,
"text": "Tailwind CSS Box Sizing"
},
{
"code": null,
"e": 31524,
"s": 31503,
"text": "Tailwind CSS Display"
},
{
"code": null,
"e": 31543,
"s": 31524,
"text": "Tailwind CSS Float"
},
{
"code": null,
"e": 31562,
"s": 31543,
"text": "Tailwind CSS Clear"
},
{
"code": null,
"e": 31586,
"s": 31562,
"text": "Tailwind CSS Object Fit"
},
{
"code": null,
"e": 31615,
"s": 31586,
"text": "Tailwind CSS Object Position"
},
{
"code": null,
"e": 31637,
"s": 31615,
"text": "Tailwind CSS Overflow"
},
{
"code": null,
"e": 31670,
"s": 31637,
"text": "Tailwind CSS overscroll Behavior"
},
{
"code": null,
"e": 31692,
"s": 31670,
"text": "Tailwind CSS Position"
},
{
"code": null,
"e": 31727,
"s": 31692,
"text": "Tailwind CSS Top/Right/Bottom/Left"
},
{
"code": null,
"e": 31751,
"s": 31727,
"text": "Tailwind CSS Visibility"
},
{
"code": null,
"e": 31772,
"s": 31751,
"text": "Tailwind CSS Z-index"
},
{
"code": null,
"e": 31919,
"s": 31772,
"text": "Tailwind CSS SizingTailwind CSS WidthTailwind CSS Min-WidthTailwind CSS Max-WidthTailwind CSS HeightTailwind CSS Min-HeightTailwind CSS Max-Height"
},
{
"code": null,
"e": 31939,
"s": 31919,
"text": "Tailwind CSS Sizing"
},
{
"code": null,
"e": 31958,
"s": 31939,
"text": "Tailwind CSS Width"
},
{
"code": null,
"e": 31981,
"s": 31958,
"text": "Tailwind CSS Min-Width"
},
{
"code": null,
"e": 32004,
"s": 31981,
"text": "Tailwind CSS Max-Width"
},
{
"code": null,
"e": 32024,
"s": 32004,
"text": "Tailwind CSS Height"
},
{
"code": null,
"e": 32048,
"s": 32024,
"text": "Tailwind CSS Min-Height"
},
{
"code": null,
"e": 32072,
"s": 32048,
"text": "Tailwind CSS Max-Height"
},
{
"code": null,
"e": 32158,
"s": 32072,
"text": "Tailwind CSS SpacingTailwind CSS PaddingTailwind CSS MarginTailwind CSS Space Between"
},
{
"code": null,
"e": 32179,
"s": 32158,
"text": "Tailwind CSS Spacing"
},
{
"code": null,
"e": 32200,
"s": 32179,
"text": "Tailwind CSS Padding"
},
{
"code": null,
"e": 32220,
"s": 32200,
"text": "Tailwind CSS Margin"
},
{
"code": null,
"e": 32247,
"s": 32220,
"text": "Tailwind CSS Space Between"
},
{
"code": null,
"e": 32325,
"s": 32247,
"text": "Tailwind CSS SVGTailwind CSS FillTailwind CSS StrokeTailwind CSS Stroke Width"
},
{
"code": null,
"e": 32342,
"s": 32325,
"text": "Tailwind CSS SVG"
},
{
"code": null,
"e": 32360,
"s": 32342,
"text": "Tailwind CSS Fill"
},
{
"code": null,
"e": 32380,
"s": 32360,
"text": "Tailwind CSS Stroke"
},
{
"code": null,
"e": 32406,
"s": 32380,
"text": "Tailwind CSS Stroke Width"
},
{
"code": null,
"e": 32985,
"s": 32406,
"text": "Tailwind CSS TypographyTailwind CSS Font FamilyTailwind CSS Font SizeTailwind CSS Font SmoothingTailwind CSS Font StyleTailwind CSS Font WeightTailwind CSS Font Variant NumericTailwind CSS Letter SpacingTailwind CSS Line HeightTailwind CSS List Style TypeTailwind CSS Placeholder ColorTailwind CSS Placeholder OpacityTailwind CSS Text AlignmentTailwind CSS Text AlignmentTailwind CSS Text ColorTailwind CSS Text OpacityTailwind CSS Text DecorationTailwind CSS Text TransformTailwind CSS Text TransformTailwind CSS Vertical AlignmentTailwind CSS WhitespaceTailwind CSS Word Break"
},
{
"code": null,
"e": 33009,
"s": 32985,
"text": "Tailwind CSS Typography"
},
{
"code": null,
"e": 33034,
"s": 33009,
"text": "Tailwind CSS Font Family"
},
{
"code": null,
"e": 33057,
"s": 33034,
"text": "Tailwind CSS Font Size"
},
{
"code": null,
"e": 33085,
"s": 33057,
"text": "Tailwind CSS Font Smoothing"
},
{
"code": null,
"e": 33109,
"s": 33085,
"text": "Tailwind CSS Font Style"
},
{
"code": null,
"e": 33134,
"s": 33109,
"text": "Tailwind CSS Font Weight"
},
{
"code": null,
"e": 33168,
"s": 33134,
"text": "Tailwind CSS Font Variant Numeric"
},
{
"code": null,
"e": 33196,
"s": 33168,
"text": "Tailwind CSS Letter Spacing"
},
{
"code": null,
"e": 33221,
"s": 33196,
"text": "Tailwind CSS Line Height"
},
{
"code": null,
"e": 33250,
"s": 33221,
"text": "Tailwind CSS List Style Type"
},
{
"code": null,
"e": 33281,
"s": 33250,
"text": "Tailwind CSS Placeholder Color"
},
{
"code": null,
"e": 33314,
"s": 33281,
"text": "Tailwind CSS Placeholder Opacity"
},
{
"code": null,
"e": 33342,
"s": 33314,
"text": "Tailwind CSS Text Alignment"
},
{
"code": null,
"e": 33370,
"s": 33342,
"text": "Tailwind CSS Text Alignment"
},
{
"code": null,
"e": 33394,
"s": 33370,
"text": "Tailwind CSS Text Color"
},
{
"code": null,
"e": 33420,
"s": 33394,
"text": "Tailwind CSS Text Opacity"
},
{
"code": null,
"e": 33449,
"s": 33420,
"text": "Tailwind CSS Text Decoration"
},
{
"code": null,
"e": 33477,
"s": 33449,
"text": "Tailwind CSS Text Transform"
},
{
"code": null,
"e": 33505,
"s": 33477,
"text": "Tailwind CSS Text Transform"
},
{
"code": null,
"e": 33537,
"s": 33505,
"text": "Tailwind CSS Vertical Alignment"
},
{
"code": null,
"e": 33561,
"s": 33537,
"text": "Tailwind CSS Whitespace"
},
{
"code": null,
"e": 33585,
"s": 33561,
"text": "Tailwind CSS Word Break"
},
{
"code": null,
"e": 33658,
"s": 33585,
"text": "Tailwind CSS TablesTailwind CSS Border CollapseTailwind CSS Table Layout"
},
{
"code": null,
"e": 33678,
"s": 33658,
"text": "Tailwind CSS Tables"
},
{
"code": null,
"e": 33707,
"s": 33678,
"text": "Tailwind CSS Border Collapse"
},
{
"code": null,
"e": 33733,
"s": 33707,
"text": "Tailwind CSS Table Layout"
},
{
"code": null,
"e": 33904,
"s": 33733,
"text": "Tailwind CSS Transitions and AnimationTailwind CSS Transition PropertyTailwind CSS Transition DurationTailwind CSS Transition Timing FunctionTailwind CSS Transition Delay"
},
{
"code": null,
"e": 33943,
"s": 33904,
"text": "Tailwind CSS Transitions and Animation"
},
{
"code": null,
"e": 33976,
"s": 33943,
"text": "Tailwind CSS Transition Property"
},
{
"code": null,
"e": 34009,
"s": 33976,
"text": "Tailwind CSS Transition Duration"
},
{
"code": null,
"e": 34049,
"s": 34009,
"text": "Tailwind CSS Transition Timing Function"
},
{
"code": null,
"e": 34079,
"s": 34049,
"text": "Tailwind CSS Transition Delay"
},
{
"code": null,
"e": 34213,
"s": 34079,
"text": "Tailwind CSS TransformsTailwind CSS TransformTailwind CSS Transform OriginTailwind CSS ScaleTailwind CSS RotateTailwind CSS Translate"
},
{
"code": null,
"e": 34237,
"s": 34213,
"text": "Tailwind CSS Transforms"
},
{
"code": null,
"e": 34260,
"s": 34237,
"text": "Tailwind CSS Transform"
},
{
"code": null,
"e": 34290,
"s": 34260,
"text": "Tailwind CSS Transform Origin"
},
{
"code": null,
"e": 34309,
"s": 34290,
"text": "Tailwind CSS Scale"
},
{
"code": null,
"e": 34329,
"s": 34309,
"text": "Tailwind CSS Rotate"
},
{
"code": null,
"e": 34352,
"s": 34329,
"text": "Tailwind CSS Translate"
},
{
"code": null,
"e": 34452,
"s": 34354,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 34526,
"s": 34452,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 34579,
"s": 34526,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 34611,
"s": 34579,
"text": "Floyd’s Cycle Finding Algorithm"
},
{
"code": null,
"e": 34681,
"s": 34611,
"text": "Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!"
},
{
"code": null,
"e": 34707,
"s": 34681,
"text": "Spring Boot - Annotations"
},
{
"code": null,
"e": 34765,
"s": 34707,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 34823,
"s": 34765,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 34854,
"s": 34823,
"text": "How to Install Git in VS Code?"
},
{
"code": null,
"e": 34902,
"s": 34854,
"text": "Git - Difference Between Git Fetch and Git Pull"
}
]
|
Python program to print checkerboard pattern of nxn using numpy | 06 Apr, 2020
Given n, print the checkboard pattern for a n x n matrix
Checkboard Pattern for n = 8:
It consists of n * n squares of alternating 0 for white and 1 for black.
We can do the same using nested for loops and some if conditions, but using Python’s numpy library, we can import a 2-D matrix and get the checkboard pattern using slicing.W2’ll be using following python function to print pattern :
x = np.zeros((n, n), dtype=int)
Using this function, we initialize a 2-D matrix with 0’s at all index using numpy
x[1::2, ::2] = 1 : Slice from 1st index row till 1+2+2... and fill all columns with 1 starting from 0th to 0+2+2... and so on.
x[::2, 1::2] = 1 : Slice from 0th row till 0+2+2... and fill all columns with 1 starting from 1 to 1+2+2+.....
Function of np.zeros((n, n), dtype=int) : Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation. Using the dtype parameter initializes all the values with int data-type.For example: np.zeros, np.ones etc.
# Python program to print nXn# checkerboard pattern using numpy import numpy as np # function to print Checkerboard patterndef printcheckboard(n): print("Checkerboard pattern:") # create a n * n matrix x = np.zeros((n, n), dtype = int) # fill with 1 the alternate rows and columns x[1::2, ::2] = 1 x[::2, 1::2] = 1 # print the pattern for i in range(n): for j in range(n): print(x[i][j], end =" ") print() # driver coden = 8printcheckboard(n)
Output:
Checkerboard pattern:
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
Improved Source Code Based on Assumption that Checkerboard is always an even nXn i.e., n is even
# Python program to print nXn Assuming that n # is always even as a checkerboard was import numpy as npdef printcheckboard(n): final = [] for i in range(n): final.append(list(np.tile([0,1],int(n/2))) if i%2==0 else list(np.tile([1,0],int(n/2)))) print(np.array(final)) # driver coden = 8printcheckboard(n)
Output:
Checkerboard pattern:
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
bsaik7
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": 54,
"s": 26,
"text": "\n06 Apr, 2020"
},
{
"code": null,
"e": 111,
"s": 54,
"text": "Given n, print the checkboard pattern for a n x n matrix"
},
{
"code": null,
"e": 141,
"s": 111,
"text": "Checkboard Pattern for n = 8:"
},
{
"code": null,
"e": 214,
"s": 141,
"text": "It consists of n * n squares of alternating 0 for white and 1 for black."
},
{
"code": null,
"e": 446,
"s": 214,
"text": "We can do the same using nested for loops and some if conditions, but using Python’s numpy library, we can import a 2-D matrix and get the checkboard pattern using slicing.W2’ll be using following python function to print pattern :"
},
{
"code": null,
"e": 478,
"s": 446,
"text": "x = np.zeros((n, n), dtype=int)"
},
{
"code": null,
"e": 560,
"s": 478,
"text": "Using this function, we initialize a 2-D matrix with 0’s at all index using numpy"
},
{
"code": null,
"e": 687,
"s": 560,
"text": "x[1::2, ::2] = 1 : Slice from 1st index row till 1+2+2... and fill all columns with 1 starting from 0th to 0+2+2... and so on."
},
{
"code": null,
"e": 798,
"s": 687,
"text": "x[::2, 1::2] = 1 : Slice from 0th row till 0+2+2... and fill all columns with 1 starting from 1 to 1+2+2+....."
},
{
"code": null,
"e": 1188,
"s": 798,
"text": "Function of np.zeros((n, n), dtype=int) : Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation. Using the dtype parameter initializes all the values with int data-type.For example: np.zeros, np.ones etc."
},
{
"code": "# Python program to print nXn# checkerboard pattern using numpy import numpy as np # function to print Checkerboard patterndef printcheckboard(n): print(\"Checkerboard pattern:\") # create a n * n matrix x = np.zeros((n, n), dtype = int) # fill with 1 the alternate rows and columns x[1::2, ::2] = 1 x[::2, 1::2] = 1 # print the pattern for i in range(n): for j in range(n): print(x[i][j], end =\" \") print() # driver coden = 8printcheckboard(n)",
"e": 1703,
"s": 1188,
"text": null
},
{
"code": null,
"e": 1711,
"s": 1703,
"text": "Output:"
},
{
"code": null,
"e": 1870,
"s": 1711,
"text": "Checkerboard pattern:\n0 1 0 1 0 1 0 1 \n1 0 1 0 1 0 1 0 \n0 1 0 1 0 1 0 1 \n1 0 1 0 1 0 1 0 \n0 1 0 1 0 1 0 1 \n1 0 1 0 1 0 1 0 \n0 1 0 1 0 1 0 1 \n1 0 1 0 1 0 1 0 \n"
},
{
"code": null,
"e": 1967,
"s": 1870,
"text": "Improved Source Code Based on Assumption that Checkerboard is always an even nXn i.e., n is even"
},
{
"code": "# Python program to print nXn Assuming that n # is always even as a checkerboard was import numpy as npdef printcheckboard(n): final = [] for i in range(n): final.append(list(np.tile([0,1],int(n/2))) if i%2==0 else list(np.tile([1,0],int(n/2)))) print(np.array(final)) # driver coden = 8printcheckboard(n)",
"e": 2293,
"s": 1967,
"text": null
},
{
"code": null,
"e": 2301,
"s": 2293,
"text": "Output:"
},
{
"code": null,
"e": 2477,
"s": 2301,
"text": "Checkerboard pattern:\n[[0 1 0 1 0 1 0 1]\n [1 0 1 0 1 0 1 0]\n [0 1 0 1 0 1 0 1]\n [1 0 1 0 1 0 1 0]\n [0 1 0 1 0 1 0 1]\n [1 0 1 0 1 0 1 0]\n [0 1 0 1 0 1 0 1]\n [1 0 1 0 1 0 1 0]]\n"
},
{
"code": null,
"e": 2484,
"s": 2477,
"text": "bsaik7"
},
{
"code": null,
"e": 2505,
"s": 2484,
"text": "Python numpy-program"
},
{
"code": null,
"e": 2518,
"s": 2505,
"text": "Python-numpy"
},
{
"code": null,
"e": 2525,
"s": 2518,
"text": "Python"
}
]
|
Java.lang.Integer class in Java | 21 Jun, 2022
Integer class is a wrapper class for the primitive type int which contains several methods to effectively deal with an int value like converting it to a string representation, and vice-versa. An object of the Integer class can hold a single int value.
Constructors:
Integer(int b): Creates an Integer object initialized with the value provided.
Syntax:
public Integer(int b)
Parameters:
b : value with which to initialize
Integer(String s): Creates an Integer object initialized with the int value provided by string representation. Default radix is taken to be 10.
Syntax:
public Integer(String s) throws NumberFormatException
Parameters:
s : string representation of the int value
Throws:
NumberFormatException :
If the string provided does not represent any int value.
Methods:
1. toString() : Returns the string corresponding to the int value.
Syntax:
public String toString(int b)
Parameters :
b : int value for which string representation required.
2. toHexString() : Returns the string corresponding to the int value in hexadecimal form, that is it returns a string representing the int value in hex characters-[0-9][a-f]
Syntax:
public String toHexString(int b)
Parameters:
b : int value for which hex string representation required.
3. toOctalString() : Returns the string corresponding to the int value in octal form, that is it returns a string representing the int value in octal characters-[0-7]
Syntax:
public String toOctalString(int b)
Parameters:
b : int value for which octal string representation required.
4. toBinaryString() : Returns the string corresponding to the int value in binary digits, that is it returns a string representing the int value in hex characters-[0/1]
Syntax:
public String toBinaryString(int b)
Parameters:
b : int value for which binary string representation required.
5. valueOf() : returns the Integer object initialised with the value provided.
Syntax:
public static Integer valueOf(int b)
Parameters:
b : a int value
valueOf(String val,int radix): Another overloaded function which provides function similar to new Integer(Integer.parseInteger(val,radix))
Syntax:
public static Integer valueOf(String val, int radix)
throws NumberFormatException
Parameters:
val : String to be parsed into int value
radix : radix to be used while parsing
Throws:
NumberFormatException : if String cannot be parsed to a int value in given radix.
valueOf(String val): Another overloaded function which provides function similar to new Integer(Integer.parseInt(val,10))
Syntax:
public static Integer valueOf(String s)
throws NumberFormatException
Parameters:
s : a String object to be parsed as int
Throws:
NumberFormatException : if String cannot be parsed to a int value in given radix.
6. parseInt() : returns int value by parsing the string in radix provided. Differs from valueOf() as it returns a primitive int value and valueOf() return Integer object.
Syntax:
public static int parseInt(String val, int radix)
throws NumberFormatException
Parameters:
val : String representation of int
radix : radix to be used while parsing
Throws:
NumberFormatException : if String cannot be parsed to a int value in given radix.
Another overloaded method containing only String as a parameter, radix is by default set to 10.
Syntax:
public static int parseInt(String val)
throws NumberFormatException
Parameters:
val : String representation of int
Throws:
NumberFormatException : if String cannot be parsed to a int value in given radix.
7. getInteger(): returns the Integer object representing the value associated with the given system property or null if it does not exist.
Syntax:
public static Integer getInteger(String prop)
Parameters :
prop : System property
Another overloaded method which returns the second argument if the property does not exist, that is it does not return null but a default value supplied by user.
Syntax:
public static Integer getInteger(String prop, int val)
Parameters:
prop : System property
val : value to return if property does not exist.
Another overloaded method which parses the value according to the value returned, that is if the value returned starts with “#”, than it is parsed as hexadecimal, if starts with “0”, than it is parsed as octal, else decimal.
Syntax:
public static Integer getInteger(String prop, Integer val)
Parameters:
prop : System property
val : value to return if property does not exist.
8. decode() : returns a Integer object holding the decoded value of string provided. String provided must be of the following form else NumberFormatException will be thrown- Decimal- (Sign)Decimal_Number Hex- (Sign)”0x”Hex_Digits Hex- (Sign)”0X”Hex_Digits Octal- (Sign)”0′′Octal_Digits
Syntax:
public static Integer decode(String s)
throws NumberFormatException
Parameters:
s : encoded string to be parsed into int val
Throws:
NumberFormatException : If the string cannot be decoded into a int value
9. rotateLeft() : Returns a primitive int by rotating the bits left by given distance in two’s complement form of the value given. When rotating left, the most significant bit is moved to the right-hand side, or least significant position i.e. cyclic movement of bits takes place. Negative distance signifies right rotation.
Syntax:
public static int rotateLeft(int val, int dist)
Parameters:
val : int value to be rotated
dist : distance to rotate
10. rotateRight() : Returns a primitive int by rotating the bits right by given distance in the twos complement form of the value given. When rotating right, the least significant bit is moved to the left hand side, or most significant position i.e. cyclic movement of bits takes place. Negative distance signifies left rotation.
Syntax:
public static int rotateRight(int val, int dist)
Parameters:
val : int value to be rotated
dist : distance to rotate
Java
// Java program to illustrate// various Integer methodspublic class Integer_test { public static void main(String args[]) { int b = 55; String bb = "45"; // Construct two Integer objects Integer x = new Integer(b); Integer y = new Integer(bb); // toString() System.out.println("toString(b) = " + Integer.toString(b)); // toHexString(),toOctalString(),toBinaryString() // converts into hexadecimal, octal and binary // forms. System.out.println("toHexString(b) =" + Integer.toHexString(b)); System.out.println("toOctalString(b) =" + Integer.toOctalString(b)); System.out.println("toBinaryString(b) =" + Integer.toBinaryString(b)); // valueOf(): return Integer object // an overloaded method takes radix as well. Integer z = Integer.valueOf(b); System.out.println("valueOf(b) = " + z); z = Integer.valueOf(bb); System.out.println("ValueOf(bb) = " + z); z = Integer.valueOf(bb, 6); System.out.println("ValueOf(bb,6) = " + z); // parseInt(): return primitive int value // an overloaded method takes radix as well int zz = Integer.parseInt(bb); System.out.println("parseInt(bb) = " + zz); zz = Integer.parseInt(bb, 6); System.out.println("parseInt(bb,6) = " + zz); // getInteger(): can be used to retrieve // int value of system property int prop = Integer.getInteger("sun.arch.data.model"); System.out.println( "getInteger(sun.arch.data.model) = " + prop); System.out.println("getInteger(abcd) =" + Integer.getInteger("abcd")); // an overloaded getInteger() method // which return default value if property not found. System.out.println( "getInteger(abcd,10) =" + Integer.getInteger("abcd", 10)); // decode() : decodes the hex,octal and decimal // string to corresponding int values. String decimal = "45"; String octal = "005"; String hex = "0x0f"; Integer dec = Integer.decode(decimal); System.out.println("decode(45) = " + dec); dec = Integer.decode(octal); System.out.println("decode(005) = " + dec); dec = Integer.decode(hex); System.out.println("decode(0x0f) = " + dec); // rotateLeft and rotateRight can be used // to rotate bits by specified distance int valrot = 2; System.out.println( "rotateLeft(0000 0000 0000 0010 , 2) =" + Integer.rotateLeft(valrot, 2)); System.out.println( "rotateRight(0000 0000 0000 0010,3) =" + Integer.rotateRight(valrot, 3)); }}
Output:
toString(b) = 55
toHexString(b) =37
toOctalString(b) =67
toBinaryString(b) =110111
valueOf(b) = 55
ValueOf(bb) = 45
ValueOf(bb,6) = 29
parseInt(bb) = 45
parseInt(bb,6) = 29
getInteger(sun.arch.data.model) = 64
getInteger(abcd) =null
getInteger(abcd,10) =10
decode(45) = 45
decode(005) = 5
decode(0x0f) = 15
rotateLeft(0000 0000 0000 0010 , 2) =8
rotateRight(0000 0000 0000 0010,3) =1073741824
11. byteValue() : returns a byte value corresponding to this Integer Object.
Syntax:
public byte byteValue()
12. shortValue() : returns a short value corresponding to this Integer Object.
Syntax:
public short shortValue()
13. intValue() : returns a int value corresponding to this Integer Object.
Syntax:
public int intValue()
13. longValue() : returns a long value corresponding to this Integer Object.
Syntax:
public long longValue()
14. doubleValue() : returns a double value corresponding to this Integer Object.
Syntax:
public double doubleValue()
15. floatValue() : returns a float value corresponding to this Integer Object.
Syntax:
public float floatValue()
16. hashCode() : returns the hashcode corresponding to this Integer Object.
Syntax:
public int hashCode()
17. bitcount() : Returns number of set bits in twos complement of the integer given.
Syntax:
public static int bitCount(int i)
Parameters:
i : int value whose set bits to count
18. numberOfLeadingZeroes() : Returns number of 0 bits preceding the highest 1 bit in twos complement form of the value, i.e. if the number in twos complement form is 0000 1010 0000 0000, then this function would return 4.
Syntax:
public static int numberofLeadingZeroes(int i)
Parameters:
i : int value whose leading zeroes to count in twos complement form
19. numberOfTrailingZeroes() : Returns number of 0 bits following the last 1 bit in twos complement form of the value, i.e. if the number in twos complement form is 0000 1010 0000 0000, then this function would return 9.
Syntax:
public static int numberofTrailingZeroes(int i)
Parameters:
i : int value whose trailing zeroes to count in twos complement form
20. highestOneBit() : Returns a value with at most a single one bit, in the position of highest one bit in the value given. Returns 0 if the value given is 0, that is if the number is 0000 0000 0000 1111, then this function return 0000 0000 0000 1000 (one at highest one bit in the given number)
Syntax:
public static int highestOneBit(int i)
Parameters:
i : int value
21. LowestOneBit() : Returns a value with at most a single one bit, in the position of lowest one bit in the value given. Returns 0 if the value given is 0, that is if the number is 0000 0000 0000 1111, then this function return 0000 0000 0000 0001 (one at highest one bit in the given number)
Syntax:
public static int LowestOneBit(int i)
Parameters:
i : int value
22. equals() : Used to compare the equality of two Integer objects. This method returns true if both the objects contain the same int value. Should be used only if checking for equality. In all other cases, the compareTo method should be preferred.
Syntax:
public boolean equals(Object obj)
Parameters:
obj : object to compare with
23. compareTo() : Used to compare two Integer objects for numerical equality. This should be used when comparing two Integer values for numerical equality as it would differentiate between less and greater values. Returns a value less than 0,0, a value greater than 0 for less than, equal to and greater than.
Syntax:
public int compareTo(Integer b)
Parameters:
b : Integer object to compare with
24. compare(): Used to compare two primitive int values for numerical equality. As it is a static method therefore it can be used without creating any object of Integer.
Syntax:
public static int compare(int x,int y)
Parameters:
x : int value
y : another int value
25. signum() : returns -1 for negative values, 0 for 0 and +1 for values greater than 0.
Syntax:
public static int signum(int val)
Parameters:
val : int value for which signum is required.
26. reverse(): returns a primitive int value reversing the order of bits in two’s complement form of the given int value.
Syntax:
public static int reverseBytes(int val)
Parameters:
val : int value whose bits to reverse in order.
27. reverseBytes() : returns a primitive int value reversing the order of bytes in two’s complement form of the given int value.
Syntax:
public static int reverseBytes(int val)
Parameters:
val : int value whose bits to reverse in order.
28. static int compareUnsigned(int x, int y): This method compares two int values numerically treating the values as unsigned.
Syntax:
public static int compareUnsigned(int x, int y)
29. static int divideUnsigned(int dividend, int divisor): This method returns the unsigned quotient of dividing the first argument by the second where each argument and the result is interpreted as an unsigned value.
Syntax:
public static int divideUnsigned(int dividend, int divisor)
30. static int max(int a, int b): This method returns the greater of two int values as if by calling Math.max.
Syntax:
public static int max(int a, int b)
31. static int min(int a, int b): This method returns the smaller of two int values as if by calling Math.min.
Syntax:
public static int min(int a, int b)
32. static int parseUnsignedInt(CharSequence s, int beginIndex, int endIndex, int radix): This method parses the CharSequence argument as an unsigned int in the specified radix, beginning at the specified beginIndex and extending to endIndex – 1.
Syntax:
public static int parseUnsignedInt(CharSequence s,
int beginIndex,
int endIndex,
int radix)
throws NumberFormatException
33. static int parseUnsignedInt(String s): This method parses the string argument as an unsigned decimal integer.
Syntax:
public static int parseUnsignedInt(String s)
throws NumberFormatException
34. static int parseUnsignedInt(String s, int radix): This method parses the string argument as an unsigned integer in the radix specified by the second argument.
Syntax:
public static int parseUnsignedInt(String s,
int radix)
throws NumberFormatException
35. static int remainderUnsigned(int dividend, int divisor): This method returns the unsigned remainder from dividing the first argument by the second where each argument and the result is interpreted as an unsigned value.
Syntax:
public static int remainderUnsigned(int dividend, int divisor)
36. static int sum(int a, int b): This method adds two integers together as per the + operator.
Syntax:
public static int sum(int a, int b)
37. static long toUnsignedLong(int x): This method converts the argument to a long by an unsigned conversion.
Syntax:
public static long toUnsignedLong(int x)
38. static String toUnsignedString(int i): This method returns a string representation of the argument as an unsigned decimal value.
Syntax:
public static String toUnsignedString(int i, int radix)
Java
// Java program to illustrate// various Integer class methodspublic class Integer_test { public static void main(String args[]) { int b = 55; String bb = "45"; // Construct two Integer objects Integer x = new Integer(b); Integer y = new Integer(bb); // xxxValue can be used to retrieve // xxx type value from int value. // xxx can be int,byte,short,long,double,float System.out.println("bytevalue(x) = " + x.byteValue()); System.out.println("shortvalue(x) = " + x.shortValue()); System.out.println("intvalue(x) = " + x.intValue()); System.out.println("longvalue(x) = " + x.longValue()); System.out.println("doublevalue(x) = " + x.doubleValue()); System.out.println("floatvalue(x) = " + x.floatValue()); int value = 45; // bitcount() : can be used to count set bits // in twos complement form of the number System.out.println("Integer.bitcount(value)=" + Integer.bitCount(value)); // numberOfTrailingZeroes and numberOfLeadingZeroes // can be used to count prefix and postfix sequence // of 0 System.out.println( "Integer.numberOfTrailingZeros(value)=" + Integer.numberOfTrailingZeros(value)); System.out.println( "Integer.numberOfLeadingZeros(value)=" + Integer.numberOfLeadingZeros(value)); // highestOneBit returns a value with one on highest // set bit position System.out.println("Integer.highestOneBit(value)=" + Integer.highestOneBit(value)); // highestOneBit returns a value with one on lowest // set bit position System.out.println("Integer.lowestOneBit(value)=" + Integer.lowestOneBit(value)); // reverse() can be used to reverse order of bits // reverseBytes() can be used to reverse order of // bytes System.out.println("Integer.reverse(value)=" + Integer.reverse(value)); System.out.println("Integer.reverseBytes(value)=" + Integer.reverseBytes(value)); // signum() returns -1,0,1 for negative,0 and // positive values System.out.println("Integer.signum(value)=" + Integer.signum(value)); // hashcode() returns hashcode of the object int hash = x.hashCode(); System.out.println("hashcode(x) = " + hash); // equals returns boolean value representing // equality boolean eq = x.equals(y); System.out.println("x.equals(y) = " + eq); // compare() used for comparing two int values int e = Integer.compare(x, y); System.out.println("compare(x,y) = " + e); // compareTo() used for comparing this value with // some other value int f = x.compareTo(y); System.out.println("x.compareTo(y) = " + f); }}
Output :
bytevalue(x) = 55
shortvalue(x) = 55
intvalue(x) = 55
longvalue(x) = 55
doublevalue(x) = 55.0
floatvalue(x) = 55.0
Integer.bitcount(value)=4
Integer.numberOfTrailingZeros(value)=0
Integer.numberOfLeadingZeros(value)=26
Integer.highestOneBit(value)=32
Integer.lowestOneBit(value)=1
Integer.reverse(value)=-1275068416
Integer.reverseBytes(value)=754974720
Integer.signum(value)=1
hashcode(x) = 55
x.equals(y) = false
compare(x,y) = 1
x.compareTo(y) = 1
Initialization of Integer wrapper class in Java :
Type 1: Initializing directly:
A constant object of Integer class will be created inside the space of constants in the heap memory. Space of constants: It is just to imagine for better understanding that there is some space for constants in heap memory.
Example:
Integer x = 200; //initializing directly
x = 300; //modifying x
x = 10; //modifying x again
Integer x = 200
The compiler converts the above statement into: Integer x=Integer.valueOf(200) . This is known as “Autoboxing”. The primitive integer value 200 is converted into an object.
( To understand Autoboxing & Unboxing check here: https://www.geeksforgeeks.org/autoboxing-unboxing-java/ )
x points to 200 which is present in the space of constants. Refer Fig. 1.
Fig. 1
x = 300
Autoboxing is done again because x is an Integer class object which is directly initialized.
Note: The directly initialized object(x) cannot be modified as it is a constant. When we try to modify the object by pointing to a new constant(300), the old constant(200) will be present in heap memory, but the object will be pointing the new constant.
x points to 300 which is present in the space of constants. Refer Fig. 2.
Fig. 2
x = 10
Note: By default for the values -128 to 127, Integer.valueOf() method will not create a new instance of Integer. It returns a value from its cache.
x points 10 which is present in cache.
Fig. 3
If we assign x = 200 or x=300 next time, it will point to the value 200 or 300 which is present already in space of constants. If we assign values to x other than these two values, then it creates a new constant.
(Check the Integer wrapper class comparison topic for better understanding)
Type 2: Initializing dynamically:
An Integer class object which is not a constant will be created outside the space of constants. It also creates a Integer constant inside the space of constants. The variable will be pointing to the Integer object & not the Integer constant.
Example:
Integer a = new Integer(250); //Initializing dynamically
a = 350; //Type 1 initialization
Integer a = new Integer(250)
250 is created inside and outside the space of constants. Variable ‘a’ will be pointing the value that is outside the space of constants. Refer Fig. 4.
Fig. 4
a = 350;
After autoboxing, ‘a’ will be pointing to 350. Refer Fig. 5.
Fig. 5
If we assign a = 250 next time, it will not point to the object already present with same value, it will create a new object.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.References: Official Java Documentation
This article is contributed by Rishabh Mahrsee. 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.
Akanksha_Rai
pravin_kumar_s
varshagumber28
kapoorsagar226
sweetyty
simranarora5sos
simmytarika5
mitalibhola94
Java-Integer
Java-lang package
java-wrapper-class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 305,
"s": 52,
"text": "Integer class is a wrapper class for the primitive type int which contains several methods to effectively deal with an int value like converting it to a string representation, and vice-versa. An object of the Integer class can hold a single int value. "
},
{
"code": null,
"e": 320,
"s": 305,
"text": "Constructors: "
},
{
"code": null,
"e": 399,
"s": 320,
"text": "Integer(int b): Creates an Integer object initialized with the value provided."
},
{
"code": null,
"e": 408,
"s": 399,
"text": "Syntax: "
},
{
"code": null,
"e": 430,
"s": 408,
"text": "public Integer(int b)"
},
{
"code": null,
"e": 442,
"s": 430,
"text": "Parameters:"
},
{
"code": null,
"e": 477,
"s": 442,
"text": "b : value with which to initialize"
},
{
"code": null,
"e": 621,
"s": 477,
"text": "Integer(String s): Creates an Integer object initialized with the int value provided by string representation. Default radix is taken to be 10."
},
{
"code": null,
"e": 630,
"s": 621,
"text": "Syntax: "
},
{
"code": null,
"e": 684,
"s": 630,
"text": "public Integer(String s) throws NumberFormatException"
},
{
"code": null,
"e": 696,
"s": 684,
"text": "Parameters:"
},
{
"code": null,
"e": 740,
"s": 696,
"text": "s : string representation of the int value "
},
{
"code": null,
"e": 748,
"s": 740,
"text": "Throws:"
},
{
"code": null,
"e": 830,
"s": 748,
"text": "NumberFormatException : \nIf the string provided does not represent any int value."
},
{
"code": null,
"e": 840,
"s": 830,
"text": "Methods: "
},
{
"code": null,
"e": 908,
"s": 840,
"text": "1. toString() : Returns the string corresponding to the int value. "
},
{
"code": null,
"e": 917,
"s": 908,
"text": "Syntax: "
},
{
"code": null,
"e": 947,
"s": 917,
"text": "public String toString(int b)"
},
{
"code": null,
"e": 960,
"s": 947,
"text": "Parameters :"
},
{
"code": null,
"e": 1016,
"s": 960,
"text": "b : int value for which string representation required."
},
{
"code": null,
"e": 1191,
"s": 1016,
"text": "2. toHexString() : Returns the string corresponding to the int value in hexadecimal form, that is it returns a string representing the int value in hex characters-[0-9][a-f] "
},
{
"code": null,
"e": 1200,
"s": 1191,
"text": "Syntax: "
},
{
"code": null,
"e": 1233,
"s": 1200,
"text": "public String toHexString(int b)"
},
{
"code": null,
"e": 1245,
"s": 1233,
"text": "Parameters:"
},
{
"code": null,
"e": 1305,
"s": 1245,
"text": "b : int value for which hex string representation required."
},
{
"code": null,
"e": 1473,
"s": 1305,
"text": "3. toOctalString() : Returns the string corresponding to the int value in octal form, that is it returns a string representing the int value in octal characters-[0-7] "
},
{
"code": null,
"e": 1482,
"s": 1473,
"text": "Syntax: "
},
{
"code": null,
"e": 1517,
"s": 1482,
"text": "public String toOctalString(int b)"
},
{
"code": null,
"e": 1529,
"s": 1517,
"text": "Parameters:"
},
{
"code": null,
"e": 1591,
"s": 1529,
"text": "b : int value for which octal string representation required."
},
{
"code": null,
"e": 1761,
"s": 1591,
"text": "4. toBinaryString() : Returns the string corresponding to the int value in binary digits, that is it returns a string representing the int value in hex characters-[0/1] "
},
{
"code": null,
"e": 1769,
"s": 1761,
"text": "Syntax:"
},
{
"code": null,
"e": 1805,
"s": 1769,
"text": "public String toBinaryString(int b)"
},
{
"code": null,
"e": 1817,
"s": 1805,
"text": "Parameters:"
},
{
"code": null,
"e": 1880,
"s": 1817,
"text": "b : int value for which binary string representation required."
},
{
"code": null,
"e": 1960,
"s": 1880,
"text": "5. valueOf() : returns the Integer object initialised with the value provided. "
},
{
"code": null,
"e": 1969,
"s": 1960,
"text": "Syntax: "
},
{
"code": null,
"e": 2006,
"s": 1969,
"text": "public static Integer valueOf(int b)"
},
{
"code": null,
"e": 2018,
"s": 2006,
"text": "Parameters:"
},
{
"code": null,
"e": 2034,
"s": 2018,
"text": "b : a int value"
},
{
"code": null,
"e": 2173,
"s": 2034,
"text": "valueOf(String val,int radix): Another overloaded function which provides function similar to new Integer(Integer.parseInteger(val,radix))"
},
{
"code": null,
"e": 2182,
"s": 2173,
"text": "Syntax: "
},
{
"code": null,
"e": 2264,
"s": 2182,
"text": "public static Integer valueOf(String val, int radix)\nthrows NumberFormatException"
},
{
"code": null,
"e": 2276,
"s": 2264,
"text": "Parameters:"
},
{
"code": null,
"e": 2356,
"s": 2276,
"text": "val : String to be parsed into int value\nradix : radix to be used while parsing"
},
{
"code": null,
"e": 2364,
"s": 2356,
"text": "Throws:"
},
{
"code": null,
"e": 2446,
"s": 2364,
"text": "NumberFormatException : if String cannot be parsed to a int value in given radix."
},
{
"code": null,
"e": 2568,
"s": 2446,
"text": "valueOf(String val): Another overloaded function which provides function similar to new Integer(Integer.parseInt(val,10))"
},
{
"code": null,
"e": 2577,
"s": 2568,
"text": "Syntax: "
},
{
"code": null,
"e": 2646,
"s": 2577,
"text": "public static Integer valueOf(String s)\nthrows NumberFormatException"
},
{
"code": null,
"e": 2658,
"s": 2646,
"text": "Parameters:"
},
{
"code": null,
"e": 2698,
"s": 2658,
"text": "s : a String object to be parsed as int"
},
{
"code": null,
"e": 2706,
"s": 2698,
"text": "Throws:"
},
{
"code": null,
"e": 2788,
"s": 2706,
"text": "NumberFormatException : if String cannot be parsed to a int value in given radix."
},
{
"code": null,
"e": 2960,
"s": 2788,
"text": "6. parseInt() : returns int value by parsing the string in radix provided. Differs from valueOf() as it returns a primitive int value and valueOf() return Integer object. "
},
{
"code": null,
"e": 2969,
"s": 2960,
"text": "Syntax: "
},
{
"code": null,
"e": 3048,
"s": 2969,
"text": "public static int parseInt(String val, int radix)\nthrows NumberFormatException"
},
{
"code": null,
"e": 3060,
"s": 3048,
"text": "Parameters:"
},
{
"code": null,
"e": 3135,
"s": 3060,
"text": "val : String representation of int \nradix : radix to be used while parsing"
},
{
"code": null,
"e": 3143,
"s": 3135,
"text": "Throws:"
},
{
"code": null,
"e": 3225,
"s": 3143,
"text": "NumberFormatException : if String cannot be parsed to a int value in given radix."
},
{
"code": null,
"e": 3321,
"s": 3225,
"text": "Another overloaded method containing only String as a parameter, radix is by default set to 10."
},
{
"code": null,
"e": 3330,
"s": 3321,
"text": "Syntax: "
},
{
"code": null,
"e": 3398,
"s": 3330,
"text": "public static int parseInt(String val)\nthrows NumberFormatException"
},
{
"code": null,
"e": 3410,
"s": 3398,
"text": "Parameters:"
},
{
"code": null,
"e": 3446,
"s": 3410,
"text": "val : String representation of int "
},
{
"code": null,
"e": 3454,
"s": 3446,
"text": "Throws:"
},
{
"code": null,
"e": 3536,
"s": 3454,
"text": "NumberFormatException : if String cannot be parsed to a int value in given radix."
},
{
"code": null,
"e": 3676,
"s": 3536,
"text": "7. getInteger(): returns the Integer object representing the value associated with the given system property or null if it does not exist. "
},
{
"code": null,
"e": 3685,
"s": 3676,
"text": "Syntax: "
},
{
"code": null,
"e": 3731,
"s": 3685,
"text": "public static Integer getInteger(String prop)"
},
{
"code": null,
"e": 3744,
"s": 3731,
"text": "Parameters :"
},
{
"code": null,
"e": 3767,
"s": 3744,
"text": "prop : System property"
},
{
"code": null,
"e": 3931,
"s": 3767,
"text": "Another overloaded method which returns the second argument if the property does not exist, that is it does not return null but a default value supplied by user. "
},
{
"code": null,
"e": 3940,
"s": 3931,
"text": "Syntax: "
},
{
"code": null,
"e": 3995,
"s": 3940,
"text": "public static Integer getInteger(String prop, int val)"
},
{
"code": null,
"e": 4007,
"s": 3995,
"text": "Parameters:"
},
{
"code": null,
"e": 4080,
"s": 4007,
"text": "prop : System property\nval : value to return if property does not exist."
},
{
"code": null,
"e": 4307,
"s": 4080,
"text": "Another overloaded method which parses the value according to the value returned, that is if the value returned starts with “#”, than it is parsed as hexadecimal, if starts with “0”, than it is parsed as octal, else decimal. "
},
{
"code": null,
"e": 4316,
"s": 4307,
"text": "Syntax: "
},
{
"code": null,
"e": 4375,
"s": 4316,
"text": "public static Integer getInteger(String prop, Integer val)"
},
{
"code": null,
"e": 4387,
"s": 4375,
"text": "Parameters:"
},
{
"code": null,
"e": 4460,
"s": 4387,
"text": "prop : System property\nval : value to return if property does not exist."
},
{
"code": null,
"e": 4748,
"s": 4460,
"text": "8. decode() : returns a Integer object holding the decoded value of string provided. String provided must be of the following form else NumberFormatException will be thrown- Decimal- (Sign)Decimal_Number Hex- (Sign)”0x”Hex_Digits Hex- (Sign)”0X”Hex_Digits Octal- (Sign)”0′′Octal_Digits "
},
{
"code": null,
"e": 4757,
"s": 4748,
"text": "Syntax: "
},
{
"code": null,
"e": 4825,
"s": 4757,
"text": "public static Integer decode(String s)\nthrows NumberFormatException"
},
{
"code": null,
"e": 4837,
"s": 4825,
"text": "Parameters:"
},
{
"code": null,
"e": 4882,
"s": 4837,
"text": "s : encoded string to be parsed into int val"
},
{
"code": null,
"e": 4890,
"s": 4882,
"text": "Throws:"
},
{
"code": null,
"e": 4963,
"s": 4890,
"text": "NumberFormatException : If the string cannot be decoded into a int value"
},
{
"code": null,
"e": 5289,
"s": 4963,
"text": "9. rotateLeft() : Returns a primitive int by rotating the bits left by given distance in two’s complement form of the value given. When rotating left, the most significant bit is moved to the right-hand side, or least significant position i.e. cyclic movement of bits takes place. Negative distance signifies right rotation. "
},
{
"code": null,
"e": 5298,
"s": 5289,
"text": "Syntax: "
},
{
"code": null,
"e": 5346,
"s": 5298,
"text": "public static int rotateLeft(int val, int dist)"
},
{
"code": null,
"e": 5358,
"s": 5346,
"text": "Parameters:"
},
{
"code": null,
"e": 5414,
"s": 5358,
"text": "val : int value to be rotated\ndist : distance to rotate"
},
{
"code": null,
"e": 5745,
"s": 5414,
"text": "10. rotateRight() : Returns a primitive int by rotating the bits right by given distance in the twos complement form of the value given. When rotating right, the least significant bit is moved to the left hand side, or most significant position i.e. cyclic movement of bits takes place. Negative distance signifies left rotation. "
},
{
"code": null,
"e": 5754,
"s": 5745,
"text": "Syntax: "
},
{
"code": null,
"e": 5803,
"s": 5754,
"text": "public static int rotateRight(int val, int dist)"
},
{
"code": null,
"e": 5815,
"s": 5803,
"text": "Parameters:"
},
{
"code": null,
"e": 5871,
"s": 5815,
"text": "val : int value to be rotated\ndist : distance to rotate"
},
{
"code": null,
"e": 5876,
"s": 5871,
"text": "Java"
},
{
"code": "// Java program to illustrate// various Integer methodspublic class Integer_test { public static void main(String args[]) { int b = 55; String bb = \"45\"; // Construct two Integer objects Integer x = new Integer(b); Integer y = new Integer(bb); // toString() System.out.println(\"toString(b) = \" + Integer.toString(b)); // toHexString(),toOctalString(),toBinaryString() // converts into hexadecimal, octal and binary // forms. System.out.println(\"toHexString(b) =\" + Integer.toHexString(b)); System.out.println(\"toOctalString(b) =\" + Integer.toOctalString(b)); System.out.println(\"toBinaryString(b) =\" + Integer.toBinaryString(b)); // valueOf(): return Integer object // an overloaded method takes radix as well. Integer z = Integer.valueOf(b); System.out.println(\"valueOf(b) = \" + z); z = Integer.valueOf(bb); System.out.println(\"ValueOf(bb) = \" + z); z = Integer.valueOf(bb, 6); System.out.println(\"ValueOf(bb,6) = \" + z); // parseInt(): return primitive int value // an overloaded method takes radix as well int zz = Integer.parseInt(bb); System.out.println(\"parseInt(bb) = \" + zz); zz = Integer.parseInt(bb, 6); System.out.println(\"parseInt(bb,6) = \" + zz); // getInteger(): can be used to retrieve // int value of system property int prop = Integer.getInteger(\"sun.arch.data.model\"); System.out.println( \"getInteger(sun.arch.data.model) = \" + prop); System.out.println(\"getInteger(abcd) =\" + Integer.getInteger(\"abcd\")); // an overloaded getInteger() method // which return default value if property not found. System.out.println( \"getInteger(abcd,10) =\" + Integer.getInteger(\"abcd\", 10)); // decode() : decodes the hex,octal and decimal // string to corresponding int values. String decimal = \"45\"; String octal = \"005\"; String hex = \"0x0f\"; Integer dec = Integer.decode(decimal); System.out.println(\"decode(45) = \" + dec); dec = Integer.decode(octal); System.out.println(\"decode(005) = \" + dec); dec = Integer.decode(hex); System.out.println(\"decode(0x0f) = \" + dec); // rotateLeft and rotateRight can be used // to rotate bits by specified distance int valrot = 2; System.out.println( \"rotateLeft(0000 0000 0000 0010 , 2) =\" + Integer.rotateLeft(valrot, 2)); System.out.println( \"rotateRight(0000 0000 0000 0010,3) =\" + Integer.rotateRight(valrot, 3)); }}",
"e": 8732,
"s": 5876,
"text": null
},
{
"code": null,
"e": 8740,
"s": 8732,
"text": "Output:"
},
{
"code": null,
"e": 9133,
"s": 8740,
"text": "toString(b) = 55\ntoHexString(b) =37\ntoOctalString(b) =67\ntoBinaryString(b) =110111\nvalueOf(b) = 55\nValueOf(bb) = 45\nValueOf(bb,6) = 29\nparseInt(bb) = 45\nparseInt(bb,6) = 29\ngetInteger(sun.arch.data.model) = 64\ngetInteger(abcd) =null\ngetInteger(abcd,10) =10\ndecode(45) = 45\ndecode(005) = 5\ndecode(0x0f) = 15\nrotateLeft(0000 0000 0000 0010 , 2) =8\nrotateRight(0000 0000 0000 0010,3) =1073741824"
},
{
"code": null,
"e": 9211,
"s": 9133,
"text": "11. byteValue() : returns a byte value corresponding to this Integer Object. "
},
{
"code": null,
"e": 9220,
"s": 9211,
"text": "Syntax: "
},
{
"code": null,
"e": 9244,
"s": 9220,
"text": "public byte byteValue()"
},
{
"code": null,
"e": 9324,
"s": 9244,
"text": "12. shortValue() : returns a short value corresponding to this Integer Object. "
},
{
"code": null,
"e": 9333,
"s": 9324,
"text": "Syntax: "
},
{
"code": null,
"e": 9359,
"s": 9333,
"text": "public short shortValue()"
},
{
"code": null,
"e": 9435,
"s": 9359,
"text": "13. intValue() : returns a int value corresponding to this Integer Object. "
},
{
"code": null,
"e": 9444,
"s": 9435,
"text": "Syntax: "
},
{
"code": null,
"e": 9466,
"s": 9444,
"text": "public int intValue()"
},
{
"code": null,
"e": 9544,
"s": 9466,
"text": "13. longValue() : returns a long value corresponding to this Integer Object. "
},
{
"code": null,
"e": 9552,
"s": 9544,
"text": "Syntax:"
},
{
"code": null,
"e": 9576,
"s": 9552,
"text": "public long longValue()"
},
{
"code": null,
"e": 9658,
"s": 9576,
"text": "14. doubleValue() : returns a double value corresponding to this Integer Object. "
},
{
"code": null,
"e": 9667,
"s": 9658,
"text": "Syntax: "
},
{
"code": null,
"e": 9695,
"s": 9667,
"text": "public double doubleValue()"
},
{
"code": null,
"e": 9775,
"s": 9695,
"text": "15. floatValue() : returns a float value corresponding to this Integer Object. "
},
{
"code": null,
"e": 9784,
"s": 9775,
"text": "Syntax: "
},
{
"code": null,
"e": 9810,
"s": 9784,
"text": "public float floatValue()"
},
{
"code": null,
"e": 9887,
"s": 9810,
"text": "16. hashCode() : returns the hashcode corresponding to this Integer Object. "
},
{
"code": null,
"e": 9896,
"s": 9887,
"text": "Syntax: "
},
{
"code": null,
"e": 9918,
"s": 9896,
"text": "public int hashCode()"
},
{
"code": null,
"e": 10004,
"s": 9918,
"text": "17. bitcount() : Returns number of set bits in twos complement of the integer given. "
},
{
"code": null,
"e": 10013,
"s": 10004,
"text": "Syntax: "
},
{
"code": null,
"e": 10047,
"s": 10013,
"text": "public static int bitCount(int i)"
},
{
"code": null,
"e": 10059,
"s": 10047,
"text": "Parameters:"
},
{
"code": null,
"e": 10097,
"s": 10059,
"text": "i : int value whose set bits to count"
},
{
"code": null,
"e": 10321,
"s": 10097,
"text": "18. numberOfLeadingZeroes() : Returns number of 0 bits preceding the highest 1 bit in twos complement form of the value, i.e. if the number in twos complement form is 0000 1010 0000 0000, then this function would return 4. "
},
{
"code": null,
"e": 10330,
"s": 10321,
"text": "Syntax: "
},
{
"code": null,
"e": 10377,
"s": 10330,
"text": "public static int numberofLeadingZeroes(int i)"
},
{
"code": null,
"e": 10389,
"s": 10377,
"text": "Parameters:"
},
{
"code": null,
"e": 10457,
"s": 10389,
"text": "i : int value whose leading zeroes to count in twos complement form"
},
{
"code": null,
"e": 10679,
"s": 10457,
"text": "19. numberOfTrailingZeroes() : Returns number of 0 bits following the last 1 bit in twos complement form of the value, i.e. if the number in twos complement form is 0000 1010 0000 0000, then this function would return 9. "
},
{
"code": null,
"e": 10688,
"s": 10679,
"text": "Syntax: "
},
{
"code": null,
"e": 10736,
"s": 10688,
"text": "public static int numberofTrailingZeroes(int i)"
},
{
"code": null,
"e": 10748,
"s": 10736,
"text": "Parameters:"
},
{
"code": null,
"e": 10817,
"s": 10748,
"text": "i : int value whose trailing zeroes to count in twos complement form"
},
{
"code": null,
"e": 11114,
"s": 10817,
"text": "20. highestOneBit() : Returns a value with at most a single one bit, in the position of highest one bit in the value given. Returns 0 if the value given is 0, that is if the number is 0000 0000 0000 1111, then this function return 0000 0000 0000 1000 (one at highest one bit in the given number) "
},
{
"code": null,
"e": 11123,
"s": 11114,
"text": "Syntax: "
},
{
"code": null,
"e": 11162,
"s": 11123,
"text": "public static int highestOneBit(int i)"
},
{
"code": null,
"e": 11174,
"s": 11162,
"text": "Parameters:"
},
{
"code": null,
"e": 11189,
"s": 11174,
"text": "i : int value "
},
{
"code": null,
"e": 11484,
"s": 11189,
"text": "21. LowestOneBit() : Returns a value with at most a single one bit, in the position of lowest one bit in the value given. Returns 0 if the value given is 0, that is if the number is 0000 0000 0000 1111, then this function return 0000 0000 0000 0001 (one at highest one bit in the given number) "
},
{
"code": null,
"e": 11493,
"s": 11484,
"text": "Syntax: "
},
{
"code": null,
"e": 11531,
"s": 11493,
"text": "public static int LowestOneBit(int i)"
},
{
"code": null,
"e": 11543,
"s": 11531,
"text": "Parameters:"
},
{
"code": null,
"e": 11558,
"s": 11543,
"text": "i : int value "
},
{
"code": null,
"e": 11808,
"s": 11558,
"text": "22. equals() : Used to compare the equality of two Integer objects. This method returns true if both the objects contain the same int value. Should be used only if checking for equality. In all other cases, the compareTo method should be preferred. "
},
{
"code": null,
"e": 11817,
"s": 11808,
"text": "Syntax: "
},
{
"code": null,
"e": 11851,
"s": 11817,
"text": "public boolean equals(Object obj)"
},
{
"code": null,
"e": 11863,
"s": 11851,
"text": "Parameters:"
},
{
"code": null,
"e": 11892,
"s": 11863,
"text": "obj : object to compare with"
},
{
"code": null,
"e": 12203,
"s": 11892,
"text": "23. compareTo() : Used to compare two Integer objects for numerical equality. This should be used when comparing two Integer values for numerical equality as it would differentiate between less and greater values. Returns a value less than 0,0, a value greater than 0 for less than, equal to and greater than. "
},
{
"code": null,
"e": 12212,
"s": 12203,
"text": "Syntax: "
},
{
"code": null,
"e": 12244,
"s": 12212,
"text": "public int compareTo(Integer b)"
},
{
"code": null,
"e": 12256,
"s": 12244,
"text": "Parameters:"
},
{
"code": null,
"e": 12291,
"s": 12256,
"text": "b : Integer object to compare with"
},
{
"code": null,
"e": 12462,
"s": 12291,
"text": "24. compare(): Used to compare two primitive int values for numerical equality. As it is a static method therefore it can be used without creating any object of Integer. "
},
{
"code": null,
"e": 12471,
"s": 12462,
"text": "Syntax: "
},
{
"code": null,
"e": 12510,
"s": 12471,
"text": "public static int compare(int x,int y)"
},
{
"code": null,
"e": 12522,
"s": 12510,
"text": "Parameters:"
},
{
"code": null,
"e": 12558,
"s": 12522,
"text": "x : int value\ny : another int value"
},
{
"code": null,
"e": 12648,
"s": 12558,
"text": "25. signum() : returns -1 for negative values, 0 for 0 and +1 for values greater than 0. "
},
{
"code": null,
"e": 12657,
"s": 12648,
"text": "Syntax: "
},
{
"code": null,
"e": 12691,
"s": 12657,
"text": "public static int signum(int val)"
},
{
"code": null,
"e": 12703,
"s": 12691,
"text": "Parameters:"
},
{
"code": null,
"e": 12749,
"s": 12703,
"text": "val : int value for which signum is required."
},
{
"code": null,
"e": 12872,
"s": 12749,
"text": "26. reverse(): returns a primitive int value reversing the order of bits in two’s complement form of the given int value. "
},
{
"code": null,
"e": 12881,
"s": 12872,
"text": "Syntax: "
},
{
"code": null,
"e": 12921,
"s": 12881,
"text": "public static int reverseBytes(int val)"
},
{
"code": null,
"e": 12933,
"s": 12921,
"text": "Parameters:"
},
{
"code": null,
"e": 12981,
"s": 12933,
"text": "val : int value whose bits to reverse in order."
},
{
"code": null,
"e": 13111,
"s": 12981,
"text": "27. reverseBytes() : returns a primitive int value reversing the order of bytes in two’s complement form of the given int value. "
},
{
"code": null,
"e": 13120,
"s": 13111,
"text": "Syntax: "
},
{
"code": null,
"e": 13160,
"s": 13120,
"text": "public static int reverseBytes(int val)"
},
{
"code": null,
"e": 13172,
"s": 13160,
"text": "Parameters:"
},
{
"code": null,
"e": 13220,
"s": 13172,
"text": "val : int value whose bits to reverse in order."
},
{
"code": null,
"e": 13347,
"s": 13220,
"text": "28. static int compareUnsigned(int x, int y): This method compares two int values numerically treating the values as unsigned."
},
{
"code": null,
"e": 13356,
"s": 13347,
"text": "Syntax: "
},
{
"code": null,
"e": 13404,
"s": 13356,
"text": "public static int compareUnsigned(int x, int y)"
},
{
"code": null,
"e": 13621,
"s": 13404,
"text": "29. static int divideUnsigned(int dividend, int divisor): This method returns the unsigned quotient of dividing the first argument by the second where each argument and the result is interpreted as an unsigned value."
},
{
"code": null,
"e": 13630,
"s": 13621,
"text": "Syntax: "
},
{
"code": null,
"e": 13690,
"s": 13630,
"text": "public static int divideUnsigned(int dividend, int divisor)"
},
{
"code": null,
"e": 13801,
"s": 13690,
"text": "30. static int max(int a, int b): This method returns the greater of two int values as if by calling Math.max."
},
{
"code": null,
"e": 13810,
"s": 13801,
"text": "Syntax: "
},
{
"code": null,
"e": 13846,
"s": 13810,
"text": "public static int max(int a, int b)"
},
{
"code": null,
"e": 13957,
"s": 13846,
"text": "31. static int min(int a, int b): This method returns the smaller of two int values as if by calling Math.min."
},
{
"code": null,
"e": 13966,
"s": 13957,
"text": "Syntax: "
},
{
"code": null,
"e": 14002,
"s": 13966,
"text": "public static int min(int a, int b)"
},
{
"code": null,
"e": 14249,
"s": 14002,
"text": "32. static int parseUnsignedInt(CharSequence s, int beginIndex, int endIndex, int radix): This method parses the CharSequence argument as an unsigned int in the specified radix, beginning at the specified beginIndex and extending to endIndex – 1."
},
{
"code": null,
"e": 14258,
"s": 14249,
"text": "Syntax: "
},
{
"code": null,
"e": 14512,
"s": 14258,
"text": "public static int parseUnsignedInt(CharSequence s,\n int beginIndex,\n int endIndex,\n int radix)\n throws NumberFormatException"
},
{
"code": null,
"e": 14626,
"s": 14512,
"text": "33. static int parseUnsignedInt(String s): This method parses the string argument as an unsigned decimal integer."
},
{
"code": null,
"e": 14635,
"s": 14626,
"text": "Syntax: "
},
{
"code": null,
"e": 14709,
"s": 14635,
"text": "public static int parseUnsignedInt(String s)\nthrows NumberFormatException"
},
{
"code": null,
"e": 14872,
"s": 14709,
"text": "34. static int parseUnsignedInt(String s, int radix): This method parses the string argument as an unsigned integer in the radix specified by the second argument."
},
{
"code": null,
"e": 14881,
"s": 14872,
"text": "Syntax: "
},
{
"code": null,
"e": 15029,
"s": 14881,
"text": "public static int parseUnsignedInt(String s,\n int radix)\n throws NumberFormatException"
},
{
"code": null,
"e": 15252,
"s": 15029,
"text": "35. static int remainderUnsigned(int dividend, int divisor): This method returns the unsigned remainder from dividing the first argument by the second where each argument and the result is interpreted as an unsigned value."
},
{
"code": null,
"e": 15261,
"s": 15252,
"text": "Syntax: "
},
{
"code": null,
"e": 15324,
"s": 15261,
"text": "public static int remainderUnsigned(int dividend, int divisor)"
},
{
"code": null,
"e": 15420,
"s": 15324,
"text": "36. static int sum(int a, int b): This method adds two integers together as per the + operator."
},
{
"code": null,
"e": 15429,
"s": 15420,
"text": "Syntax: "
},
{
"code": null,
"e": 15465,
"s": 15429,
"text": "public static int sum(int a, int b)"
},
{
"code": null,
"e": 15575,
"s": 15465,
"text": "37. static long toUnsignedLong(int x): This method converts the argument to a long by an unsigned conversion."
},
{
"code": null,
"e": 15584,
"s": 15575,
"text": "Syntax: "
},
{
"code": null,
"e": 15629,
"s": 15584,
"text": "public static long toUnsignedLong(int x) "
},
{
"code": null,
"e": 15762,
"s": 15629,
"text": "38. static String toUnsignedString(int i): This method returns a string representation of the argument as an unsigned decimal value."
},
{
"code": null,
"e": 15771,
"s": 15762,
"text": "Syntax: "
},
{
"code": null,
"e": 15828,
"s": 15771,
"text": "public static String toUnsignedString(int i, int radix) "
},
{
"code": null,
"e": 15833,
"s": 15828,
"text": "Java"
},
{
"code": "// Java program to illustrate// various Integer class methodspublic class Integer_test { public static void main(String args[]) { int b = 55; String bb = \"45\"; // Construct two Integer objects Integer x = new Integer(b); Integer y = new Integer(bb); // xxxValue can be used to retrieve // xxx type value from int value. // xxx can be int,byte,short,long,double,float System.out.println(\"bytevalue(x) = \" + x.byteValue()); System.out.println(\"shortvalue(x) = \" + x.shortValue()); System.out.println(\"intvalue(x) = \" + x.intValue()); System.out.println(\"longvalue(x) = \" + x.longValue()); System.out.println(\"doublevalue(x) = \" + x.doubleValue()); System.out.println(\"floatvalue(x) = \" + x.floatValue()); int value = 45; // bitcount() : can be used to count set bits // in twos complement form of the number System.out.println(\"Integer.bitcount(value)=\" + Integer.bitCount(value)); // numberOfTrailingZeroes and numberOfLeadingZeroes // can be used to count prefix and postfix sequence // of 0 System.out.println( \"Integer.numberOfTrailingZeros(value)=\" + Integer.numberOfTrailingZeros(value)); System.out.println( \"Integer.numberOfLeadingZeros(value)=\" + Integer.numberOfLeadingZeros(value)); // highestOneBit returns a value with one on highest // set bit position System.out.println(\"Integer.highestOneBit(value)=\" + Integer.highestOneBit(value)); // highestOneBit returns a value with one on lowest // set bit position System.out.println(\"Integer.lowestOneBit(value)=\" + Integer.lowestOneBit(value)); // reverse() can be used to reverse order of bits // reverseBytes() can be used to reverse order of // bytes System.out.println(\"Integer.reverse(value)=\" + Integer.reverse(value)); System.out.println(\"Integer.reverseBytes(value)=\" + Integer.reverseBytes(value)); // signum() returns -1,0,1 for negative,0 and // positive values System.out.println(\"Integer.signum(value)=\" + Integer.signum(value)); // hashcode() returns hashcode of the object int hash = x.hashCode(); System.out.println(\"hashcode(x) = \" + hash); // equals returns boolean value representing // equality boolean eq = x.equals(y); System.out.println(\"x.equals(y) = \" + eq); // compare() used for comparing two int values int e = Integer.compare(x, y); System.out.println(\"compare(x,y) = \" + e); // compareTo() used for comparing this value with // some other value int f = x.compareTo(y); System.out.println(\"x.compareTo(y) = \" + f); }}",
"e": 18947,
"s": 15833,
"text": null
},
{
"code": null,
"e": 18958,
"s": 18947,
"text": "Output : "
},
{
"code": null,
"e": 19409,
"s": 18958,
"text": "bytevalue(x) = 55\nshortvalue(x) = 55\nintvalue(x) = 55\nlongvalue(x) = 55\ndoublevalue(x) = 55.0\nfloatvalue(x) = 55.0\nInteger.bitcount(value)=4\nInteger.numberOfTrailingZeros(value)=0\nInteger.numberOfLeadingZeros(value)=26\nInteger.highestOneBit(value)=32\nInteger.lowestOneBit(value)=1\nInteger.reverse(value)=-1275068416\nInteger.reverseBytes(value)=754974720\nInteger.signum(value)=1\nhashcode(x) = 55\nx.equals(y) = false\ncompare(x,y) = 1\nx.compareTo(y) = 1"
},
{
"code": null,
"e": 19461,
"s": 19411,
"text": "Initialization of Integer wrapper class in Java :"
},
{
"code": null,
"e": 19492,
"s": 19461,
"text": "Type 1: Initializing directly:"
},
{
"code": null,
"e": 19715,
"s": 19492,
"text": "A constant object of Integer class will be created inside the space of constants in the heap memory. Space of constants: It is just to imagine for better understanding that there is some space for constants in heap memory."
},
{
"code": null,
"e": 19725,
"s": 19715,
"text": "Example: "
},
{
"code": null,
"e": 19833,
"s": 19725,
"text": "Integer x = 200; //initializing directly\nx = 300; //modifying x\nx = 10; //modifying x again"
},
{
"code": null,
"e": 19850,
"s": 19833,
"text": "Integer x = 200 "
},
{
"code": null,
"e": 20023,
"s": 19850,
"text": "The compiler converts the above statement into: Integer x=Integer.valueOf(200) . This is known as “Autoboxing”. The primitive integer value 200 is converted into an object."
},
{
"code": null,
"e": 20132,
"s": 20023,
"text": "( To understand Autoboxing & Unboxing check here: https://www.geeksforgeeks.org/autoboxing-unboxing-java/ ) "
},
{
"code": null,
"e": 20206,
"s": 20132,
"text": "x points to 200 which is present in the space of constants. Refer Fig. 1."
},
{
"code": null,
"e": 20213,
"s": 20206,
"text": "Fig. 1"
},
{
"code": null,
"e": 20221,
"s": 20213,
"text": "x = 300"
},
{
"code": null,
"e": 20314,
"s": 20221,
"text": "Autoboxing is done again because x is an Integer class object which is directly initialized."
},
{
"code": null,
"e": 20568,
"s": 20314,
"text": "Note: The directly initialized object(x) cannot be modified as it is a constant. When we try to modify the object by pointing to a new constant(300), the old constant(200) will be present in heap memory, but the object will be pointing the new constant."
},
{
"code": null,
"e": 20642,
"s": 20568,
"text": "x points to 300 which is present in the space of constants. Refer Fig. 2."
},
{
"code": null,
"e": 20649,
"s": 20642,
"text": "Fig. 2"
},
{
"code": null,
"e": 20656,
"s": 20649,
"text": "x = 10"
},
{
"code": null,
"e": 20804,
"s": 20656,
"text": "Note: By default for the values -128 to 127, Integer.valueOf() method will not create a new instance of Integer. It returns a value from its cache."
},
{
"code": null,
"e": 20843,
"s": 20804,
"text": "x points 10 which is present in cache."
},
{
"code": null,
"e": 20850,
"s": 20843,
"text": "Fig. 3"
},
{
"code": null,
"e": 21063,
"s": 20850,
"text": "If we assign x = 200 or x=300 next time, it will point to the value 200 or 300 which is present already in space of constants. If we assign values to x other than these two values, then it creates a new constant."
},
{
"code": null,
"e": 21139,
"s": 21063,
"text": "(Check the Integer wrapper class comparison topic for better understanding)"
},
{
"code": null,
"e": 21173,
"s": 21139,
"text": "Type 2: Initializing dynamically:"
},
{
"code": null,
"e": 21415,
"s": 21173,
"text": "An Integer class object which is not a constant will be created outside the space of constants. It also creates a Integer constant inside the space of constants. The variable will be pointing to the Integer object & not the Integer constant."
},
{
"code": null,
"e": 21425,
"s": 21415,
"text": "Example: "
},
{
"code": null,
"e": 21528,
"s": 21425,
"text": "Integer a = new Integer(250); //Initializing dynamically\na = 350; //Type 1 initialization"
},
{
"code": null,
"e": 21558,
"s": 21528,
"text": "Integer a = new Integer(250) "
},
{
"code": null,
"e": 21710,
"s": 21558,
"text": "250 is created inside and outside the space of constants. Variable ‘a’ will be pointing the value that is outside the space of constants. Refer Fig. 4."
},
{
"code": null,
"e": 21717,
"s": 21710,
"text": "Fig. 4"
},
{
"code": null,
"e": 21728,
"s": 21717,
"text": "a = 350; "
},
{
"code": null,
"e": 21789,
"s": 21728,
"text": "After autoboxing, ‘a’ will be pointing to 350. Refer Fig. 5."
},
{
"code": null,
"e": 21796,
"s": 21789,
"text": "Fig. 5"
},
{
"code": null,
"e": 21922,
"s": 21796,
"text": "If we assign a = 250 next time, it will not point to the object already present with same value, it will create a new object."
},
{
"code": null,
"e": 22088,
"s": 21922,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.References: Official Java Documentation "
},
{
"code": null,
"e": 22389,
"s": 22090,
"text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 22402,
"s": 22389,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 22417,
"s": 22402,
"text": "pravin_kumar_s"
},
{
"code": null,
"e": 22432,
"s": 22417,
"text": "varshagumber28"
},
{
"code": null,
"e": 22447,
"s": 22432,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 22456,
"s": 22447,
"text": "sweetyty"
},
{
"code": null,
"e": 22472,
"s": 22456,
"text": "simranarora5sos"
},
{
"code": null,
"e": 22485,
"s": 22472,
"text": "simmytarika5"
},
{
"code": null,
"e": 22499,
"s": 22485,
"text": "mitalibhola94"
},
{
"code": null,
"e": 22512,
"s": 22499,
"text": "Java-Integer"
},
{
"code": null,
"e": 22530,
"s": 22512,
"text": "Java-lang package"
},
{
"code": null,
"e": 22549,
"s": 22530,
"text": "java-wrapper-class"
},
{
"code": null,
"e": 22554,
"s": 22549,
"text": "Java"
},
{
"code": null,
"e": 22559,
"s": 22554,
"text": "Java"
},
{
"code": null,
"e": 22657,
"s": 22559,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 22672,
"s": 22657,
"text": "Arrays in Java"
},
{
"code": null,
"e": 22708,
"s": 22672,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 22752,
"s": 22708,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 22777,
"s": 22752,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 22828,
"s": 22777,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 22850,
"s": 22828,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 22881,
"s": 22850,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 22900,
"s": 22881,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 22930,
"s": 22900,
"text": "HashMap in Java with Examples"
}
]
|
Python | Ways to shuffle a list | 24 Jun, 2021
Shuffling a sequence of numbers have always been an useful utility and the question that has appeared in many company placement interviews as well. Knowing more than one method to achieve this can always be a plus. Let’s discuss certain ways in which this can be achieved.Method #1 : Fisher–Yates shuffle AlgorithmThis is one of the famous algorithms that is mainly employed to shuffle a sequence of numbers in python. This algorithm just takes the higher index value, and swaps it with current value, this process repeats in a loop till end of the list.
Python3
# Python3 code to demonstrate# shuffle a list# using Fisher–Yates shuffle Algorithm import random # initializing listtest_list = [1, 4, 5, 6, 3] # Printing original listprint ("The original list is : " + str(test_list)) # using Fisher–Yates shuffle Algorithm# to shuffle a listfor i in range(len(test_list)-1, 0, -1): # Pick a random index from 0 to i j = random.randint(0, i + 1) # Swap arr[i] with the element at random index test_list[i], test_list[j] = test_list[j], test_list[i] # Printing shuffled listprint ("The shuffled list is : " + str(test_list))
The original list is : [1, 4, 5, 6, 3]
The shuffled list is : [4, 3, 1, 5, 6]
Method #2 : Using random.shuffle() This is most recommended method to shuffle a list. Python in its random library provides this inbuilt function which in-place shuffles the list. Drawback of this is that list ordering is lost in this process. Useful for developers who choose to save time and hustle.
Python3
# Python3 code to demonstrate# shuffle a list# using random.shuffle() import random # initializing listtest_list = [1, 4, 5, 6, 3] # Printing original listprint ("The original list is : " + str(test_list)) # using random.shuffle()# to shuffle a listrandom.shuffle(test_list) # Printing shuffled listprint ("The shuffled list is : " + str(test_list))
The original list is : [1, 4, 5, 6, 3]
The shuffled list is : [5, 6, 4, 3, 1]
Method #3 : Using random.sample() This is quite a useful function, better than the shuffle method used above in aspect that it creates a new shuffled list and returns it rather than disturbing the order of original list. This is useful in cases we require to retain the original list.
Python3
# Python3 code to demonstrate# shuffle a list# using random.sample() import random # initializing listtest_list = [1, 4, 5, 6, 3] # Printing original listprint ("The original list is : " + str(test_list)) # using random.sample()# to shuffle a listres = random.sample(test_list, len(test_list)) # Printing shuffled listprint ("The shuffled list is : " + str(res))
The original list is : [1, 4, 5, 6, 3]
The shuffled list is : [5, 3, 6, 1, 4]
Method 4:
In this method we select a index randomly and append that element at that index to the list.
Python3
import random # Assign arrayarr = [1, 2, 3, 4, 5, 6] # Display original arrayprint("Original List: ", arr) # Get length of Listn = len(arr) #repeat the following for n number of timesfor i in range(n): #select an index randomly j = random.randint(0, n-1) #delete the element at that index. element=arr.pop(j) #now append that deleted element to the list arr.append(element)print("Shuffled List: ",arr)
Original List: [1, 2, 3, 4, 5, 6]
Shuffled List: [4, 5, 3, 2, 6, 1]
pulamolusaimohan
Python list-programs
python-list
Python
python-list
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
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 | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 610,
"s": 53,
"text": "Shuffling a sequence of numbers have always been an useful utility and the question that has appeared in many company placement interviews as well. Knowing more than one method to achieve this can always be a plus. Let’s discuss certain ways in which this can be achieved.Method #1 : Fisher–Yates shuffle AlgorithmThis is one of the famous algorithms that is mainly employed to shuffle a sequence of numbers in python. This algorithm just takes the higher index value, and swaps it with current value, this process repeats in a loop till end of the list. "
},
{
"code": null,
"e": 618,
"s": 610,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# shuffle a list# using Fisher–Yates shuffle Algorithm import random # initializing listtest_list = [1, 4, 5, 6, 3] # Printing original listprint (\"The original list is : \" + str(test_list)) # using Fisher–Yates shuffle Algorithm# to shuffle a listfor i in range(len(test_list)-1, 0, -1): # Pick a random index from 0 to i j = random.randint(0, i + 1) # Swap arr[i] with the element at random index test_list[i], test_list[j] = test_list[j], test_list[i] # Printing shuffled listprint (\"The shuffled list is : \" + str(test_list))",
"e": 1202,
"s": 618,
"text": null
},
{
"code": null,
"e": 1280,
"s": 1202,
"text": "The original list is : [1, 4, 5, 6, 3]\nThe shuffled list is : [4, 3, 1, 5, 6]"
},
{
"code": null,
"e": 1587,
"s": 1282,
"text": " Method #2 : Using random.shuffle() This is most recommended method to shuffle a list. Python in its random library provides this inbuilt function which in-place shuffles the list. Drawback of this is that list ordering is lost in this process. Useful for developers who choose to save time and hustle. "
},
{
"code": null,
"e": 1595,
"s": 1587,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# shuffle a list# using random.shuffle() import random # initializing listtest_list = [1, 4, 5, 6, 3] # Printing original listprint (\"The original list is : \" + str(test_list)) # using random.shuffle()# to shuffle a listrandom.shuffle(test_list) # Printing shuffled listprint (\"The shuffled list is : \" + str(test_list))",
"e": 1946,
"s": 1595,
"text": null
},
{
"code": null,
"e": 2024,
"s": 1946,
"text": "The original list is : [1, 4, 5, 6, 3]\nThe shuffled list is : [5, 6, 4, 3, 1]"
},
{
"code": null,
"e": 2314,
"s": 2026,
"text": " Method #3 : Using random.sample() This is quite a useful function, better than the shuffle method used above in aspect that it creates a new shuffled list and returns it rather than disturbing the order of original list. This is useful in cases we require to retain the original list. "
},
{
"code": null,
"e": 2322,
"s": 2314,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# shuffle a list# using random.sample() import random # initializing listtest_list = [1, 4, 5, 6, 3] # Printing original listprint (\"The original list is : \" + str(test_list)) # using random.sample()# to shuffle a listres = random.sample(test_list, len(test_list)) # Printing shuffled listprint (\"The shuffled list is : \" + str(res))",
"e": 2686,
"s": 2322,
"text": null
},
{
"code": null,
"e": 2764,
"s": 2686,
"text": "The original list is : [1, 4, 5, 6, 3]\nThe shuffled list is : [5, 3, 6, 1, 4]"
},
{
"code": null,
"e": 2776,
"s": 2766,
"text": "Method 4:"
},
{
"code": null,
"e": 2869,
"s": 2776,
"text": "In this method we select a index randomly and append that element at that index to the list."
},
{
"code": null,
"e": 2877,
"s": 2869,
"text": "Python3"
},
{
"code": "import random # Assign arrayarr = [1, 2, 3, 4, 5, 6] # Display original arrayprint(\"Original List: \", arr) # Get length of Listn = len(arr) #repeat the following for n number of timesfor i in range(n): #select an index randomly j = random.randint(0, n-1) #delete the element at that index. element=arr.pop(j) #now append that deleted element to the list arr.append(element)print(\"Shuffled List: \",arr)",
"e": 3297,
"s": 2877,
"text": null
},
{
"code": null,
"e": 3367,
"s": 3297,
"text": "Original List: [1, 2, 3, 4, 5, 6]\nShuffled List: [4, 5, 3, 2, 6, 1]"
},
{
"code": null,
"e": 3384,
"s": 3367,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 3405,
"s": 3384,
"text": "Python list-programs"
},
{
"code": null,
"e": 3417,
"s": 3405,
"text": "python-list"
},
{
"code": null,
"e": 3424,
"s": 3417,
"text": "Python"
},
{
"code": null,
"e": 3436,
"s": 3424,
"text": "python-list"
},
{
"code": null,
"e": 3534,
"s": 3436,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3576,
"s": 3534,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3598,
"s": 3576,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3624,
"s": 3598,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3656,
"s": 3624,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3685,
"s": 3656,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3712,
"s": 3685,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3748,
"s": 3712,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3779,
"s": 3748,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3816,
"s": 3779,
"text": "Create a Pandas DataFrame from Lists"
}
]
|
How to compare String equality in Java? | You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
import java.lang.*
public class StringDemo {
public static void main(String[] args) {
String str1 = "Tutorialspoint";
String str2 = "Tutorialspoint";
String str3 = "Hi";
// checking for equality
boolean retval1 = str2.equals(str1);
boolean retval2 = str2.equals(str3);
// prints the return value
System.out.println("str2 is equal to str1 = " + retval1);
System.out.println("str2 is equal to str3 = " + retval2);
}
}
str2 is equal to str1 = true
str2 is equal to str3 = false | [
{
"code": null,
"e": 1468,
"s": 1187,
"text": "You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object."
},
{
"code": null,
"e": 1956,
"s": 1468,
"text": "import java.lang.*\npublic class StringDemo {\n public static void main(String[] args) {\n String str1 = \"Tutorialspoint\";\n String str2 = \"Tutorialspoint\";\n String str3 = \"Hi\";\n \n // checking for equality\n boolean retval1 = str2.equals(str1);\n boolean retval2 = str2.equals(str3);\n \n // prints the return value\n System.out.println(\"str2 is equal to str1 = \" + retval1);\n System.out.println(\"str2 is equal to str3 = \" + retval2);\n }\n}"
},
{
"code": null,
"e": 2015,
"s": 1956,
"text": "str2 is equal to str1 = true\nstr2 is equal to str3 = false"
}
]
|
How to count the number of lines in a CSV file in Python? | 24 Jan, 2021
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.
In this article, we are going to discuss various approaches to count the number of lines in a CSV file using Python.
We are going to use the below dataset to perform all operations:
Python3
# import moduleimport pandas as pd # read the csv fileresults = pd.read_csv('Data.csv') # display datasetprint(results)
Output:
To count the number of lines/rows present in a CSV file, we have two different types of methods:
Using len() function.
Using a counter.
Under this method, we need to read the CSV file using pandas library and then use the len() function with the imported CSV file, which will return an int value of a number of lines/rows present in the CSV file.
Python3
# import moduleimport pandas as pd # read CSV fileresults = pd.read_csv('Data.csv') # count no. of linesprint("Number of lines present:-", len(results))
Output:
Under this approach, we will be initializing an integer rowcount to -1 (not 0 as iteration will start from the heading and not the first row)at the beginning and iterate through the whole file and incrementing the rowcount by one. And in the end, we will be printing the rowcount value.
Python3
#Setting initial value of the counter to zerorowcount = 0#iterating through the whole filefor row in open("Data.csv"): rowcount+= 1 #printing the resultprint("Number of lines present:-", rowcount)
Output:
Picked
python-csv
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 429,
"s": 53,
"text": "CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format."
},
{
"code": null,
"e": 546,
"s": 429,
"text": "In this article, we are going to discuss various approaches to count the number of lines in a CSV file using Python."
},
{
"code": null,
"e": 611,
"s": 546,
"text": "We are going to use the below dataset to perform all operations:"
},
{
"code": null,
"e": 619,
"s": 611,
"text": "Python3"
},
{
"code": "# import moduleimport pandas as pd # read the csv fileresults = pd.read_csv('Data.csv') # display datasetprint(results)",
"e": 741,
"s": 619,
"text": null
},
{
"code": null,
"e": 749,
"s": 741,
"text": "Output:"
},
{
"code": null,
"e": 846,
"s": 749,
"text": "To count the number of lines/rows present in a CSV file, we have two different types of methods:"
},
{
"code": null,
"e": 868,
"s": 846,
"text": "Using len() function."
},
{
"code": null,
"e": 885,
"s": 868,
"text": "Using a counter."
},
{
"code": null,
"e": 1096,
"s": 885,
"text": "Under this method, we need to read the CSV file using pandas library and then use the len() function with the imported CSV file, which will return an int value of a number of lines/rows present in the CSV file."
},
{
"code": null,
"e": 1104,
"s": 1096,
"text": "Python3"
},
{
"code": "# import moduleimport pandas as pd # read CSV fileresults = pd.read_csv('Data.csv') # count no. of linesprint(\"Number of lines present:-\", len(results))",
"e": 1265,
"s": 1104,
"text": null
},
{
"code": null,
"e": 1273,
"s": 1265,
"text": "Output:"
},
{
"code": null,
"e": 1560,
"s": 1273,
"text": "Under this approach, we will be initializing an integer rowcount to -1 (not 0 as iteration will start from the heading and not the first row)at the beginning and iterate through the whole file and incrementing the rowcount by one. And in the end, we will be printing the rowcount value."
},
{
"code": null,
"e": 1568,
"s": 1560,
"text": "Python3"
},
{
"code": "#Setting initial value of the counter to zerorowcount = 0#iterating through the whole filefor row in open(\"Data.csv\"): rowcount+= 1 #printing the resultprint(\"Number of lines present:-\", rowcount)",
"e": 1767,
"s": 1568,
"text": null
},
{
"code": null,
"e": 1775,
"s": 1767,
"text": "Output:"
},
{
"code": null,
"e": 1782,
"s": 1775,
"text": "Picked"
},
{
"code": null,
"e": 1793,
"s": 1782,
"text": "python-csv"
},
{
"code": null,
"e": 1800,
"s": 1793,
"text": "Python"
},
{
"code": null,
"e": 1898,
"s": 1800,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1930,
"s": 1898,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1957,
"s": 1930,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1978,
"s": 1957,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2001,
"s": 1978,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2057,
"s": 2001,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2088,
"s": 2057,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2130,
"s": 2088,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2172,
"s": 2130,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2211,
"s": 2172,
"text": "Python | datetime.timedelta() function"
}
]
|
Python Program for How to check if a given number is Fibonacci number? | 24 Feb, 2022
Given a number \’n\’, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .. Examples :
Input : 8
Output : Yes
Input : 34
Output : Yes
Input : 41
Output : No
Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not. A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki).
Python3
# python program to check if x is a perfect squareimport math # A utility function that returns true if x is perfect squaredef isPerfectSquare(x): s = int(math.sqrt(x)) return s*s == x # Returns true if n is a Fibonacci Number, else falsedef isFibonacci(n): # n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both # is a perfect square return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4) # A utility function to test above functionsfor i in range(1,11): if (isFibonacci(i) == True): print (i,"is a Fibonacci Number") else: print (i,"is a not Fibonacci Number ")
1 is a Fibonacci Number
2 is a Fibonacci Number
3 is a Fibonacci Number
4 is a not Fibonacci Number
5 is a Fibonacci Number
6 is a not Fibonacci Number
7 is a not Fibonacci Number
8 is a Fibonacci Number
9 is a not Fibonacci Number
10 is a not Fibonacci Number
Please refer complete article on How to check if a given number is Fibonacci number? for more details!
tiwaryshobhit
varshagumber28
amartyaghoshgfg
simmytarika5
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 208,
"s": 52,
"text": "Given a number \\’n\\’, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .. Examples : "
},
{
"code": null,
"e": 280,
"s": 208,
"text": "Input : 8\nOutput : Yes\n\nInput : 34\nOutput : Yes\n\nInput : 41\nOutput : No"
},
{
"code": null,
"e": 526,
"s": 280,
"text": "Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not. A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki). "
},
{
"code": null,
"e": 534,
"s": 526,
"text": "Python3"
},
{
"code": "# python program to check if x is a perfect squareimport math # A utility function that returns true if x is perfect squaredef isPerfectSquare(x): s = int(math.sqrt(x)) return s*s == x # Returns true if n is a Fibonacci Number, else falsedef isFibonacci(n): # n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both # is a perfect square return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4) # A utility function to test above functionsfor i in range(1,11): if (isFibonacci(i) == True): print (i,\"is a Fibonacci Number\") else: print (i,\"is a not Fibonacci Number \")",
"e": 1153,
"s": 534,
"text": null
},
{
"code": null,
"e": 1419,
"s": 1153,
"text": "1 is a Fibonacci Number\n2 is a Fibonacci Number\n3 is a Fibonacci Number\n4 is a not Fibonacci Number \n5 is a Fibonacci Number\n6 is a not Fibonacci Number \n7 is a not Fibonacci Number \n8 is a Fibonacci Number\n9 is a not Fibonacci Number \n10 is a not Fibonacci Number "
},
{
"code": null,
"e": 1523,
"s": 1419,
"text": "Please refer complete article on How to check if a given number is Fibonacci number? for more details! "
},
{
"code": null,
"e": 1537,
"s": 1523,
"text": "tiwaryshobhit"
},
{
"code": null,
"e": 1552,
"s": 1537,
"text": "varshagumber28"
},
{
"code": null,
"e": 1568,
"s": 1552,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 1581,
"s": 1568,
"text": "simmytarika5"
},
{
"code": null,
"e": 1597,
"s": 1581,
"text": "Python Programs"
}
]
|
Find smallest string with whose characters all given Strings can be generated | 17 Jan, 2022
Given an array of strings arr[]. The task is to generate the string which contains all the characters of all the strings present in array and smallest in size. There can be many such possible strings and any one is acceptable.
Examples:
Input: arr[] = {“your”, “you”, “or”, “yo”}Output: ruyoExplanation: The string “ruyo” is the string which contains all the characters present in all the strings in arr[].There can be many other strings of size 4 e.g. “oury”. Those are also acceptable.
Input: arr[] = {“abm”, “bmt”, “cd”, “tca”}Output: abctdm
Approach: This problem can be solved by using the Set Data Structure. Set has the capability to remove duplicates, which is needed in this problem in order to minimize the string size. Add all the characters in the set from all the strings in the array arr[] and form a string containing all the characters remaining in the set, which is the required answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ code for the above approach#include <bits/stdc++.h>using namespace std; string minSubstr(vector<string> s){ // Stores the concatenated string // of all the given strings string str = ""; // Loop to iterate through all // the given strings for (int i = 0; i < s.size(); i++) { str += s[i]; } // Set to store the characters unordered_set<char> set; // Loop to iterate over all // the characters in str for (int i = 0; i < str.length(); i++) { set.insert(str[i]); } string res = ""; // Loop to iterate over the set for (auto itr = set.begin(); itr != set.end(); itr++) { res = res + (*itr); } // Return Answer return res;} // Driver Codeint main(){ vector<string> arr = {"your", "you", "or", "yo"}; cout << (minSubstr(arr)); return 0;} // This code is contributed by Potta Lokesh
// Java program to implement above approachimport java.util.*; public class GfG { public static String minSubstr(String s[]) { // Stores the concatenated string // of all the given strings String str = ""; // Loop to iterate through all // the given strings for (int i = 0; i < s.length; i++) { str += s[i]; } // Set to store the characters Set<Character> set = new HashSet<Character>(); // Loop to iterate over all // the characters in str for (int i = 0; i < str.length(); i++) { set.add(str.charAt(i)); } // Stores the required answer String res = ""; Iterator<Character> itr = set.iterator(); // Loop to iterate over the set while (itr.hasNext()) { res += itr.next(); } // Return Answer return res; } // Driver Code public static void main(String[] args) { String arr[] = new String[] { "your", "you", "or", "yo" }; System.out.println(minSubstr(arr)); }}
# Python program to implement above approachdef minSubstr(s): # Stores the concatenated string # of all the given strings str = ""; # Loop to iterate through all # the given strings for i in range(len(s)): str += s[i]; # Set to store the characters setv = set(); # Loop to iterate over all # the characters in str for i in range(len(str)): setv.add(str[i]); # Stores the required answer res = ""; # Loop to iterate over the set for itr in setv: res += itr; # Return Answer return res; # Driver Codeif __name__ == '__main__': arr = ["your", "you", "or", "yo"]; print(minSubstr(arr)); # This code is contributed by 29AjayKumar
// C# program to implement above approachusing System;using System.Collections.Generic; public class GfG { public static String minSubstr(String []s) { // Stores the concatenated string // of all the given strings String str = ""; // Loop to iterate through all // the given strings for (int i = 0; i < s.Length; i++) { str += s[i]; } // Set to store the characters HashSet<char> set = new HashSet<char>(); // Loop to iterate over all // the characters in str for (int i = 0; i < str.Length; i++) { set.Add(str[i]); } // Stores the required answer String res = ""; // Loop to iterate over the set foreach (char itr in set) { res += itr; } // Return Answer return res; } // Driver Code public static void Main(String[] args) { String []arr = new String[] { "your", "you", "or", "yo" }; Console.WriteLine(minSubstr(arr)); }} // This code is contributed by 29AjayKumar
<script>// javascript program to implement above approachpublic class GfG{ function minSubstr(s) { // Stores the concatenated string // of all the given strings var str = ""; // Loop to iterate through all // the given strings for (var i = 0; i < s.length; i++) { str += s[i]; } // Set to store the characters var set = new Set(); // Loop to iterate over all // the characters in str for (var i = 0; i < str.length; i++) { set.add(str.charAt(i)); } // Stores the required answer var res = ""; // Loop to iterate over the set for(let itr of set){ res += itr; } // Return Answer return res; } // Driver Codevar arr = [ "your", "you", "or", "yo" ];document.write(minSubstr(arr)); // This code is contributed by 29AjayKumar</script>
ruyo
Time Complexity: O(N*M), where M is the average length of strings in the given arrayAuxiliary Space: O(1)
lokeshpotta20
29AjayKumar
Algo-Geek 2021
cpp-set
frequency-counting
Algo Geek
Hash
Mathematical
Searching
Strings
Searching
Hash
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Number of ways to divide a N elements equally into group of at least 2
Count of ordered pairs (i, j) such that arr[i] and arr[j] concatenates to X
Sort strings on the basis of their numeric part
Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index
Check if the given string is valid English word or not
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 281,
"s": 54,
"text": "Given an array of strings arr[]. The task is to generate the string which contains all the characters of all the strings present in array and smallest in size. There can be many such possible strings and any one is acceptable."
},
{
"code": null,
"e": 291,
"s": 281,
"text": "Examples:"
},
{
"code": null,
"e": 542,
"s": 291,
"text": "Input: arr[] = {“your”, “you”, “or”, “yo”}Output: ruyoExplanation: The string “ruyo” is the string which contains all the characters present in all the strings in arr[].There can be many other strings of size 4 e.g. “oury”. Those are also acceptable."
},
{
"code": null,
"e": 599,
"s": 542,
"text": "Input: arr[] = {“abm”, “bmt”, “cd”, “tca”}Output: abctdm"
},
{
"code": null,
"e": 958,
"s": 599,
"text": "Approach: This problem can be solved by using the Set Data Structure. Set has the capability to remove duplicates, which is needed in this problem in order to minimize the string size. Add all the characters in the set from all the strings in the array arr[] and form a string containing all the characters remaining in the set, which is the required answer."
},
{
"code": null,
"e": 1009,
"s": 958,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 1013,
"s": 1009,
"text": "C++"
},
{
"code": null,
"e": 1018,
"s": 1013,
"text": "Java"
},
{
"code": null,
"e": 1026,
"s": 1018,
"text": "Python3"
},
{
"code": null,
"e": 1029,
"s": 1026,
"text": "C#"
},
{
"code": null,
"e": 1040,
"s": 1029,
"text": "Javascript"
},
{
"code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; string minSubstr(vector<string> s){ // Stores the concatenated string // of all the given strings string str = \"\"; // Loop to iterate through all // the given strings for (int i = 0; i < s.size(); i++) { str += s[i]; } // Set to store the characters unordered_set<char> set; // Loop to iterate over all // the characters in str for (int i = 0; i < str.length(); i++) { set.insert(str[i]); } string res = \"\"; // Loop to iterate over the set for (auto itr = set.begin(); itr != set.end(); itr++) { res = res + (*itr); } // Return Answer return res;} // Driver Codeint main(){ vector<string> arr = {\"your\", \"you\", \"or\", \"yo\"}; cout << (minSubstr(arr)); return 0;} // This code is contributed by Potta Lokesh",
"e": 1956,
"s": 1040,
"text": null
},
{
"code": "// Java program to implement above approachimport java.util.*; public class GfG { public static String minSubstr(String s[]) { // Stores the concatenated string // of all the given strings String str = \"\"; // Loop to iterate through all // the given strings for (int i = 0; i < s.length; i++) { str += s[i]; } // Set to store the characters Set<Character> set = new HashSet<Character>(); // Loop to iterate over all // the characters in str for (int i = 0; i < str.length(); i++) { set.add(str.charAt(i)); } // Stores the required answer String res = \"\"; Iterator<Character> itr = set.iterator(); // Loop to iterate over the set while (itr.hasNext()) { res += itr.next(); } // Return Answer return res; } // Driver Code public static void main(String[] args) { String arr[] = new String[] { \"your\", \"you\", \"or\", \"yo\" }; System.out.println(minSubstr(arr)); }}",
"e": 3110,
"s": 1956,
"text": null
},
{
"code": "# Python program to implement above approachdef minSubstr(s): # Stores the concatenated string # of all the given strings str = \"\"; # Loop to iterate through all # the given strings for i in range(len(s)): str += s[i]; # Set to store the characters setv = set(); # Loop to iterate over all # the characters in str for i in range(len(str)): setv.add(str[i]); # Stores the required answer res = \"\"; # Loop to iterate over the set for itr in setv: res += itr; # Return Answer return res; # Driver Codeif __name__ == '__main__': arr = [\"your\", \"you\", \"or\", \"yo\"]; print(minSubstr(arr)); # This code is contributed by 29AjayKumar",
"e": 3823,
"s": 3110,
"text": null
},
{
"code": "// C# program to implement above approachusing System;using System.Collections.Generic; public class GfG { public static String minSubstr(String []s) { // Stores the concatenated string // of all the given strings String str = \"\"; // Loop to iterate through all // the given strings for (int i = 0; i < s.Length; i++) { str += s[i]; } // Set to store the characters HashSet<char> set = new HashSet<char>(); // Loop to iterate over all // the characters in str for (int i = 0; i < str.Length; i++) { set.Add(str[i]); } // Stores the required answer String res = \"\"; // Loop to iterate over the set foreach (char itr in set) { res += itr; } // Return Answer return res; } // Driver Code public static void Main(String[] args) { String []arr = new String[] { \"your\", \"you\", \"or\", \"yo\" }; Console.WriteLine(minSubstr(arr)); }} // This code is contributed by 29AjayKumar",
"e": 4828,
"s": 3823,
"text": null
},
{
"code": "<script>// javascript program to implement above approachpublic class GfG{ function minSubstr(s) { // Stores the concatenated string // of all the given strings var str = \"\"; // Loop to iterate through all // the given strings for (var i = 0; i < s.length; i++) { str += s[i]; } // Set to store the characters var set = new Set(); // Loop to iterate over all // the characters in str for (var i = 0; i < str.length; i++) { set.add(str.charAt(i)); } // Stores the required answer var res = \"\"; // Loop to iterate over the set for(let itr of set){ res += itr; } // Return Answer return res; } // Driver Codevar arr = [ \"your\", \"you\", \"or\", \"yo\" ];document.write(minSubstr(arr)); // This code is contributed by 29AjayKumar</script>",
"e": 5793,
"s": 4828,
"text": null
},
{
"code": null,
"e": 5801,
"s": 5796,
"text": "ruyo"
},
{
"code": null,
"e": 5909,
"s": 5803,
"text": "Time Complexity: O(N*M), where M is the average length of strings in the given arrayAuxiliary Space: O(1)"
},
{
"code": null,
"e": 5925,
"s": 5911,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 5937,
"s": 5925,
"text": "29AjayKumar"
},
{
"code": null,
"e": 5952,
"s": 5937,
"text": "Algo-Geek 2021"
},
{
"code": null,
"e": 5960,
"s": 5952,
"text": "cpp-set"
},
{
"code": null,
"e": 5979,
"s": 5960,
"text": "frequency-counting"
},
{
"code": null,
"e": 5989,
"s": 5979,
"text": "Algo Geek"
},
{
"code": null,
"e": 5994,
"s": 5989,
"text": "Hash"
},
{
"code": null,
"e": 6007,
"s": 5994,
"text": "Mathematical"
},
{
"code": null,
"e": 6017,
"s": 6007,
"text": "Searching"
},
{
"code": null,
"e": 6025,
"s": 6017,
"text": "Strings"
},
{
"code": null,
"e": 6035,
"s": 6025,
"text": "Searching"
},
{
"code": null,
"e": 6040,
"s": 6035,
"text": "Hash"
},
{
"code": null,
"e": 6048,
"s": 6040,
"text": "Strings"
},
{
"code": null,
"e": 6061,
"s": 6048,
"text": "Mathematical"
},
{
"code": null,
"e": 6159,
"s": 6061,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6230,
"s": 6159,
"text": "Number of ways to divide a N elements equally into group of at least 2"
},
{
"code": null,
"e": 6306,
"s": 6230,
"text": "Count of ordered pairs (i, j) such that arr[i] and arr[j] concatenates to X"
},
{
"code": null,
"e": 6354,
"s": 6306,
"text": "Sort strings on the basis of their numeric part"
},
{
"code": null,
"e": 6451,
"s": 6354,
"text": "Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index"
},
{
"code": null,
"e": 6506,
"s": 6451,
"text": "Check if the given string is valid English word or not"
},
{
"code": null,
"e": 6591,
"s": 6506,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 6629,
"s": 6591,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6665,
"s": 6629,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 6696,
"s": 6665,
"text": "Hashing | Set 1 (Introduction)"
}
]
|
MySQL Tryit Editor v1.0 | SELECT LENGTH("SQL Tutorial") AS LengthOfString;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 49,
"s": 0,
"text": "SELECT LENGTH(\"SQL Tutorial\") AS LengthOfString;"
},
{
"code": null,
"e": 51,
"s": 49,
"text": ""
},
{
"code": null,
"e": 123,
"s": 60,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 183,
"s": 123,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 251,
"s": 183,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 289,
"s": 251,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 374,
"s": 289,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 548,
"s": 374,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 599,
"s": 548,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 667,
"s": 599,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 838,
"s": 667,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 938,
"s": 838,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 988,
"s": 938,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
]
|
Longest Continuous Increasing Subsequence in C++ | Suppose we have an array of integers; we have to find the length of longest continuous
increasing subarray.
So, if the input is like [2,4,6,5,8], then the output will be 3. As the longest continuous increasing subsequence is [2,4,6], and its length is 3.
To solve this, we will follow these steps −
if size of nums <= 1, then −return size of nums
return size of nums
answer := 1, count := 1
for initialize i := 0, when i < size of nums, update (increase i by 1), do −if nums[i] < nums[i + 1], then −(increase count by 1)answer := maximum of answer and countOtherwisecount := 1
if nums[i] < nums[i + 1], then −(increase count by 1)answer := maximum of answer and count
(increase count by 1)
answer := maximum of answer and count
Otherwisecount := 1
count := 1
return answer
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findLengthOfLCIS(vector<int>& nums) {
if (nums.size() <= 1)
return nums.size();
int answer = 1, count = 1;
for (int i = 0; i < nums.size() - 1; i++) {
if (nums[i] < nums[i + 1]) {
count++;
answer = max(answer, count);
}
else {
count = 1;
}
}
return answer;
}
};
main(){
Solution ob;
vector<int> v = {2,4,6,5,8};
cout << (ob.findLengthOfLCIS(v));
}
{2,4,6,5,8}
3 | [
{
"code": null,
"e": 1170,
"s": 1062,
"text": "Suppose we have an array of integers; we have to find the length of longest continuous\nincreasing subarray."
},
{
"code": null,
"e": 1317,
"s": 1170,
"text": "So, if the input is like [2,4,6,5,8], then the output will be 3. As the longest continuous increasing subsequence is [2,4,6], and its length is 3."
},
{
"code": null,
"e": 1361,
"s": 1317,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1409,
"s": 1361,
"text": "if size of nums <= 1, then −return size of nums"
},
{
"code": null,
"e": 1429,
"s": 1409,
"text": "return size of nums"
},
{
"code": null,
"e": 1453,
"s": 1429,
"text": "answer := 1, count := 1"
},
{
"code": null,
"e": 1639,
"s": 1453,
"text": "for initialize i := 0, when i < size of nums, update (increase i by 1), do −if nums[i] < nums[i + 1], then −(increase count by 1)answer := maximum of answer and countOtherwisecount := 1"
},
{
"code": null,
"e": 1730,
"s": 1639,
"text": "if nums[i] < nums[i + 1], then −(increase count by 1)answer := maximum of answer and count"
},
{
"code": null,
"e": 1752,
"s": 1730,
"text": "(increase count by 1)"
},
{
"code": null,
"e": 1790,
"s": 1752,
"text": "answer := maximum of answer and count"
},
{
"code": null,
"e": 1810,
"s": 1790,
"text": "Otherwisecount := 1"
},
{
"code": null,
"e": 1821,
"s": 1810,
"text": "count := 1"
},
{
"code": null,
"e": 1835,
"s": 1821,
"text": "return answer"
},
{
"code": null,
"e": 1905,
"s": 1835,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1916,
"s": 1905,
"text": " Live Demo"
},
{
"code": null,
"e": 2465,
"s": 1916,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int findLengthOfLCIS(vector<int>& nums) {\n if (nums.size() <= 1)\n return nums.size();\n int answer = 1, count = 1;\n for (int i = 0; i < nums.size() - 1; i++) {\n if (nums[i] < nums[i + 1]) {\n count++;\n answer = max(answer, count);\n }\n else {\n count = 1;\n }\n }\n return answer;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {2,4,6,5,8};\n cout << (ob.findLengthOfLCIS(v));\n}"
},
{
"code": null,
"e": 2477,
"s": 2465,
"text": "{2,4,6,5,8}"
},
{
"code": null,
"e": 2479,
"s": 2477,
"text": "3"
}
]
|
Practice questions on Strings - GeeksforGeeks | 21 Apr, 2020
String is an important topic from GATE exam point of view. We will discuss key points on strings as well different types of questions based on that.
There are two ways to store strings as character array (char p[20]) or a pointer pointing to a string (char* s = “string”), both of which can be accessed as arrays. Assuming p as character array and s as pointer pointing to a string, following are the key points:
The operator sizeof(p) will give the memory allocated to character array. However, sizeof(s) will give size of pointer which is independent of the string pointed by p.
Each string is appended by a null character (‘\0’) which depicts end of the string.
The length of string can be calculated using strlen() function. However, the function does not include null character ‘\0’ in the length. For example, strlen(s) will return 6.
Single character from strings can be printed as:printf(“%c”, s[0]);
printf(“%c”, p[1]);
printf(“%c”, s[0]);
printf(“%c”, p[1]);
Complete string can be printed as:printf(“%s”, s);
printf(“%s”, p);
printf(“%s”, s);
printf(“%s”, p);
As p is a character array, its individual elements can be modified (p[i] = ‘c’). However, using s (a pointer to string), individual elements of string can’t be modified.
As s is a pointer, it can be pointed to any other string as well (s =”string2”). However, using p, it is not possible.
Let us discuss some problems based on the concepts discussed:
Que – 1. What does the following fragment of C-program print?
char c[] = "GEEK2018";
char *p =c;
printf("%c,%c", *p,*(p+p[3]-p[1]));
(A) G, 1(B) G, K(C) GEEK2018(D) None of the above
Solution: As given in the question, p points to character array c[] which can be represented as:
As p is a pointer of type character, *p will print ‘G’
Using pointer arithmetic,*(p+p[3]-p[1]) = *(p+75-69) (Using ascii values of K and E) = *(p+6) = 1(as we know p is holding the address of base string means 0th poision string, let assume the address of string starts with 2000 so p+6 means the address of p(we are adding 6 in 2000 that means 2006, and in 2006 the “1”is stored that is why answer is 1).Therefore, the output will be G, 1.
Que – 2. Which of the following C code snippet is not valid?
(A) char* p = “string1”; printf(“%c”, *++p);(B) char q[] = “string1”; printf(“%c”, *++q);(C) char* r = “string1”; printf(“%c”, r[1]);(D) None of the above
Solution: Option (A) is valid as p is a pointer pointing to character ‘s’ of “string1”. Using ++p, p will point to character ‘t’ in “string1”. Therefore, *++p will print ‘t’.Option (B) is invalid as q being base address of character array, ++q(increasing base address) is invalid.Option (C) is valid as r is a pointer pointing to character ‘s’ of “string1”. Therefore,
r[1] = *(r+1) = ‘t’ and it will print ‘t’.
Que – 3. Consider the following C program segment: (GATE CS 2004)
char p[20];
char *s = "string";
int length = strlen(s);
int i;
for (i = 0; i < length; i++)
p[i] = s[length — i];
printf("%s",p);
The output of the program is:(A) gnirts(B) gnirt(C) string(D) no output is printed
Solution: In the given code, p[20] is declared as a character array and s is a pointer pointing to a string. The length will be initialized to 6. In the first iteration of for loop (i = 0),
p[i] = s[6-0] and s[6] is ‘\0’Therefore, p[0] becomes ‘\0’. As discussed, ‘\0’ means end of string. Therefore, nothing is printed as first character of string is ‘\0’.
Que – 4. What does the following fragment of C-program print?
char c[] = "GATE2011";
char *p =c;
printf("%s", p + p[3] - p[1]) ;
(A) GATE2011(B) E2011(C) 2011(D) 011
Solution: As given in the question, p points to character array c[] which can be represented as:
As p is a pointer of type character, using pointer arithmetic,p + p[3] – p[1] = p + 69 – 65 (Using Ascii values of A and E) = p + 4
Now, p + 4 will point to 2, the string starting from 2 till ‘\0’ will be printed which is 2011.
sharmanishi9868
GATE CS
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Cache Memory in Computer Organization
Semaphores in Process Synchronization
Reverse a string in Java
C++ Data Types
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 26309,
"s": 26281,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 26458,
"s": 26309,
"text": "String is an important topic from GATE exam point of view. We will discuss key points on strings as well different types of questions based on that."
},
{
"code": null,
"e": 26722,
"s": 26458,
"text": "There are two ways to store strings as character array (char p[20]) or a pointer pointing to a string (char* s = “string”), both of which can be accessed as arrays. Assuming p as character array and s as pointer pointing to a string, following are the key points:"
},
{
"code": null,
"e": 26890,
"s": 26722,
"text": "The operator sizeof(p) will give the memory allocated to character array. However, sizeof(s) will give size of pointer which is independent of the string pointed by p."
},
{
"code": null,
"e": 26974,
"s": 26890,
"text": "Each string is appended by a null character (‘\\0’) which depicts end of the string."
},
{
"code": null,
"e": 27150,
"s": 26974,
"text": "The length of string can be calculated using strlen() function. However, the function does not include null character ‘\\0’ in the length. For example, strlen(s) will return 6."
},
{
"code": null,
"e": 27238,
"s": 27150,
"text": "Single character from strings can be printed as:printf(“%c”, s[0]);\nprintf(“%c”, p[1]);"
},
{
"code": null,
"e": 27278,
"s": 27238,
"text": "printf(“%c”, s[0]);\nprintf(“%c”, p[1]);"
},
{
"code": null,
"e": 27346,
"s": 27278,
"text": "Complete string can be printed as:printf(“%s”, s);\nprintf(“%s”, p);"
},
{
"code": null,
"e": 27380,
"s": 27346,
"text": "printf(“%s”, s);\nprintf(“%s”, p);"
},
{
"code": null,
"e": 27550,
"s": 27380,
"text": "As p is a character array, its individual elements can be modified (p[i] = ‘c’). However, using s (a pointer to string), individual elements of string can’t be modified."
},
{
"code": null,
"e": 27669,
"s": 27550,
"text": "As s is a pointer, it can be pointed to any other string as well (s =”string2”). However, using p, it is not possible."
},
{
"code": null,
"e": 27731,
"s": 27669,
"text": "Let us discuss some problems based on the concepts discussed:"
},
{
"code": null,
"e": 27793,
"s": 27731,
"text": "Que – 1. What does the following fragment of C-program print?"
},
{
"code": null,
"e": 27864,
"s": 27793,
"text": "char c[] = \"GEEK2018\";\nchar *p =c;\nprintf(\"%c,%c\", *p,*(p+p[3]-p[1]));"
},
{
"code": null,
"e": 27914,
"s": 27864,
"text": "(A) G, 1(B) G, K(C) GEEK2018(D) None of the above"
},
{
"code": null,
"e": 28011,
"s": 27914,
"text": "Solution: As given in the question, p points to character array c[] which can be represented as:"
},
{
"code": null,
"e": 28066,
"s": 28011,
"text": "As p is a pointer of type character, *p will print ‘G’"
},
{
"code": null,
"e": 28452,
"s": 28066,
"text": "Using pointer arithmetic,*(p+p[3]-p[1]) = *(p+75-69) (Using ascii values of K and E) = *(p+6) = 1(as we know p is holding the address of base string means 0th poision string, let assume the address of string starts with 2000 so p+6 means the address of p(we are adding 6 in 2000 that means 2006, and in 2006 the “1”is stored that is why answer is 1).Therefore, the output will be G, 1."
},
{
"code": null,
"e": 28513,
"s": 28452,
"text": "Que – 2. Which of the following C code snippet is not valid?"
},
{
"code": null,
"e": 28668,
"s": 28513,
"text": "(A) char* p = “string1”; printf(“%c”, *++p);(B) char q[] = “string1”; printf(“%c”, *++q);(C) char* r = “string1”; printf(“%c”, r[1]);(D) None of the above"
},
{
"code": null,
"e": 29037,
"s": 28668,
"text": "Solution: Option (A) is valid as p is a pointer pointing to character ‘s’ of “string1”. Using ++p, p will point to character ‘t’ in “string1”. Therefore, *++p will print ‘t’.Option (B) is invalid as q being base address of character array, ++q(increasing base address) is invalid.Option (C) is valid as r is a pointer pointing to character ‘s’ of “string1”. Therefore,"
},
{
"code": null,
"e": 29080,
"s": 29037,
"text": "r[1] = *(r+1) = ‘t’ and it will print ‘t’."
},
{
"code": null,
"e": 29146,
"s": 29080,
"text": "Que – 3. Consider the following C program segment: (GATE CS 2004)"
},
{
"code": null,
"e": 29281,
"s": 29146,
"text": "char p[20];\nchar *s = \"string\";\nint length = strlen(s);\nint i;\nfor (i = 0; i < length; i++)\n p[i] = s[length — i];\nprintf(\"%s\",p);"
},
{
"code": null,
"e": 29364,
"s": 29281,
"text": "The output of the program is:(A) gnirts(B) gnirt(C) string(D) no output is printed"
},
{
"code": null,
"e": 29554,
"s": 29364,
"text": "Solution: In the given code, p[20] is declared as a character array and s is a pointer pointing to a string. The length will be initialized to 6. In the first iteration of for loop (i = 0),"
},
{
"code": null,
"e": 29722,
"s": 29554,
"text": "p[i] = s[6-0] and s[6] is ‘\\0’Therefore, p[0] becomes ‘\\0’. As discussed, ‘\\0’ means end of string. Therefore, nothing is printed as first character of string is ‘\\0’."
},
{
"code": null,
"e": 29784,
"s": 29722,
"text": "Que – 4. What does the following fragment of C-program print?"
},
{
"code": null,
"e": 29851,
"s": 29784,
"text": "char c[] = \"GATE2011\";\nchar *p =c;\nprintf(\"%s\", p + p[3] - p[1]) ;"
},
{
"code": null,
"e": 29888,
"s": 29851,
"text": "(A) GATE2011(B) E2011(C) 2011(D) 011"
},
{
"code": null,
"e": 29985,
"s": 29888,
"text": "Solution: As given in the question, p points to character array c[] which can be represented as:"
},
{
"code": null,
"e": 30117,
"s": 29985,
"text": "As p is a pointer of type character, using pointer arithmetic,p + p[3] – p[1] = p + 69 – 65 (Using Ascii values of A and E) = p + 4"
},
{
"code": null,
"e": 30213,
"s": 30117,
"text": "Now, p + 4 will point to 2, the string starting from 2 till ‘\\0’ will be printed which is 2011."
},
{
"code": null,
"e": 30229,
"s": 30213,
"text": "sharmanishi9868"
},
{
"code": null,
"e": 30237,
"s": 30229,
"text": "GATE CS"
},
{
"code": null,
"e": 30245,
"s": 30237,
"text": "Strings"
},
{
"code": null,
"e": 30253,
"s": 30245,
"text": "Strings"
},
{
"code": null,
"e": 30351,
"s": 30253,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30372,
"s": 30351,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 30421,
"s": 30372,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 30453,
"s": 30421,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 30491,
"s": 30453,
"text": "Cache Memory in Computer Organization"
},
{
"code": null,
"e": 30529,
"s": 30491,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 30554,
"s": 30529,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30569,
"s": 30554,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30603,
"s": 30569,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 30663,
"s": 30603,
"text": "Write a program to print all permutations of a given string"
}
]
|
How to build an integration between AutoML and MLFlow | by Bogdan Cojocar | Towards Data Science | In this article, we will go over the concept of AutoML, how it can improve your productivity and how to track it’s performance metrics.
We will use the following technologies:
Python 3
H2O AutoML
MLFlow
As the name suggests, it is the process to automate a machine learning pipeline. We can automate various stages of the process like data preparation, feature engineering, model selection, and hyperparameter selection. In this tutorial, we will focus mainly on model selection.
There are numerous benefits in using this approach such as:
cost reduction by increasing the productivity of the data scientist
reducing the amount of repetitive work and boring tasks that they have to do
the performance of the model selection can be used as a benchmark and to figure out what models would be best to investigate further by the data scientists
What is MLFlow?
MLFlow is an open-source platform used to monitor and save machine learning models after training. The great thing about it is that it can integrate with other frameworks such as H2O or Spark building a uniform and easy to use environment.
Now let’s dive into the steps to use AutoML in practice.
TL;DR: The code is stored in Github.
To get the environment ready we need to install the new dependencies found in the folder of the project:
pip install -r requirements.txt
Also we need to start the MLFlow server by typing in the terminal:
mlflow ui
We sound be able to see the MlFlow ui now by running in the browser http://127.0.0.1:5000:
Now we should be able to visualise all the experiments (training steps) we run. We can also start the Jupyter lab notebook which is the environment where we write our code:
jupyter lab
H2O is a distributed framework and in order to use it locally we need to start a server. This might take a minute or so, depending on your setup:
h2o.init()
MLFlow uses the concept of experiments to track the progress of a machine learning model.
try: experiment = mlflow.create_experiment(experiment_name)except: experiment = client.get_experiment_by_name(experiment_name)mlflow.set_experiment(experiment_name)
If the experiment is already created, we just reuse it.
We have reached the most interesting part, using auto ml to do the training. Multiple models are trained in parallel and validated (6 fold cross-validation) using an independent subset of the data. Every new training run will save some validation metrics and the model that has performed the best (leader).
with mlflow.start_run(): model = H2OAutoML(max_models=10, max_runtime_secs=300, seed=24, nfolds=6) model.train(x=x_cols, y=y_cols, training_frame=train, validation_frame=valid) mlflow.log_metric("rmse", model.leader.rmse()) mlflow.log_metric("log_loss", model.leader.logloss()) mlflow.log_metric("mean_per_class_error", model.leader.mean_per_class_error()) mlflow.h2o.log_model(model.leader, "model") lb = model.leaderboard lb = get_leaderboard(model, extra_columns='ALL') print(lb.head(rows=lb.nrows))
We have decided to run 10 models. Using the get_leaderboard function we get to see what machine learning algorithms have run:
And the training is recorded in MLFlow, and we can compare it with future experiments:
The last step is to actually do the prediction with the newly elected leader. For the purpose of this tutorial we will just use the validation data, but in practice we need to use new data.
all_mlflow_runs = client.list_run_infos(experiment.experiment_id)if len(all_mlflow_runs) > 0: run_info = all_mlflow_runs[-1] model = mlflow.h2o.load_model("mlruns/{exp_id}/{run_id}/artifacts/model/".format(exp_id=experiment.experiment_id,run_id=run_info.run_uuid)) result = model.predict(valid)else: raise Exception('Run the training first')
Again we use MLFlow to read the latest run in the experiment and load the GLM model. If we never run the training we can throw an exception to notify the user that he has to do that first.
We’ve seen how in a few simple steps we can have an automated process for model selection, tracking and loading/saving the best machine learning model for a given set of data. Although on competitions like Kaggle we can see that humans are still easily beating AutoML frameworks, we can still use them as another tool in our data science kit, to boost and improve our performance. | [
{
"code": null,
"e": 307,
"s": 171,
"text": "In this article, we will go over the concept of AutoML, how it can improve your productivity and how to track it’s performance metrics."
},
{
"code": null,
"e": 347,
"s": 307,
"text": "We will use the following technologies:"
},
{
"code": null,
"e": 356,
"s": 347,
"text": "Python 3"
},
{
"code": null,
"e": 367,
"s": 356,
"text": "H2O AutoML"
},
{
"code": null,
"e": 374,
"s": 367,
"text": "MLFlow"
},
{
"code": null,
"e": 651,
"s": 374,
"text": "As the name suggests, it is the process to automate a machine learning pipeline. We can automate various stages of the process like data preparation, feature engineering, model selection, and hyperparameter selection. In this tutorial, we will focus mainly on model selection."
},
{
"code": null,
"e": 711,
"s": 651,
"text": "There are numerous benefits in using this approach such as:"
},
{
"code": null,
"e": 779,
"s": 711,
"text": "cost reduction by increasing the productivity of the data scientist"
},
{
"code": null,
"e": 856,
"s": 779,
"text": "reducing the amount of repetitive work and boring tasks that they have to do"
},
{
"code": null,
"e": 1012,
"s": 856,
"text": "the performance of the model selection can be used as a benchmark and to figure out what models would be best to investigate further by the data scientists"
},
{
"code": null,
"e": 1028,
"s": 1012,
"text": "What is MLFlow?"
},
{
"code": null,
"e": 1268,
"s": 1028,
"text": "MLFlow is an open-source platform used to monitor and save machine learning models after training. The great thing about it is that it can integrate with other frameworks such as H2O or Spark building a uniform and easy to use environment."
},
{
"code": null,
"e": 1325,
"s": 1268,
"text": "Now let’s dive into the steps to use AutoML in practice."
},
{
"code": null,
"e": 1362,
"s": 1325,
"text": "TL;DR: The code is stored in Github."
},
{
"code": null,
"e": 1467,
"s": 1362,
"text": "To get the environment ready we need to install the new dependencies found in the folder of the project:"
},
{
"code": null,
"e": 1499,
"s": 1467,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 1566,
"s": 1499,
"text": "Also we need to start the MLFlow server by typing in the terminal:"
},
{
"code": null,
"e": 1576,
"s": 1566,
"text": "mlflow ui"
},
{
"code": null,
"e": 1667,
"s": 1576,
"text": "We sound be able to see the MlFlow ui now by running in the browser http://127.0.0.1:5000:"
},
{
"code": null,
"e": 1840,
"s": 1667,
"text": "Now we should be able to visualise all the experiments (training steps) we run. We can also start the Jupyter lab notebook which is the environment where we write our code:"
},
{
"code": null,
"e": 1852,
"s": 1840,
"text": "jupyter lab"
},
{
"code": null,
"e": 1998,
"s": 1852,
"text": "H2O is a distributed framework and in order to use it locally we need to start a server. This might take a minute or so, depending on your setup:"
},
{
"code": null,
"e": 2009,
"s": 1998,
"text": "h2o.init()"
},
{
"code": null,
"e": 2099,
"s": 2009,
"text": "MLFlow uses the concept of experiments to track the progress of a machine learning model."
},
{
"code": null,
"e": 2270,
"s": 2099,
"text": "try: experiment = mlflow.create_experiment(experiment_name)except: experiment = client.get_experiment_by_name(experiment_name)mlflow.set_experiment(experiment_name)"
},
{
"code": null,
"e": 2326,
"s": 2270,
"text": "If the experiment is already created, we just reuse it."
},
{
"code": null,
"e": 2633,
"s": 2326,
"text": "We have reached the most interesting part, using auto ml to do the training. Multiple models are trained in parallel and validated (6 fold cross-validation) using an independent subset of the data. Every new training run will save some validation metrics and the model that has performed the best (leader)."
},
{
"code": null,
"e": 3167,
"s": 2633,
"text": "with mlflow.start_run(): model = H2OAutoML(max_models=10, max_runtime_secs=300, seed=24, nfolds=6) model.train(x=x_cols, y=y_cols, training_frame=train, validation_frame=valid) mlflow.log_metric(\"rmse\", model.leader.rmse()) mlflow.log_metric(\"log_loss\", model.leader.logloss()) mlflow.log_metric(\"mean_per_class_error\", model.leader.mean_per_class_error()) mlflow.h2o.log_model(model.leader, \"model\") lb = model.leaderboard lb = get_leaderboard(model, extra_columns='ALL') print(lb.head(rows=lb.nrows))"
},
{
"code": null,
"e": 3293,
"s": 3167,
"text": "We have decided to run 10 models. Using the get_leaderboard function we get to see what machine learning algorithms have run:"
},
{
"code": null,
"e": 3380,
"s": 3293,
"text": "And the training is recorded in MLFlow, and we can compare it with future experiments:"
},
{
"code": null,
"e": 3570,
"s": 3380,
"text": "The last step is to actually do the prediction with the newly elected leader. For the purpose of this tutorial we will just use the validation data, but in practice we need to use new data."
},
{
"code": null,
"e": 3924,
"s": 3570,
"text": "all_mlflow_runs = client.list_run_infos(experiment.experiment_id)if len(all_mlflow_runs) > 0: run_info = all_mlflow_runs[-1] model = mlflow.h2o.load_model(\"mlruns/{exp_id}/{run_id}/artifacts/model/\".format(exp_id=experiment.experiment_id,run_id=run_info.run_uuid)) result = model.predict(valid)else: raise Exception('Run the training first')"
},
{
"code": null,
"e": 4113,
"s": 3924,
"text": "Again we use MLFlow to read the latest run in the experiment and load the GLM model. If we never run the training we can throw an exception to notify the user that he has to do that first."
}
]
|
HBase - Enabling a Table | Syntax to enable a table:
enable ‘emp’
Given below is an example to enable a table.
hbase(main):005:0> enable 'emp'
0 row(s) in 0.4580 seconds
After enabling the table, scan it. If you can see the schema, your table is successfully enabled.
hbase(main):006:0> scan 'emp'
ROW COLUMN + CELL
1 column = personal data:city, timestamp = 1417516501, value = hyderabad
1 column = personal data:name, timestamp = 1417525058, value = ramu
1 column = professional data:designation, timestamp = 1417532601, value = manager
1 column = professional data:salary, timestamp = 1417524244109, value = 50000
2 column = personal data:city, timestamp = 1417524574905, value = chennai
2 column = personal data:name, timestamp = 1417524556125, value = ravi
2 column = professional data:designation, timestamp = 14175292204, value = sr:engg
2 column = professional data:salary, timestamp = 1417524604221, value = 30000
3 column = personal data:city, timestamp = 1417524681780, value = delhi
3 column = personal data:name, timestamp = 1417524672067, value = rajesh
3 column = professional data:designation, timestamp = 14175246987, value = jr:engg
3 column = professional data:salary, timestamp = 1417524702514, value = 25000
3 row(s) in 0.0400 seconds
This command is used to find whether a table is enabled. Its syntax is as follows:
hbase> is_enabled 'table name'
The following code verifies whether the table named emp is enabled. If it is enabled, it will return true and if not, it will return false.
hbase(main):031:0> is_enabled 'emp'
true
0 row(s) in 0.0440 seconds
To verify whether a table is enabled, isTableEnabled() method is used; and to enable a table, enableTable() method is used. These methods belong to HBaseAdmin class. Follow the steps given below to enable a table.
Instantiate HBaseAdmin class as shown below.
// Creating configuration object
Configuration conf = HBaseConfiguration.create();
// Creating HBaseAdmin object
HBaseAdmin admin = new HBaseAdmin(conf);
Verify whether the table is enabled using isTableEnabled() method as shown below.
Boolean bool = admin.isTableEnabled("emp");
If the table is not disabled, disable it as shown below.
if(!bool){
admin.enableTable("emp");
System.out.println("Table enabled");
}
Given below is the complete program to verify whether the table is enabled and if it is not, then how to enable it.
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.client.HBaseAdmin;
public class EnableTable{
public static void main(String args[]) throws MasterNotRunningException, IOException{
// Instantiating configuration class
Configuration conf = HBaseConfiguration.create();
// Instantiating HBaseAdmin class
HBaseAdmin admin = new HBaseAdmin(conf);
// Verifying whether the table is disabled
Boolean bool = admin.isTableEnabled("emp");
System.out.println(bool);
// Enabling the table using HBaseAdmin object
if(!bool){
admin.enableTable("emp");
System.out.println("Table Enabled");
}
}
}
Compile and execute the above program as shown below.
$javac EnableTable.java
$java EnableTable
The following should be the output:
false
Table Enabled
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2063,
"s": 2037,
"text": "Syntax to enable a table:"
},
{
"code": null,
"e": 2077,
"s": 2063,
"text": "enable ‘emp’\n"
},
{
"code": null,
"e": 2122,
"s": 2077,
"text": "Given below is an example to enable a table."
},
{
"code": null,
"e": 2182,
"s": 2122,
"text": "hbase(main):005:0> enable 'emp'\n0 row(s) in 0.4580 seconds\n"
},
{
"code": null,
"e": 2280,
"s": 2182,
"text": "After enabling the table, scan it. If you can see the schema, your table is successfully enabled."
},
{
"code": null,
"e": 3310,
"s": 2280,
"text": "hbase(main):006:0> scan 'emp'\n\n ROW COLUMN + CELL\n\n1 column = personal data:city, timestamp = 1417516501, value = hyderabad\n\n1 column = personal data:name, timestamp = 1417525058, value = ramu\n\n1 column = professional data:designation, timestamp = 1417532601, value = manager\n\n1 column = professional data:salary, timestamp = 1417524244109, value = 50000\n\n2 column = personal data:city, timestamp = 1417524574905, value = chennai\n\n2 column = personal data:name, timestamp = 1417524556125, value = ravi\n\n2 column = professional data:designation, timestamp = 14175292204, value = sr:engg\n\n2 column = professional data:salary, timestamp = 1417524604221, value = 30000 \n\n3 column = personal data:city, timestamp = 1417524681780, value = delhi\n\n3 column = personal data:name, timestamp = 1417524672067, value = rajesh\n\n3 column = professional data:designation, timestamp = 14175246987, value = jr:engg\n\n3 column = professional data:salary, timestamp = 1417524702514, value = 25000\n\n3 row(s) in 0.0400 seconds\n"
},
{
"code": null,
"e": 3393,
"s": 3310,
"text": "This command is used to find whether a table is enabled. Its syntax is as follows:"
},
{
"code": null,
"e": 3425,
"s": 3393,
"text": "hbase> is_enabled 'table name'\n"
},
{
"code": null,
"e": 3565,
"s": 3425,
"text": "The following code verifies whether the table named emp is enabled. If it is enabled, it will return true and if not, it will return false."
},
{
"code": null,
"e": 3634,
"s": 3565,
"text": "hbase(main):031:0> is_enabled 'emp'\ntrue\n0 row(s) in 0.0440 seconds\n"
},
{
"code": null,
"e": 3848,
"s": 3634,
"text": "To verify whether a table is enabled, isTableEnabled() method is used; and to enable a table, enableTable() method is used. These methods belong to HBaseAdmin class. Follow the steps given below to enable a table."
},
{
"code": null,
"e": 3893,
"s": 3848,
"text": "Instantiate HBaseAdmin class as shown below."
},
{
"code": null,
"e": 4049,
"s": 3893,
"text": "// Creating configuration object\nConfiguration conf = HBaseConfiguration.create();\n\n// Creating HBaseAdmin object\nHBaseAdmin admin = new HBaseAdmin(conf);\n"
},
{
"code": null,
"e": 4131,
"s": 4049,
"text": "Verify whether the table is enabled using isTableEnabled() method as shown below."
},
{
"code": null,
"e": 4176,
"s": 4131,
"text": "Boolean bool = admin.isTableEnabled(\"emp\");\n"
},
{
"code": null,
"e": 4233,
"s": 4176,
"text": "If the table is not disabled, disable it as shown below."
},
{
"code": null,
"e": 4315,
"s": 4233,
"text": "if(!bool){\n admin.enableTable(\"emp\");\n System.out.println(\"Table enabled\");\n}"
},
{
"code": null,
"e": 4431,
"s": 4315,
"text": "Given below is the complete program to verify whether the table is enabled and if it is not, then how to enable it."
},
{
"code": null,
"e": 5268,
"s": 4431,
"text": "import java.io.IOException;\n\nimport org.apache.hadoop.conf.Configuration;\n\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.MasterNotRunningException;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\n\npublic class EnableTable{\n\n public static void main(String args[]) throws MasterNotRunningException, IOException{\n\n // Instantiating configuration class\n Configuration conf = HBaseConfiguration.create();\n\n // Instantiating HBaseAdmin class\n HBaseAdmin admin = new HBaseAdmin(conf);\n\n // Verifying whether the table is disabled\n Boolean bool = admin.isTableEnabled(\"emp\");\n System.out.println(bool);\n\n // Enabling the table using HBaseAdmin object\n if(!bool){\n admin.enableTable(\"emp\");\n System.out.println(\"Table Enabled\");\n }\n }\n}"
},
{
"code": null,
"e": 5322,
"s": 5268,
"text": "Compile and execute the above program as shown below."
},
{
"code": null,
"e": 5365,
"s": 5322,
"text": "$javac EnableTable.java\n$java EnableTable\n"
},
{
"code": null,
"e": 5401,
"s": 5365,
"text": "The following should be the output:"
},
{
"code": null,
"e": 5422,
"s": 5401,
"text": "false\nTable Enabled\n"
},
{
"code": null,
"e": 5429,
"s": 5422,
"text": " Print"
},
{
"code": null,
"e": 5440,
"s": 5429,
"text": " Add Notes"
}
]
|
C# Linq Contains Method | To check for an element in a string, use the Contains() method.
The following is our string array.
string[] arr = { "Java", "C++", "Python"};
Now, use Contains() method to find a specific string in the string array.
arr.AsQueryable().Contains(str);
Let us see the complete example.
Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
class Demo {
static void Main() {
string[] arr = { "Java", "C++", "Python"};
string str = "Python";
bool res = arr.AsQueryable().Contains(str);
Console.WriteLine("Array has Python? "+res);
}
}
Array has Python? True | [
{
"code": null,
"e": 1126,
"s": 1062,
"text": "To check for an element in a string, use the Contains() method."
},
{
"code": null,
"e": 1161,
"s": 1126,
"text": "The following is our string array."
},
{
"code": null,
"e": 1204,
"s": 1161,
"text": "string[] arr = { \"Java\", \"C++\", \"Python\"};"
},
{
"code": null,
"e": 1278,
"s": 1204,
"text": "Now, use Contains() method to find a specific string in the string array."
},
{
"code": null,
"e": 1311,
"s": 1278,
"text": "arr.AsQueryable().Contains(str);"
},
{
"code": null,
"e": 1344,
"s": 1311,
"text": "Let us see the complete example."
},
{
"code": null,
"e": 1355,
"s": 1344,
"text": " Live Demo"
},
{
"code": null,
"e": 1645,
"s": 1355,
"text": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\nclass Demo {\n static void Main() {\n string[] arr = { \"Java\", \"C++\", \"Python\"};\n string str = \"Python\";\n bool res = arr.AsQueryable().Contains(str);\n Console.WriteLine(\"Array has Python? \"+res);\n }\n}"
},
{
"code": null,
"e": 1668,
"s": 1645,
"text": "Array has Python? True"
}
]
|
Create a text to speech application using ReactJS - GeeksforGeeks | 09 Nov, 2021
React.js: React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook.
Steps to Create Line Charts using Recharts in React JS :
Step 1: Create React Project
npx create-react-app my-app
Step 2: Change your directory and enter your main folder charting as
cd my-app
The project Structure is as follows:
Step 2: Installing react-speech-kit by below command:
npm i react-speech-kit
Step 3: Write code on App.js:
Javascript
import './App.css';import Speech from './speech';function App() { return ( <div className="App"> <Speech/> </div> );}export default App;
Step 4: Write code in the Speech.js file
Javascript
import React from "react";import { useSpeechSynthesis } from "react-speech-kit";const Speech = () => { const [value, setValue] = React.useState(""); const { speak } = useSpeechSynthesis(); return ( <div className="speech"> <div className="group"> <h2>Text To Speech Converter Using React Js</h2> </div> <div className="group"> <textarea rows="10" value={value} onChange={(e) => setValue(e.target.value)} ></textarea> </div> <div className="group"> <button onClick={() => speak({ text: value })}> Speech </button> </div> </div> );};export default Speech;
Step 5: Write code on App.css
CSS
* { margin: 0; padding: 20px; box-sizing: border-box;}body { font-family: sans-serif;}.Speech { width: 50px;}.group { margin: 7px 0;}textarea { width: 100%; padding: 5px 10px; border: 1px solid rgb(228, 20, 20); outline: none; border-radius: 3px;}button { width: 100%; display: block; padding: 10px 22px; color: rgb(10, 10, 10); font-weight: bold; cursor: pointer; outline: none; background: rgb(227, 240, 219);;}h2 { margin-bottom: 10px; text-align: center;}
Step 6: Step to run the application: Open the terminal and type the following command.
npm start
Output: Open the browser and our project is shown in the URL http://localhost:3000/
singghakshay
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
Axios in React: A Guide for Beginners
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26181,
"s": 26153,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 26452,
"s": 26181,
"text": "React.js: React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook."
},
{
"code": null,
"e": 26509,
"s": 26452,
"text": "Steps to Create Line Charts using Recharts in React JS :"
},
{
"code": null,
"e": 26539,
"s": 26509,
"text": "Step 1: Create React Project "
},
{
"code": null,
"e": 26567,
"s": 26539,
"text": "npx create-react-app my-app"
},
{
"code": null,
"e": 26636,
"s": 26567,
"text": "Step 2: Change your directory and enter your main folder charting as"
},
{
"code": null,
"e": 26646,
"s": 26636,
"text": "cd my-app"
},
{
"code": null,
"e": 26684,
"s": 26646,
"text": "The project Structure is as follows: "
},
{
"code": null,
"e": 26739,
"s": 26684,
"text": "Step 2: Installing react-speech-kit by below command: "
},
{
"code": null,
"e": 26762,
"s": 26739,
"text": "npm i react-speech-kit"
},
{
"code": null,
"e": 26793,
"s": 26762,
"text": "Step 3: Write code on App.js: "
},
{
"code": null,
"e": 26804,
"s": 26793,
"text": "Javascript"
},
{
"code": "import './App.css';import Speech from './speech';function App() { return ( <div className=\"App\"> <Speech/> </div> );}export default App;",
"e": 26954,
"s": 26804,
"text": null
},
{
"code": null,
"e": 26997,
"s": 26954,
"text": " Step 4: Write code in the Speech.js file "
},
{
"code": null,
"e": 27008,
"s": 26997,
"text": "Javascript"
},
{
"code": "import React from \"react\";import { useSpeechSynthesis } from \"react-speech-kit\";const Speech = () => { const [value, setValue] = React.useState(\"\"); const { speak } = useSpeechSynthesis(); return ( <div className=\"speech\"> <div className=\"group\"> <h2>Text To Speech Converter Using React Js</h2> </div> <div className=\"group\"> <textarea rows=\"10\" value={value} onChange={(e) => setValue(e.target.value)} ></textarea> </div> <div className=\"group\"> <button onClick={() => speak({ text: value })}> Speech </button> </div> </div> );};export default Speech;",
"e": 27673,
"s": 27008,
"text": null
},
{
"code": null,
"e": 27703,
"s": 27673,
"text": "Step 5: Write code on App.css"
},
{
"code": null,
"e": 27707,
"s": 27703,
"text": "CSS"
},
{
"code": "* { margin: 0; padding: 20px; box-sizing: border-box;}body { font-family: sans-serif;}.Speech { width: 50px;}.group { margin: 7px 0;}textarea { width: 100%; padding: 5px 10px; border: 1px solid rgb(228, 20, 20); outline: none; border-radius: 3px;}button { width: 100%; display: block; padding: 10px 22px; color: rgb(10, 10, 10); font-weight: bold; cursor: pointer; outline: none; background: rgb(227, 240, 219);;}h2 { margin-bottom: 10px; text-align: center;}",
"e": 28189,
"s": 27707,
"text": null
},
{
"code": null,
"e": 28280,
"s": 28189,
"text": " Step 6: Step to run the application: Open the terminal and type the following command. "
},
{
"code": null,
"e": 28290,
"s": 28280,
"text": "npm start"
},
{
"code": null,
"e": 28375,
"s": 28290,
"text": "Output: Open the browser and our project is shown in the URL http://localhost:3000/ "
},
{
"code": null,
"e": 28390,
"s": 28377,
"text": "singghakshay"
},
{
"code": null,
"e": 28406,
"s": 28390,
"text": "React-Questions"
},
{
"code": null,
"e": 28414,
"s": 28406,
"text": "ReactJS"
},
{
"code": null,
"e": 28431,
"s": 28414,
"text": "Web Technologies"
},
{
"code": null,
"e": 28529,
"s": 28431,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28556,
"s": 28529,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 28594,
"s": 28556,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 28636,
"s": 28594,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 28671,
"s": 28636,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 28729,
"s": 28671,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 28769,
"s": 28729,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28802,
"s": 28769,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28847,
"s": 28802,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28897,
"s": 28847,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
How to resize SVG icon using Tailwind CSS ? | 17 Jun, 2021
SVG stands for Scalable Vector Graphics and is an XML-based ( can be edited ) vector image format. SVG is commonly used for icons, animations, interactive charts, graphs, and other dynamic graphics in the browser. As it is XML-based, you can easily resize the SVG icon using Tailwind.
Approach: You can simply customize the class of SVG by changing the height and width of the icons or by changing the values of viewBox attributes of SVG.
Syntax:
<svg class="h-30 w-30" viewBox="0 0 24 24">
<path d=" "/>
</svg>
Note: The viewBox attribute defines the position and dimension of an SVG viewport. The value of the viewBox attribute is a list of four numbers, min-x, min-y, width, and height. So the viewBox doesn’t set the size of the SVG, it just determines the frame or window through which we will see the SVG.
Example 1: Using viewBox attribute to resize SVG icon.
HTML
<!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Resize SVG icon</b> <div class=" m-4 grid grid-flow-col gap-4 p-5"> <!--- Home Icon ---> <svg xmlns="http://www.w3.org/2000/svg" class="text-red-500" fill="none" viewBox="0 0 80 80" stroke="currentColor" height="100px" width="100px"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" /> </svg> <!--- Emoji Icon ---> <svg xmlns="http://www.w3.org/2000/svg" class="text-yellow-400" fill="none" viewBox="0 0 80 80" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> </div></body> </html>
Output:
Example 2: Simply changing the width and height of the class of an icon.
HTML
<!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS SVG</b> <div class=" m-4 grid grid-flow-col gap-4 p-5"> <!--- Home Icon ---> <svg xmlns="http://www.w3.org/2000/svg" class=" text-red-500 h-70 w-50" viewBox="0 0 80 80" fill="none" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" /> </svg> <svg xmlns="http://www.w3.org/2000/svg" class="bg-red-400 text-green-300 h-40 w-20 fill-current" viewBox="0 0 80 80" fill="none" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l -3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783 .57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00- .363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1 .81h4.914a1 1 0 00.951-.69l1.519-4.674z" /> </svg> </div></body> </html>
Output:
Picked
Tailwind CSS-Questions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 313,
"s": 28,
"text": "SVG stands for Scalable Vector Graphics and is an XML-based ( can be edited ) vector image format. SVG is commonly used for icons, animations, interactive charts, graphs, and other dynamic graphics in the browser. As it is XML-based, you can easily resize the SVG icon using Tailwind."
},
{
"code": null,
"e": 467,
"s": 313,
"text": "Approach: You can simply customize the class of SVG by changing the height and width of the icons or by changing the values of viewBox attributes of SVG."
},
{
"code": null,
"e": 476,
"s": 467,
"text": "Syntax: "
},
{
"code": null,
"e": 545,
"s": 476,
"text": "<svg class=\"h-30 w-30\" viewBox=\"0 0 24 24\">\n <path d=\" \"/>\n</svg>"
},
{
"code": null,
"e": 845,
"s": 545,
"text": "Note: The viewBox attribute defines the position and dimension of an SVG viewport. The value of the viewBox attribute is a list of four numbers, min-x, min-y, width, and height. So the viewBox doesn’t set the size of the SVG, it just determines the frame or window through which we will see the SVG."
},
{
"code": null,
"e": 900,
"s": 845,
"text": "Example 1: Using viewBox attribute to resize SVG icon."
},
{
"code": null,
"e": 905,
"s": 900,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Resize SVG icon</b> <div class=\" m-4 grid grid-flow-col gap-4 p-5\"> <!--- Home Icon ---> <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"text-red-500\" fill=\"none\" viewBox=\"0 0 80 80\" stroke=\"currentColor\" height=\"100px\" width=\"100px\"> <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6\" /> </svg> <!--- Emoji Icon ---> <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"text-yellow-400\" fill=\"none\" viewBox=\"0 0 80 80\" stroke=\"currentColor\"> <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\" /> </svg> </div></body> </html>",
"e": 2218,
"s": 905,
"text": null
},
{
"code": null,
"e": 2226,
"s": 2218,
"text": "Output:"
},
{
"code": null,
"e": 2299,
"s": 2226,
"text": "Example 2: Simply changing the width and height of the class of an icon."
},
{
"code": null,
"e": 2304,
"s": 2299,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS SVG</b> <div class=\" m-4 grid grid-flow-col gap-4 p-5\"> <!--- Home Icon ---> <svg xmlns=\"http://www.w3.org/2000/svg\" class=\" text-red-500 h-70 w-50\" viewBox=\"0 0 80 80\" fill=\"none\" stroke=\"currentColor\"> <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6\" /> </svg> <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"bg-red-400 text-green-300 h-40 w-20 fill-current\" viewBox=\"0 0 80 80\" fill=\"none\" stroke=\"currentColor\"> <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l -3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783 .57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00- .363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1 .81h4.914a1 1 0 00.951-.69l1.519-4.674z\" /> </svg> </div></body> </html>",
"e": 3937,
"s": 2304,
"text": null
},
{
"code": null,
"e": 3945,
"s": 3937,
"text": "Output:"
},
{
"code": null,
"e": 3952,
"s": 3945,
"text": "Picked"
},
{
"code": null,
"e": 3975,
"s": 3952,
"text": "Tailwind CSS-Questions"
},
{
"code": null,
"e": 3979,
"s": 3975,
"text": "CSS"
},
{
"code": null,
"e": 3996,
"s": 3979,
"text": "Web Technologies"
}
]
|
Number of rectangles in N*M grid | 13 Jun, 2022
We are given a N*M grid, print the number of rectangles in it.Examples:
Input : N = 2, M = 2
Output : 9
There are 4 rectangles of size 1 x 1.
There are 2 rectangles of size 1 x 2
There are 2 rectangles of size 2 x 1
There is one rectangle of size 2 x 2.
Input : N = 5, M = 4
Output : 150
Input : N = 4, M = 3
Output: 60
We have discussed counting number of squares in a n x m grid,Let us derive a formula for number of rectangles.If the grid is 1×1, there is 1 rectangle. If the grid is 2×1, there will be 2 + 1 = 3 rectangles If it grid is 3×1, there will be 3 + 2 + 1 = 6 rectangles. we can say that for N*1 there will be N + (N-1) + (n-2) ... + 1 = (N)(N+1)/2 rectanglesIf we add one more column to N×1, firstly we will have as many rectangles in the 2nd column as the first, and then we have that same number of 2×M rectangles. So N×2 = 3 (N)(N+1)/2After deducing this we can say For N*M we’ll have (M)(M+1)/2 (N)(N+1)/2 = M(M+1)(N)(N+1)/4So the formula for total rectangles will be M(M+1)(N)(N+1)/4
.
Combinatorial Logic:
N*M grid can be represented as (N+1) vertical lines and (M+1) horizontal lines.In a rectangle, we need two distinct horizontal and two distinct verticals.So going by the logic of Combinatorial Mathematics we can choose 2 vertical lines and 2 horizontal lines to form a rectangle. And total number of these combinations is the number of rectangles possible in the grid.
Total Number of Rectangles in N*M grid: N+1C2 * M+1C2 = (N*(N+1)/2!)*(M*(M+1)/2!) = N*(N+1)*M*(M+1)/4
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count number of rectangles// in a n x m grid#include <bits/stdc++.h>using namespace std; int rectCount(int n, int m){ return (m * n * (n + 1) * (m + 1)) / 4;} /* driver code */int main(){ int n = 5, m = 4; cout << rectCount(n, m); return 0;}
// JAVA Code to count number of// rectangles in N*M gridimport java.util.*; class GFG { public static long rectCount(int n, int m) { return (m * n * (n + 1) * (m + 1)) / 4; } /* Driver program to test above function */ public static void main(String[] args) { int n = 5, m = 4; System.out.println(rectCount(n, m)); }} // This code is contributed by Arnav Kr. Mandal.
# Python3 program to count number# of rectangles in a n x m grid def rectCount(n, m): return (m * n * (n + 1) * (m + 1)) // 4 # Driver coden, m = 5, 4print(rectCount(n, m)) # This code is contributed by Anant Agarwal.
// C# Code to count number of// rectangles in N*M gridusing System; class GFG { public static long rectCount(int n, int m) { return (m * n * (n + 1) * (m + 1)) / 4; } // Driver program public static void Main() { int n = 5, m = 4; Console.WriteLine(rectCount(n, m)); }} // This code is contributed by Anant Agarwal.
<?php// PHP program to count// number of rectangles// in a n x m grid function rectCount($n, $m){ return ($m * $n * ($n + 1) * ($m + 1)) / 4;} // Driver Code$n = 5;$m = 4;echo rectCount($n, $m); // This code is contributed// by ajit?>
<script> // Javascript Code to count number // of rectangles in N*M grid function rectCount(n, m) { return parseInt((m * n * (n + 1) * (m + 1)) / 4, 10); } let n = 5, m = 4; document.write(rectCount(n, m)); </script>
Output:
150
Time complexity: O(1)
Auxiliary Space: O(1)
This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
arora_hritik
perfecto_pride
decode2207
hasani
square-rectangle
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Find if two rectangles overlap
Check whether triangle is valid or not if sides are given
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Program for Point of Intersection of Two Lines
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 126,
"s": 52,
"text": "We are given a N*M grid, print the number of rectangles in it.Examples: "
},
{
"code": null,
"e": 379,
"s": 126,
"text": "Input : N = 2, M = 2\nOutput : 9\nThere are 4 rectangles of size 1 x 1.\nThere are 2 rectangles of size 1 x 2\nThere are 2 rectangles of size 2 x 1\nThere is one rectangle of size 2 x 2.\n\nInput : N = 5, M = 4\nOutput : 150\n\nInput : N = 4, M = 3\nOutput: 60"
},
{
"code": null,
"e": 1066,
"s": 381,
"text": "We have discussed counting number of squares in a n x m grid,Let us derive a formula for number of rectangles.If the grid is 1×1, there is 1 rectangle. If the grid is 2×1, there will be 2 + 1 = 3 rectangles If it grid is 3×1, there will be 3 + 2 + 1 = 6 rectangles. we can say that for N*1 there will be N + (N-1) + (n-2) ... + 1 = (N)(N+1)/2 rectanglesIf we add one more column to N×1, firstly we will have as many rectangles in the 2nd column as the first, and then we have that same number of 2×M rectangles. So N×2 = 3 (N)(N+1)/2After deducing this we can say For N*M we’ll have (M)(M+1)/2 (N)(N+1)/2 = M(M+1)(N)(N+1)/4So the formula for total rectangles will be M(M+1)(N)(N+1)/4 "
},
{
"code": null,
"e": 1068,
"s": 1066,
"text": "."
},
{
"code": null,
"e": 1089,
"s": 1068,
"text": "Combinatorial Logic:"
},
{
"code": null,
"e": 1458,
"s": 1089,
"text": "N*M grid can be represented as (N+1) vertical lines and (M+1) horizontal lines.In a rectangle, we need two distinct horizontal and two distinct verticals.So going by the logic of Combinatorial Mathematics we can choose 2 vertical lines and 2 horizontal lines to form a rectangle. And total number of these combinations is the number of rectangles possible in the grid."
},
{
"code": null,
"e": 1561,
"s": 1458,
"text": "Total Number of Rectangles in N*M grid: N+1C2 * M+1C2 = (N*(N+1)/2!)*(M*(M+1)/2!) = N*(N+1)*M*(M+1)/4 "
},
{
"code": null,
"e": 1565,
"s": 1561,
"text": "C++"
},
{
"code": null,
"e": 1570,
"s": 1565,
"text": "Java"
},
{
"code": null,
"e": 1578,
"s": 1570,
"text": "Python3"
},
{
"code": null,
"e": 1581,
"s": 1578,
"text": "C#"
},
{
"code": null,
"e": 1585,
"s": 1581,
"text": "PHP"
},
{
"code": null,
"e": 1596,
"s": 1585,
"text": "Javascript"
},
{
"code": "// C++ program to count number of rectangles// in a n x m grid#include <bits/stdc++.h>using namespace std; int rectCount(int n, int m){ return (m * n * (n + 1) * (m + 1)) / 4;} /* driver code */int main(){ int n = 5, m = 4; cout << rectCount(n, m); return 0;}",
"e": 1868,
"s": 1596,
"text": null
},
{
"code": "// JAVA Code to count number of// rectangles in N*M gridimport java.util.*; class GFG { public static long rectCount(int n, int m) { return (m * n * (n + 1) * (m + 1)) / 4; } /* Driver program to test above function */ public static void main(String[] args) { int n = 5, m = 4; System.out.println(rectCount(n, m)); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 2287,
"s": 1868,
"text": null
},
{
"code": "# Python3 program to count number# of rectangles in a n x m grid def rectCount(n, m): return (m * n * (n + 1) * (m + 1)) // 4 # Driver coden, m = 5, 4print(rectCount(n, m)) # This code is contributed by Anant Agarwal.",
"e": 2509,
"s": 2287,
"text": null
},
{
"code": "// C# Code to count number of// rectangles in N*M gridusing System; class GFG { public static long rectCount(int n, int m) { return (m * n * (n + 1) * (m + 1)) / 4; } // Driver program public static void Main() { int n = 5, m = 4; Console.WriteLine(rectCount(n, m)); }} // This code is contributed by Anant Agarwal.",
"e": 2880,
"s": 2509,
"text": null
},
{
"code": "<?php// PHP program to count// number of rectangles// in a n x m grid function rectCount($n, $m){ return ($m * $n * ($n + 1) * ($m + 1)) / 4;} // Driver Code$n = 5;$m = 4;echo rectCount($n, $m); // This code is contributed// by ajit?>",
"e": 3138,
"s": 2880,
"text": null
},
{
"code": "<script> // Javascript Code to count number // of rectangles in N*M grid function rectCount(n, m) { return parseInt((m * n * (n + 1) * (m + 1)) / 4, 10); } let n = 5, m = 4; document.write(rectCount(n, m)); </script>",
"e": 3425,
"s": 3138,
"text": null
},
{
"code": null,
"e": 3435,
"s": 3425,
"text": "Output: "
},
{
"code": null,
"e": 3439,
"s": 3435,
"text": "150"
},
{
"code": null,
"e": 3461,
"s": 3439,
"text": "Time complexity: O(1)"
},
{
"code": null,
"e": 3483,
"s": 3461,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3898,
"s": 3483,
"text": "This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3904,
"s": 3898,
"text": "jit_t"
},
{
"code": null,
"e": 3917,
"s": 3904,
"text": "arora_hritik"
},
{
"code": null,
"e": 3932,
"s": 3917,
"text": "perfecto_pride"
},
{
"code": null,
"e": 3943,
"s": 3932,
"text": "decode2207"
},
{
"code": null,
"e": 3950,
"s": 3943,
"text": "hasani"
},
{
"code": null,
"e": 3967,
"s": 3950,
"text": "square-rectangle"
},
{
"code": null,
"e": 3977,
"s": 3967,
"text": "Geometric"
},
{
"code": null,
"e": 3990,
"s": 3977,
"text": "Mathematical"
},
{
"code": null,
"e": 4003,
"s": 3990,
"text": "Mathematical"
},
{
"code": null,
"e": 4013,
"s": 4003,
"text": "Geometric"
},
{
"code": null,
"e": 4111,
"s": 4013,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4160,
"s": 4111,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 4191,
"s": 4160,
"text": "Find if two rectangles overlap"
},
{
"code": null,
"e": 4249,
"s": 4191,
"text": "Check whether triangle is valid or not if sides are given"
},
{
"code": null,
"e": 4300,
"s": 4249,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 4347,
"s": 4300,
"text": "Program for Point of Intersection of Two Lines"
},
{
"code": null,
"e": 4377,
"s": 4347,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 4420,
"s": 4377,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4480,
"s": 4420,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4495,
"s": 4480,
"text": "C++ Data Types"
}
]
|
Python | Ways to convert array of strings to array of floats | 11 Aug, 2021
Sometimes in a competitive coding environment, we get input in some other datatypes and we need to convert them in other forms this problem is same as that we have an input in the form of string and we need to convert it into floats.Let’s discuss a few ways to convert an array of strings to array of floats.Method #1 : Using astype
Python3
# Python code to demonstrate converting# array of strings to array of floats# using astype import numpy as np # initialising arrayini_array = np.array(["1.1", "1.5", "2.7", "8.9"]) # printing initial arrayprint ("initial array", str(ini_array)) # converting to array of floats# using np.astyperes = ini_array.astype(np.float) # printing final resultprint ("final array", str(res))
initial array ['1.1' '1.5' '2.7' '8.9']
final array [ 1.1 1.5 2.7 8.9]
Method #2: Using np.fromstring
Python3
# Python code to demonstrate converting# array of strings to array of floats# using fromstring import numpy as np # initialising arrayini_array = np.array(["1.1", "1.5", "2.7", "8.9"]) # printing initial arrayprint ("initial array", str(ini_array)) # converting to array of floats# using np.fromstringini_array = ', '.join(ini_array)ini_array = np.fromstring(ini_array, dtype = np.float, sep =', ' ) # printing final resultprint ("final array", str(ini_array))
initial array ['1.1' '1.5' '2.7' '8.9']
final array [ 1.1 1.5 2.7 8.9]
Method #3: Using np.asarray() and type
Python3
# Python code to demonstrate# converting array of strings to array of floats# using asarray import numpy as np # initialising arrayini_array = np.array(["1.1", "1.5", "2.7", "8.9"]) # printing initial arrayprint ("initial array", str(ini_array)) # converting to array of floats# using np.asarrayfinal_array = b = np.asarray(ini_array, dtype = np.float64, order ='C') # printing final resultprint ("final array", str(final_array))
initial array ['1.1' '1.5' '2.7' '8.9']
final array [ 1.1 1.5 2.7 8.9]
sagar0719kumar
Python-numpy
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 363,
"s": 28,
"text": "Sometimes in a competitive coding environment, we get input in some other datatypes and we need to convert them in other forms this problem is same as that we have an input in the form of string and we need to convert it into floats.Let’s discuss a few ways to convert an array of strings to array of floats.Method #1 : Using astype "
},
{
"code": null,
"e": 371,
"s": 363,
"text": "Python3"
},
{
"code": "# Python code to demonstrate converting# array of strings to array of floats# using astype import numpy as np # initialising arrayini_array = np.array([\"1.1\", \"1.5\", \"2.7\", \"8.9\"]) # printing initial arrayprint (\"initial array\", str(ini_array)) # converting to array of floats# using np.astyperes = ini_array.astype(np.float) # printing final resultprint (\"final array\", str(res))",
"e": 752,
"s": 371,
"text": null
},
{
"code": null,
"e": 826,
"s": 752,
"text": "initial array ['1.1' '1.5' '2.7' '8.9']\nfinal array [ 1.1 1.5 2.7 8.9]"
},
{
"code": null,
"e": 863,
"s": 828,
"text": " Method #2: Using np.fromstring "
},
{
"code": null,
"e": 871,
"s": 863,
"text": "Python3"
},
{
"code": "# Python code to demonstrate converting# array of strings to array of floats# using fromstring import numpy as np # initialising arrayini_array = np.array([\"1.1\", \"1.5\", \"2.7\", \"8.9\"]) # printing initial arrayprint (\"initial array\", str(ini_array)) # converting to array of floats# using np.fromstringini_array = ', '.join(ini_array)ini_array = np.fromstring(ini_array, dtype = np.float, sep =', ' ) # printing final resultprint (\"final array\", str(ini_array))",
"e": 1374,
"s": 871,
"text": null
},
{
"code": null,
"e": 1448,
"s": 1374,
"text": "initial array ['1.1' '1.5' '2.7' '8.9']\nfinal array [ 1.1 1.5 2.7 8.9]"
},
{
"code": null,
"e": 1493,
"s": 1450,
"text": " Method #3: Using np.asarray() and type "
},
{
"code": null,
"e": 1501,
"s": 1493,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# converting array of strings to array of floats# using asarray import numpy as np # initialising arrayini_array = np.array([\"1.1\", \"1.5\", \"2.7\", \"8.9\"]) # printing initial arrayprint (\"initial array\", str(ini_array)) # converting to array of floats# using np.asarrayfinal_array = b = np.asarray(ini_array, dtype = np.float64, order ='C') # printing final resultprint (\"final array\", str(final_array))",
"e": 1938,
"s": 1501,
"text": null
},
{
"code": null,
"e": 2012,
"s": 1938,
"text": "initial array ['1.1' '1.5' '2.7' '8.9']\nfinal array [ 1.1 1.5 2.7 8.9]"
},
{
"code": null,
"e": 2029,
"s": 2014,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2042,
"s": 2029,
"text": "Python-numpy"
},
{
"code": null,
"e": 2049,
"s": 2042,
"text": "Python"
},
{
"code": null,
"e": 2065,
"s": 2049,
"text": "Python Programs"
},
{
"code": null,
"e": 2163,
"s": 2065,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2195,
"s": 2163,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2222,
"s": 2195,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2243,
"s": 2222,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2266,
"s": 2243,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2297,
"s": 2266,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2319,
"s": 2297,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2358,
"s": 2319,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2396,
"s": 2358,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2445,
"s": 2396,
"text": "Python | Convert string dictionary to dictionary"
}
]
|
Python | Add keys to nested dictionary | 14 May, 2020
Addition of keys in dictionaries have been discussed many times, but sometimes, we might have a problem in which we require to alter/add keys in the nested dictionary. This type of problem is common in today’s world with advent of NoSQL databases. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using dictionary bracketsThis task can be easily performed using the naive method of just keep nesting the dictionary brackets with the new value and new key is created on the go and the dictionary is updated.
# Python3 code to demonstrate working of# Update nested dictionary keys# Using dictionary brackets # initializing dictionarytest_dict = {'GFG' : {'rate' : 4, 'since' : 2012}} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using dictionary brackets# Update nested dictionary keystest_dict['GFG']['rank'] = 1 # printing result print("Dictionary after nested key update : " + str(test_dict))
The original dictionary is : {'GFG': {'rate': 4, 'since': 2012}}
Dictionary after nested key update : {'GFG': {'rate': 4, 'since': 2012, 'rank': 1}}
Method #2 : Using update()This method is used in cases where more than one keys need to be added to the nested dictionaries. The update function accepts the dictionary and added the dictionary with the keys in it.
# Python3 code to demonstrate working of# Update nested dictionary keys# Using update() # initializing dictionariestest_dict = {'GFG' : {'rate' : 4, 'since' : 2012}}upd_dict = {'rank' : 1, 'popularity' : 5} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using update()# Update nested dictionary keystest_dict['GFG'].update(upd_dict) # printing result print("Dictionary after nested key update : " + str(test_dict))
The original dictionary is : {'GFG': {'rate': 4, 'since': 2012}}
Dictionary after nested key update : {'GFG': {'popularity': 5, 'rate': 4, 'since': 2012, 'rank': 1}}
Python dictionary-programs
Python-nested-dictionary
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 May, 2020"
},
{
"code": null,
"e": 364,
"s": 52,
"text": "Addition of keys in dictionaries have been discussed many times, but sometimes, we might have a problem in which we require to alter/add keys in the nested dictionary. This type of problem is common in today’s world with advent of NoSQL databases. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 586,
"s": 364,
"text": "Method #1 : Using dictionary bracketsThis task can be easily performed using the naive method of just keep nesting the dictionary brackets with the new value and new key is created on the go and the dictionary is updated."
},
{
"code": "# Python3 code to demonstrate working of# Update nested dictionary keys# Using dictionary brackets # initializing dictionarytest_dict = {'GFG' : {'rate' : 4, 'since' : 2012}} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using dictionary brackets# Update nested dictionary keystest_dict['GFG']['rank'] = 1 # printing result print(\"Dictionary after nested key update : \" + str(test_dict))",
"e": 1020,
"s": 586,
"text": null
},
{
"code": null,
"e": 1170,
"s": 1020,
"text": "The original dictionary is : {'GFG': {'rate': 4, 'since': 2012}}\nDictionary after nested key update : {'GFG': {'rate': 4, 'since': 2012, 'rank': 1}}\n"
},
{
"code": null,
"e": 1386,
"s": 1172,
"text": "Method #2 : Using update()This method is used in cases where more than one keys need to be added to the nested dictionaries. The update function accepts the dictionary and added the dictionary with the keys in it."
},
{
"code": "# Python3 code to demonstrate working of# Update nested dictionary keys# Using update() # initializing dictionariestest_dict = {'GFG' : {'rate' : 4, 'since' : 2012}}upd_dict = {'rank' : 1, 'popularity' : 5} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using update()# Update nested dictionary keystest_dict['GFG'].update(upd_dict) # printing result print(\"Dictionary after nested key update : \" + str(test_dict))",
"e": 1846,
"s": 1386,
"text": null
},
{
"code": null,
"e": 2013,
"s": 1846,
"text": "The original dictionary is : {'GFG': {'rate': 4, 'since': 2012}}\nDictionary after nested key update : {'GFG': {'popularity': 5, 'rate': 4, 'since': 2012, 'rank': 1}}\n"
},
{
"code": null,
"e": 2040,
"s": 2013,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2065,
"s": 2040,
"text": "Python-nested-dictionary"
},
{
"code": null,
"e": 2072,
"s": 2065,
"text": "Python"
},
{
"code": null,
"e": 2088,
"s": 2072,
"text": "Python Programs"
}
]
|
Substitution Cipher | 29 Sep, 2021
Hiding some data is known as encryption. When plain text is encrypted it becomes unreadable and is known as ciphertext. In a Substitution cipher, any character of plain text from the given fixed set of characters is substituted by some other character from the same set depending on a key. For example with a shift of 1, A would be replaced by B, B would become C, and so on.
Note: Special case of Substitution cipher is known as Caesar cipher where the key is taken as 3.
The encryption can be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A = 0, B = 1,..., Z = 25. Encryption of a letter by a shift n can be described mathematically as.
(Encryption Phase with shift n)
(Decryption Phase with shift n)
Examples:
Plain Text: I am studying Data Encryption
Key: 4
Output: M eq wxyhCmrk Hexe IrgvCtxmsr
Plain Text: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Key: 4
Output: EFGHIJKLMNOPQRSTUVWXYZabcd
Algorithm for Substitution Cipher:
Input:
A String of both lower and upper case letters, called PlainText.
An Integer denoting the required key.
Procedure:
Create a list of all the characters.
Create a dictionary to store the substitution for all characters.
For each character, transform the given character as per the rule, depending on whether we’re encrypting or decrypting the text.
Print the new string generated.
Below is the implementation.
Python3
# Python program to demonstrate# Substitution Cipher import string # A list containing all charactersall_letters= string.ascii_letters """create a dictionary to store the substitutionfor the given alphabet in the plain textbased on the key""" dict1 = {}key = 4 for i in range(len(all_letters)): dict1[all_letters[i]] = all_letters[(i+key)%len(all_letters)] plain_txt= "I am studying Data Encryption"cipher_txt=[] # loop to generate ciphertext for char in plain_txt: if char in all_letters: temp = dict1[char] cipher_txt.append(temp) else: temp =char cipher_txt.append(temp) cipher_txt= "".join(cipher_txt)print("Cipher Text is: ",cipher_txt) """create a dictionary to store the substitutionfor the given alphabet in the ciphertext based on the key""" dict2 = {} for i in range(len(all_letters)): dict2[all_letters[i]] = all_letters[(i-key)%(len(all_letters))] # loop to recover plain textdecrypt_txt = [] for char in cipher_txt: if char in all_letters: temp = dict2[char] decrypt_txt.append(temp) else: temp = char decrypt_txt.append(temp) decrypt_txt = "".join(decrypt_txt)print("Recovered plain text :", decrypt_txt)
Output:
Cipher Text is: M eq wxyhCmrk Hexe IrgvCtxmsr
Recovered plain text : I am studying Data Encryption
sumitgumber28
cryptography
Python
Technical Scripter
cryptography
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 431,
"s": 54,
"text": "Hiding some data is known as encryption. When plain text is encrypted it becomes unreadable and is known as ciphertext. In a Substitution cipher, any character of plain text from the given fixed set of characters is substituted by some other character from the same set depending on a key. For example with a shift of 1, A would be replaced by B, B would become C, and so on. "
},
{
"code": null,
"e": 528,
"s": 431,
"text": "Note: Special case of Substitution cipher is known as Caesar cipher where the key is taken as 3."
},
{
"code": null,
"e": 759,
"s": 528,
"text": "The encryption can be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A = 0, B = 1,..., Z = 25. Encryption of a letter by a shift n can be described mathematically as. "
},
{
"code": null,
"e": 792,
"s": 759,
"text": "(Encryption Phase with shift n) "
},
{
"code": null,
"e": 825,
"s": 792,
"text": "(Decryption Phase with shift n) "
},
{
"code": null,
"e": 836,
"s": 825,
"text": "Examples: "
},
{
"code": null,
"e": 1005,
"s": 836,
"text": "Plain Text: I am studying Data Encryption\nKey: 4\nOutput: M eq wxyhCmrk Hexe IrgvCtxmsr\n\nPlain Text: ABCDEFGHIJKLMNOPQRSTUVWXYZ\nKey: 4\nOutput: EFGHIJKLMNOPQRSTUVWXYZabcd"
},
{
"code": null,
"e": 1041,
"s": 1005,
"text": "Algorithm for Substitution Cipher: "
},
{
"code": null,
"e": 1049,
"s": 1041,
"text": "Input: "
},
{
"code": null,
"e": 1115,
"s": 1049,
"text": "A String of both lower and upper case letters, called PlainText. "
},
{
"code": null,
"e": 1154,
"s": 1115,
"text": "An Integer denoting the required key. "
},
{
"code": null,
"e": 1166,
"s": 1154,
"text": "Procedure: "
},
{
"code": null,
"e": 1204,
"s": 1166,
"text": "Create a list of all the characters. "
},
{
"code": null,
"e": 1271,
"s": 1204,
"text": "Create a dictionary to store the substitution for all characters. "
},
{
"code": null,
"e": 1401,
"s": 1271,
"text": "For each character, transform the given character as per the rule, depending on whether we’re encrypting or decrypting the text. "
},
{
"code": null,
"e": 1434,
"s": 1401,
"text": "Print the new string generated. "
},
{
"code": null,
"e": 1463,
"s": 1434,
"text": "Below is the implementation."
},
{
"code": null,
"e": 1471,
"s": 1463,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# Substitution Cipher import string # A list containing all charactersall_letters= string.ascii_letters \"\"\"create a dictionary to store the substitutionfor the given alphabet in the plain textbased on the key\"\"\" dict1 = {}key = 4 for i in range(len(all_letters)): dict1[all_letters[i]] = all_letters[(i+key)%len(all_letters)] plain_txt= \"I am studying Data Encryption\"cipher_txt=[] # loop to generate ciphertext for char in plain_txt: if char in all_letters: temp = dict1[char] cipher_txt.append(temp) else: temp =char cipher_txt.append(temp) cipher_txt= \"\".join(cipher_txt)print(\"Cipher Text is: \",cipher_txt) \"\"\"create a dictionary to store the substitutionfor the given alphabet in the ciphertext based on the key\"\"\" dict2 = {} for i in range(len(all_letters)): dict2[all_letters[i]] = all_letters[(i-key)%(len(all_letters))] # loop to recover plain textdecrypt_txt = [] for char in cipher_txt: if char in all_letters: temp = dict2[char] decrypt_txt.append(temp) else: temp = char decrypt_txt.append(temp) decrypt_txt = \"\".join(decrypt_txt)print(\"Recovered plain text :\", decrypt_txt)",
"e": 2720,
"s": 1471,
"text": null
},
{
"code": null,
"e": 2728,
"s": 2720,
"text": "Output:"
},
{
"code": null,
"e": 2828,
"s": 2728,
"text": "Cipher Text is: M eq wxyhCmrk Hexe IrgvCtxmsr\nRecovered plain text : I am studying Data Encryption"
},
{
"code": null,
"e": 2844,
"s": 2830,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2857,
"s": 2844,
"text": "cryptography"
},
{
"code": null,
"e": 2864,
"s": 2857,
"text": "Python"
},
{
"code": null,
"e": 2883,
"s": 2864,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2896,
"s": 2883,
"text": "cryptography"
},
{
"code": null,
"e": 2994,
"s": 2896,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3036,
"s": 2994,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3058,
"s": 3036,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3084,
"s": 3058,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3116,
"s": 3084,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3145,
"s": 3116,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3172,
"s": 3145,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3193,
"s": 3172,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3216,
"s": 3193,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3252,
"s": 3216,
"text": "Convert integer to string in Python"
}
]
|
Logistic Regression in R Programming | 05 Jun, 2020
Logistic regression in R Programming is a classification algorithm used to find the probability of event success and event failure. Logistic regression is used when the dependent variable is binary(0/1, True/False, Yes/No) in nature. Logit function is used as a link function in a binomial distribution.
Logistic regression is also known as Binomial logistics regression. It is based on sigmoid function where output is probability and input can be from -infinity to +infinity.
Logistics regression is also known as generalized linear model. As it is used as a classification technique to predict a qualitative response, Value of y ranges from 0 to 1 and can be represented by following equation:
p is probability of characteristic of interest. The odds ratio is defined as the probability of success in comparison to the probability of failure. It is a key representation of logistic regression coefficients and can take values between 0 and infinity. Odds ratio of 1 is when the probability of success is equal to the probability of failure. Odds ratio of 2 is when the probability of success is twice the probability of failure. Odds ratio of 0.5 is when the probability of failure is twice the probability of success.
Since we are working with a binomial distribution(dependent variable), we need to choose a link function that is best suited for this distribution.
It is logit function. In the equation above, the parenthesis is chosen to maximize the likelihood of observing the sample values rather than minimizing the sum of squared errors(like ordinary regression). The logit is also known as a log of odds. The logit function must be linearly related to the independent variables. This is from equation A, where the left-hand side is a linear combination of x. This is similar to the OLS assumption that y be linearly related to x.
Variables b0, b1, b2 ... etc are unknown and must be estimated on available training data. In a logistic regression model, multiplying b1 by one unit changes the logit by b0. The P changes due to a one-unit change will depend upon the value multiplied. If b1 is positive then P will increase and if b1 is negative then P will decrease.
mtcars(motor trend car road test) comprises fuel consumption, performance and 10 aspects of automobile design for 32 automobiles. It comes pre installed with dplyr package in R.
# Installing the packageinstall.packages("dplyr") # Loading packagelibrary(dplyr) # Summary of dataset in packagesummary(mtcars)
Logistic regression is implemented in R using glm() by training the model using features or variables in the dataset.
# Installing the packageinstall.packages("caTools") # For Logistic regressioninstall.packages("ROCR") # For ROC curve to evaluate model # Loading packagelibrary(caTools)library(ROCR) # Splitting datasetsplit <- sample.split(mtcars, SplitRatio = 0.8)split train_reg <- subset(mtcars, split == "TRUE")test_reg <- subset(mtcars, split == "FALSE") # Training modellogistic_model <- glm(vs ~ wt + disp, data = train_reg, family = "binomial")logistic_model # Summarysummary(logistic_model) # Predict test data based on modelpredict_reg <- predict(logistic_model, test_reg, type = "response")predict_reg # Changing probabilitiespredict_reg <- ifelse(predict_reg >0.5, 1, 0) # Evaluating model accuracy# using confusion matrixtable(test_reg$vs, predict_reg) missing_classerr <- mean(predict_reg != test_reg$vs)print(paste('Accuracy =', 1 - missing_classerr)) # ROC-AUC CurveROCPred <- prediction(predict_reg, test_reg$vs) ROCPer <- performance(ROCPred, measure = "tpr", x.measure = "fpr") auc <- performance(ROCPred, measure = "auc")auc <- [email protected][[1]]auc # Plotting curveplot(ROCPer)plot(ROCPer, colorize = TRUE, print.cutoffs.at = seq(0.1, by = 0.1), main = "ROC CURVE")abline(a = 0, b = 1) auc <- round(auc, 4)legend(.6, .4, auc, title = "AUC", cex = 1)
wt influences dependent variables positively and one unit increase in wt increases the log of odds for vs =1 by 1.44. disp influences dependent variables negatively and one unit increase in disp decreases the log of odds for vs =1 by 0.0344. Null deviance is 31.755(fit dependent variable with intercept) and Residual deviance is 14.457(fit dependent variable with all independent variable). AIC(Alkaline Information criteria) value is 20.457 i.e the lesser the better for the model. Accuracy comes out to be 0.75 i.e 75%.
Model is evaluated using the Confusion matrix, AUC(Area under the curve), and ROC(Receiver operating characteristics) curve. In the confusion matrix, we should not always look for accuracy but also for sensitivity and specificity. ROC and AUC curve is plotted.
Output:
Evaluating model accuracy using confusion matrix:There are 0 Type 2 errors i.e Fail to reject it when it is false. Also, there are 3 Type 1 errors i.e rejecting it when it is true.
There are 0 Type 2 errors i.e Fail to reject it when it is false. Also, there are 3 Type 1 errors i.e rejecting it when it is true.
ROC curve:In ROC curve, the more the area under the curve, the better the model.
In ROC curve, the more the area under the curve, the better the model.
ROC-AUC Curve:AUC is 0.7333, so the more AUC is, the better the model performs.
AUC is 0.7333, so the more AUC is, the better the model performs.
R Machine-Learning
Machine Learning
R Language
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "Logistic regression in R Programming is a classification algorithm used to find the probability of event success and event failure. Logistic regression is used when the dependent variable is binary(0/1, True/False, Yes/No) in nature. Logit function is used as a link function in a binomial distribution."
},
{
"code": null,
"e": 506,
"s": 332,
"text": "Logistic regression is also known as Binomial logistics regression. It is based on sigmoid function where output is probability and input can be from -infinity to +infinity."
},
{
"code": null,
"e": 725,
"s": 506,
"text": "Logistics regression is also known as generalized linear model. As it is used as a classification technique to predict a qualitative response, Value of y ranges from 0 to 1 and can be represented by following equation:"
},
{
"code": null,
"e": 1250,
"s": 725,
"text": "p is probability of characteristic of interest. The odds ratio is defined as the probability of success in comparison to the probability of failure. It is a key representation of logistic regression coefficients and can take values between 0 and infinity. Odds ratio of 1 is when the probability of success is equal to the probability of failure. Odds ratio of 2 is when the probability of success is twice the probability of failure. Odds ratio of 0.5 is when the probability of failure is twice the probability of success."
},
{
"code": null,
"e": 1398,
"s": 1250,
"text": "Since we are working with a binomial distribution(dependent variable), we need to choose a link function that is best suited for this distribution."
},
{
"code": null,
"e": 1870,
"s": 1398,
"text": "It is logit function. In the equation above, the parenthesis is chosen to maximize the likelihood of observing the sample values rather than minimizing the sum of squared errors(like ordinary regression). The logit is also known as a log of odds. The logit function must be linearly related to the independent variables. This is from equation A, where the left-hand side is a linear combination of x. This is similar to the OLS assumption that y be linearly related to x."
},
{
"code": null,
"e": 2206,
"s": 1870,
"text": "Variables b0, b1, b2 ... etc are unknown and must be estimated on available training data. In a logistic regression model, multiplying b1 by one unit changes the logit by b0. The P changes due to a one-unit change will depend upon the value multiplied. If b1 is positive then P will increase and if b1 is negative then P will decrease."
},
{
"code": null,
"e": 2384,
"s": 2206,
"text": "mtcars(motor trend car road test) comprises fuel consumption, performance and 10 aspects of automobile design for 32 automobiles. It comes pre installed with dplyr package in R."
},
{
"code": "# Installing the packageinstall.packages(\"dplyr\") # Loading packagelibrary(dplyr) # Summary of dataset in packagesummary(mtcars)",
"e": 2517,
"s": 2384,
"text": null
},
{
"code": null,
"e": 2635,
"s": 2517,
"text": "Logistic regression is implemented in R using glm() by training the model using features or variables in the dataset."
},
{
"code": "# Installing the packageinstall.packages(\"caTools\") # For Logistic regressioninstall.packages(\"ROCR\") # For ROC curve to evaluate model # Loading packagelibrary(caTools)library(ROCR) # Splitting datasetsplit <- sample.split(mtcars, SplitRatio = 0.8)split train_reg <- subset(mtcars, split == \"TRUE\")test_reg <- subset(mtcars, split == \"FALSE\") # Training modellogistic_model <- glm(vs ~ wt + disp, data = train_reg, family = \"binomial\")logistic_model # Summarysummary(logistic_model) # Predict test data based on modelpredict_reg <- predict(logistic_model, test_reg, type = \"response\")predict_reg # Changing probabilitiespredict_reg <- ifelse(predict_reg >0.5, 1, 0) # Evaluating model accuracy# using confusion matrixtable(test_reg$vs, predict_reg) missing_classerr <- mean(predict_reg != test_reg$vs)print(paste('Accuracy =', 1 - missing_classerr)) # ROC-AUC CurveROCPred <- prediction(predict_reg, test_reg$vs) ROCPer <- performance(ROCPred, measure = \"tpr\", x.measure = \"fpr\") auc <- performance(ROCPred, measure = \"auc\")auc <- [email protected][[1]]auc # Plotting curveplot(ROCPer)plot(ROCPer, colorize = TRUE, print.cutoffs.at = seq(0.1, by = 0.1), main = \"ROC CURVE\")abline(a = 0, b = 1) auc <- round(auc, 4)legend(.6, .4, auc, title = \"AUC\", cex = 1)",
"e": 4034,
"s": 2635,
"text": null
},
{
"code": null,
"e": 4557,
"s": 4034,
"text": "wt influences dependent variables positively and one unit increase in wt increases the log of odds for vs =1 by 1.44. disp influences dependent variables negatively and one unit increase in disp decreases the log of odds for vs =1 by 0.0344. Null deviance is 31.755(fit dependent variable with intercept) and Residual deviance is 14.457(fit dependent variable with all independent variable). AIC(Alkaline Information criteria) value is 20.457 i.e the lesser the better for the model. Accuracy comes out to be 0.75 i.e 75%."
},
{
"code": null,
"e": 4818,
"s": 4557,
"text": "Model is evaluated using the Confusion matrix, AUC(Area under the curve), and ROC(Receiver operating characteristics) curve. In the confusion matrix, we should not always look for accuracy but also for sensitivity and specificity. ROC and AUC curve is plotted."
},
{
"code": null,
"e": 4826,
"s": 4818,
"text": "Output:"
},
{
"code": null,
"e": 5007,
"s": 4826,
"text": "Evaluating model accuracy using confusion matrix:There are 0 Type 2 errors i.e Fail to reject it when it is false. Also, there are 3 Type 1 errors i.e rejecting it when it is true."
},
{
"code": null,
"e": 5139,
"s": 5007,
"text": "There are 0 Type 2 errors i.e Fail to reject it when it is false. Also, there are 3 Type 1 errors i.e rejecting it when it is true."
},
{
"code": null,
"e": 5220,
"s": 5139,
"text": "ROC curve:In ROC curve, the more the area under the curve, the better the model."
},
{
"code": null,
"e": 5291,
"s": 5220,
"text": "In ROC curve, the more the area under the curve, the better the model."
},
{
"code": null,
"e": 5371,
"s": 5291,
"text": "ROC-AUC Curve:AUC is 0.7333, so the more AUC is, the better the model performs."
},
{
"code": null,
"e": 5437,
"s": 5371,
"text": "AUC is 0.7333, so the more AUC is, the better the model performs."
},
{
"code": null,
"e": 5456,
"s": 5437,
"text": "R Machine-Learning"
},
{
"code": null,
"e": 5473,
"s": 5456,
"text": "Machine Learning"
},
{
"code": null,
"e": 5484,
"s": 5473,
"text": "R Language"
},
{
"code": null,
"e": 5501,
"s": 5484,
"text": "Machine Learning"
},
{
"code": null,
"e": 5599,
"s": 5501,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5622,
"s": 5599,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 5646,
"s": 5622,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 5684,
"s": 5646,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 5725,
"s": 5684,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 5761,
"s": 5725,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 5806,
"s": 5761,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 5858,
"s": 5806,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 5916,
"s": 5858,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 5968,
"s": 5916,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
}
]
|
How to retrieve Python module path? | For a pure python module you can find the location of the source files by looking at the module.__file__. For example,
>>> import mymodule
>>> mymodule.__file__
C:/Users/Ayush/mymodule.py
Many built-in modules, however,are written in C, and therefore module.__file__ points to a .so file (there is no module.__file__ on Windows), and therefore, you can't see the source.
Running "python -v"from the command line tells you what is being imported and from where. This is useful if you want to know the location of built-in modules. | [
{
"code": null,
"e": 1306,
"s": 1187,
"text": "For a pure python module you can find the location of the source files by looking at the module.__file__. For example,"
},
{
"code": null,
"e": 1377,
"s": 1306,
"text": " >>> import mymodule\n>>> mymodule.__file__\nC:/Users/Ayush/mymodule.py "
},
{
"code": null,
"e": 1561,
"s": 1377,
"text": " Many built-in modules, however,are written in C, and therefore module.__file__ points to a .so file (there is no module.__file__ on Windows), and therefore, you can't see the source."
},
{
"code": null,
"e": 1721,
"s": 1561,
"text": " Running \"python -v\"from the command line tells you what is being imported and from where. This is useful if you want to know the location of built-in modules."
}
]
|
std::memcmp() in C++ | 11 Apr, 2022
It compares the first count characters of the arrays pointed to by buf1 and buf2.Syntax:
int memcmp(const void *buf1, const void *buf2, size_t count);
Return Value: it returns an integer.
Parameters:
buf1 : Pointer to block of memory.
buf2 : Pointer to block of memory.
count : Maximum numbers of bytes to compare.
Return Value is interpreted as :
Value Meaning
Less than zero buf1 is less than buf2.
Zero buf1 is equal to buf2.
Greater than zero buf1 is greater than buf2.
Example 1. When count Greater than zero( > 0)
// CPP program to illustrate std::memcmp()#include <iostream>#include <cstring> int main(){ char buff1[] = "Welcome to GeeksforGeeks"; char buff2[] = "Hello Geeks "; int a; a = std::memcmp(buff1, buff2, sizeof(buff1)); if (a > 0) std::cout << buff1 << " is greater than " << buff2; else if (a < 0) std::cout << buff1 << "is less than " << buff2; else std::cout << buff1 << " is the same as " << buff2; return 0;}
Output:
Welcome to GeeksforGeeks is greater than Hello Geeks
Example 2. When count less than zero( < 0)
// CPP program to illustrate std::memcmp() #include <cstring>#include <iostream> int main(){ int comp = memcmp("GEEKSFORGEEKS", "geeksforgeeks", 6); if (comp == 0) { std::cout << "both are equal"; } else if (comp < 0) { std::cout << "String 1 is less than String 2"; } else { std::cout << "String 1 is greater than String 2"; }}
Output:
String 1 is less than String 2
Example 3 : When count equal to zero ( = 0)
// CPP program to illustrate std::memcmp()#include <iostream>#include <cstring> int main(){ char buff1[] = "Welcome to GeeksforGeeks"; char buff2[] = "Welcome to GeeksforGeeks"; int a; a = std::memcmp(buff1, buff2, sizeof(buff1)); if (a > 0) std::cout << buff1 << " is greater than " << buff2; else if (a < 0) std::cout << buff1 << "is less than " << buff2; else std::cout << buff1 << " is the same as " << buff2; return 0;}
Output:
Welcome to GeeksforGeeks is the same as Welcome to GeeksforGeeks
This article is contributed by Shivani Ghughtyal. 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.
yash_760
CPP-Library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 141,
"s": 52,
"text": "It compares the first count characters of the arrays pointed to by buf1 and buf2.Syntax:"
},
{
"code": null,
"e": 633,
"s": 141,
"text": "int memcmp(const void *buf1, const void *buf2, size_t count);\nReturn Value: it returns an integer.\nParameters: \nbuf1 : Pointer to block of memory.\nbuf2 : Pointer to block of memory.\ncount : Maximum numbers of bytes to compare.\nReturn Value is interpreted as :\nValue Meaning\nLess than zero buf1 is less than buf2.\nZero buf1 is equal to buf2.\nGreater than zero buf1 is greater than buf2.\n"
},
{
"code": null,
"e": 679,
"s": 633,
"text": "Example 1. When count Greater than zero( > 0)"
},
{
"code": "// CPP program to illustrate std::memcmp()#include <iostream>#include <cstring> int main(){ char buff1[] = \"Welcome to GeeksforGeeks\"; char buff2[] = \"Hello Geeks \"; int a; a = std::memcmp(buff1, buff2, sizeof(buff1)); if (a > 0) std::cout << buff1 << \" is greater than \" << buff2; else if (a < 0) std::cout << buff1 << \"is less than \" << buff2; else std::cout << buff1 << \" is the same as \" << buff2; return 0;}",
"e": 1146,
"s": 679,
"text": null
},
{
"code": null,
"e": 1154,
"s": 1146,
"text": "Output:"
},
{
"code": null,
"e": 1209,
"s": 1154,
"text": "Welcome to GeeksforGeeks is greater than Hello Geeks \n"
},
{
"code": null,
"e": 1252,
"s": 1209,
"text": "Example 2. When count less than zero( < 0)"
},
{
"code": "// CPP program to illustrate std::memcmp() #include <cstring>#include <iostream> int main(){ int comp = memcmp(\"GEEKSFORGEEKS\", \"geeksforgeeks\", 6); if (comp == 0) { std::cout << \"both are equal\"; } else if (comp < 0) { std::cout << \"String 1 is less than String 2\"; } else { std::cout << \"String 1 is greater than String 2\"; }}",
"e": 1623,
"s": 1252,
"text": null
},
{
"code": null,
"e": 1631,
"s": 1623,
"text": "Output:"
},
{
"code": null,
"e": 1663,
"s": 1631,
"text": "String 1 is less than String 2\n"
},
{
"code": null,
"e": 1707,
"s": 1663,
"text": "Example 3 : When count equal to zero ( = 0)"
},
{
"code": "// CPP program to illustrate std::memcmp()#include <iostream>#include <cstring> int main(){ char buff1[] = \"Welcome to GeeksforGeeks\"; char buff2[] = \"Welcome to GeeksforGeeks\"; int a; a = std::memcmp(buff1, buff2, sizeof(buff1)); if (a > 0) std::cout << buff1 << \" is greater than \" << buff2; else if (a < 0) std::cout << buff1 << \"is less than \" << buff2; else std::cout << buff1 << \" is the same as \" << buff2; return 0;}",
"e": 2186,
"s": 1707,
"text": null
},
{
"code": null,
"e": 2194,
"s": 2186,
"text": "Output:"
},
{
"code": null,
"e": 2260,
"s": 2194,
"text": "Welcome to GeeksforGeeks is the same as Welcome to GeeksforGeeks\n"
},
{
"code": null,
"e": 2565,
"s": 2260,
"text": "This article is contributed by Shivani Ghughtyal. 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": 2690,
"s": 2565,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2699,
"s": 2690,
"text": "yash_760"
},
{
"code": null,
"e": 2711,
"s": 2699,
"text": "CPP-Library"
},
{
"code": null,
"e": 2715,
"s": 2711,
"text": "STL"
},
{
"code": null,
"e": 2719,
"s": 2715,
"text": "C++"
},
{
"code": null,
"e": 2723,
"s": 2719,
"text": "STL"
},
{
"code": null,
"e": 2727,
"s": 2723,
"text": "CPP"
},
{
"code": null,
"e": 2825,
"s": 2727,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2849,
"s": 2825,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2869,
"s": 2849,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2902,
"s": 2869,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2946,
"s": 2902,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2971,
"s": 2946,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3016,
"s": 2971,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3064,
"s": 3016,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3081,
"s": 3064,
"text": "std::find in C++"
},
{
"code": null,
"e": 3125,
"s": 3081,
"text": "List in C++ Standard Template Library (STL)"
}
]
|
Creating Decorator inside a class in Python | 05 Sep, 2020
We can easily create decorators inside a class and it is easily accessible for its child classes. During Decorator creation, we must take care that the function that we are defining inside the decorator must take current object reference (self) as a parameter, and while we are accessing that decorator from child class that time we must call that decorator using the class name(class in which Decorator is present).
Example 1: Here in this example we are creating a decorator function inside Class A. Inside Class A “fun1” Instance Method is calling the decorator function “Decorators” inside Class B “fun2”. Instance Method is calling the decorator function of Class A. To use the decorator of Class A, we must require using Class name in which decorator is present that’s why we use “@A.Decorators” here.
Python3
# creating class Aclass A : def Decorators(func) : def inner(self) : print('Decoration started.') func(self) print('Decoration of function completed.\n') return inner @Decorators def fun1(self) : print('Decorating - Class A methods.') # creating class Bclass B(A) : @A.Decorators def fun2(self) : print('Decoration - Class B methods.') obj = B()obj.fun1()obj.fun2()
Output:
Decoration started.
Decorating - Class A methods.
Decoration of function completed.
Decoration started.
Decoration - Class B methods.
Decoration of function completed.
Example 2: Checking number is Even or Odd using Decorator.
Python3
class Check_no : # decorator function def decor(func) : def check(self, no) : func(self, no) if no % 2 == 0 : print('Yes, it\'s EVEN Number.') else : print('No, it\'s ODD Number.') return check @decor #instance method def is_even(self, no) : print('User Input : ', no) obj = Check_no()obj.is_even(45)obj.is_even(2)obj.is_even(7)
Output:
User Input : 45
No, it's ODD Number.
User Input : 2
Yes, it's EVEN Number.
User Input : 7
No, it's ODD Number.
Example 3: Checking Grade from Marks.
Python3
# parent classclass Student : # decorator function def decor(func) : def grade(self,marks) : func(self,marks) if marks < 35 : print('Grade : F') elif marks < 50 : print('Grade : E') elif marks < 60 : print('Grade : D') elif marks < 70 : print('Grade : C') elif marks < 80 : print('Grade : B') elif marks < 100 : print('Grade : A') return grade # child classclass Result(Student) : @Student.decor # instance method def result(self,marks) : print('Your Score : ',marks) # creating object of parent classobj = Result() obj.result(89) obj.result(34)
Output:
Your Score : 89
Grade : A
Your Score : 34
Grade : F
Python Decorators
Python-OOP
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
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 471,
"s": 54,
"text": "We can easily create decorators inside a class and it is easily accessible for its child classes. During Decorator creation, we must take care that the function that we are defining inside the decorator must take current object reference (self) as a parameter, and while we are accessing that decorator from child class that time we must call that decorator using the class name(class in which Decorator is present)."
},
{
"code": null,
"e": 862,
"s": 471,
"text": "Example 1: Here in this example we are creating a decorator function inside Class A. Inside Class A “fun1” Instance Method is calling the decorator function “Decorators” inside Class B “fun2”. Instance Method is calling the decorator function of Class A. To use the decorator of Class A, we must require using Class name in which decorator is present that’s why we use “@A.Decorators” here."
},
{
"code": null,
"e": 870,
"s": 862,
"text": "Python3"
},
{
"code": "# creating class Aclass A : def Decorators(func) : def inner(self) : print('Decoration started.') func(self) print('Decoration of function completed.\\n') return inner @Decorators def fun1(self) : print('Decorating - Class A methods.') # creating class Bclass B(A) : @A.Decorators def fun2(self) : print('Decoration - Class B methods.') obj = B()obj.fun1()obj.fun2()",
"e": 1316,
"s": 870,
"text": null
},
{
"code": null,
"e": 1324,
"s": 1316,
"text": "Output:"
},
{
"code": null,
"e": 1494,
"s": 1324,
"text": "Decoration started.\nDecorating - Class A methods.\nDecoration of function completed.\n\nDecoration started.\nDecoration - Class B methods.\nDecoration of function completed.\n"
},
{
"code": null,
"e": 1553,
"s": 1494,
"text": "Example 2: Checking number is Even or Odd using Decorator."
},
{
"code": null,
"e": 1561,
"s": 1553,
"text": "Python3"
},
{
"code": "class Check_no : # decorator function def decor(func) : def check(self, no) : func(self, no) if no % 2 == 0 : print('Yes, it\\'s EVEN Number.') else : print('No, it\\'s ODD Number.') return check @decor #instance method def is_even(self, no) : print('User Input : ', no) obj = Check_no()obj.is_even(45)obj.is_even(2)obj.is_even(7)",
"e": 2026,
"s": 1561,
"text": null
},
{
"code": null,
"e": 2034,
"s": 2026,
"text": "Output:"
},
{
"code": null,
"e": 2149,
"s": 2034,
"text": "User Input : 45\nNo, it's ODD Number.\nUser Input : 2\nYes, it's EVEN Number.\nUser Input : 7\nNo, it's ODD Number.\n"
},
{
"code": null,
"e": 2187,
"s": 2149,
"text": "Example 3: Checking Grade from Marks."
},
{
"code": null,
"e": 2195,
"s": 2187,
"text": "Python3"
},
{
"code": "# parent classclass Student : # decorator function def decor(func) : def grade(self,marks) : func(self,marks) if marks < 35 : print('Grade : F') elif marks < 50 : print('Grade : E') elif marks < 60 : print('Grade : D') elif marks < 70 : print('Grade : C') elif marks < 80 : print('Grade : B') elif marks < 100 : print('Grade : A') return grade # child classclass Result(Student) : @Student.decor # instance method def result(self,marks) : print('Your Score : ',marks) # creating object of parent classobj = Result() obj.result(89) obj.result(34)",
"e": 3015,
"s": 2195,
"text": null
},
{
"code": null,
"e": 3023,
"s": 3015,
"text": "Output:"
},
{
"code": null,
"e": 3078,
"s": 3023,
"text": "Your Score : 89\nGrade : A\nYour Score : 34\nGrade : F\n"
},
{
"code": null,
"e": 3096,
"s": 3078,
"text": "Python Decorators"
},
{
"code": null,
"e": 3107,
"s": 3096,
"text": "Python-OOP"
},
{
"code": null,
"e": 3114,
"s": 3107,
"text": "Python"
},
{
"code": null,
"e": 3212,
"s": 3114,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3230,
"s": 3212,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3272,
"s": 3230,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3294,
"s": 3272,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3320,
"s": 3294,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3352,
"s": 3320,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3381,
"s": 3352,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3408,
"s": 3381,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3429,
"s": 3408,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3465,
"s": 3429,
"text": "Convert integer to string in Python"
}
]
|
Program to find sum of harmonic series | 23 Jun, 2022
Harmonic series is inverse of a arithmetic progression. In general, the terms in a harmonic progression can be denoted as 1/a, 1/(a + d), 1/(a + 2d), 1/(a + 3d) .... 1/(a + nd). As Nth term of AP is given as ( a + (n – 1)d). Hence, Nth term of harmonic progression is reciprocal of Nth term of AP, which is 1/(a + (n – 1)d), where “a” is the 1st term of AP and “d” is a common difference.
Method #1: Simple approach
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of harmonic series#include<bits/stdc++.h>using namespace std; // Function to return sum of harmonic seriesdouble sum(int n){ double i, s = 0.0; for(i = 1; i <= n; i++) s = s + 1 / i; return s;} // Driver codeint main(){ int n = 5; cout << "Sum is " << sum(n); return 0;} // This code is contributed by SHUBHAMSINGH10
// C program to find sum of harmonic series#include <stdio.h> // Function to return sum of harmonic seriesdouble sum(int n){ double i, s = 0.0; for (i = 1; i <= n; i++) s = s + 1/i; return s;} int main(){ int n = 5; printf("Sum is %f", sum(n)); return 0;}
// Java Program to find sum of harmonic seriesimport java.io.*; class GFG { // Function to return sum of // harmonic series static double sum(int n) { double i, s = 0.0; for (i = 1; i <= n; i++) s = s + 1/i; return s; } // Driven Program public static void main(String args[]) { int n = 5; System.out.printf("Sum is %f", sum(n)); }}
# Python program to find the sum of harmonic series def sum(n): i = 1 s = 0.0 for i in range(1, n+1): s = s + 1/i; return s; # Driver Coden = 5print("Sum is", round(sum(n), 6))
// C# Program to find sum of harmonic seriesusing System; class GFG { // Function to return sum of // harmonic series static float sum(int n) { double i, s = 0.0; for (i = 1; i <= n; i++) s = s + 1/i; return (float)s; } // Driven Program public static void Main() { int n = 5; Console.WriteLine("Sum is " + sum(n)); }}
<?php// PHP program to find sum of harmonic series // Function to return sum of// harmonic seriesfunction sum( $n){ $i; $s = 0.0; for ($i = 1; $i <= $n; $i++) $s = $s + 1 / $i; return $s;} // Driver Code $n = 5; echo("Sum is "); echo(sum($n)); ?>
<script>// JavaScript program to find sum of harmonic series // Function to return sum of harmonic seriesfunction sum(n){let i, s = 0.0;for(i = 1; i <= n; i++) s = s + 1 / i; return s;} // Driver codelet n = 5;document.write("Sum is " + sum(n)); // This code is contributed by Surbhi Tyagi.</script>
Sum is 2.283333
Time Complexity : O(n) ,as we are traversing once in array.
Auxiliary Space : O(1) ,no extra space needed.
Method #2: Using recursion
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find sum of// harmonic series using recursion#include<bits/stdc++.h>using namespace std; float sum(float n){ // Base condition if (n < 2) return 1; else return 1 / n + (sum(n - 1));} // Driven Codeint main(){ cout << (sum(8)) << endl; cout << (sum(10)) << endl; return 0;} // This code is contributed by// Shashank_Sharma
// Java program to find sum of// harmonic series using recursionimport java.io.*; class GFG{ float sum(float n){ // Base condition if (n < 2) return 1; else return 1 / n + (sum(n - 1));} // Driven Codepublic static void main(String args[]){ GFG g = new GFG(); System.out.println(g.sum(8)); System.out.print(g.sum(10));}} // This code is contributed by Shivi_Aggarwal
# Python program to find sum of# harmonic series using recursion def sum(n): # Base condition if n < 2: return 1 else: return 1 / n + (sum(n - 1)) print(sum(8))print(sum(10))
//C# program to find sum of// harmonic series using recursionusing System; class GFG{ static float sum(float n){ // Base condition if (n < 2) return 1; else return 1 / n + (sum(n - 1));} // Driven Codepublic static void Main(){ Console.WriteLine(sum(8)); Console.WriteLine(sum(10));}} // This code is contributed by shs..
<?php// PHP program to find sum of// harmonic series using recursion function sum($n){ // Base condition if ($n < 2) return 1; else return 1 / $n + (sum($n - 1));} // Driver Codeecho sum(8) . "\n";echo sum(10); // This code is contributed by Ryuga?>
<script> // Javascript program to find sum of// harmonic series using recursionfunction sum(n){ // Base condition if (n < 2) { return 1 } else { return 1 / n + (sum(n - 1)) }} // Driver codedocument.write(sum(8));document.write("<br>");document.write(sum(10)); // This code is contributed by bunnyram19 </script>
2.7178571428571425
2.9289682539682538
Time Complexity : O(n), as we are recursing for n times.
Auxiliary Space : O(n), due to recursive stack space.
ankthon
Shivi_Aggarwal
Shashank_Sharma
Shashank12
SHUBHAMSINGH10
surbhityagi15
bunnyram19
aditya942003patil
sushmitamittal1329
harmonic progression
series
series-sum
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Sieve of Eratosthenes
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
The Knight's tour problem | Backtracking-1
Program for Decimal to Binary Conversion | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 441,
"s": 52,
"text": "Harmonic series is inverse of a arithmetic progression. In general, the terms in a harmonic progression can be denoted as 1/a, 1/(a + d), 1/(a + 2d), 1/(a + 3d) .... 1/(a + nd). As Nth term of AP is given as ( a + (n – 1)d). Hence, Nth term of harmonic progression is reciprocal of Nth term of AP, which is 1/(a + (n – 1)d), where “a” is the 1st term of AP and “d” is a common difference."
},
{
"code": null,
"e": 469,
"s": 441,
"text": "Method #1: Simple approach "
},
{
"code": null,
"e": 473,
"s": 469,
"text": "C++"
},
{
"code": null,
"e": 475,
"s": 473,
"text": "C"
},
{
"code": null,
"e": 480,
"s": 475,
"text": "Java"
},
{
"code": null,
"e": 488,
"s": 480,
"text": "Python3"
},
{
"code": null,
"e": 491,
"s": 488,
"text": "C#"
},
{
"code": null,
"e": 495,
"s": 491,
"text": "PHP"
},
{
"code": null,
"e": 506,
"s": 495,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of harmonic series#include<bits/stdc++.h>using namespace std; // Function to return sum of harmonic seriesdouble sum(int n){ double i, s = 0.0; for(i = 1; i <= n; i++) s = s + 1 / i; return s;} // Driver codeint main(){ int n = 5; cout << \"Sum is \" << sum(n); return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 880,
"s": 506,
"text": null
},
{
"code": "// C program to find sum of harmonic series#include <stdio.h> // Function to return sum of harmonic seriesdouble sum(int n){ double i, s = 0.0; for (i = 1; i <= n; i++) s = s + 1/i; return s;} int main(){ int n = 5; printf(\"Sum is %f\", sum(n)); return 0;}",
"e": 1153,
"s": 880,
"text": null
},
{
"code": "// Java Program to find sum of harmonic seriesimport java.io.*; class GFG { // Function to return sum of // harmonic series static double sum(int n) { double i, s = 0.0; for (i = 1; i <= n; i++) s = s + 1/i; return s; } // Driven Program public static void main(String args[]) { int n = 5; System.out.printf(\"Sum is %f\", sum(n)); }}",
"e": 1569,
"s": 1153,
"text": null
},
{
"code": "# Python program to find the sum of harmonic series def sum(n): i = 1 s = 0.0 for i in range(1, n+1): s = s + 1/i; return s; # Driver Coden = 5print(\"Sum is\", round(sum(n), 6))",
"e": 1765,
"s": 1569,
"text": null
},
{
"code": "// C# Program to find sum of harmonic seriesusing System; class GFG { // Function to return sum of // harmonic series static float sum(int n) { double i, s = 0.0; for (i = 1; i <= n; i++) s = s + 1/i; return (float)s; } // Driven Program public static void Main() { int n = 5; Console.WriteLine(\"Sum is \" + sum(n)); }}",
"e": 2230,
"s": 1765,
"text": null
},
{
"code": "<?php// PHP program to find sum of harmonic series // Function to return sum of// harmonic seriesfunction sum( $n){ $i; $s = 0.0; for ($i = 1; $i <= $n; $i++) $s = $s + 1 / $i; return $s;} // Driver Code $n = 5; echo(\"Sum is \"); echo(sum($n)); ?>",
"e": 2513,
"s": 2230,
"text": null
},
{
"code": "<script>// JavaScript program to find sum of harmonic series // Function to return sum of harmonic seriesfunction sum(n){let i, s = 0.0;for(i = 1; i <= n; i++) s = s + 1 / i; return s;} // Driver codelet n = 5;document.write(\"Sum is \" + sum(n)); // This code is contributed by Surbhi Tyagi.</script>",
"e": 2824,
"s": 2513,
"text": null
},
{
"code": null,
"e": 2840,
"s": 2824,
"text": "Sum is 2.283333"
},
{
"code": null,
"e": 2902,
"s": 2842,
"text": "Time Complexity : O(n) ,as we are traversing once in array."
},
{
"code": null,
"e": 2949,
"s": 2902,
"text": "Auxiliary Space : O(1) ,no extra space needed."
},
{
"code": null,
"e": 2977,
"s": 2949,
"text": "Method #2: Using recursion "
},
{
"code": null,
"e": 2981,
"s": 2977,
"text": "C++"
},
{
"code": null,
"e": 2986,
"s": 2981,
"text": "Java"
},
{
"code": null,
"e": 2994,
"s": 2986,
"text": "Python3"
},
{
"code": null,
"e": 2997,
"s": 2994,
"text": "C#"
},
{
"code": null,
"e": 3001,
"s": 2997,
"text": "PHP"
},
{
"code": null,
"e": 3012,
"s": 3001,
"text": "Javascript"
},
{
"code": "// CPP program to find sum of// harmonic series using recursion#include<bits/stdc++.h>using namespace std; float sum(float n){ // Base condition if (n < 2) return 1; else return 1 / n + (sum(n - 1));} // Driven Codeint main(){ cout << (sum(8)) << endl; cout << (sum(10)) << endl; return 0;} // This code is contributed by// Shashank_Sharma",
"e": 3385,
"s": 3012,
"text": null
},
{
"code": "// Java program to find sum of// harmonic series using recursionimport java.io.*; class GFG{ float sum(float n){ // Base condition if (n < 2) return 1; else return 1 / n + (sum(n - 1));} // Driven Codepublic static void main(String args[]){ GFG g = new GFG(); System.out.println(g.sum(8)); System.out.print(g.sum(10));}} // This code is contributed by Shivi_Aggarwal",
"e": 3779,
"s": 3385,
"text": null
},
{
"code": "# Python program to find sum of# harmonic series using recursion def sum(n): # Base condition if n < 2: return 1 else: return 1 / n + (sum(n - 1)) print(sum(8))print(sum(10))",
"e": 3987,
"s": 3779,
"text": null
},
{
"code": "//C# program to find sum of// harmonic series using recursionusing System; class GFG{ static float sum(float n){ // Base condition if (n < 2) return 1; else return 1 / n + (sum(n - 1));} // Driven Codepublic static void Main(){ Console.WriteLine(sum(8)); Console.WriteLine(sum(10));}} // This code is contributed by shs..",
"e": 4339,
"s": 3987,
"text": null
},
{
"code": "<?php// PHP program to find sum of// harmonic series using recursion function sum($n){ // Base condition if ($n < 2) return 1; else return 1 / $n + (sum($n - 1));} // Driver Codeecho sum(8) . \"\\n\";echo sum(10); // This code is contributed by Ryuga?>",
"e": 4614,
"s": 4339,
"text": null
},
{
"code": "<script> // Javascript program to find sum of// harmonic series using recursionfunction sum(n){ // Base condition if (n < 2) { return 1 } else { return 1 / n + (sum(n - 1)) }} // Driver codedocument.write(sum(8));document.write(\"<br>\");document.write(sum(10)); // This code is contributed by bunnyram19 </script>",
"e": 4969,
"s": 4614,
"text": null
},
{
"code": null,
"e": 5007,
"s": 4969,
"text": "2.7178571428571425\n2.9289682539682538"
},
{
"code": null,
"e": 5066,
"s": 5009,
"text": "Time Complexity : O(n), as we are recursing for n times."
},
{
"code": null,
"e": 5120,
"s": 5066,
"text": "Auxiliary Space : O(n), due to recursive stack space."
},
{
"code": null,
"e": 5128,
"s": 5120,
"text": "ankthon"
},
{
"code": null,
"e": 5143,
"s": 5128,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 5159,
"s": 5143,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 5170,
"s": 5159,
"text": "Shashank12"
},
{
"code": null,
"e": 5185,
"s": 5170,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 5199,
"s": 5185,
"text": "surbhityagi15"
},
{
"code": null,
"e": 5210,
"s": 5199,
"text": "bunnyram19"
},
{
"code": null,
"e": 5228,
"s": 5210,
"text": "aditya942003patil"
},
{
"code": null,
"e": 5247,
"s": 5228,
"text": "sushmitamittal1329"
},
{
"code": null,
"e": 5268,
"s": 5247,
"text": "harmonic progression"
},
{
"code": null,
"e": 5275,
"s": 5268,
"text": "series"
},
{
"code": null,
"e": 5286,
"s": 5275,
"text": "series-sum"
},
{
"code": null,
"e": 5299,
"s": 5286,
"text": "Mathematical"
},
{
"code": null,
"e": 5312,
"s": 5299,
"text": "Mathematical"
},
{
"code": null,
"e": 5319,
"s": 5312,
"text": "series"
},
{
"code": null,
"e": 5417,
"s": 5319,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5441,
"s": 5417,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 5462,
"s": 5441,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 5476,
"s": 5462,
"text": "Prime Numbers"
},
{
"code": null,
"e": 5498,
"s": 5476,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 5540,
"s": 5498,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 5593,
"s": 5540,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 5630,
"s": 5593,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 5662,
"s": 5630,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 5705,
"s": 5662,
"text": "The Knight's tour problem | Backtracking-1"
}
]
|
Encryption and Decryption of String according to given technique | 31 May, 2021
Given a string S, the task is to encrypt the string and decrypt the string again to the original form. Encryption Technique: If L is the length of the string, then take two values, one the ceil of √L (say b), and the other floor of √L (say a), and make a two-dimensional matrix having rows = a, and columns = b. If rows*columns < L, then increase the value of a or b, whichever is minimum. Fill the matrix with the characters of the original string sequentially. After obtaining the matrix, read the matrix column-wise and print the obtained string.
Decryption Technique: If L is the length of the encrypted string, then again find the two values a and b, where a is the ceil value of the √L and b is the floor value of the √L. Similarly create a 2D Matrix in which store the string column-wise and read the matrix row-wise to get the string in the original form.
Encryption Approach:
Find the length L of the string.
Find the ceil and floor values of √Length and assign them to the variables.
Check if the product of the two variables >= Length, if not then increments the variable having a lesser value by 1.
Create a 2D matrix and fill the characters of the string row-wise.
Read the matrix column-wise to get the encrypted string.
Decryption Approach:
Find the length L of the string.
Find the ceil and floor values of √Length and assign them to the variables.
Create a 2D matrix and fill the matrix by characters of string column-wise.
Read the matrix row-wise to get the decrypted string.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation for Custom// Encryption and Decryption of String #include <bits/stdc++.h>using namespace std; // Function to encrypt the stringstring encryption(string s){ int l = s.length(); int b = ceil(sqrt(l)); int a = floor(sqrt(l)); string encrypted; if (b * a < l) { if (min(b, a) == b) { b = b + 1; } else { a = a + 1; } } // Matrix to generate the // Encrypted String char arr[a][b]; memset(arr, ' ', sizeof(arr)); int k = 0; // Fill the matrix row-wise for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { if (k < l){ arr[j][i] = s[k]; } k++; } } // Loop to generate // encrypted string for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { encrypted = encrypted + arr[i][j]; } } return encrypted;} // Function to decrypt the stringstring decryption(string s){ int l = s.length(); int b = ceil(sqrt(l)); int a = floor(sqrt(l)); string decrypted; // Matrix to generate the // Encrypted String char arr[a][b]; memset(arr, ' ', sizeof(arr)); int k = 0; // Fill the matrix column-wise for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { if (k < l){ arr[j][i] = s[k]; } k++; } } // Loop to generate // decrypted string for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { decrypted = decrypted + arr[i][j]; } } return decrypted;} // Driver Codeint main(){ string s = "Geeks For Geeks"; string encrypted; string decrypted; // Encryption of String encrypted = encryption(s); cout << encrypted << endl; // Decryption of String decrypted = decryption(encrypted); cout << decrypted; return 0;}
// Java implementation for Custom// Encryption and Decryption of Stringclass GFG{ // Function to encrypt the Stringstatic String encryption(char[] s){ int l = s.length; int b = (int) Math.ceil(Math.sqrt(l)); int a = (int) Math.floor(Math.sqrt(l)); String encrypted = ""; if (b * a < l) { if (Math.min(b, a) == b) { b = b + 1; } else { a = a + 1; } } // Matrix to generate the // Encrypted String char [][]arr = new char[a][b]; int k = 0; // Fill the matrix row-wise for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { if (k < l) { arr[j][i] = s[k]; } k++; } } // Loop to generate // encrypted String for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { encrypted = encrypted + arr[i][j]; } } return encrypted;} // Function to decrypt the Stringstatic String decryption(char []s){ int l = s.length; int b = (int) Math.ceil(Math.sqrt(l)); int a = (int) Math.floor(Math.sqrt(l)); String decrypted=""; // Matrix to generate the // Encrypted String char [][]arr = new char[a][b]; int k = 0; // Fill the matrix column-wise for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { if (k < l) { arr[j][i] = s[k]; } k++; } } // Loop to generate // decrypted String for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { decrypted = decrypted + arr[i][j]; } } return decrypted;} // Driver Codepublic static void main(String[] args){ String s = "Geeks For Geeks"; String encrypted; String decrypted; // Encryption of String encrypted = encryption(s.toCharArray()); System.out.print(encrypted +"\n"); // Decryption of String decrypted = decryption(encrypted.toCharArray()); System.out.print(decrypted);}} // This code is contributed by PrinciRaj1992
# Python3 implementation for Custom# Encryption and Decryption of Stringfrom math import ceil,floor,sqrt # Function to encrypt thedef encryption(s): l = len(s) b = ceil(sqrt(l)) a = floor(sqrt(l)) encrypted="" if (b * a < l): if (min(b, a) == b): b = b + 1 else: a = a + 1 # Matrix to generate the # Encrypted String arr = [[' ' for i in range(a)] for j in range(b)] k = 0 # Fill the matrix row-wise for j in range(a): for i in range(b): if (k < l): arr[j][i] = s[k] k += 1 # Loop to generate # encrypted for j in range(b): for i in range(a): encrypted = encrypted + arr[i][j] return encrypted # Function to decrypt thedef decryption(s): l = len(s) b = ceil(sqrt(l)) a = floor(sqrt(l)) decrypted="" # Matrix to generate the # Encrypted String arr = [[' ' for i in range(a)] for j in range(b)] k = 0 # Fill the matrix column-wise for j in range(b): for i in range(a): if (k < l): arr[j][i] = s[k] k += 1 # Loop to generate # decrypted for j in range(a): for i in range(b): decrypted = decrypted + arr[i][j] return decrypted # Driver Code s = "Geeks For Geeks"encrypted=""decrypted="" # Encryption of Stringencrypted = encryption(s)print(encrypted) # Decryption of Stringdecrypted = decryption(encrypted)print(decrypted) # This code is contributed by mohit kumar 29
// C# implementation for Custom// Encryption and Decryption of Stringusing System; class GFG{ // Function to encrypt the Stringstatic String encryption(char[] s){ int l = s.Length; int b = (int) Math.Ceiling(Math.Sqrt(l)); int a = (int) Math.Floor(Math.Sqrt(l)); String encrypted = ""; if (b * a < l) { if (Math.Min(b, a) == b) { b = b + 1; } else { a = a + 1; } } // Matrix to generate the // Encrypted String char [,]arr = new char[a, b]; int k = 0; // Fill the matrix row-wise for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { if (k < l) { arr[j, i] = s[k]; } k++; } } // Loop to generate // encrypted String for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { encrypted = encrypted + arr[i, j]; } } return encrypted;} // Function to decrypt the Stringstatic String decryption(char []s){ int l = s.Length; int b = (int) Math.Ceiling(Math.Sqrt(l)); int a = (int) Math.Floor(Math.Sqrt(l)); String decrypted=""; // Matrix to generate the // Encrypted String char [,]arr = new char[a, b]; int k = 0; // Fill the matrix column-wise for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { if (k < l) { arr[j, i] = s[k]; } k++; } } // Loop to generate // decrypted String for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { decrypted = decrypted + arr[i, j]; } } return decrypted;} // Driver Codepublic static void Main(String[] args){ String s = "Geeks For Geeks"; String encrypted; String decrypted; // Encryption of String encrypted = encryption(s.ToCharArray()); Console.Write(encrypted +"\n"); // Decryption of String decrypted = decryption(encrypted.ToCharArray()); Console.Write(decrypted);}} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation for Custom// Encryption and Decryption of let // Function to encrypt the letfunction encryption(s) { let l = s.length; let b = Math.ceil(Math.sqrt(l)); let a = Math.floor(Math.sqrt(l)); let encrypted = ''; if (b * a < l) { if (Math.min(b, a) == b) { b = b + 1; } else { a = a + 1; } } // Matrix to generate the // Encrypted let let arr = new Array(); for (let i = 0; i < a; i++) { let temp = []; for (let j = 0; j < b; j++) { temp.push([]) } arr.push(temp) } for (let i = 0; i < a; i++) { for (let j = 0; j < b; j++) { arr[i][j] = " " } } let k = 0; // Fill the matrix row-wise for (let j = 0; j < a; j++) { for (let i = 0; i < b; i++) { if (k < l) { arr[j][i] = s[k]; } k++; } } // Loop to generate // encrypted let for (let j = 0; j < b; j++) { for (let i = 0; i < a; i++) { encrypted = encrypted + arr[i][j]; } } return encrypted;} // Function to decrypt the letfunction decryption(s) { let l = s.length; let b = Math.ceil(Math.sqrt(l)); let a = Math.floor(Math.sqrt(l)); let decrypted = ''; // Matrix to generate the // Encrypted let let arr = new Array(); for (let i = 0; i < a; i++) { let temp = []; for (let j = 0; j < b; j++) { temp.push([]) } arr.push(temp) } for (let i = 0; i < a; i++) { for (let j = 0; j < b; j++) { arr[i][j] = " " } } let k = 0; // Fill the matrix column-wise for (let j = 0; j < b; j++) { for (let i = 0; i < a; i++) { if (k < l) { arr[j][i] = s[k]; } k++; } } // Loop to generate // decrypted let for (let j = 0; j < a; j++) { for (let i = 0; i < b; i++) { decrypted = decrypted + arr[i][j]; } } return decrypted;} // Driver Code let s = "Geeks For Geeks";let encrypted;let decrypted; // Encryption of letencrypted = encryption(s);document.write(encrypted + "<br>"); // Decryption of letdecrypted = decryption(encrypted);document.write(decrypted); // This code is contributed by gfgking </script>
Gsree keFGskoe
Geeks For Geeks
princiraj1992
mohit kumar 29
gfgking
Arrays
Data Structures
Matrix
Strings
Data Structures
Arrays
Strings
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 606,
"s": 54,
"text": "Given a string S, the task is to encrypt the string and decrypt the string again to the original form. Encryption Technique: If L is the length of the string, then take two values, one the ceil of √L (say b), and the other floor of √L (say a), and make a two-dimensional matrix having rows = a, and columns = b. If rows*columns < L, then increase the value of a or b, whichever is minimum. Fill the matrix with the characters of the original string sequentially. After obtaining the matrix, read the matrix column-wise and print the obtained string. "
},
{
"code": null,
"e": 922,
"s": 606,
"text": "Decryption Technique: If L is the length of the encrypted string, then again find the two values a and b, where a is the ceil value of the √L and b is the floor value of the √L. Similarly create a 2D Matrix in which store the string column-wise and read the matrix row-wise to get the string in the original form. "
},
{
"code": null,
"e": 947,
"s": 924,
"text": "Encryption Approach: "
},
{
"code": null,
"e": 980,
"s": 947,
"text": "Find the length L of the string."
},
{
"code": null,
"e": 1056,
"s": 980,
"text": "Find the ceil and floor values of √Length and assign them to the variables."
},
{
"code": null,
"e": 1173,
"s": 1056,
"text": "Check if the product of the two variables >= Length, if not then increments the variable having a lesser value by 1."
},
{
"code": null,
"e": 1240,
"s": 1173,
"text": "Create a 2D matrix and fill the characters of the string row-wise."
},
{
"code": null,
"e": 1297,
"s": 1240,
"text": "Read the matrix column-wise to get the encrypted string."
},
{
"code": null,
"e": 1320,
"s": 1297,
"text": "Decryption Approach: "
},
{
"code": null,
"e": 1353,
"s": 1320,
"text": "Find the length L of the string."
},
{
"code": null,
"e": 1429,
"s": 1353,
"text": "Find the ceil and floor values of √Length and assign them to the variables."
},
{
"code": null,
"e": 1505,
"s": 1429,
"text": "Create a 2D matrix and fill the matrix by characters of string column-wise."
},
{
"code": null,
"e": 1559,
"s": 1505,
"text": "Read the matrix row-wise to get the decrypted string."
},
{
"code": null,
"e": 1611,
"s": 1559,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1615,
"s": 1611,
"text": "C++"
},
{
"code": null,
"e": 1620,
"s": 1615,
"text": "Java"
},
{
"code": null,
"e": 1628,
"s": 1620,
"text": "Python3"
},
{
"code": null,
"e": 1631,
"s": 1628,
"text": "C#"
},
{
"code": null,
"e": 1642,
"s": 1631,
"text": "Javascript"
},
{
"code": "// C++ implementation for Custom// Encryption and Decryption of String #include <bits/stdc++.h>using namespace std; // Function to encrypt the stringstring encryption(string s){ int l = s.length(); int b = ceil(sqrt(l)); int a = floor(sqrt(l)); string encrypted; if (b * a < l) { if (min(b, a) == b) { b = b + 1; } else { a = a + 1; } } // Matrix to generate the // Encrypted String char arr[a][b]; memset(arr, ' ', sizeof(arr)); int k = 0; // Fill the matrix row-wise for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { if (k < l){ arr[j][i] = s[k]; } k++; } } // Loop to generate // encrypted string for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { encrypted = encrypted + arr[i][j]; } } return encrypted;} // Function to decrypt the stringstring decryption(string s){ int l = s.length(); int b = ceil(sqrt(l)); int a = floor(sqrt(l)); string decrypted; // Matrix to generate the // Encrypted String char arr[a][b]; memset(arr, ' ', sizeof(arr)); int k = 0; // Fill the matrix column-wise for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { if (k < l){ arr[j][i] = s[k]; } k++; } } // Loop to generate // decrypted string for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { decrypted = decrypted + arr[i][j]; } } return decrypted;} // Driver Codeint main(){ string s = \"Geeks For Geeks\"; string encrypted; string decrypted; // Encryption of String encrypted = encryption(s); cout << encrypted << endl; // Decryption of String decrypted = decryption(encrypted); cout << decrypted; return 0;}",
"e": 3604,
"s": 1642,
"text": null
},
{
"code": "// Java implementation for Custom// Encryption and Decryption of Stringclass GFG{ // Function to encrypt the Stringstatic String encryption(char[] s){ int l = s.length; int b = (int) Math.ceil(Math.sqrt(l)); int a = (int) Math.floor(Math.sqrt(l)); String encrypted = \"\"; if (b * a < l) { if (Math.min(b, a) == b) { b = b + 1; } else { a = a + 1; } } // Matrix to generate the // Encrypted String char [][]arr = new char[a][b]; int k = 0; // Fill the matrix row-wise for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { if (k < l) { arr[j][i] = s[k]; } k++; } } // Loop to generate // encrypted String for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { encrypted = encrypted + arr[i][j]; } } return encrypted;} // Function to decrypt the Stringstatic String decryption(char []s){ int l = s.length; int b = (int) Math.ceil(Math.sqrt(l)); int a = (int) Math.floor(Math.sqrt(l)); String decrypted=\"\"; // Matrix to generate the // Encrypted String char [][]arr = new char[a][b]; int k = 0; // Fill the matrix column-wise for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { if (k < l) { arr[j][i] = s[k]; } k++; } } // Loop to generate // decrypted String for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { decrypted = decrypted + arr[i][j]; } } return decrypted;} // Driver Codepublic static void main(String[] args){ String s = \"Geeks For Geeks\"; String encrypted; String decrypted; // Encryption of String encrypted = encryption(s.toCharArray()); System.out.print(encrypted +\"\\n\"); // Decryption of String decrypted = decryption(encrypted.toCharArray()); System.out.print(decrypted);}} // This code is contributed by PrinciRaj1992",
"e": 5767,
"s": 3604,
"text": null
},
{
"code": "# Python3 implementation for Custom# Encryption and Decryption of Stringfrom math import ceil,floor,sqrt # Function to encrypt thedef encryption(s): l = len(s) b = ceil(sqrt(l)) a = floor(sqrt(l)) encrypted=\"\" if (b * a < l): if (min(b, a) == b): b = b + 1 else: a = a + 1 # Matrix to generate the # Encrypted String arr = [[' ' for i in range(a)] for j in range(b)] k = 0 # Fill the matrix row-wise for j in range(a): for i in range(b): if (k < l): arr[j][i] = s[k] k += 1 # Loop to generate # encrypted for j in range(b): for i in range(a): encrypted = encrypted + arr[i][j] return encrypted # Function to decrypt thedef decryption(s): l = len(s) b = ceil(sqrt(l)) a = floor(sqrt(l)) decrypted=\"\" # Matrix to generate the # Encrypted String arr = [[' ' for i in range(a)] for j in range(b)] k = 0 # Fill the matrix column-wise for j in range(b): for i in range(a): if (k < l): arr[j][i] = s[k] k += 1 # Loop to generate # decrypted for j in range(a): for i in range(b): decrypted = decrypted + arr[i][j] return decrypted # Driver Code s = \"Geeks For Geeks\"encrypted=\"\"decrypted=\"\" # Encryption of Stringencrypted = encryption(s)print(encrypted) # Decryption of Stringdecrypted = decryption(encrypted)print(decrypted) # This code is contributed by mohit kumar 29",
"e": 7285,
"s": 5767,
"text": null
},
{
"code": "// C# implementation for Custom// Encryption and Decryption of Stringusing System; class GFG{ // Function to encrypt the Stringstatic String encryption(char[] s){ int l = s.Length; int b = (int) Math.Ceiling(Math.Sqrt(l)); int a = (int) Math.Floor(Math.Sqrt(l)); String encrypted = \"\"; if (b * a < l) { if (Math.Min(b, a) == b) { b = b + 1; } else { a = a + 1; } } // Matrix to generate the // Encrypted String char [,]arr = new char[a, b]; int k = 0; // Fill the matrix row-wise for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { if (k < l) { arr[j, i] = s[k]; } k++; } } // Loop to generate // encrypted String for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { encrypted = encrypted + arr[i, j]; } } return encrypted;} // Function to decrypt the Stringstatic String decryption(char []s){ int l = s.Length; int b = (int) Math.Ceiling(Math.Sqrt(l)); int a = (int) Math.Floor(Math.Sqrt(l)); String decrypted=\"\"; // Matrix to generate the // Encrypted String char [,]arr = new char[a, b]; int k = 0; // Fill the matrix column-wise for (int j = 0; j < b; j++) { for (int i = 0; i < a; i++) { if (k < l) { arr[j, i] = s[k]; } k++; } } // Loop to generate // decrypted String for (int j = 0; j < a; j++) { for (int i = 0; i < b; i++) { decrypted = decrypted + arr[i, j]; } } return decrypted;} // Driver Codepublic static void Main(String[] args){ String s = \"Geeks For Geeks\"; String encrypted; String decrypted; // Encryption of String encrypted = encryption(s.ToCharArray()); Console.Write(encrypted +\"\\n\"); // Decryption of String decrypted = decryption(encrypted.ToCharArray()); Console.Write(decrypted);}} // This code is contributed by PrinciRaj1992",
"e": 9469,
"s": 7285,
"text": null
},
{
"code": "<script> // JavaScript implementation for Custom// Encryption and Decryption of let // Function to encrypt the letfunction encryption(s) { let l = s.length; let b = Math.ceil(Math.sqrt(l)); let a = Math.floor(Math.sqrt(l)); let encrypted = ''; if (b * a < l) { if (Math.min(b, a) == b) { b = b + 1; } else { a = a + 1; } } // Matrix to generate the // Encrypted let let arr = new Array(); for (let i = 0; i < a; i++) { let temp = []; for (let j = 0; j < b; j++) { temp.push([]) } arr.push(temp) } for (let i = 0; i < a; i++) { for (let j = 0; j < b; j++) { arr[i][j] = \" \" } } let k = 0; // Fill the matrix row-wise for (let j = 0; j < a; j++) { for (let i = 0; i < b; i++) { if (k < l) { arr[j][i] = s[k]; } k++; } } // Loop to generate // encrypted let for (let j = 0; j < b; j++) { for (let i = 0; i < a; i++) { encrypted = encrypted + arr[i][j]; } } return encrypted;} // Function to decrypt the letfunction decryption(s) { let l = s.length; let b = Math.ceil(Math.sqrt(l)); let a = Math.floor(Math.sqrt(l)); let decrypted = ''; // Matrix to generate the // Encrypted let let arr = new Array(); for (let i = 0; i < a; i++) { let temp = []; for (let j = 0; j < b; j++) { temp.push([]) } arr.push(temp) } for (let i = 0; i < a; i++) { for (let j = 0; j < b; j++) { arr[i][j] = \" \" } } let k = 0; // Fill the matrix column-wise for (let j = 0; j < b; j++) { for (let i = 0; i < a; i++) { if (k < l) { arr[j][i] = s[k]; } k++; } } // Loop to generate // decrypted let for (let j = 0; j < a; j++) { for (let i = 0; i < b; i++) { decrypted = decrypted + arr[i][j]; } } return decrypted;} // Driver Code let s = \"Geeks For Geeks\";let encrypted;let decrypted; // Encryption of letencrypted = encryption(s);document.write(encrypted + \"<br>\"); // Decryption of letdecrypted = decryption(encrypted);document.write(decrypted); // This code is contributed by gfgking </script>",
"e": 11841,
"s": 9469,
"text": null
},
{
"code": null,
"e": 11874,
"s": 11841,
"text": "Gsree keFGskoe \nGeeks For Geeks"
},
{
"code": null,
"e": 11890,
"s": 11876,
"text": "princiraj1992"
},
{
"code": null,
"e": 11905,
"s": 11890,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 11913,
"s": 11905,
"text": "gfgking"
},
{
"code": null,
"e": 11920,
"s": 11913,
"text": "Arrays"
},
{
"code": null,
"e": 11936,
"s": 11920,
"text": "Data Structures"
},
{
"code": null,
"e": 11943,
"s": 11936,
"text": "Matrix"
},
{
"code": null,
"e": 11951,
"s": 11943,
"text": "Strings"
},
{
"code": null,
"e": 11967,
"s": 11951,
"text": "Data Structures"
},
{
"code": null,
"e": 11974,
"s": 11967,
"text": "Arrays"
},
{
"code": null,
"e": 11982,
"s": 11974,
"text": "Strings"
},
{
"code": null,
"e": 11989,
"s": 11982,
"text": "Matrix"
}
]
|
Map putAll() Method in Java with Examples | 02 Jan, 2019
This method is used to copy all of the mappings from the specified map to this map.
Syntax:
void putAll(Map m)
Parameters: This method has the only argument map m, which contains key-value mappings to be copied to given map.
Returns: This method returns previous value associated with the key if present, else return -1.
Below programs show the implementation of int putAll() method.
Program 1:
// Java code to show the implementation of// putAll method in Map interface import java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a Map of type HashMap Map<Integer, String> map = new HashMap<>(); map.put(1, "One"); map.put(3, "Three"); map.put(5, "Five"); map.put(7, "Seven"); map.put(9, "Nine"); System.out.println(map); Map<Integer, String> mp = new HashMap<>(); mp.put(10, "Ten"); mp.put(30, "Thirty"); mp.put(50, "Fifty"); map.putAll(mp); System.out.println(map); }}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
{1=One, 50=Fifty, 3=Three, 5=Five, 7=Seven, 9=Nine, 10=Ten, 30=Thirty}
Program 2: Below is the code to show implementation of put().
// Java code to show the implementation of// putAll method in Map interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a Map of type HashMap Map<String, String> map = new HashMap<>(); map.put("1", "One"); map.put("3", "Three"); map.put("5", "Five"); map.put("7", "Seven"); map.put("9", "Nine"); System.out.println(map); Map<String, String> mp = new HashMap<>(); mp.put("10", "Ten"); mp.put("30", "Thirty"); mp.put("50", "Fifty"); map.putAll(mp); System.out.println(map); }}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine, 50=Fifty, 30=Thirty, 10=Ten}
Reference:Oracle Docs
Java - util package
Java-Collections
Java-Functions
java-map
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jan, 2019"
},
{
"code": null,
"e": 112,
"s": 28,
"text": "This method is used to copy all of the mappings from the specified map to this map."
},
{
"code": null,
"e": 120,
"s": 112,
"text": "Syntax:"
},
{
"code": null,
"e": 139,
"s": 120,
"text": "void putAll(Map m)"
},
{
"code": null,
"e": 253,
"s": 139,
"text": "Parameters: This method has the only argument map m, which contains key-value mappings to be copied to given map."
},
{
"code": null,
"e": 349,
"s": 253,
"text": "Returns: This method returns previous value associated with the key if present, else return -1."
},
{
"code": null,
"e": 412,
"s": 349,
"text": "Below programs show the implementation of int putAll() method."
},
{
"code": null,
"e": 423,
"s": 412,
"text": "Program 1:"
},
{
"code": "// Java code to show the implementation of// putAll method in Map interface import java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a Map of type HashMap Map<Integer, String> map = new HashMap<>(); map.put(1, \"One\"); map.put(3, \"Three\"); map.put(5, \"Five\"); map.put(7, \"Seven\"); map.put(9, \"Nine\"); System.out.println(map); Map<Integer, String> mp = new HashMap<>(); mp.put(10, \"Ten\"); mp.put(30, \"Thirty\"); mp.put(50, \"Fifty\"); map.putAll(mp); System.out.println(map); }}",
"e": 1071,
"s": 423,
"text": null
},
{
"code": null,
"e": 1185,
"s": 1071,
"text": "{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}\n{1=One, 50=Fifty, 3=Three, 5=Five, 7=Seven, 9=Nine, 10=Ten, 30=Thirty}\n"
},
{
"code": null,
"e": 1247,
"s": 1185,
"text": "Program 2: Below is the code to show implementation of put()."
},
{
"code": "// Java code to show the implementation of// putAll method in Map interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a Map of type HashMap Map<String, String> map = new HashMap<>(); map.put(\"1\", \"One\"); map.put(\"3\", \"Three\"); map.put(\"5\", \"Five\"); map.put(\"7\", \"Seven\"); map.put(\"9\", \"Nine\"); System.out.println(map); Map<String, String> mp = new HashMap<>(); mp.put(\"10\", \"Ten\"); mp.put(\"30\", \"Thirty\"); mp.put(\"50\", \"Fifty\"); map.putAll(mp); System.out.println(map); }}",
"e": 1907,
"s": 1247,
"text": null
},
{
"code": null,
"e": 2021,
"s": 1907,
"text": "{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}\n{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine, 50=Fifty, 30=Thirty, 10=Ten}\n"
},
{
"code": null,
"e": 2043,
"s": 2021,
"text": "Reference:Oracle Docs"
},
{
"code": null,
"e": 2063,
"s": 2043,
"text": "Java - util package"
},
{
"code": null,
"e": 2080,
"s": 2063,
"text": "Java-Collections"
},
{
"code": null,
"e": 2095,
"s": 2080,
"text": "Java-Functions"
},
{
"code": null,
"e": 2104,
"s": 2095,
"text": "java-map"
},
{
"code": null,
"e": 2109,
"s": 2104,
"text": "Java"
},
{
"code": null,
"e": 2114,
"s": 2109,
"text": "Java"
},
{
"code": null,
"e": 2131,
"s": 2114,
"text": "Java-Collections"
}
]
|
How to Find the Slope of a Line on an Excel Graph? | 18 Jul, 2021
In this article, we will look into how to calculate the slope of a line in an Excel graph.
Slope of a line basically determines two parameters :
The direction of a line. The steepness of a line (rise or fall).
The direction of a line.
The steepness of a line (rise or fall).
It is generally denoted by the letter “m”. The equation of a line is given by the expression :
Where,
m: Slope
c: Intercept
The mathematical formula for the slope of a line is given by the ratio of rise and run and in geometry, it is denoted using tan theta.
In this article we are going to discuss various methods on how to find the slope of a line in Excel using a few examples.
Example 1 : Consider the dataset having x and y coordinates of a particle moving in 2-D plane.
Line Graph
There are three methods :
1. By using the Excel in-built function SLOPE. The syntax is :
=SLOPE(known_ys,knownx_s)
known_ys : An array of numeric data points which are dependent. These are dependent on value of horizontal axis.
known_xs : An array of numeric data points which are independent.
2. By using the slope formula as discussed.
The steps are :
From the data set take any pair of points.
The points are (x1, y1) and (x2, y2).
Use the formula and “-“,”/” operators to find the slope, m.
3. By plotting a trendline on the line graph and find its equation. From the equation of the trendline we can easily get the slope.
Here, Y-axis array is stored in B column. The array ranges from B2 to B11.
The X-axis array is stored in A column of the Excel sheet. The array ranges from A2 to A11.
Consider the points (1,2) and (2,4). Here, y1=2 and stored in the location B2 and y2=4 stored in location B3 and x1=1 stored in the location A2 and x2=2 stored in the location A3 of the worksheet.
The steps are :
Plot the line graph by selecting the dataset and then go to the Insert Tab and then click on Insert Line or Area Chart.
The line chart is plotted.
Now select the chart and then click on the “+” button in the top right corner of the Chart.
The Chart Elements dialog box appears. In this check the Trendline option. This will add the trendline to the existing line graph.
Now select the Trendline in the chart and right-click on it and then click on Format Trendline.
The Format Trendline dialog box opens. By default, the trendline will be linear.
Now, check the box “Display Equation on the chart”.
This will add the equation of the line on the chart.
The equation of the line is
y=2x
By comparing with the general equation y = mx + c, we get
m=2, c=0
The slope is 2 for the given line.
Example 2: Consider the dataset shown below :
Similarly, by using the trendline and its equation you can easily find the slope of the line is -0.5.
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Trendlines in Excel
How to Extract Text Only from Alphanumeric String in Excel?
Average Cells Based On Multiple Criteria in Excel
How to Show Percentages in Stacked Column Chart in Excel?
How to Normalize Data in Excel?
How To Calculate Average (mean) in Excel?
How to Create a Waterfall Chart in Excel?
Charts in Excel
Import Export of Data in Excel
IFERROR Function in Excel With Examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "In this article, we will look into how to calculate the slope of a line in an Excel graph."
},
{
"code": null,
"e": 173,
"s": 119,
"text": "Slope of a line basically determines two parameters :"
},
{
"code": null,
"e": 238,
"s": 173,
"text": "The direction of a line. The steepness of a line (rise or fall)."
},
{
"code": null,
"e": 263,
"s": 238,
"text": "The direction of a line."
},
{
"code": null,
"e": 304,
"s": 263,
"text": " The steepness of a line (rise or fall)."
},
{
"code": null,
"e": 399,
"s": 304,
"text": "It is generally denoted by the letter “m”. The equation of a line is given by the expression :"
},
{
"code": null,
"e": 406,
"s": 399,
"text": "Where,"
},
{
"code": null,
"e": 415,
"s": 406,
"text": "m: Slope"
},
{
"code": null,
"e": 428,
"s": 415,
"text": "c: Intercept"
},
{
"code": null,
"e": 563,
"s": 428,
"text": "The mathematical formula for the slope of a line is given by the ratio of rise and run and in geometry, it is denoted using tan theta."
},
{
"code": null,
"e": 685,
"s": 563,
"text": "In this article we are going to discuss various methods on how to find the slope of a line in Excel using a few examples."
},
{
"code": null,
"e": 780,
"s": 685,
"text": "Example 1 : Consider the dataset having x and y coordinates of a particle moving in 2-D plane."
},
{
"code": null,
"e": 791,
"s": 780,
"text": "Line Graph"
},
{
"code": null,
"e": 817,
"s": 791,
"text": "There are three methods :"
},
{
"code": null,
"e": 880,
"s": 817,
"text": "1. By using the Excel in-built function SLOPE. The syntax is :"
},
{
"code": null,
"e": 1086,
"s": 880,
"text": "=SLOPE(known_ys,knownx_s)\n\nknown_ys : An array of numeric data points which are dependent. These are dependent on value of horizontal axis.\nknown_xs : An array of numeric data points which are independent."
},
{
"code": null,
"e": 1131,
"s": 1086,
"text": "2. By using the slope formula as discussed. "
},
{
"code": null,
"e": 1147,
"s": 1131,
"text": "The steps are :"
},
{
"code": null,
"e": 1190,
"s": 1147,
"text": "From the data set take any pair of points."
},
{
"code": null,
"e": 1228,
"s": 1190,
"text": "The points are (x1, y1) and (x2, y2)."
},
{
"code": null,
"e": 1288,
"s": 1228,
"text": "Use the formula and “-“,”/” operators to find the slope, m."
},
{
"code": null,
"e": 1420,
"s": 1288,
"text": "3. By plotting a trendline on the line graph and find its equation. From the equation of the trendline we can easily get the slope."
},
{
"code": null,
"e": 1495,
"s": 1420,
"text": "Here, Y-axis array is stored in B column. The array ranges from B2 to B11."
},
{
"code": null,
"e": 1587,
"s": 1495,
"text": "The X-axis array is stored in A column of the Excel sheet. The array ranges from A2 to A11."
},
{
"code": null,
"e": 1784,
"s": 1587,
"text": "Consider the points (1,2) and (2,4). Here, y1=2 and stored in the location B2 and y2=4 stored in location B3 and x1=1 stored in the location A2 and x2=2 stored in the location A3 of the worksheet."
},
{
"code": null,
"e": 1800,
"s": 1784,
"text": "The steps are :"
},
{
"code": null,
"e": 1920,
"s": 1800,
"text": "Plot the line graph by selecting the dataset and then go to the Insert Tab and then click on Insert Line or Area Chart."
},
{
"code": null,
"e": 1947,
"s": 1920,
"text": "The line chart is plotted."
},
{
"code": null,
"e": 2039,
"s": 1947,
"text": "Now select the chart and then click on the “+” button in the top right corner of the Chart."
},
{
"code": null,
"e": 2170,
"s": 2039,
"text": "The Chart Elements dialog box appears. In this check the Trendline option. This will add the trendline to the existing line graph."
},
{
"code": null,
"e": 2266,
"s": 2170,
"text": "Now select the Trendline in the chart and right-click on it and then click on Format Trendline."
},
{
"code": null,
"e": 2347,
"s": 2266,
"text": "The Format Trendline dialog box opens. By default, the trendline will be linear."
},
{
"code": null,
"e": 2399,
"s": 2347,
"text": "Now, check the box “Display Equation on the chart”."
},
{
"code": null,
"e": 2452,
"s": 2399,
"text": "This will add the equation of the line on the chart."
},
{
"code": null,
"e": 2481,
"s": 2452,
"text": "The equation of the line is "
},
{
"code": null,
"e": 2486,
"s": 2481,
"text": "y=2x"
},
{
"code": null,
"e": 2544,
"s": 2486,
"text": "By comparing with the general equation y = mx + c, we get"
},
{
"code": null,
"e": 2553,
"s": 2544,
"text": "m=2, c=0"
},
{
"code": null,
"e": 2588,
"s": 2553,
"text": "The slope is 2 for the given line."
},
{
"code": null,
"e": 2634,
"s": 2588,
"text": "Example 2: Consider the dataset shown below :"
},
{
"code": null,
"e": 2736,
"s": 2634,
"text": "Similarly, by using the trendline and its equation you can easily find the slope of the line is -0.5."
},
{
"code": null,
"e": 2743,
"s": 2736,
"text": "Picked"
},
{
"code": null,
"e": 2749,
"s": 2743,
"text": "Excel"
},
{
"code": null,
"e": 2847,
"s": 2749,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2876,
"s": 2847,
"text": "Types of Trendlines in Excel"
},
{
"code": null,
"e": 2936,
"s": 2876,
"text": "How to Extract Text Only from Alphanumeric String in Excel?"
},
{
"code": null,
"e": 2986,
"s": 2936,
"text": "Average Cells Based On Multiple Criteria in Excel"
},
{
"code": null,
"e": 3044,
"s": 2986,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
},
{
"code": null,
"e": 3076,
"s": 3044,
"text": "How to Normalize Data in Excel?"
},
{
"code": null,
"e": 3118,
"s": 3076,
"text": "How To Calculate Average (mean) in Excel?"
},
{
"code": null,
"e": 3160,
"s": 3118,
"text": "How to Create a Waterfall Chart in Excel?"
},
{
"code": null,
"e": 3176,
"s": 3160,
"text": "Charts in Excel"
},
{
"code": null,
"e": 3207,
"s": 3176,
"text": "Import Export of Data in Excel"
}
]
|
IsoChronology localDateTime() method in Java with Example | 27 Mar, 2020
The localDateTime() method of java.time.chrono.IsoChronology class is used to retrieve the local date and time according to Iso calendar system from any other object of temporal accessor.
Syntax:
public LocalDateTime localDateTime(
TemporalAccessor temporal)
Parameter: This method takes the object of any temporal accessor as a parameter.
Return Value: This method returns the local date and time according to Iso calendar system from any other object of the temporal accessor.
Below are the examples to illustrate the localDateTime() method:
Example 1:
// Java program to demonstrate// localDateTime() method import java.util.*;import java.io.*;import java.time.*;import java.time.chrono.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing // LocalDate Object LocalDate hidate = LocalDate.now(); // getting IsoChronology // used in LocalDate IsoChronology crono = hidate.getChronology(); // creating and initializing // TemporalAccessor object ZonedDateTime zonedate = ZonedDateTime.parse( "2018-10-25T23:12:31." + "123+02:00[Europe/Paris]"); // getting LocalDate for the // given TemporalAccessor object // by using localDateTime() method LocalDateTime date = crono.localDateTime(zonedate); // display the result System.out.println("LocalDateTime is: " + date); } catch (DateTimeException e) { System.out.println("passed parameter can" + " not form a date"); System.out.println("Exception thrown: " + e); } }}
LocalDateTime is: 2018-10-25T23:12:31.123
Example 2:
// Java program to demonstrate// localDateTime() method import java.util.*;import java.io.*;import java.time.*;import java.time.chrono.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing // LocalDate Object LocalDate hidate = LocalDate.now(); // getting IsoChronology // used in LocalDate IsoChronology crono = hidate.getChronology(); // creating and initializing // TemporalAccessor object LocalDateTime localdate = LocalDateTime .parse("2018-12-30T19:34:50.63"); // getting LocalDate for the // given TemporalAccessor object // by using localDateTime() method LocalDateTime date = crono.localDateTime(localdate); // display the result System.out.println("LocalDateTime is: " + date); } catch (DateTimeException e) { System.out.println("passed parameter can" + " not form a date"); System.out.println("Exception thrown: " + e); } }}
LocalDateTime is: 2018-12-30T19:34:50.630
Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/IsoChronology.html#localDateTime-java.time.temporal.TemporalAccessor-
Java-Functions
Java-Time-Chrono package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Mar, 2020"
},
{
"code": null,
"e": 216,
"s": 28,
"text": "The localDateTime() method of java.time.chrono.IsoChronology class is used to retrieve the local date and time according to Iso calendar system from any other object of temporal accessor."
},
{
"code": null,
"e": 224,
"s": 216,
"text": "Syntax:"
},
{
"code": null,
"e": 297,
"s": 224,
"text": "public LocalDateTime localDateTime(\n TemporalAccessor temporal)\n"
},
{
"code": null,
"e": 378,
"s": 297,
"text": "Parameter: This method takes the object of any temporal accessor as a parameter."
},
{
"code": null,
"e": 517,
"s": 378,
"text": "Return Value: This method returns the local date and time according to Iso calendar system from any other object of the temporal accessor."
},
{
"code": null,
"e": 582,
"s": 517,
"text": "Below are the examples to illustrate the localDateTime() method:"
},
{
"code": null,
"e": 593,
"s": 582,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// localDateTime() method import java.util.*;import java.io.*;import java.time.*;import java.time.chrono.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing // LocalDate Object LocalDate hidate = LocalDate.now(); // getting IsoChronology // used in LocalDate IsoChronology crono = hidate.getChronology(); // creating and initializing // TemporalAccessor object ZonedDateTime zonedate = ZonedDateTime.parse( \"2018-10-25T23:12:31.\" + \"123+02:00[Europe/Paris]\"); // getting LocalDate for the // given TemporalAccessor object // by using localDateTime() method LocalDateTime date = crono.localDateTime(zonedate); // display the result System.out.println(\"LocalDateTime is: \" + date); } catch (DateTimeException e) { System.out.println(\"passed parameter can\" + \" not form a date\"); System.out.println(\"Exception thrown: \" + e); } }}",
"e": 1889,
"s": 593,
"text": null
},
{
"code": null,
"e": 1932,
"s": 1889,
"text": "LocalDateTime is: 2018-10-25T23:12:31.123\n"
},
{
"code": null,
"e": 1943,
"s": 1932,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// localDateTime() method import java.util.*;import java.io.*;import java.time.*;import java.time.chrono.*; public class GFG { public static void main(String[] argv) { try { // creating and initializing // LocalDate Object LocalDate hidate = LocalDate.now(); // getting IsoChronology // used in LocalDate IsoChronology crono = hidate.getChronology(); // creating and initializing // TemporalAccessor object LocalDateTime localdate = LocalDateTime .parse(\"2018-12-30T19:34:50.63\"); // getting LocalDate for the // given TemporalAccessor object // by using localDateTime() method LocalDateTime date = crono.localDateTime(localdate); // display the result System.out.println(\"LocalDateTime is: \" + date); } catch (DateTimeException e) { System.out.println(\"passed parameter can\" + \" not form a date\"); System.out.println(\"Exception thrown: \" + e); } }}",
"e": 3198,
"s": 1943,
"text": null
},
{
"code": null,
"e": 3241,
"s": 3198,
"text": "LocalDateTime is: 2018-12-30T19:34:50.630\n"
},
{
"code": null,
"e": 3381,
"s": 3241,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/IsoChronology.html#localDateTime-java.time.temporal.TemporalAccessor-"
},
{
"code": null,
"e": 3396,
"s": 3381,
"text": "Java-Functions"
},
{
"code": null,
"e": 3421,
"s": 3396,
"text": "Java-Time-Chrono package"
},
{
"code": null,
"e": 3426,
"s": 3421,
"text": "Java"
},
{
"code": null,
"e": 3431,
"s": 3426,
"text": "Java"
}
]
|
Python | Union Operation in two Strings | 27 Feb, 2020
One of the string operation can be computing the union of two strings. This can be useful application that can be dealt with. This article deals with computing the same through different ways.
Method 1 : Naive MethodThe task of performing string union can be computed by naive method by creating an empty string and checking for new occurrence of character common to both string and not common strings and appending it and hence computing the new union string. This can be achieved by loops and if/else statements.
# Python 3 code to demonstrate # Union Operation in two Strings# using naive method # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks' # Printing initial stringsprint ("The original string 1 is : " + test_str1)print ("The original string 2 is : " + test_str2) # using naive method to# Union Operation in two Stringsres = ""temp = test_str1for i in test_str2: if i not in temp: test_str1 += i # printing resultprint ("The string union is : " + test_str1)
The original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string union is : GeeksforGeeksCda
Method 2 : Using set() + union()Set in python usually can perform the task of performing set operations such as set union. This utility of sets can be used to perform this task as well. Firstly, both the strings are converted into sets using set() and then union is performed using union(). Returns the sorted set.
# Python 3 code to demonstrate # Union Operation in two Strings# using set() + union() # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks' # Printing initial stringsprint ("The original string 1 is : " + test_str1)print ("The original string 2 is : " + test_str2) # using set() + union() to# Union Operation in two Stringsres = set(test_str1).union(test_str2) # printing resultprint ("The string union is : " + str(res))
The original string 1 is : GeeksforGeeks
The original string 2 is : Codefreaks
The string union is : {'s', 'G', 'r', 'e', 'o', 'f', 'k', 'C', 'd', 'a'}
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 221,
"s": 28,
"text": "One of the string operation can be computing the union of two strings. This can be useful application that can be dealt with. This article deals with computing the same through different ways."
},
{
"code": null,
"e": 543,
"s": 221,
"text": "Method 1 : Naive MethodThe task of performing string union can be computed by naive method by creating an empty string and checking for new occurrence of character common to both string and not common strings and appending it and hence computing the new union string. This can be achieved by loops and if/else statements."
},
{
"code": "# Python 3 code to demonstrate # Union Operation in two Strings# using naive method # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks' # Printing initial stringsprint (\"The original string 1 is : \" + test_str1)print (\"The original string 2 is : \" + test_str2) # using naive method to# Union Operation in two Stringsres = \"\"temp = test_str1for i in test_str2: if i not in temp: test_str1 += i # printing resultprint (\"The string union is : \" + test_str1)",
"e": 1043,
"s": 543,
"text": null
},
{
"code": null,
"e": 1162,
"s": 1043,
"text": "The original string 1 is : GeeksforGeeks\nThe original string 2 is : Codefreaks\nThe string union is : GeeksforGeeksCda\n"
},
{
"code": null,
"e": 1479,
"s": 1164,
"text": "Method 2 : Using set() + union()Set in python usually can perform the task of performing set operations such as set union. This utility of sets can be used to perform this task as well. Firstly, both the strings are converted into sets using set() and then union is performed using union(). Returns the sorted set."
},
{
"code": "# Python 3 code to demonstrate # Union Operation in two Strings# using set() + union() # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks' # Printing initial stringsprint (\"The original string 1 is : \" + test_str1)print (\"The original string 2 is : \" + test_str2) # using set() + union() to# Union Operation in two Stringsres = set(test_str1).union(test_str2) # printing resultprint (\"The string union is : \" + str(res))",
"e": 1934,
"s": 1479,
"text": null
},
{
"code": null,
"e": 2087,
"s": 1934,
"text": "The original string 1 is : GeeksforGeeks\nThe original string 2 is : Codefreaks\nThe string union is : {'s', 'G', 'r', 'e', 'o', 'f', 'k', 'C', 'd', 'a'}\n"
},
{
"code": null,
"e": 2108,
"s": 2087,
"text": "Python list-programs"
},
{
"code": null,
"e": 2115,
"s": 2108,
"text": "Python"
},
{
"code": null,
"e": 2131,
"s": 2115,
"text": "Python Programs"
},
{
"code": null,
"e": 2229,
"s": 2131,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2261,
"s": 2229,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2288,
"s": 2261,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2309,
"s": 2288,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2340,
"s": 2309,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2396,
"s": 2340,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2418,
"s": 2396,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2457,
"s": 2418,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2495,
"s": 2457,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2544,
"s": 2495,
"text": "Python | Convert string dictionary to dictionary"
}
]
|
Floor in a Sorted Array | Practice | GeeksforGeeks | Given a sorted array arr[] of size N without duplicates, and given a value x. Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x. Find the index of K(0-based indexing).
Example 1:
Input:
N = 7, x = 0
arr[] = {1,2,8,10,11,12,19}
Output: -1
Explanation: No element less
than 0 is found. So output
is "-1".
Example 2:
Input:
N = 7, x = 5
arr[] = {1,2,8,10,11,12,19}
Output: 1
Explanation: Largest Number less than 5 is
2 (i.e K = 2), whose index is 1(0-based
indexing).
Your Task:
The task is to complete the function findFloor() which returns an integer denoting the index value of K or return -1 if there isn't any such number.
Expected Time Complexity: O(log N).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 107
1 ≤ arr[i] ≤ 1018
0 ≤ X ≤ arr[n-1]
0
anujtube2995 hours ago
simple python solution
class Solution: def findFloor(self,A,N,X): p=-1 for i in range(N): if A[i]<=X: p=A[i] if A[i]>X: break if p!=-1: return(A.index(p)) else: return(p)
0
divakarkumar2000
This comment was deleted.
0
code_24x71 week ago
int findFloor(vector<long long> v, long long n, long long x){
long long result = -1, mid, low = 0, high = n - 1;
while(low <= high) {
mid = low + (high - low) / 2;
if(v[mid] == x) return mid;
else if(x > v[mid]) {
low = mid + 1;
result = mid;
}
else high = mid - 1;
}
return result;
}
0
rohitjug19csPremium1 week ago
JAVA Solution :
static int findFloor(long arr[], int n, long x)
{
int ans=-1;
int low = 0;
int high = n-1;
while(low <= high){
int mid = (low + high)/2;
if(arr[mid] == x)return mid;
if(arr[mid] < x){
ans = mid;
low = mid + 1;
}
else high = mid - 1;
}
return ans;
}
0
aditya_shekhar_1 week ago
int findFloor(vector<long long> arr, long long n, long long x){
if (arr[0]>x) return -1;
if (arr[n-1]<x) return n;
int left=0, right=n-1, mid;
while(left<=right){
if (arr[mid]==x) return mid;
else if (mid>0 && arr[mid]>x && arr[mid-1]<=x) return mid-1;//x is between mid and mid-1
else if (arr[mid]>x) right=mid-1;
else left=mid+1;
}
return -1;
}
This code gives TLE error in the first test case, but I've tried doing this in O(logn) time complexity. Can anyone help with this?
Thanks in advance!
0
expresscode2 weeks ago
long long findFloor(vector<long long> v, long long n, long long x){
auto i= lower_bound ( v.begin(), v.end(), x);
if(*i==x)
return i-v.begin();
if(i==v.begin())
return -1;
return (i-v.begin()-1 );
}
0
expresscode
This comment was deleted.
0
ajitvishwakarma3602 weeks ago
int findFloor(vector<long long> v, long long n, long long x){
int K = floor (x);
long long s = 0;
long long e = n-1;
long long mx =-1;
if (x < v[0])
return -1;
while( s<=e){
long long mid = s+(e-s)/2;
if (v[mid] <=K)
{
mx =max( mid, mx);
s =mid +1;
}
else
e =mid -1;
}
// Your code here
return mx;
}
0
himanshuharsh19992 weeks ago
long long low = 0, high = n-1, res = -1;
if (x < v[low]) return -1;
if (x >= v[high]) return high;
while(low<=high){
long long mid = (low+high)/2;
if (v[mid] == x)
return mid;
else if (v[mid] > x)
high = mid-1;
else{
res = max(res,mid);
low = mid+1;
}
}
return res;
+1
vteradali52 weeks ago
class Solution{ static int findFloor(long arr[], int n, long x) { for(int i=n-1;i>0;i--){ if(arr[i]<x){ return i; } else if(arr[i]<=x){ return i; } } return -1; } }
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": 454,
"s": 238,
"text": "Given a sorted array arr[] of size N without duplicates, and given a value x. Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x. Find the index of K(0-based indexing)."
},
{
"code": null,
"e": 465,
"s": 454,
"text": "Example 1:"
},
{
"code": null,
"e": 592,
"s": 465,
"text": "Input:\nN = 7, x = 0 \narr[] = {1,2,8,10,11,12,19}\nOutput: -1\nExplanation: No element less \nthan 0 is found. So output \nis \"-1\"."
},
{
"code": null,
"e": 603,
"s": 592,
"text": "Example 2:"
},
{
"code": null,
"e": 758,
"s": 603,
"text": "Input:\nN = 7, x = 5 \narr[] = {1,2,8,10,11,12,19}\nOutput: 1\nExplanation: Largest Number less than 5 is\n2 (i.e K = 2), whose index is 1(0-based \nindexing).\n"
},
{
"code": null,
"e": 918,
"s": 758,
"text": "Your Task:\nThe task is to complete the function findFloor() which returns an integer denoting the index value of K or return -1 if there isn't any such number."
},
{
"code": null,
"e": 986,
"s": 918,
"text": "Expected Time Complexity: O(log N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1046,
"s": 986,
"text": "Constraints:\n1 ≤ N ≤ 107\n1 ≤ arr[i] ≤ 1018\n0 ≤ X ≤ arr[n-1]"
},
{
"code": null,
"e": 1048,
"s": 1046,
"text": "0"
},
{
"code": null,
"e": 1071,
"s": 1048,
"text": "anujtube2995 hours ago"
},
{
"code": null,
"e": 1094,
"s": 1071,
"text": "simple python solution"
},
{
"code": null,
"e": 1338,
"s": 1096,
"text": "class Solution: def findFloor(self,A,N,X): p=-1 for i in range(N): if A[i]<=X: p=A[i] if A[i]>X: break if p!=-1: return(A.index(p)) else: return(p)"
},
{
"code": null,
"e": 1340,
"s": 1338,
"text": "0"
},
{
"code": null,
"e": 1357,
"s": 1340,
"text": "divakarkumar2000"
},
{
"code": null,
"e": 1383,
"s": 1357,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1385,
"s": 1383,
"text": "0"
},
{
"code": null,
"e": 1405,
"s": 1385,
"text": "code_24x71 week ago"
},
{
"code": null,
"e": 1819,
"s": 1405,
"text": "int findFloor(vector<long long> v, long long n, long long x){\n long long result = -1, mid, low = 0, high = n - 1; \n while(low <= high) {\n mid = low + (high - low) / 2;\n if(v[mid] == x) return mid;\n else if(x > v[mid]) {\n low = mid + 1;\n result = mid;\n }\n else high = mid - 1;\n }\n return result;\n }"
},
{
"code": null,
"e": 1821,
"s": 1819,
"text": "0"
},
{
"code": null,
"e": 1851,
"s": 1821,
"text": "rohitjug19csPremium1 week ago"
},
{
"code": null,
"e": 1867,
"s": 1851,
"text": "JAVA Solution :"
},
{
"code": null,
"e": 2233,
"s": 1867,
"text": "static int findFloor(long arr[], int n, long x)\n {\n int ans=-1;\n int low = 0;\n int high = n-1;\n while(low <= high){\n int mid = (low + high)/2;\n \n if(arr[mid] == x)return mid;\n if(arr[mid] < x){\n ans = mid;\n low = mid + 1;\n }\n else high = mid - 1;\n }\n return ans;\n }"
},
{
"code": null,
"e": 2235,
"s": 2233,
"text": "0"
},
{
"code": null,
"e": 2261,
"s": 2235,
"text": "aditya_shekhar_1 week ago"
},
{
"code": null,
"e": 2735,
"s": 2261,
"text": "int findFloor(vector<long long> arr, long long n, long long x){\n \n if (arr[0]>x) return -1;\n if (arr[n-1]<x) return n;\n \n int left=0, right=n-1, mid;\n \n while(left<=right){\n if (arr[mid]==x) return mid;\n else if (mid>0 && arr[mid]>x && arr[mid-1]<=x) return mid-1;//x is between mid and mid-1\n else if (arr[mid]>x) right=mid-1;\n else left=mid+1;\n }\n return -1;\n }"
},
{
"code": null,
"e": 2866,
"s": 2735,
"text": "This code gives TLE error in the first test case, but I've tried doing this in O(logn) time complexity. Can anyone help with this?"
},
{
"code": null,
"e": 2887,
"s": 2868,
"text": "Thanks in advance!"
},
{
"code": null,
"e": 2891,
"s": 2889,
"text": "0"
},
{
"code": null,
"e": 2914,
"s": 2891,
"text": "expresscode2 weeks ago"
},
{
"code": null,
"e": 3206,
"s": 2914,
"text": " long long findFloor(vector<long long> v, long long n, long long x){\n\n auto i= lower_bound ( v.begin(), v.end(), x);\n \n if(*i==x)\n return i-v.begin();\n \n if(i==v.begin())\n return -1;\n \n return (i-v.begin()-1 );\n \n }"
},
{
"code": null,
"e": 3208,
"s": 3206,
"text": "0"
},
{
"code": null,
"e": 3220,
"s": 3208,
"text": "expresscode"
},
{
"code": null,
"e": 3246,
"s": 3220,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3248,
"s": 3246,
"text": "0"
},
{
"code": null,
"e": 3278,
"s": 3248,
"text": "ajitvishwakarma3602 weeks ago"
},
{
"code": null,
"e": 3801,
"s": 3278,
"text": " int findFloor(vector<long long> v, long long n, long long x){\n \n int K = floor (x);\n \n long long s = 0;\n long long e = n-1;\n long long mx =-1;\n if (x < v[0])\n return -1;\n while( s<=e){\n long long mid = s+(e-s)/2;\n \n if (v[mid] <=K)\n {\n mx =max( mid, mx);\n s =mid +1;\n }\n else \n e =mid -1;\n }\n // Your code here\n return mx;\n }"
},
{
"code": null,
"e": 3803,
"s": 3801,
"text": "0"
},
{
"code": null,
"e": 3832,
"s": 3803,
"text": "himanshuharsh19992 weeks ago"
},
{
"code": null,
"e": 4225,
"s": 3832,
"text": "\tlong long low = 0, high = n-1, res = -1;\n \n\tif (x < v[low]) return -1;\n if (x >= v[high]) return high;\n \n while(low<=high){\n \tlong long mid = (low+high)/2;\n if (v[mid] == x)\n \treturn mid;\n else if (v[mid] > x)\n \thigh = mid-1;\n else{\n res = max(res,mid);\n low = mid+1;\n }\n }\n return res;"
},
{
"code": null,
"e": 4228,
"s": 4225,
"text": "+1"
},
{
"code": null,
"e": 4250,
"s": 4228,
"text": "vteradali52 weeks ago"
},
{
"code": null,
"e": 4524,
"s": 4250,
"text": "class Solution{ static int findFloor(long arr[], int n, long x) { for(int i=n-1;i>0;i--){ if(arr[i]<x){ return i; } else if(arr[i]<=x){ return i; } } return -1; } }"
},
{
"code": null,
"e": 4670,
"s": 4524,
"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": 4706,
"s": 4670,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4716,
"s": 4706,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4726,
"s": 4716,
"text": "\nContest\n"
},
{
"code": null,
"e": 4789,
"s": 4726,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4974,
"s": 4789,
"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": 5258,
"s": 4974,
"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": 5404,
"s": 5258,
"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": 5481,
"s": 5404,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 5522,
"s": 5481,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 5550,
"s": 5522,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 5621,
"s": 5550,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 5808,
"s": 5621,
"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."
}
]
|
How to deal with missing values in a Timeseries in Python? | 05 Nov, 2021
In this article, we will discuss how to deal with missing values in a time series using the Python programming language.
Time series is a sequence of observations recorded at regular time intervals. Time series analysis can be useful to see how a given asset, security, or economic variable changes over time. Another big question here is why we need to deal with missing values in the dataset and why the missing values are present in the data?
The handling of missing data is very important during the preprocessing of the dataset as many machine learning algorithms do not support missing values.
Time series are subject to have missing points due to problems in reading or recording the data.
Why can’t we change the missing values with global mean because the time series data might have some like seasonality or trend? A conventional method such as mean and mode imputation, deletion, and other methods are not good enough to handle missing values as those methods can cause bias to the data. Estimation or imputation of the missing data with the values produced by some procedures or algorithms can be the best possible solution to minimize the bias effect of the conventional method of the data. So that at last, the data will be completed and ready to use for another step of analysis or data mining.
The method fills missing values according to sequence and conditions. It means that the method replaces ‘nan’s value with the last observed non-nan value or the next observed non-nan value.
backfill – bfill : according to the last observed valueforwardfill – ffill : according to the next observed value
backfill – bfill : according to the last observed value
forwardfill – ffill : according to the next observed value
Python3
# import the librariesimport pandas as pdimport numpy as np # dataframe with index as timeseriestime_sdata = pd.date_range("09/10/2021", periods=9, freq="W") df = pd.DataFrame(index=time_sdata)print(df) # there are four missing valuesdf["example"] = [10001.0, 10002.0, 10003.0, np.nan, 10004.0, np.nan, np.nan, 10005.0, np.nan] gfg1 = df.ffill()print("Using ffill() function:-")print(gfg1) # here we are doing Backfill Missing Values# in the output the last value has NaN because # there is no backward value for thatgfg2 = df.bfill()print("Using bfill() function:-")print(gfg2)
Output:
The method is more complex than the above fillna() method. It consists of different methodologies, including ‘linear’, ‘quadratic’, ‘nearest’. Interpolation is a powerful method to fill missing values in time-series data. Go through the below link provided for a few more examples.
Python3
# import the librariesimport pandas as pdimport numpy as np # dataframe with index as timeseriestime_sdata = pd.date_range("09/10/2021", periods=9, freq="W") df = pd.DataFrame(index=time_sdata)print(df) # there are four missing valuesdf["example"] = [10001.0, 10002.0, 10003.0, np.nan, 10004.0, np.nan, np.nan, 10005.0, np.nan] # using interpolate() to fill the missing # values in a specific order# dealing with missing valuesdataframe1 = df.interpolate()print(dataframe1)
Output:
This is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled.
Syntax:
DataFrame.interpolate(method=’linear’, axis=0, limit=None, inplace=False, limit_direction=None, limit_area=None, downcast=None, **kwargs)
Note: Only method=’linear’ is supported for DataFrame/Series with a MultiIndex.
Python3
# import the librariesimport pandas as pdimport numpy as np # dataframe with index as timeseriestime_sdata = pd.date_range("09/10/2021", periods=9, freq="W") df = pd.DataFrame(index=time_sdata)print(df) # there are four missing valuesdf["example"] = [10001.0, 10002.0, 10003.0, np.nan, 10004.0, np.nan, np.nan, 10005.0, np.nan] # Interpolating Missing Values to two valuesdataframe = df.interpolate(limit=2, limit_direction="forward")print(dataframe)
Output:
Picked
Python-pandas
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": 54,
"s": 26,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 175,
"s": 54,
"text": "In this article, we will discuss how to deal with missing values in a time series using the Python programming language."
},
{
"code": null,
"e": 500,
"s": 175,
"text": "Time series is a sequence of observations recorded at regular time intervals. Time series analysis can be useful to see how a given asset, security, or economic variable changes over time. Another big question here is why we need to deal with missing values in the dataset and why the missing values are present in the data?"
},
{
"code": null,
"e": 654,
"s": 500,
"text": "The handling of missing data is very important during the preprocessing of the dataset as many machine learning algorithms do not support missing values."
},
{
"code": null,
"e": 751,
"s": 654,
"text": "Time series are subject to have missing points due to problems in reading or recording the data."
},
{
"code": null,
"e": 1366,
"s": 751,
"text": "Why can’t we change the missing values with global mean because the time series data might have some like seasonality or trend? A conventional method such as mean and mode imputation, deletion, and other methods are not good enough to handle missing values as those methods can cause bias to the data. Estimation or imputation of the missing data with the values produced by some procedures or algorithms can be the best possible solution to minimize the bias effect of the conventional method of the data. So that at last, the data will be completed and ready to use for another step of analysis or data mining. "
},
{
"code": null,
"e": 1557,
"s": 1366,
"text": " The method fills missing values according to sequence and conditions. It means that the method replaces ‘nan’s value with the last observed non-nan value or the next observed non-nan value."
},
{
"code": null,
"e": 1671,
"s": 1557,
"text": "backfill – bfill : according to the last observed valueforwardfill – ffill : according to the next observed value"
},
{
"code": null,
"e": 1727,
"s": 1671,
"text": "backfill – bfill : according to the last observed value"
},
{
"code": null,
"e": 1786,
"s": 1727,
"text": "forwardfill – ffill : according to the next observed value"
},
{
"code": null,
"e": 1794,
"s": 1786,
"text": "Python3"
},
{
"code": "# import the librariesimport pandas as pdimport numpy as np # dataframe with index as timeseriestime_sdata = pd.date_range(\"09/10/2021\", periods=9, freq=\"W\") df = pd.DataFrame(index=time_sdata)print(df) # there are four missing valuesdf[\"example\"] = [10001.0, 10002.0, 10003.0, np.nan, 10004.0, np.nan, np.nan, 10005.0, np.nan] gfg1 = df.ffill()print(\"Using ffill() function:-\")print(gfg1) # here we are doing Backfill Missing Values# in the output the last value has NaN because # there is no backward value for thatgfg2 = df.bfill()print(\"Using bfill() function:-\")print(gfg2)",
"e": 2394,
"s": 1794,
"text": null
},
{
"code": null,
"e": 2402,
"s": 2394,
"text": "Output:"
},
{
"code": null,
"e": 2685,
"s": 2402,
"text": "The method is more complex than the above fillna() method. It consists of different methodologies, including ‘linear’, ‘quadratic’, ‘nearest’. Interpolation is a powerful method to fill missing values in time-series data. Go through the below link provided for a few more examples. "
},
{
"code": null,
"e": 2693,
"s": 2685,
"text": "Python3"
},
{
"code": "# import the librariesimport pandas as pdimport numpy as np # dataframe with index as timeseriestime_sdata = pd.date_range(\"09/10/2021\", periods=9, freq=\"W\") df = pd.DataFrame(index=time_sdata)print(df) # there are four missing valuesdf[\"example\"] = [10001.0, 10002.0, 10003.0, np.nan, 10004.0, np.nan, np.nan, 10005.0, np.nan] # using interpolate() to fill the missing # values in a specific order# dealing with missing valuesdataframe1 = df.interpolate()print(dataframe1)",
"e": 3187,
"s": 2693,
"text": null
},
{
"code": null,
"e": 3195,
"s": 3187,
"text": "Output:"
},
{
"code": null,
"e": 3390,
"s": 3195,
"text": "This is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled."
},
{
"code": null,
"e": 3401,
"s": 3390,
"text": "Syntax: "
},
{
"code": null,
"e": 3540,
"s": 3401,
"text": "DataFrame.interpolate(method=’linear’, axis=0, limit=None, inplace=False, limit_direction=None, limit_area=None, downcast=None, **kwargs) "
},
{
"code": null,
"e": 3620,
"s": 3540,
"text": "Note: Only method=’linear’ is supported for DataFrame/Series with a MultiIndex."
},
{
"code": null,
"e": 3628,
"s": 3620,
"text": "Python3"
},
{
"code": "# import the librariesimport pandas as pdimport numpy as np # dataframe with index as timeseriestime_sdata = pd.date_range(\"09/10/2021\", periods=9, freq=\"W\") df = pd.DataFrame(index=time_sdata)print(df) # there are four missing valuesdf[\"example\"] = [10001.0, 10002.0, 10003.0, np.nan, 10004.0, np.nan, np.nan, 10005.0, np.nan] # Interpolating Missing Values to two valuesdataframe = df.interpolate(limit=2, limit_direction=\"forward\")print(dataframe)",
"e": 4099,
"s": 3628,
"text": null
},
{
"code": null,
"e": 4107,
"s": 4099,
"text": "Output:"
},
{
"code": null,
"e": 4114,
"s": 4107,
"text": "Picked"
},
{
"code": null,
"e": 4128,
"s": 4114,
"text": "Python-pandas"
},
{
"code": null,
"e": 4135,
"s": 4128,
"text": "Python"
},
{
"code": null,
"e": 4233,
"s": 4135,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4265,
"s": 4233,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4292,
"s": 4265,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4313,
"s": 4292,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4336,
"s": 4313,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4367,
"s": 4336,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4423,
"s": 4367,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4465,
"s": 4423,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4507,
"s": 4465,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4546,
"s": 4507,
"text": "Python | Get unique values from a list"
}
]
|
Functional Programming in Java 8+ using the Stream API with Example | 09 Dec, 2021
API is an acronym for Application Programming Interface, which is software and the java streams work on a data source. Consider a stream like a flow of water in a small canal. Let’s take a real-life example. Each time a user uses an application that is popular these days like WhatsApp in order to communicate via delivering text messages or calls to other users. Both users are using an API.
Java streams work on three operations which as mentioned below
Data SourceIntermediate operationTerminal operation
Data Source
Intermediate operation
Terminal operation
Methods: Streams can be created in three ways
Using an object of any class from the collection frameworkUsing an array of the reference data typeUsing the interface defined in the ‘java.util.stream’ package
Using an object of any class from the collection framework
Using an array of the reference data type
Using the interface defined in the ‘java.util.stream’ package
Method 1: Data Source
The data source can be widely varied such as an array, List, etc
Syntax:
ArrayList<Integer> numbers = new ArrayList<>();
Integer[] numbers = {1,2,3};
Example 1: Using an object as a data source
Java
// Java Program showcasing data source// using an object as a data source // Importing input output classesimport java.io.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Data Source // Creating an arrayList object // Declaring object of String type ArrayList<String> gfgNames = new ArrayList<>(); // Custom input elements to above object gfgNames.add("Dean"); gfgNames.add("castee"); gfgNames.add("robert"); // Creating object of Stream where Stream is created // using arrayList and object as data source Stream<String> streamOfNames = gfgNames.stream(); // Print and display element System.out.print(streamOfNames); }}
Example 2: Using an array as a data source
// Data Source
Integer[] numbers = {1,2,3,4,5};
// Stream using an array
Stream<Integer> streamOfNumbers = Arrays.stream(numbers);
// using predefined Instream interface
integerStream = IntStream.range(1,100); // a stream from 1 to 99;
Java
// Java Program showcasing data source// using an array as a data source // Importing java input output classimport java.io.*; // Importing all classes from// java.util packageimport java.util.*; // Importing class for additional operations,// additionls and pipelinesimport java.util.stream.IntStream; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a predefined stream using range method // Custom inputs for range as parameters var stream = IntStream.range(1, 100); // Stream is created var max = stream.filter(number -> number % 4 == 0) .count(); // Print and display the maximum number // from the stream System.out.println(max); }}
24
Method 2: Intermediate Operation
Intermediate operations are some methods that one can apply on a stream.
Note: It can be of any number
filter()
Example:
Java
import java.io.*; class GFG { public static void main(String[] args) { // Data Source Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 } // Stream Stream<Integer> streamOfNumbers = Arrays.stream(numbers); // filter all the even numbers Stream<Integer> evenNumbersStream = streamOfNumbers.filter( number -> number % 2 == 0) }}
Method 3: Terminal operation
Terminal operation methods that we can apply on a stream that will cause a stream to be “closed”.
Concept:
Some terminal operations can be used to iterate on the elements of the stream.
min(),max(),count()
forEach(),noneMatch()
Example 1: Explaining stream API
Java
// Importing input output classesimport java.io.*;// Importing all classes from// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Data source // Custom integer inputs Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // Stream var streamOfNumbers = Arrays.stream(numbers); // Using filter method var evenNumbersStream = streamOfNumbers .filter(number -> number % 3 == 0) .count(); // Print and display System.out.println(evenNumbersStream); }}
4
Example 2:
Java
// Importing all classes from java.util packageimport java.io.*;import java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList of Integer type ArrayList<Integer> list = new ArrayList<>(); // Adding elements to above object of Arraylist // Custom inputs list.add(20); list.add(4); list.add(76); list.add(21); list.add(3); list.add(80); var stream = list.stream(); var numbers = stream.filter(number -> number % 2 == 0) .filter(number -> number > 20); // Print all the elements of the stream on the console numbers.forEach(System.out::println); }}
76
80
Note: One can pass lambda also number -> System.out.println(number + ” “)
gulshankumarar231
kevinm2052
sagartomar9927
rajeev0719singh
rizwanakhatoon
Java 8
Java-Functional Programming
java-stream
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 445,
"s": 52,
"text": "API is an acronym for Application Programming Interface, which is software and the java streams work on a data source. Consider a stream like a flow of water in a small canal. Let’s take a real-life example. Each time a user uses an application that is popular these days like WhatsApp in order to communicate via delivering text messages or calls to other users. Both users are using an API."
},
{
"code": null,
"e": 509,
"s": 445,
"text": "Java streams work on three operations which as mentioned below "
},
{
"code": null,
"e": 561,
"s": 509,
"text": "Data SourceIntermediate operationTerminal operation"
},
{
"code": null,
"e": 573,
"s": 561,
"text": "Data Source"
},
{
"code": null,
"e": 596,
"s": 573,
"text": "Intermediate operation"
},
{
"code": null,
"e": 615,
"s": 596,
"text": "Terminal operation"
},
{
"code": null,
"e": 661,
"s": 615,
"text": "Methods: Streams can be created in three ways"
},
{
"code": null,
"e": 822,
"s": 661,
"text": "Using an object of any class from the collection frameworkUsing an array of the reference data typeUsing the interface defined in the ‘java.util.stream’ package"
},
{
"code": null,
"e": 881,
"s": 822,
"text": "Using an object of any class from the collection framework"
},
{
"code": null,
"e": 923,
"s": 881,
"text": "Using an array of the reference data type"
},
{
"code": null,
"e": 985,
"s": 923,
"text": "Using the interface defined in the ‘java.util.stream’ package"
},
{
"code": null,
"e": 1008,
"s": 985,
"text": "Method 1: Data Source "
},
{
"code": null,
"e": 1074,
"s": 1008,
"text": "The data source can be widely varied such as an array, List, etc "
},
{
"code": null,
"e": 1083,
"s": 1074,
"text": "Syntax: "
},
{
"code": null,
"e": 1160,
"s": 1083,
"text": "ArrayList<Integer> numbers = new ArrayList<>();\nInteger[] numbers = {1,2,3};"
},
{
"code": null,
"e": 1204,
"s": 1160,
"text": "Example 1: Using an object as a data source"
},
{
"code": null,
"e": 1209,
"s": 1204,
"text": "Java"
},
{
"code": "// Java Program showcasing data source// using an object as a data source // Importing input output classesimport java.io.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Data Source // Creating an arrayList object // Declaring object of String type ArrayList<String> gfgNames = new ArrayList<>(); // Custom input elements to above object gfgNames.add(\"Dean\"); gfgNames.add(\"castee\"); gfgNames.add(\"robert\"); // Creating object of Stream where Stream is created // using arrayList and object as data source Stream<String> streamOfNames = gfgNames.stream(); // Print and display element System.out.print(streamOfNames); }}",
"e": 1979,
"s": 1209,
"text": null
},
{
"code": null,
"e": 2023,
"s": 1979,
"text": " Example 2: Using an array as a data source"
},
{
"code": null,
"e": 2071,
"s": 2023,
"text": "// Data Source\nInteger[] numbers = {1,2,3,4,5};"
},
{
"code": null,
"e": 2154,
"s": 2071,
"text": "// Stream using an array\nStream<Integer> streamOfNumbers = Arrays.stream(numbers);"
},
{
"code": null,
"e": 2259,
"s": 2154,
"text": "// using predefined Instream interface\nintegerStream = IntStream.range(1,100); // a stream from 1 to 99;"
},
{
"code": null,
"e": 2264,
"s": 2259,
"text": "Java"
},
{
"code": "// Java Program showcasing data source// using an array as a data source // Importing java input output classimport java.io.*; // Importing all classes from// java.util packageimport java.util.*; // Importing class for additional operations,// additionls and pipelinesimport java.util.stream.IntStream; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a predefined stream using range method // Custom inputs for range as parameters var stream = IntStream.range(1, 100); // Stream is created var max = stream.filter(number -> number % 4 == 0) .count(); // Print and display the maximum number // from the stream System.out.println(max); }}",
"e": 3041,
"s": 2264,
"text": null
},
{
"code": null,
"e": 3044,
"s": 3041,
"text": "24"
},
{
"code": null,
"e": 3077,
"s": 3044,
"text": "Method 2: Intermediate Operation"
},
{
"code": null,
"e": 3151,
"s": 3077,
"text": "Intermediate operations are some methods that one can apply on a stream. "
},
{
"code": null,
"e": 3181,
"s": 3151,
"text": "Note: It can be of any number"
},
{
"code": null,
"e": 3190,
"s": 3181,
"text": "filter()"
},
{
"code": null,
"e": 3199,
"s": 3190,
"text": "Example:"
},
{
"code": null,
"e": 3204,
"s": 3199,
"text": "Java"
},
{
"code": "import java.io.*; class GFG { public static void main(String[] args) { // Data Source Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 } // Stream Stream<Integer> streamOfNumbers = Arrays.stream(numbers); // filter all the even numbers Stream<Integer> evenNumbersStream = streamOfNumbers.filter( number -> number % 2 == 0) }}",
"e": 3622,
"s": 3204,
"text": null
},
{
"code": null,
"e": 3652,
"s": 3622,
"text": " Method 3: Terminal operation"
},
{
"code": null,
"e": 3750,
"s": 3652,
"text": "Terminal operation methods that we can apply on a stream that will cause a stream to be “closed”."
},
{
"code": null,
"e": 3760,
"s": 3750,
"text": "Concept: "
},
{
"code": null,
"e": 3839,
"s": 3760,
"text": "Some terminal operations can be used to iterate on the elements of the stream."
},
{
"code": null,
"e": 3859,
"s": 3839,
"text": "min(),max(),count()"
},
{
"code": null,
"e": 3881,
"s": 3859,
"text": "forEach(),noneMatch()"
},
{
"code": null,
"e": 3914,
"s": 3881,
"text": "Example 1: Explaining stream API"
},
{
"code": null,
"e": 3919,
"s": 3914,
"text": "Java"
},
{
"code": "// Importing input output classesimport java.io.*;// Importing all classes from// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Data source // Custom integer inputs Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // Stream var streamOfNumbers = Arrays.stream(numbers); // Using filter method var evenNumbersStream = streamOfNumbers .filter(number -> number % 3 == 0) .count(); // Print and display System.out.println(evenNumbersStream); }}",
"e": 4577,
"s": 3919,
"text": null
},
{
"code": null,
"e": 4579,
"s": 4577,
"text": "4"
},
{
"code": null,
"e": 4590,
"s": 4579,
"text": "Example 2:"
},
{
"code": null,
"e": 4595,
"s": 4590,
"text": "Java"
},
{
"code": "// Importing all classes from java.util packageimport java.io.*;import java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList of Integer type ArrayList<Integer> list = new ArrayList<>(); // Adding elements to above object of Arraylist // Custom inputs list.add(20); list.add(4); list.add(76); list.add(21); list.add(3); list.add(80); var stream = list.stream(); var numbers = stream.filter(number -> number % 2 == 0) .filter(number -> number > 20); // Print all the elements of the stream on the console numbers.forEach(System.out::println); }}",
"e": 5351,
"s": 4595,
"text": null
},
{
"code": null,
"e": 5357,
"s": 5351,
"text": "76\n80"
},
{
"code": null,
"e": 5431,
"s": 5357,
"text": "Note: One can pass lambda also number -> System.out.println(number + ” “)"
},
{
"code": null,
"e": 5449,
"s": 5431,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 5460,
"s": 5449,
"text": "kevinm2052"
},
{
"code": null,
"e": 5475,
"s": 5460,
"text": "sagartomar9927"
},
{
"code": null,
"e": 5491,
"s": 5475,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 5506,
"s": 5491,
"text": "rizwanakhatoon"
},
{
"code": null,
"e": 5513,
"s": 5506,
"text": "Java 8"
},
{
"code": null,
"e": 5541,
"s": 5513,
"text": "Java-Functional Programming"
},
{
"code": null,
"e": 5553,
"s": 5541,
"text": "java-stream"
},
{
"code": null,
"e": 5577,
"s": 5553,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5582,
"s": 5577,
"text": "Java"
},
{
"code": null,
"e": 5601,
"s": 5582,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5606,
"s": 5601,
"text": "Java"
},
{
"code": null,
"e": 5704,
"s": 5606,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5719,
"s": 5704,
"text": "Stream In Java"
},
{
"code": null,
"e": 5740,
"s": 5719,
"text": "Introduction to Java"
},
{
"code": null,
"e": 5761,
"s": 5740,
"text": "Constructors in Java"
},
{
"code": null,
"e": 5780,
"s": 5761,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 5797,
"s": 5780,
"text": "Generics in Java"
},
{
"code": null,
"e": 5827,
"s": 5797,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 5853,
"s": 5827,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 5869,
"s": 5853,
"text": "Strings in Java"
},
{
"code": null,
"e": 5906,
"s": 5869,
"text": "Differences between JDK, JRE and JVM"
}
]
|
PySpark - MLlib | Apache Spark offers a Machine Learning API called MLlib. PySpark has this machine learning API in Python as well. It supports different kind of algorithms, which are mentioned below −
mllib.classification − The spark.mllib package supports various methods for binary classification, multiclass classification and regression analysis. Some of the most popular algorithms in classification are Random Forest, Naive Bayes, Decision Tree, etc.
mllib.classification − The spark.mllib package supports various methods for binary classification, multiclass classification and regression analysis. Some of the most popular algorithms in classification are Random Forest, Naive Bayes, Decision Tree, etc.
mllib.clustering − Clustering is an unsupervised learning problem, whereby you aim to group subsets of entities with one another based on some notion of similarity.
mllib.clustering − Clustering is an unsupervised learning problem, whereby you aim to group subsets of entities with one another based on some notion of similarity.
mllib.fpm − Frequent pattern matching is mining frequent items, itemsets, subsequences or other substructures that are usually among the first steps to analyze a large-scale dataset. This has been an active research topic in data mining for years.
mllib.fpm − Frequent pattern matching is mining frequent items, itemsets, subsequences or other substructures that are usually among the first steps to analyze a large-scale dataset. This has been an active research topic in data mining for years.
mllib.linalg − MLlib utilities for linear algebra.
mllib.linalg − MLlib utilities for linear algebra.
mllib.recommendation − Collaborative filtering is commonly used for recommender systems. These techniques aim to fill in the missing entries of a user item association matrix.
mllib.recommendation − Collaborative filtering is commonly used for recommender systems. These techniques aim to fill in the missing entries of a user item association matrix.
spark.mllib − It ¬currently supports model-based collaborative filtering, in which users and products are described by a small set of latent factors that can be used to predict missing entries. spark.mllib uses the Alternating Least Squares (ALS) algorithm to learn these latent factors.
spark.mllib − It ¬currently supports model-based collaborative filtering, in which users and products are described by a small set of latent factors that can be used to predict missing entries. spark.mllib uses the Alternating Least Squares (ALS) algorithm to learn these latent factors.
mllib.regression − Linear regression belongs to the family of regression algorithms. The goal of regression is to find relationships and dependencies between variables. The interface for working with linear regression models and model summaries is similar to the logistic regression case.
mllib.regression − Linear regression belongs to the family of regression algorithms. The goal of regression is to find relationships and dependencies between variables. The interface for working with linear regression models and model summaries is similar to the logistic regression case.
There are other algorithms, classes and functions also as a part of the mllib package. As of now, let us understand a demonstration on pyspark.mllib.
The following example is of collaborative filtering using ALS algorithm to build the recommendation model and evaluate it on training data.
Dataset used − test.data
1,1,5.0
1,2,1.0
1,3,5.0
1,4,1.0
2,1,5.0
2,2,1.0
2,3,5.0
2,4,1.0
3,1,1.0
3,2,5.0
3,3,1.0
3,4,5.0
4,1,1.0
4,2,5.0
4,3,1.0
4,4,5.0
--------------------------------------recommend.py----------------------------------------
from __future__ import print_function
from pyspark import SparkContext
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
if __name__ == "__main__":
sc = SparkContext(appName="Pspark mllib Example")
data = sc.textFile("test.data")
ratings = data.map(lambda l: l.split(','))\
.map(lambda l: Rating(int(l[0]), int(l[1]), float(l[2])))
# Build the recommendation model using Alternating Least Squares
rank = 10
numIterations = 10
model = ALS.train(ratings, rank, numIterations)
# Evaluate the model on training data
testdata = ratings.map(lambda p: (p[0], p[1]))
predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2]))
ratesAndPreds = ratings.map(lambda r: ((r[0], r[1]), r[2])).join(predictions)
MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).mean()
print("Mean Squared Error = " + str(MSE))
# Save and load model
model.save(sc, "target/tmp/myCollaborativeFilter")
sameModel = MatrixFactorizationModel.load(sc, "target/tmp/myCollaborativeFilter")
--------------------------------------recommend.py----------------------------------------
Command − The command will be as follows −
$SPARK_HOME/bin/spark-submit recommend.py
Output − The output of the above command will be −
Mean Squared Error = 1.20536041839e-05 | [
{
"code": null,
"e": 2123,
"s": 1939,
"text": "Apache Spark offers a Machine Learning API called MLlib. PySpark has this machine learning API in Python as well. It supports different kind of algorithms, which are mentioned below −"
},
{
"code": null,
"e": 2379,
"s": 2123,
"text": "mllib.classification − The spark.mllib package supports various methods for binary classification, multiclass classification and regression analysis. Some of the most popular algorithms in classification are Random Forest, Naive Bayes, Decision Tree, etc."
},
{
"code": null,
"e": 2635,
"s": 2379,
"text": "mllib.classification − The spark.mllib package supports various methods for binary classification, multiclass classification and regression analysis. Some of the most popular algorithms in classification are Random Forest, Naive Bayes, Decision Tree, etc."
},
{
"code": null,
"e": 2800,
"s": 2635,
"text": "mllib.clustering − Clustering is an unsupervised learning problem, whereby you aim to group subsets of entities with one another based on some notion of similarity."
},
{
"code": null,
"e": 2965,
"s": 2800,
"text": "mllib.clustering − Clustering is an unsupervised learning problem, whereby you aim to group subsets of entities with one another based on some notion of similarity."
},
{
"code": null,
"e": 3213,
"s": 2965,
"text": "mllib.fpm − Frequent pattern matching is mining frequent items, itemsets, subsequences or other substructures that are usually among the first steps to analyze a large-scale dataset. This has been an active research topic in data mining for years."
},
{
"code": null,
"e": 3461,
"s": 3213,
"text": "mllib.fpm − Frequent pattern matching is mining frequent items, itemsets, subsequences or other substructures that are usually among the first steps to analyze a large-scale dataset. This has been an active research topic in data mining for years."
},
{
"code": null,
"e": 3512,
"s": 3461,
"text": "mllib.linalg − MLlib utilities for linear algebra."
},
{
"code": null,
"e": 3563,
"s": 3512,
"text": "mllib.linalg − MLlib utilities for linear algebra."
},
{
"code": null,
"e": 3739,
"s": 3563,
"text": "mllib.recommendation − Collaborative filtering is commonly used for recommender systems. These techniques aim to fill in the missing entries of a user item association matrix."
},
{
"code": null,
"e": 3915,
"s": 3739,
"text": "mllib.recommendation − Collaborative filtering is commonly used for recommender systems. These techniques aim to fill in the missing entries of a user item association matrix."
},
{
"code": null,
"e": 4203,
"s": 3915,
"text": "spark.mllib − It ¬currently supports model-based collaborative filtering, in which users and products are described by a small set of latent factors that can be used to predict missing entries. spark.mllib uses the Alternating Least Squares (ALS) algorithm to learn these latent factors."
},
{
"code": null,
"e": 4491,
"s": 4203,
"text": "spark.mllib − It ¬currently supports model-based collaborative filtering, in which users and products are described by a small set of latent factors that can be used to predict missing entries. spark.mllib uses the Alternating Least Squares (ALS) algorithm to learn these latent factors."
},
{
"code": null,
"e": 4780,
"s": 4491,
"text": "mllib.regression − Linear regression belongs to the family of regression algorithms. The goal of regression is to find relationships and dependencies between variables. The interface for working with linear regression models and model summaries is similar to the logistic regression case."
},
{
"code": null,
"e": 5069,
"s": 4780,
"text": "mllib.regression − Linear regression belongs to the family of regression algorithms. The goal of regression is to find relationships and dependencies between variables. The interface for working with linear regression models and model summaries is similar to the logistic regression case."
},
{
"code": null,
"e": 5219,
"s": 5069,
"text": "There are other algorithms, classes and functions also as a part of the mllib package. As of now, let us understand a demonstration on pyspark.mllib."
},
{
"code": null,
"e": 5359,
"s": 5219,
"text": "The following example is of collaborative filtering using ALS algorithm to build the recommendation model and evaluate it on training data."
},
{
"code": null,
"e": 5384,
"s": 5359,
"text": "Dataset used − test.data"
},
{
"code": null,
"e": 5513,
"s": 5384,
"text": "1,1,5.0\n1,2,1.0\n1,3,5.0\n1,4,1.0\n2,1,5.0\n2,2,1.0\n2,3,5.0\n2,4,1.0\n3,1,1.0\n3,2,5.0\n3,3,1.0\n3,4,5.0\n4,1,1.0\n4,2,5.0\n4,3,1.0\n4,4,5.0\n"
},
{
"code": null,
"e": 6767,
"s": 5513,
"text": "--------------------------------------recommend.py----------------------------------------\nfrom __future__ import print_function\nfrom pyspark import SparkContext\nfrom pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating\nif __name__ == \"__main__\":\n sc = SparkContext(appName=\"Pspark mllib Example\")\n data = sc.textFile(\"test.data\")\n ratings = data.map(lambda l: l.split(','))\\\n .map(lambda l: Rating(int(l[0]), int(l[1]), float(l[2])))\n \n # Build the recommendation model using Alternating Least Squares\n rank = 10\n numIterations = 10\n model = ALS.train(ratings, rank, numIterations)\n \n # Evaluate the model on training data\n testdata = ratings.map(lambda p: (p[0], p[1]))\n predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2]))\n ratesAndPreds = ratings.map(lambda r: ((r[0], r[1]), r[2])).join(predictions)\n MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).mean()\n print(\"Mean Squared Error = \" + str(MSE))\n \n # Save and load model\n model.save(sc, \"target/tmp/myCollaborativeFilter\")\n sameModel = MatrixFactorizationModel.load(sc, \"target/tmp/myCollaborativeFilter\")\n--------------------------------------recommend.py----------------------------------------\n"
},
{
"code": null,
"e": 6810,
"s": 6767,
"text": "Command − The command will be as follows −"
},
{
"code": null,
"e": 6853,
"s": 6810,
"text": "$SPARK_HOME/bin/spark-submit recommend.py\n"
},
{
"code": null,
"e": 6904,
"s": 6853,
"text": "Output − The output of the above command will be −"
}
]
|
TensorFlow – How to add padding to a tensor | 01 Aug, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks.
Padding means adding values before and after Tensor values.
Method Used:
tf.pad: This method accepts input tensor and padding tensor with other optional arguments and returns a Tensor with added padding and same type as input Tensor. Padding tensor is a Tensor with shape(n, 2).
Example 1: This example uses constant padding mode i.e. value at all the padded indices will be constant.
Python3
# importing the libraryimport tensorflow as tf # Initializing the Inputinput = tf.constant([[1, 2], [3, 4]])padding = tf.constant([[2, 2], [2, 2]]) # Printing the Inputprint("Input: ", input)print("Padding: ", padding) # Generating padded Tensorres = tf.pad(input, padding, mode ='CONSTANT') # Printing the resulting Tensorsprint("Res: ", res )
Output:
Input: tf.Tensor(
[[1 2]
[3 4]], shape=(2, 2), dtype=int32)
Padding: tf.Tensor(
[[2 2]
[2 2]], shape=(2, 2), dtype=int32)
Res: tf.Tensor(
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 1 2 0 0]
[0 0 3 4 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]], shape=(6, 6), dtype=int32)
Example 2: This example uses REFLECT padding mode. For this mode to work paddings[D, 0] and paddings[D, 1] must be less than or equal to tensor.dim_size(D) – 1.
Python3
# importing the libraryimport tensorflow as tf # Initializing the Inputinput = tf.constant([[1, 2, 5], [3, 4, 6]])padding = tf.constant([[1, 1], [2, 2]]) # Printing the Inputprint("Input: ", input)print("Padding: ", padding) # Generating padded Tensorres = tf.pad(input, padding, mode ='REFLECT') # Printing the resulting Tensorsprint("Res: ", res )
Output:
Input: tf.Tensor(
[[1 2 5]
[3 4 6]], shape=(2, 3), dtype=int32)
Padding: tf.Tensor(
[[1 1]
[2 2]], shape=(2, 2), dtype=int32)
Res: tf.Tensor(
[[6 4 3 4 6 4 3]
[5 2 1 2 5 2 1]
[6 4 3 4 6 4 3]
[5 2 1 2 5 2 1]], shape=(4, 7), dtype=int32)
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 159,
"s": 28,
"text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks."
},
{
"code": null,
"e": 219,
"s": 159,
"text": "Padding means adding values before and after Tensor values."
},
{
"code": null,
"e": 232,
"s": 219,
"text": "Method Used:"
},
{
"code": null,
"e": 438,
"s": 232,
"text": "tf.pad: This method accepts input tensor and padding tensor with other optional arguments and returns a Tensor with added padding and same type as input Tensor. Padding tensor is a Tensor with shape(n, 2)."
},
{
"code": null,
"e": 544,
"s": 438,
"text": "Example 1: This example uses constant padding mode i.e. value at all the padded indices will be constant."
},
{
"code": null,
"e": 552,
"s": 544,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing the Inputinput = tf.constant([[1, 2], [3, 4]])padding = tf.constant([[2, 2], [2, 2]]) # Printing the Inputprint(\"Input: \", input)print(\"Padding: \", padding) # Generating padded Tensorres = tf.pad(input, padding, mode ='CONSTANT') # Printing the resulting Tensorsprint(\"Res: \", res )",
"e": 901,
"s": 552,
"text": null
},
{
"code": null,
"e": 909,
"s": 901,
"text": "Output:"
},
{
"code": null,
"e": 1173,
"s": 909,
"text": "Input: tf.Tensor(\n[[1 2]\n [3 4]], shape=(2, 2), dtype=int32)\nPadding: tf.Tensor(\n[[2 2]\n [2 2]], shape=(2, 2), dtype=int32)\nRes: tf.Tensor(\n[[0 0 0 0 0 0]\n [0 0 0 0 0 0]\n [0 0 1 2 0 0]\n [0 0 3 4 0 0]\n [0 0 0 0 0 0]\n [0 0 0 0 0 0]], shape=(6, 6), dtype=int32)\n\n"
},
{
"code": null,
"e": 1334,
"s": 1173,
"text": "Example 2: This example uses REFLECT padding mode. For this mode to work paddings[D, 0] and paddings[D, 1] must be less than or equal to tensor.dim_size(D) – 1."
},
{
"code": null,
"e": 1342,
"s": 1334,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing the Inputinput = tf.constant([[1, 2, 5], [3, 4, 6]])padding = tf.constant([[1, 1], [2, 2]]) # Printing the Inputprint(\"Input: \", input)print(\"Padding: \", padding) # Generating padded Tensorres = tf.pad(input, padding, mode ='REFLECT') # Printing the resulting Tensorsprint(\"Res: \", res )",
"e": 1696,
"s": 1342,
"text": null
},
{
"code": null,
"e": 1704,
"s": 1696,
"text": "Output:"
},
{
"code": null,
"e": 1950,
"s": 1704,
"text": "Input: tf.Tensor(\n[[1 2 5]\n [3 4 6]], shape=(2, 3), dtype=int32)\nPadding: tf.Tensor(\n[[1 1]\n [2 2]], shape=(2, 2), dtype=int32)\nRes: tf.Tensor(\n[[6 4 3 4 6 4 3]\n [5 2 1 2 5 2 1]\n [6 4 3 4 6 4 3]\n [5 2 1 2 5 2 1]], shape=(4, 7), dtype=int32)\n\n"
},
{
"code": null,
"e": 1968,
"s": 1950,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 1975,
"s": 1968,
"text": "Python"
},
{
"code": null,
"e": 2073,
"s": 1975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2105,
"s": 2073,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2132,
"s": 2105,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2153,
"s": 2132,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2176,
"s": 2153,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2232,
"s": 2176,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2263,
"s": 2232,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2305,
"s": 2263,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2347,
"s": 2305,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2386,
"s": 2347,
"text": "Python | Get unique values from a list"
}
]
|
Python program to convert exponential to float | 23 Dec, 2020
Given a number in exponential format, the task is to write a Python program to convert the number from exponential format to float. The exponential number is a way of representing a number.
Examples:
Input: 1.900000e+01
Output: 19.0
Input: 2.002000e+03
Output: 2002.0
Input: 1.101020e+05
Output: 110102.0
Approach:
First, we will declare an exponential number and save it in a variable.
Then we will use the float() function to convert it to float datatype.
Then we will print the converted number.
Syntax:
float(x)
The float() method is used to return a floating-point number from a number or a string.
Example:
Python3
# Python program to convert exponential to float # Declaring the exponential numberexp_number = "{:e}".format(110102) # Converting it to float data typefloat_number = float(exp_number) # Printing the converted numberprint("Exponent Number:",exp_number)print("Float Number:",float_number)
Output:
Exponent Number: 1.101020e+05
Float Number: 110102.0
Picked
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 218,
"s": 28,
"text": "Given a number in exponential format, the task is to write a Python program to convert the number from exponential format to float. The exponential number is a way of representing a number."
},
{
"code": null,
"e": 228,
"s": 218,
"text": "Examples:"
},
{
"code": null,
"e": 335,
"s": 228,
"text": "Input: 1.900000e+01\nOutput: 19.0\n\nInput: 2.002000e+03\nOutput: 2002.0\n\nInput: 1.101020e+05\nOutput: 110102.0"
},
{
"code": null,
"e": 345,
"s": 335,
"text": "Approach:"
},
{
"code": null,
"e": 417,
"s": 345,
"text": "First, we will declare an exponential number and save it in a variable."
},
{
"code": null,
"e": 488,
"s": 417,
"text": "Then we will use the float() function to convert it to float datatype."
},
{
"code": null,
"e": 529,
"s": 488,
"text": "Then we will print the converted number."
},
{
"code": null,
"e": 537,
"s": 529,
"text": "Syntax:"
},
{
"code": null,
"e": 546,
"s": 537,
"text": "float(x)"
},
{
"code": null,
"e": 634,
"s": 546,
"text": "The float() method is used to return a floating-point number from a number or a string."
},
{
"code": null,
"e": 643,
"s": 634,
"text": "Example:"
},
{
"code": null,
"e": 651,
"s": 643,
"text": "Python3"
},
{
"code": "# Python program to convert exponential to float # Declaring the exponential numberexp_number = \"{:e}\".format(110102) # Converting it to float data typefloat_number = float(exp_number) # Printing the converted numberprint(\"Exponent Number:\",exp_number)print(\"Float Number:\",float_number)",
"e": 942,
"s": 651,
"text": null
},
{
"code": null,
"e": 950,
"s": 942,
"text": "Output:"
},
{
"code": null,
"e": 1003,
"s": 950,
"text": "Exponent Number: 1.101020e+05\nFloat Number: 110102.0"
},
{
"code": null,
"e": 1010,
"s": 1003,
"text": "Picked"
},
{
"code": null,
"e": 1034,
"s": 1010,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1041,
"s": 1034,
"text": "Python"
},
{
"code": null,
"e": 1057,
"s": 1041,
"text": "Python Programs"
},
{
"code": null,
"e": 1076,
"s": 1057,
"text": "Technical Scripter"
}
]
|
What is APIPA (Automatic Private IP Addressing)? | 22 May, 2020
APIPA stands for Automatic Private IP Addressing (APIPA). It is a feature or characteristic in operating systems (eg. Windows) which enables computers to self-configure an IP address and subnet mask automatically when their DHCP(Dynamic Host Configuration Protocol) server isn’t reachable. The IP address range for APIPA is (169.254.0.1 to 169.254.255.254) having 65, 534 usable IP addresses, with the subnet mask of 255.255.0.0.
Initially, the Internet Engineering Task Force (IETF) has reserved the IPv4 address block 169.254.0.0/16 (169.254.0.0 – 169.254.255.255) for link-local addressing. Due to the simultaneous use of IPv4 addresses of different scopes, traffic overload becomes high. The link-local addresses are allocated to interface i.e., stateless in nature such that communication will be established when not getting a response from DHCP Server. After that Microsoft refers to this address autoconfiguration method as “Automatic Private IP Addressing (APIPA)”.
It starts with when the user(client) is unable to find the data/information, then uses APIPA to configure the system with an IP address automatically(ipconfig). The APIPA provides the configuration to check for the presence of a DHCP server(in every five minutes, stated by Microsoft). If APIPA detects a DHCP server on the network configuration area, it stops, and let run the DHCP server that replaces APIPA with dynamically allocated addresses.
Note: To Know the given IP address is provided by which addressing, just run the following command:
ipconfig/all
Communication can be established properly if not getting response from DHCP Server.
APIPA regulates the service, by which always checking response and status of the main DHCP server in a specific period of time.
It can be used as a backup of DHCP because when DHCP stops working then APIPA has the ability to assign IP to the networking hosts.
It stops unwanted broadcasting.
It uses ARP(Address Resolution Protocol) to confirm the address isn’t currently in use.
APIPA ip addresses can slow you network.
APIPA doesnot provide network gateway as DHCP does.
APIPA addresses are restricted for use in local area network.
APIPA configured devices follow the peer to peer communication rule.
Picked
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 May, 2020"
},
{
"code": null,
"e": 482,
"s": 52,
"text": "APIPA stands for Automatic Private IP Addressing (APIPA). It is a feature or characteristic in operating systems (eg. Windows) which enables computers to self-configure an IP address and subnet mask automatically when their DHCP(Dynamic Host Configuration Protocol) server isn’t reachable. The IP address range for APIPA is (169.254.0.1 to 169.254.255.254) having 65, 534 usable IP addresses, with the subnet mask of 255.255.0.0."
},
{
"code": null,
"e": 1027,
"s": 482,
"text": "Initially, the Internet Engineering Task Force (IETF) has reserved the IPv4 address block 169.254.0.0/16 (169.254.0.0 – 169.254.255.255) for link-local addressing. Due to the simultaneous use of IPv4 addresses of different scopes, traffic overload becomes high. The link-local addresses are allocated to interface i.e., stateless in nature such that communication will be established when not getting a response from DHCP Server. After that Microsoft refers to this address autoconfiguration method as “Automatic Private IP Addressing (APIPA)”."
},
{
"code": null,
"e": 1475,
"s": 1027,
"text": "It starts with when the user(client) is unable to find the data/information, then uses APIPA to configure the system with an IP address automatically(ipconfig). The APIPA provides the configuration to check for the presence of a DHCP server(in every five minutes, stated by Microsoft). If APIPA detects a DHCP server on the network configuration area, it stops, and let run the DHCP server that replaces APIPA with dynamically allocated addresses."
},
{
"code": null,
"e": 1575,
"s": 1475,
"text": "Note: To Know the given IP address is provided by which addressing, just run the following command:"
},
{
"code": null,
"e": 1588,
"s": 1575,
"text": "ipconfig/all"
},
{
"code": null,
"e": 1672,
"s": 1588,
"text": "Communication can be established properly if not getting response from DHCP Server."
},
{
"code": null,
"e": 1800,
"s": 1672,
"text": "APIPA regulates the service, by which always checking response and status of the main DHCP server in a specific period of time."
},
{
"code": null,
"e": 1932,
"s": 1800,
"text": "It can be used as a backup of DHCP because when DHCP stops working then APIPA has the ability to assign IP to the networking hosts."
},
{
"code": null,
"e": 1964,
"s": 1932,
"text": "It stops unwanted broadcasting."
},
{
"code": null,
"e": 2052,
"s": 1964,
"text": "It uses ARP(Address Resolution Protocol) to confirm the address isn’t currently in use."
},
{
"code": null,
"e": 2093,
"s": 2052,
"text": "APIPA ip addresses can slow you network."
},
{
"code": null,
"e": 2145,
"s": 2093,
"text": "APIPA doesnot provide network gateway as DHCP does."
},
{
"code": null,
"e": 2207,
"s": 2145,
"text": "APIPA addresses are restricted for use in local area network."
},
{
"code": null,
"e": 2276,
"s": 2207,
"text": "APIPA configured devices follow the peer to peer communication rule."
},
{
"code": null,
"e": 2283,
"s": 2276,
"text": "Picked"
},
{
"code": null,
"e": 2301,
"s": 2283,
"text": "Computer Networks"
},
{
"code": null,
"e": 2319,
"s": 2301,
"text": "Computer Networks"
}
]
|
Undecidability and Reducibility in TOC | 28 Jun, 2021
Decidable ProblemsA problem is decidable if we can construct a Turing machine which will halt in finite amount of time for every input and give answer as ‘yes’ or ‘no’. A decidable problem has an algorithm to determine the answer for a given input.
Examples
Equivalence of two regular languages: Given two regular languages, there is an algorithm and Turing machine to decide whether two regular languages are equal or not.
Finiteness of regular language: Given a regular language, there is an algorithm and Turing machine to decide whether regular language is finite or not.
Emptiness of context free language: Given a context free language, there is an algorithm whether CFL is empty or not.
Undecidable ProblemsA problem is undecidable if there is no Turing machine which will always halt in finite amount of time to give answer as ‘yes’ or ‘no’. An undecidable problem has no algorithm to determine the answer for a given input.
Examples
Ambiguity of context-free languages: Given a context-free language, there is no Turing machine which will always halt in finite amount of time and give answer whether language is ambiguous or not.
Equivalence of two context-free languages: Given two context-free languages, there is no Turing machine which will always halt in finite amount of time and give answer whether two context free languages are equal or not.
Everything or completeness of CFG: Given a CFG and input alphabet, whether CFG will generate all possible strings of input alphabet (∑*)is undecidable.
Regularity of CFL, CSL, REC and REC: Given a CFL, CSL, REC or REC, determining whether this language is regular is undecidable.
Note: Two popular undecidable problems are halting problem of TM and PCP (Post Correspondence Problem). Semi-decidable ProblemsA semi-decidable problem is subset of undecidable problems for which Turing machine will always halt in finite amount of time for answer as ‘yes’ and may or may not halt for answer as ‘no’.Relationship between semi-decidable and decidable problem has been shown in Figure 1 as:
Rice’s TheoremEvery non-trivial (answer is not known) problem on Recursive Enumerable languages is undecidable.e.g.; If a language is Recursive Enumerable, its complement will be recursive enumerable or not is undecidable.
Reducibility and UndecidabilityLanguage A is reducible to language B (represented as A≤B) if there exists a function f which will convert strings in A to strings in B as:
w ɛ A <=> f(w) ɛ B
Theorem 1: If A≤B and B is decidable then A is also decidable.Theorem 2: If A≤B and A is undecidable then B is also undecidable.
Question: Which of the following is/are undecidable?
G is a CFG. Is L(G)=ɸ? G is a CFG. Is L(G)=∑*?M is a Turing machine. Is L(M) regular? A is a DFA and N is an NFA. Is L(A)=L(N)?
G is a CFG. Is L(G)=ɸ?
G is a CFG. Is L(G)=∑*?
M is a Turing machine. Is L(M) regular?
A is a DFA and N is an NFA. Is L(A)=L(N)?
A. 3 onlyB. 3 and 4 onlyC. 1, 2 and 3 onlyD. 2 and 3 only
Explanation:
Option 1 is whether a CFG is empty or not, this problem is decidable.
Option 2 is whether a CFG will generate all possible strings (everything or completeness of CFG), this problem is undecidable.
Option 3 is whether language generated by TM is regular is undecidable.
Option 4 is whether language generated by DFA and NFA are same is decidable. So option D is correct.
Question: Which of the following problems are decidable?
Does a given program ever produce an output? If L is context free language then L’ is also context free? If L is regular language then L’ is also regular? If L is recursive language then L’ is also recursive?
Does a given program ever produce an output?
If L is context free language then L’ is also context free?
If L is regular language then L’ is also regular?
If L is recursive language then L’ is also recursive?
A. 1,2,3,4B. 1,2C. 2,3,4D. 3,4
Explanation:
As regular and recursive languages are closed under complementation, option 3 and 4 are decidable problems.
Context free languages are not closed under complementation, option 2 is undecidable.
Option 1 is also undecidable as there is no TM to determine whether a given program will produce an output. So, option D is correct.
Question: Consider three decision problems P1, P2 and P3. It is known that P1 is decidable and P2 is undecidable. Which one of the following is TRUE?
A. P3 is undecidable if P2 is reducible to P3B. P3 is decidable if P3 is reducible to P2’s complementC. P3 is undecidable if P3 is reducible to P2D. P3 is decidable if P1 is reducible to P3Explanation:
Option A says P2≤P3. According to theorem 2 discussed, if P2 is undecidable then P3 is undecidable. It is given that P2 is undecidable, so P3 will also be undecidable. So option (A) is correct.
Option C says P3≤P2. According to theorem 2 discussed, if P3 is undecidable then P2 is undecidable. But it is not given in question about undecidability of P3. So option (C) is not correct.
Option D says P1≤P3. According to theorem 1 discussed, if P3 is decidable then P1 is also decidable. But it is not given in question about decidability of P3. So option (D) is not correct.
Option (B) says P3≤P2’. According to theorem 2 discussed, if P3 is undecidable then P2’ is undecidable. But it is not given in question about undecidability of P3. So option (B) is not correct.
Quiz on Undecidability
This article is contributed by Sonal Tuteja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Bhumika_Rani
amritanshu7
fahadahmedkhan07
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
TCP/IP Model
Difference between DFA and NFA
Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)
Post Correspondence Problem
Church’s Thesis for Turing Machine
Variation of Turing Machine | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 305,
"s": 56,
"text": "Decidable ProblemsA problem is decidable if we can construct a Turing machine which will halt in finite amount of time for every input and give answer as ‘yes’ or ‘no’. A decidable problem has an algorithm to determine the answer for a given input."
},
{
"code": null,
"e": 314,
"s": 305,
"text": "Examples"
},
{
"code": null,
"e": 480,
"s": 314,
"text": "Equivalence of two regular languages: Given two regular languages, there is an algorithm and Turing machine to decide whether two regular languages are equal or not."
},
{
"code": null,
"e": 632,
"s": 480,
"text": "Finiteness of regular language: Given a regular language, there is an algorithm and Turing machine to decide whether regular language is finite or not."
},
{
"code": null,
"e": 750,
"s": 632,
"text": "Emptiness of context free language: Given a context free language, there is an algorithm whether CFL is empty or not."
},
{
"code": null,
"e": 989,
"s": 750,
"text": "Undecidable ProblemsA problem is undecidable if there is no Turing machine which will always halt in finite amount of time to give answer as ‘yes’ or ‘no’. An undecidable problem has no algorithm to determine the answer for a given input."
},
{
"code": null,
"e": 998,
"s": 989,
"text": "Examples"
},
{
"code": null,
"e": 1195,
"s": 998,
"text": "Ambiguity of context-free languages: Given a context-free language, there is no Turing machine which will always halt in finite amount of time and give answer whether language is ambiguous or not."
},
{
"code": null,
"e": 1416,
"s": 1195,
"text": "Equivalence of two context-free languages: Given two context-free languages, there is no Turing machine which will always halt in finite amount of time and give answer whether two context free languages are equal or not."
},
{
"code": null,
"e": 1568,
"s": 1416,
"text": "Everything or completeness of CFG: Given a CFG and input alphabet, whether CFG will generate all possible strings of input alphabet (∑*)is undecidable."
},
{
"code": null,
"e": 1696,
"s": 1568,
"text": "Regularity of CFL, CSL, REC and REC: Given a CFL, CSL, REC or REC, determining whether this language is regular is undecidable."
},
{
"code": null,
"e": 2101,
"s": 1696,
"text": "Note: Two popular undecidable problems are halting problem of TM and PCP (Post Correspondence Problem). Semi-decidable ProblemsA semi-decidable problem is subset of undecidable problems for which Turing machine will always halt in finite amount of time for answer as ‘yes’ and may or may not halt for answer as ‘no’.Relationship between semi-decidable and decidable problem has been shown in Figure 1 as:"
},
{
"code": null,
"e": 2324,
"s": 2101,
"text": "Rice’s TheoremEvery non-trivial (answer is not known) problem on Recursive Enumerable languages is undecidable.e.g.; If a language is Recursive Enumerable, its complement will be recursive enumerable or not is undecidable."
},
{
"code": null,
"e": 2495,
"s": 2324,
"text": "Reducibility and UndecidabilityLanguage A is reducible to language B (represented as A≤B) if there exists a function f which will convert strings in A to strings in B as:"
},
{
"code": null,
"e": 2514,
"s": 2495,
"text": "w ɛ A <=> f(w) ɛ B"
},
{
"code": null,
"e": 2643,
"s": 2514,
"text": "Theorem 1: If A≤B and B is decidable then A is also decidable.Theorem 2: If A≤B and A is undecidable then B is also undecidable."
},
{
"code": null,
"e": 2696,
"s": 2643,
"text": "Question: Which of the following is/are undecidable?"
},
{
"code": null,
"e": 2825,
"s": 2696,
"text": " G is a CFG. Is L(G)=ɸ? G is a CFG. Is L(G)=∑*?M is a Turing machine. Is L(M) regular? A is a DFA and N is an NFA. Is L(A)=L(N)?"
},
{
"code": null,
"e": 2849,
"s": 2825,
"text": " G is a CFG. Is L(G)=ɸ?"
},
{
"code": null,
"e": 2874,
"s": 2849,
"text": " G is a CFG. Is L(G)=∑*?"
},
{
"code": null,
"e": 2914,
"s": 2874,
"text": "M is a Turing machine. Is L(M) regular?"
},
{
"code": null,
"e": 2957,
"s": 2914,
"text": " A is a DFA and N is an NFA. Is L(A)=L(N)?"
},
{
"code": null,
"e": 3015,
"s": 2957,
"text": "A. 3 onlyB. 3 and 4 onlyC. 1, 2 and 3 onlyD. 2 and 3 only"
},
{
"code": null,
"e": 3028,
"s": 3015,
"text": "Explanation:"
},
{
"code": null,
"e": 3098,
"s": 3028,
"text": "Option 1 is whether a CFG is empty or not, this problem is decidable."
},
{
"code": null,
"e": 3225,
"s": 3098,
"text": "Option 2 is whether a CFG will generate all possible strings (everything or completeness of CFG), this problem is undecidable."
},
{
"code": null,
"e": 3297,
"s": 3225,
"text": "Option 3 is whether language generated by TM is regular is undecidable."
},
{
"code": null,
"e": 3398,
"s": 3297,
"text": "Option 4 is whether language generated by DFA and NFA are same is decidable. So option D is correct."
},
{
"code": null,
"e": 3455,
"s": 3398,
"text": "Question: Which of the following problems are decidable?"
},
{
"code": null,
"e": 3665,
"s": 3455,
"text": " Does a given program ever produce an output? If L is context free language then L’ is also context free? If L is regular language then L’ is also regular? If L is recursive language then L’ is also recursive?"
},
{
"code": null,
"e": 3711,
"s": 3665,
"text": " Does a given program ever produce an output?"
},
{
"code": null,
"e": 3772,
"s": 3711,
"text": " If L is context free language then L’ is also context free?"
},
{
"code": null,
"e": 3823,
"s": 3772,
"text": " If L is regular language then L’ is also regular?"
},
{
"code": null,
"e": 3878,
"s": 3823,
"text": " If L is recursive language then L’ is also recursive?"
},
{
"code": null,
"e": 3909,
"s": 3878,
"text": "A. 1,2,3,4B. 1,2C. 2,3,4D. 3,4"
},
{
"code": null,
"e": 3922,
"s": 3909,
"text": "Explanation:"
},
{
"code": null,
"e": 4030,
"s": 3922,
"text": "As regular and recursive languages are closed under complementation, option 3 and 4 are decidable problems."
},
{
"code": null,
"e": 4116,
"s": 4030,
"text": "Context free languages are not closed under complementation, option 2 is undecidable."
},
{
"code": null,
"e": 4249,
"s": 4116,
"text": "Option 1 is also undecidable as there is no TM to determine whether a given program will produce an output. So, option D is correct."
},
{
"code": null,
"e": 4399,
"s": 4249,
"text": "Question: Consider three decision problems P1, P2 and P3. It is known that P1 is decidable and P2 is undecidable. Which one of the following is TRUE?"
},
{
"code": null,
"e": 4601,
"s": 4399,
"text": "A. P3 is undecidable if P2 is reducible to P3B. P3 is decidable if P3 is reducible to P2’s complementC. P3 is undecidable if P3 is reducible to P2D. P3 is decidable if P1 is reducible to P3Explanation:"
},
{
"code": null,
"e": 4795,
"s": 4601,
"text": "Option A says P2≤P3. According to theorem 2 discussed, if P2 is undecidable then P3 is undecidable. It is given that P2 is undecidable, so P3 will also be undecidable. So option (A) is correct."
},
{
"code": null,
"e": 4985,
"s": 4795,
"text": "Option C says P3≤P2. According to theorem 2 discussed, if P3 is undecidable then P2 is undecidable. But it is not given in question about undecidability of P3. So option (C) is not correct."
},
{
"code": null,
"e": 5174,
"s": 4985,
"text": "Option D says P1≤P3. According to theorem 1 discussed, if P3 is decidable then P1 is also decidable. But it is not given in question about decidability of P3. So option (D) is not correct."
},
{
"code": null,
"e": 5368,
"s": 5174,
"text": "Option (B) says P3≤P2’. According to theorem 2 discussed, if P3 is undecidable then P2’ is undecidable. But it is not given in question about undecidability of P3. So option (B) is not correct."
},
{
"code": null,
"e": 5391,
"s": 5368,
"text": "Quiz on Undecidability"
},
{
"code": null,
"e": 5560,
"s": 5391,
"text": "This article is contributed by Sonal Tuteja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 5573,
"s": 5560,
"text": "Bhumika_Rani"
},
{
"code": null,
"e": 5585,
"s": 5573,
"text": "amritanshu7"
},
{
"code": null,
"e": 5602,
"s": 5585,
"text": "fahadahmedkhan07"
},
{
"code": null,
"e": 5610,
"s": 5602,
"text": "GATE CS"
},
{
"code": null,
"e": 5643,
"s": 5610,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 5741,
"s": 5643,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5761,
"s": 5741,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 5785,
"s": 5761,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 5812,
"s": 5785,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 5833,
"s": 5812,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 5846,
"s": 5833,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 5877,
"s": 5846,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 5957,
"s": 5877,
"text": "Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)"
},
{
"code": null,
"e": 5985,
"s": 5957,
"text": "Post Correspondence Problem"
},
{
"code": null,
"e": 6020,
"s": 5985,
"text": "Church’s Thesis for Turing Machine"
}
]
|
How To Visualize Machine Learning Results Like a Pro | by Edwin Tan | Towards Data Science | Evaluating machine learning models is a essential step in the Machine Learning workflow. In this article, we examine how to easily visualize various common machine learning metrics with Scikit-plot. While it’s name may suggest that it is only compatible with Scikit-learn models, Scikit-plot can be used for any machine learning framework. Under the hood, Scikit-plot uses matplotlib as its graphing library.
The best part of Scikit-plot is it only requires one line of code to visualize each metric.
Install package
pip install scikit-plot==0.3.7
Import necessary packages
import pandas as pdimport numpy as npfrom sklearn import datasetsfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifierfrom sklearn.model_selection import cross_val_predict, train_test_splitimport scikitplot as skplt
For the purpose of demonstrating Scikit-plot we will train a simple random forest and gradient boosting classifier with the breast cancer dataset.
X,y = datasets.load_breast_cancer(return_X_y = True)X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.3, stratify = y)gbc = GradientBoostingClassifier()gbc_model = gbc.fit(X_train, y_train)y_gbc_proba = gbc_model.predict_proba(X_test)y_gbc_pred = np.where(y_gbc_proba[:,1] > 0.5, 1, 0)rfc = RandomForestClassifier()rfc_model = rfc.fit(X_train, y_train)y_rfc_proba = rfc_model.predict_proba(X_test)y_rfc_pred = np.where(y_rfc_proba[:,1] > 0.5, 1, 0)
Lets take a look at how to use Scikit-plot for visualizing various metrics.
Confusion matrix compares the ground truth to the predicted label and classifies the results into True Positive, True Negative, False Positive and False Negative. To plot the confusion matrix, we simply call the plot_confusion_matrix method.
skplt.metrics.plot_confusion_matrix(y_test, y_gbc_pred, normalize=False, title = 'Confusion Matrix for GBC')
To display normalized values between 0 to 1 simply set normalize parameter to True
skplt.metrics.plot_confusion_matrix(y_test, y_gbc_pred, normalize=True, title = 'Confusion Matrix for GBC')
An ROC curve shows the performance (True Positive Rate aka Recall and False Positive Rate) of a classifier at all classification thresholds against a random baseline classifier.
skplt.metrics.plot_roc(y_test, y_gbc_proba, title = 'ROC Plot for GBC')
By default, ROC plot comes with macro and micro averages. We can hide these plot lines by setting the plot_micro or plot_macro parameters to False. plot_roc method displays all roc curves for all the classes and the chart might become cluttered in multi-class plots therefore we can choose to plot roc curves for specific classes by passing the classes_to_plot parameter.
A precision and recall curve shows precision and recall values at all classification thresholds. It summarizes the trade off between precision and recall.
skplt.metrics.plot_precision_recall(y_test, y_gbc_proba, title = 'PR Curve for GBC')
By default, precision recall curve comes with macro and micro averages. We can hide these plot lines by setting the plot_micro or plot_macro parameters to False. plot_precision_recall displays PR curves for all the classes and the chart might become cluttered in multi-class plots therefore we can choose to plot PR curves for specific classes by passing the classes_to_plot parameter.
Calibration plots also known as probability calibration curves is a diagnostic method to check if the predicted value can directly be interpreted as confidence level. For example, a well calibrated binary classifier should classify samples such that for samples with probability around 0.8, approximately 80% of them are from the positive class. This function only works for binary classification tasks.
probas_list = [y_gbc_proba, y_rfc_proba]clf_names = ['GBC', 'RF']skplt.metrics.plot_calibration_curve(y_test, probas_list = probas_list, clf_names = clf_names)
Cumulative gains curve shows the performance of a model and compares against a random baseline classifier. It shows the percentage of target achieved when considering a portion of the population with the highest probability. This function only work for binary classification.
skplt.metrics.plot_cumulative_gain(y_test, y_gbc_proba, title = 'Cumulative Gains Chart for GBC')
The lift curve shows the response rate for each class compared to a random baseline classifier when considering a portion of the population with the highest probability.
skplt.metrics.plot_lift_curve(y_test, y_gbc_proba, title = 'Lift Curve for GBC')
Scikit-plot allow users to adjust basic properties such as figure size, title font size and text font size using the figsize, title_fontsize and text_fontsize parameters respectively.
skplt.metrics.plot_lift_curve(y_test, y_gbc_proba, title = 'Lift Curve for GBC', figsize = (10,10), title_fontsize = 20, text_fontsize = 20)
In addition, the methods also accepts matplotlib.axes.Axes object through the ax parameter. This comes in useful as we can define the axis to be plotted on. For example, we would like to plot the cumulative gains chart and lift curve side-by-side on the same subplot. We can create a 1x2 subplot grid first and plot each of the chart in different grid within the subplot using the ax parameter.
fig, ax = plt.subplots(1,2)skplt.metrics.plot_cumulative_gain(y_test, y_gbc_proba, ax = ax[0], title = 'Cumulative Gains Chart for GBC')skplt.metrics.plot_lift_curve(y_test, y_gbc_proba, ax = ax[1], title = 'Lift Curve for GBC')plt.show()
The output for these methods are matplotlib.axes._subplots.AxesSubplot objects which we can further manipulate using matplotlib methods. For example, we can do the following to adjust the range of the vertical axis.
import matplotlib.pyplot as pltax = skplt.metrics.plot_lift_curve(y_test, y_gbc_proba, title = 'Lift Curve for GBC')ax.set_ylim(0,3)
We examined how to plot various common machine learning metrics using just one line of code each and how we can use matplotlib to adjust the chart properties to fit our needs. There are many more functions in Scikit-plot that we did not cover in this article such as plotting elbow and silhouette chart for clustering problems. Check out Scikit-plot documentations for more details. | [
{
"code": null,
"e": 581,
"s": 172,
"text": "Evaluating machine learning models is a essential step in the Machine Learning workflow. In this article, we examine how to easily visualize various common machine learning metrics with Scikit-plot. While it’s name may suggest that it is only compatible with Scikit-learn models, Scikit-plot can be used for any machine learning framework. Under the hood, Scikit-plot uses matplotlib as its graphing library."
},
{
"code": null,
"e": 673,
"s": 581,
"text": "The best part of Scikit-plot is it only requires one line of code to visualize each metric."
},
{
"code": null,
"e": 689,
"s": 673,
"text": "Install package"
},
{
"code": null,
"e": 720,
"s": 689,
"text": "pip install scikit-plot==0.3.7"
},
{
"code": null,
"e": 746,
"s": 720,
"text": "Import necessary packages"
},
{
"code": null,
"e": 988,
"s": 746,
"text": "import pandas as pdimport numpy as npfrom sklearn import datasetsfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifierfrom sklearn.model_selection import cross_val_predict, train_test_splitimport scikitplot as skplt"
},
{
"code": null,
"e": 1135,
"s": 988,
"text": "For the purpose of demonstrating Scikit-plot we will train a simple random forest and gradient boosting classifier with the breast cancer dataset."
},
{
"code": null,
"e": 1605,
"s": 1135,
"text": "X,y = datasets.load_breast_cancer(return_X_y = True)X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.3, stratify = y)gbc = GradientBoostingClassifier()gbc_model = gbc.fit(X_train, y_train)y_gbc_proba = gbc_model.predict_proba(X_test)y_gbc_pred = np.where(y_gbc_proba[:,1] > 0.5, 1, 0)rfc = RandomForestClassifier()rfc_model = rfc.fit(X_train, y_train)y_rfc_proba = rfc_model.predict_proba(X_test)y_rfc_pred = np.where(y_rfc_proba[:,1] > 0.5, 1, 0)"
},
{
"code": null,
"e": 1681,
"s": 1605,
"text": "Lets take a look at how to use Scikit-plot for visualizing various metrics."
},
{
"code": null,
"e": 1923,
"s": 1681,
"text": "Confusion matrix compares the ground truth to the predicted label and classifies the results into True Positive, True Negative, False Positive and False Negative. To plot the confusion matrix, we simply call the plot_confusion_matrix method."
},
{
"code": null,
"e": 2032,
"s": 1923,
"text": "skplt.metrics.plot_confusion_matrix(y_test, y_gbc_pred, normalize=False, title = 'Confusion Matrix for GBC')"
},
{
"code": null,
"e": 2115,
"s": 2032,
"text": "To display normalized values between 0 to 1 simply set normalize parameter to True"
},
{
"code": null,
"e": 2223,
"s": 2115,
"text": "skplt.metrics.plot_confusion_matrix(y_test, y_gbc_pred, normalize=True, title = 'Confusion Matrix for GBC')"
},
{
"code": null,
"e": 2401,
"s": 2223,
"text": "An ROC curve shows the performance (True Positive Rate aka Recall and False Positive Rate) of a classifier at all classification thresholds against a random baseline classifier."
},
{
"code": null,
"e": 2473,
"s": 2401,
"text": "skplt.metrics.plot_roc(y_test, y_gbc_proba, title = 'ROC Plot for GBC')"
},
{
"code": null,
"e": 2845,
"s": 2473,
"text": "By default, ROC plot comes with macro and micro averages. We can hide these plot lines by setting the plot_micro or plot_macro parameters to False. plot_roc method displays all roc curves for all the classes and the chart might become cluttered in multi-class plots therefore we can choose to plot roc curves for specific classes by passing the classes_to_plot parameter."
},
{
"code": null,
"e": 3000,
"s": 2845,
"text": "A precision and recall curve shows precision and recall values at all classification thresholds. It summarizes the trade off between precision and recall."
},
{
"code": null,
"e": 3085,
"s": 3000,
"text": "skplt.metrics.plot_precision_recall(y_test, y_gbc_proba, title = 'PR Curve for GBC')"
},
{
"code": null,
"e": 3471,
"s": 3085,
"text": "By default, precision recall curve comes with macro and micro averages. We can hide these plot lines by setting the plot_micro or plot_macro parameters to False. plot_precision_recall displays PR curves for all the classes and the chart might become cluttered in multi-class plots therefore we can choose to plot PR curves for specific classes by passing the classes_to_plot parameter."
},
{
"code": null,
"e": 3875,
"s": 3471,
"text": "Calibration plots also known as probability calibration curves is a diagnostic method to check if the predicted value can directly be interpreted as confidence level. For example, a well calibrated binary classifier should classify samples such that for samples with probability around 0.8, approximately 80% of them are from the positive class. This function only works for binary classification tasks."
},
{
"code": null,
"e": 4035,
"s": 3875,
"text": "probas_list = [y_gbc_proba, y_rfc_proba]clf_names = ['GBC', 'RF']skplt.metrics.plot_calibration_curve(y_test, probas_list = probas_list, clf_names = clf_names)"
},
{
"code": null,
"e": 4311,
"s": 4035,
"text": "Cumulative gains curve shows the performance of a model and compares against a random baseline classifier. It shows the percentage of target achieved when considering a portion of the population with the highest probability. This function only work for binary classification."
},
{
"code": null,
"e": 4409,
"s": 4311,
"text": "skplt.metrics.plot_cumulative_gain(y_test, y_gbc_proba, title = 'Cumulative Gains Chart for GBC')"
},
{
"code": null,
"e": 4579,
"s": 4409,
"text": "The lift curve shows the response rate for each class compared to a random baseline classifier when considering a portion of the population with the highest probability."
},
{
"code": null,
"e": 4660,
"s": 4579,
"text": "skplt.metrics.plot_lift_curve(y_test, y_gbc_proba, title = 'Lift Curve for GBC')"
},
{
"code": null,
"e": 4844,
"s": 4660,
"text": "Scikit-plot allow users to adjust basic properties such as figure size, title font size and text font size using the figsize, title_fontsize and text_fontsize parameters respectively."
},
{
"code": null,
"e": 4985,
"s": 4844,
"text": "skplt.metrics.plot_lift_curve(y_test, y_gbc_proba, title = 'Lift Curve for GBC', figsize = (10,10), title_fontsize = 20, text_fontsize = 20)"
},
{
"code": null,
"e": 5380,
"s": 4985,
"text": "In addition, the methods also accepts matplotlib.axes.Axes object through the ax parameter. This comes in useful as we can define the axis to be plotted on. For example, we would like to plot the cumulative gains chart and lift curve side-by-side on the same subplot. We can create a 1x2 subplot grid first and plot each of the chart in different grid within the subplot using the ax parameter."
},
{
"code": null,
"e": 5620,
"s": 5380,
"text": "fig, ax = plt.subplots(1,2)skplt.metrics.plot_cumulative_gain(y_test, y_gbc_proba, ax = ax[0], title = 'Cumulative Gains Chart for GBC')skplt.metrics.plot_lift_curve(y_test, y_gbc_proba, ax = ax[1], title = 'Lift Curve for GBC')plt.show()"
},
{
"code": null,
"e": 5836,
"s": 5620,
"text": "The output for these methods are matplotlib.axes._subplots.AxesSubplot objects which we can further manipulate using matplotlib methods. For example, we can do the following to adjust the range of the vertical axis."
},
{
"code": null,
"e": 5969,
"s": 5836,
"text": "import matplotlib.pyplot as pltax = skplt.metrics.plot_lift_curve(y_test, y_gbc_proba, title = 'Lift Curve for GBC')ax.set_ylim(0,3)"
}
]
|
Assembly - System Calls | System calls are APIs for the interface between the user space and the kernel space. We have already used the system calls. sys_write and sys_exit, for writing into the screen and exiting from the program, respectively.
You can make use of Linux system calls in your assembly programs. You need to take the following steps for using Linux system calls in your program −
Put the system call number in the EAX register.
Store the arguments to the system call in the registers EBX, ECX, etc.
Call the relevant interrupt (80h).
The result is usually returned in the EAX register.
There are six registers that store the arguments of the system call used. These are the EBX, ECX, EDX, ESI, EDI, and EBP. These registers take the consecutive arguments, starting with the EBX register. If there are more than six arguments, then the memory location of the first argument is stored in the EBX register.
The following code snippet shows the use of the system call sys_exit −
mov eax,1 ; system call number (sys_exit)
int 0x80 ; call kernel
The following code snippet shows the use of the system call sys_write −
mov edx,4 ; message length
mov ecx,msg ; message to write
mov ebx,1 ; file descriptor (stdout)
mov eax,4 ; system call number (sys_write)
int 0x80 ; call kernel
All the syscalls are listed in /usr/include/asm/unistd.h, together with their numbers (the value to put in EAX before you call int 80h).
The following table shows some of the system calls used in this tutorial −
The following example reads a number from the keyboard and displays it on the screen −
section .data ;Data segment
userMsg db 'Please enter a number: ' ;Ask the user to enter a number
lenUserMsg equ $-userMsg ;The length of the message
dispMsg db 'You have entered: '
lenDispMsg equ $-dispMsg
section .bss ;Uninitialized data
num resb 5
section .text ;Code Segment
global _start
_start: ;User prompt
mov eax, 4
mov ebx, 1
mov ecx, userMsg
mov edx, lenUserMsg
int 80h
;Read and store the user input
mov eax, 3
mov ebx, 2
mov ecx, num
mov edx, 5 ;5 bytes (numeric, 1 for sign) of that information
int 80h
;Output the message 'The entered number is: '
mov eax, 4
mov ebx, 1
mov ecx, dispMsg
mov edx, lenDispMsg
int 80h
;Output the number entered
mov eax, 4
mov ebx, 1
mov ecx, num
mov edx, 5
int 80h
; Exit code
mov eax, 1
mov ebx, 0
int 80h
When the above code is compiled and executed, it produces the following result −
Please enter a number:
1234
You have entered:1234
46 Lectures
2 hours
Frahaan Hussain
23 Lectures
12 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2305,
"s": 2085,
"text": "System calls are APIs for the interface between the user space and the kernel space. We have already used the system calls. sys_write and sys_exit, for writing into the screen and exiting from the program, respectively."
},
{
"code": null,
"e": 2455,
"s": 2305,
"text": "You can make use of Linux system calls in your assembly programs. You need to take the following steps for using Linux system calls in your program −"
},
{
"code": null,
"e": 2503,
"s": 2455,
"text": "Put the system call number in the EAX register."
},
{
"code": null,
"e": 2574,
"s": 2503,
"text": "Store the arguments to the system call in the registers EBX, ECX, etc."
},
{
"code": null,
"e": 2609,
"s": 2574,
"text": "Call the relevant interrupt (80h)."
},
{
"code": null,
"e": 2661,
"s": 2609,
"text": "The result is usually returned in the EAX register."
},
{
"code": null,
"e": 2979,
"s": 2661,
"text": "There are six registers that store the arguments of the system call used. These are the EBX, ECX, EDX, ESI, EDI, and EBP. These registers take the consecutive arguments, starting with the EBX register. If there are more than six arguments, then the memory location of the first argument is stored in the EBX register."
},
{
"code": null,
"e": 3050,
"s": 2979,
"text": "The following code snippet shows the use of the system call sys_exit −"
},
{
"code": null,
"e": 3117,
"s": 3050,
"text": "mov\teax,1\t\t; system call number (sys_exit)\nint\t0x80\t\t; call kernel"
},
{
"code": null,
"e": 3189,
"s": 3117,
"text": "The following code snippet shows the use of the system call sys_write −"
},
{
"code": null,
"e": 3355,
"s": 3189,
"text": "mov\tedx,4\t\t; message length\nmov\tecx,msg\t\t; message to write\nmov\tebx,1\t\t; file descriptor (stdout)\nmov\teax,4\t\t; system call number (sys_write)\nint\t0x80\t\t; call kernel"
},
{
"code": null,
"e": 3492,
"s": 3355,
"text": "All the syscalls are listed in /usr/include/asm/unistd.h, together with their numbers (the value to put in EAX before you call int 80h)."
},
{
"code": null,
"e": 3567,
"s": 3492,
"text": "The following table shows some of the system calls used in this tutorial −"
},
{
"code": null,
"e": 3654,
"s": 3567,
"text": "The following example reads a number from the keyboard and displays it on the screen −"
},
{
"code": null,
"e": 4623,
"s": 3654,
"text": "section .data ;Data segment\n userMsg db 'Please enter a number: ' ;Ask the user to enter a number\n lenUserMsg equ $-userMsg ;The length of the message\n dispMsg db 'You have entered: '\n lenDispMsg equ $-dispMsg \n\nsection .bss ;Uninitialized data\n num resb 5\n\t\nsection .text ;Code Segment\n global _start\n\t\n_start: ;User prompt\n mov eax, 4\n mov ebx, 1\n mov ecx, userMsg\n mov edx, lenUserMsg\n int 80h\n\n ;Read and store the user input\n mov eax, 3\n mov ebx, 2\n mov ecx, num \n mov edx, 5 ;5 bytes (numeric, 1 for sign) of that information\n int 80h\n\t\n ;Output the message 'The entered number is: '\n mov eax, 4\n mov ebx, 1\n mov ecx, dispMsg\n mov edx, lenDispMsg\n int 80h \n\n ;Output the number entered\n mov eax, 4\n mov ebx, 1\n mov ecx, num\n mov edx, 5\n int 80h \n \n ; Exit code\n mov eax, 1\n mov ebx, 0\n int 80h"
},
{
"code": null,
"e": 4704,
"s": 4623,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4757,
"s": 4704,
"text": "Please enter a number:\n1234 \nYou have entered:1234\n"
},
{
"code": null,
"e": 4790,
"s": 4757,
"text": "\n 46 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4807,
"s": 4790,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4841,
"s": 4807,
"text": "\n 23 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 4849,
"s": 4841,
"text": " Uplatz"
},
{
"code": null,
"e": 4856,
"s": 4849,
"text": " Print"
},
{
"code": null,
"e": 4867,
"s": 4856,
"text": " Add Notes"
}
]
|
Creating and Using Serializers - Django REST Framework - GeeksforGeeks | 10 Sep, 2021
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. The serializers in REST framework work very similarly to Django’s Form and ModelForm classes.
To check how to setup Django RESt Framework and create a API visit – How to Create a basic API using Django Rest Framework ?
To create a basic serializer one needs to import serializers class from rest_framework and define fields for a serializer just like creating a form or model in Django.
Example
Python3
# import serializer from rest_frameworkfrom rest_framework import serializers # create a serializerclass CommentSerializer(serializers.Serializer): # initialize fields email = serializers.EmailField() content = serializers.CharField(max_length = 200) created = serializers.DateTimeField()
This way one can declare serializer for any particular entity or object based on fields required. Serializers can be used to serialize as well as deserialize the data.
One can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class. Let’s create a Comment class first to create a object of type comment that can be understood by our serializer.
Python3
# import datetime objectfrom datetime import datetime # create a classclass Comment(object): def __init__(self, email, content, created = None): self.email = email self.content = content self.created = created or datetime.now()# create a objectcomment = Comment(email ='[email protected]', content ='foo bar')
Now that our object is ready, let’s try serializing this comment object. Run following command,
Python manage.py shell
Now run the following code
# import comment serializer
>>> from apis.serializers import CommentSerializer
# import datetime for date and time
>>> from datetime import datetime
# create a object
>>> class Comment(object):
... def __init__(self, email, content, created=None):
... self.email = email
... self.content = content
... self.created = created or datetime.now()
...
# create a comment object
>>> comment = Comment(email='[email protected]', content='foo bar')
# serialize the data
>>> serializer = CommentSerializer(comment)
# print serialized data
>>> serializer.data
Now let’s check output for this,
We can convert this data to JSON or XML format using Python’s inbuilt functions or rest framework’s parsers.
Python3
# import JSON Rendererfrom rest_framework.renderers import JSONRenderer # convert data to JSONjson = JSONRenderer().render(serializer.data)
Deserialization is similar to Serialization. It means to convert the data from JSON format to a given data type. First we parse a stream into Python native datatypes... (define which datatype to deserialize to....) First we need to convert this json data back to data that can be understood by the serializer for deserializing,
Python3
import iofrom rest_framework.parsers import JSONParser stream = io.BytesIO(json)data = JSONParser().parse(stream)
and Now let’s deserialize the data back to its original state
Python3
serializer = CommentSerializer(data = data)serializer.is_valid()# Trueserializer.validated_data
Let’s check output and if data has been deserialized –
ruhelaa48
simmytarika5
Django-REST
Python Django
rest-framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24330,
"s": 24302,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 24880,
"s": 24330,
"text": "In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. The serializers in REST framework work very similarly to Django’s Form and ModelForm classes. "
},
{
"code": null,
"e": 25006,
"s": 24880,
"text": "To check how to setup Django RESt Framework and create a API visit – How to Create a basic API using Django Rest Framework ? "
},
{
"code": null,
"e": 25175,
"s": 25006,
"text": "To create a basic serializer one needs to import serializers class from rest_framework and define fields for a serializer just like creating a form or model in Django. "
},
{
"code": null,
"e": 25184,
"s": 25175,
"text": "Example "
},
{
"code": null,
"e": 25192,
"s": 25184,
"text": "Python3"
},
{
"code": "# import serializer from rest_frameworkfrom rest_framework import serializers # create a serializerclass CommentSerializer(serializers.Serializer): # initialize fields email = serializers.EmailField() content = serializers.CharField(max_length = 200) created = serializers.DateTimeField()",
"e": 25493,
"s": 25192,
"text": null
},
{
"code": null,
"e": 25661,
"s": 25493,
"text": "This way one can declare serializer for any particular entity or object based on fields required. Serializers can be used to serialize as well as deserialize the data."
},
{
"code": null,
"e": 25925,
"s": 25661,
"text": "One can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class. Let’s create a Comment class first to create a object of type comment that can be understood by our serializer. "
},
{
"code": null,
"e": 25933,
"s": 25925,
"text": "Python3"
},
{
"code": "# import datetime objectfrom datetime import datetime # create a classclass Comment(object): def __init__(self, email, content, created = None): self.email = email self.content = content self.created = created or datetime.now()# create a objectcomment = Comment(email ='[email protected]', content ='foo bar')",
"e": 26267,
"s": 25933,
"text": null
},
{
"code": null,
"e": 26364,
"s": 26267,
"text": "Now that our object is ready, let’s try serializing this comment object. Run following command, "
},
{
"code": null,
"e": 26387,
"s": 26364,
"text": "Python manage.py shell"
},
{
"code": null,
"e": 26416,
"s": 26387,
"text": "Now run the following code "
},
{
"code": null,
"e": 27000,
"s": 26416,
"text": "# import comment serializer\n>>> from apis.serializers import CommentSerializer\n\n# import datetime for date and time\n>>> from datetime import datetime\n\n# create a object\n>>> class Comment(object):\n... def __init__(self, email, content, created=None):\n... self.email = email\n... self.content = content\n... self.created = created or datetime.now()\n... \n\n# create a comment object\n>>> comment = Comment(email='[email protected]', content='foo bar')\n\n# serialize the data\n>>> serializer = CommentSerializer(comment)\n\n# print serialized data\n>>> serializer.data"
},
{
"code": null,
"e": 27034,
"s": 27000,
"text": "Now let’s check output for this, "
},
{
"code": null,
"e": 27144,
"s": 27034,
"text": "We can convert this data to JSON or XML format using Python’s inbuilt functions or rest framework’s parsers. "
},
{
"code": null,
"e": 27152,
"s": 27144,
"text": "Python3"
},
{
"code": "# import JSON Rendererfrom rest_framework.renderers import JSONRenderer # convert data to JSONjson = JSONRenderer().render(serializer.data)",
"e": 27292,
"s": 27152,
"text": null
},
{
"code": null,
"e": 27621,
"s": 27292,
"text": "Deserialization is similar to Serialization. It means to convert the data from JSON format to a given data type. First we parse a stream into Python native datatypes... (define which datatype to deserialize to....) First we need to convert this json data back to data that can be understood by the serializer for deserializing, "
},
{
"code": null,
"e": 27629,
"s": 27621,
"text": "Python3"
},
{
"code": "import iofrom rest_framework.parsers import JSONParser stream = io.BytesIO(json)data = JSONParser().parse(stream)",
"e": 27743,
"s": 27629,
"text": null
},
{
"code": null,
"e": 27805,
"s": 27743,
"text": "and Now let’s deserialize the data back to its original state"
},
{
"code": null,
"e": 27813,
"s": 27805,
"text": "Python3"
},
{
"code": "serializer = CommentSerializer(data = data)serializer.is_valid()# Trueserializer.validated_data",
"e": 27909,
"s": 27813,
"text": null
},
{
"code": null,
"e": 27965,
"s": 27909,
"text": "Let’s check output and if data has been deserialized – "
},
{
"code": null,
"e": 27977,
"s": 27967,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27990,
"s": 27977,
"text": "simmytarika5"
},
{
"code": null,
"e": 28002,
"s": 27990,
"text": "Django-REST"
},
{
"code": null,
"e": 28016,
"s": 28002,
"text": "Python Django"
},
{
"code": null,
"e": 28031,
"s": 28016,
"text": "rest-framework"
},
{
"code": null,
"e": 28038,
"s": 28031,
"text": "Python"
},
{
"code": null,
"e": 28136,
"s": 28038,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28145,
"s": 28136,
"text": "Comments"
},
{
"code": null,
"e": 28158,
"s": 28145,
"text": "Old Comments"
},
{
"code": null,
"e": 28176,
"s": 28158,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28208,
"s": 28176,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28243,
"s": 28208,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28265,
"s": 28243,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28295,
"s": 28265,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28337,
"s": 28295,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28380,
"s": 28337,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28417,
"s": 28380,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28443,
"s": 28417,
"text": "Python String | replace()"
}
]
|
Binary Search program in JavaScript | Create a function, say binarySearch() that takes in 4 arguments −
a sorted Number / String literal array
starting index of array (0)
ending index of array (length - 1)
number to be searched
If the number exists in the array, then the index of the number should be returned, otherwise -1
should be returned. Here is the full code −
const arr = [2,4,6,6,8,8,9,10,13,15,17,21,24,26,28,36,58,78,90];
//binary search function
//returns the element index if found otherwise -1
const binarySearch = (arr, start, end, num) => {
const mid = start + Math.floor((end - start)/2);
if(start <= end){
if(arr[mid] === num){
return mid;
}
if(num < arr[mid]){
return binarySearch(arr, start, mid-1, num);
}
if(num > arr[mid]){
return binarySearch(arr, mid+1, end, num);
}
}
return -1;
};
console.log(binarySearch(arr, 0, arr.length-1, 13));
console.log(binarySearch(arr, 0, arr.length-1, 11));
The output of this code in the console will be −
8
-1 | [
{
"code": null,
"e": 1128,
"s": 1062,
"text": "Create a function, say binarySearch() that takes in 4 arguments −"
},
{
"code": null,
"e": 1167,
"s": 1128,
"text": "a sorted Number / String literal array"
},
{
"code": null,
"e": 1195,
"s": 1167,
"text": "starting index of array (0)"
},
{
"code": null,
"e": 1230,
"s": 1195,
"text": "ending index of array (length - 1)"
},
{
"code": null,
"e": 1252,
"s": 1230,
"text": "number to be searched"
},
{
"code": null,
"e": 1393,
"s": 1252,
"text": "If the number exists in the array, then the index of the number should be returned, otherwise -1\nshould be returned. Here is the full code −"
},
{
"code": null,
"e": 2014,
"s": 1393,
"text": "const arr = [2,4,6,6,8,8,9,10,13,15,17,21,24,26,28,36,58,78,90];\n//binary search function\n//returns the element index if found otherwise -1\nconst binarySearch = (arr, start, end, num) => {\n const mid = start + Math.floor((end - start)/2);\n if(start <= end){\n if(arr[mid] === num){\n return mid;\n }\n if(num < arr[mid]){\n return binarySearch(arr, start, mid-1, num);\n }\n if(num > arr[mid]){\n return binarySearch(arr, mid+1, end, num);\n }\n }\n return -1;\n};\nconsole.log(binarySearch(arr, 0, arr.length-1, 13));\nconsole.log(binarySearch(arr, 0, arr.length-1, 11));"
},
{
"code": null,
"e": 2063,
"s": 2014,
"text": "The output of this code in the console will be −"
},
{
"code": null,
"e": 2068,
"s": 2063,
"text": "8\n-1"
}
]
|
How to Use and Create a Z-Table (Standard Normal Table) | by Michael Galarnyk | Towards Data Science | To be able to utilize a z-table and answer these questions, you have to turn the scores on the different tests into a standard normal distribution N(mean = 0, std = 1). Since these scores on these tests have a normal distribution, we can convert both of them into standard normal distributions by using the following formula.
With this formula, you can calculate z-scores for Zoe and Mike.
Since Zoe has a higher z-score than Mike, Zoe performed better on her test.
While we know that Zoe performed better, a z-table can tell you in what percentile the test takers are in. The following parital z-table (I cut it off so it wouldn’t take up too much space) can tell you the area underneath the curve to the left of our z-score. This is the probability.
Zoe (z-score = 1.25)
To use the z-score table, start on the left side of the table go down to 1.2. At the top of the table, go to 0.05 (this corresponds to the value of 1.2 + .05 = 1.25). The value in the table is .8944 which is the probability. Roughly 89.44% of people scored worse than her on the ACT.
Mike (z-score = 1.0)
To use the z-score table, start on the left side of the table go down to 1.0 and now at the top of the table, go to 0.00 (this corresponds to the value of 1.0 + .00 = 1.00). The value in the table is .8413 which is the probability. Roughly 84.13% of people scored worse than him on the SAT.
It is important to keep in mind that if you have a negative z-score, you can simply use a table that contains negative z-scores.
This section will answer where the values in the z table come from by going through the process of creating a z-score table. Please do not worry if you do not understand this section, it is not important if you just want to know how to use a z-score table.
This part of the post is very similar to the 68–95–99.7 rule article, but adapted for creating a z table. To be able to understand where the values come from, it is important to know about the probability density function (PDF). A PDF is used to specify the probability of the random variable falling within a particular range of values, as opposed to taking on any one value. This probability is given by the integral of this variable’s PDF over that range — that is, it is given by the area under the density function but above the horizontal axis and between the lowest and greatest values of the range. This definition might not make much sense so let’s clear it up by graphing the probability density function for a normal distribution. The equation below is the probability density function for a normal distribution
Let’s simplify it by assuming we have a mean (μ) of 0 and a standard deviation (σ) of 1 (standard normal distribution).
This can be graphed using anything, but I choose to graph it using Python.
# Import all libraries for this portion of the blog postfrom scipy.integrate import quadimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd%matplotlib inlinex = np.linspace(-4, 4, num = 100)constant = 1.0 / np.sqrt(2*np.pi)pdf_normal_distribution = constant * np.exp((-x**2) / 2.0)fig, ax = plt.subplots(figsize=(10, 5));ax.plot(x, pdf_normal_distribution);ax.set_ylim(0);ax.set_title('Normal Distribution', size = 20);ax.set_ylabel('Probability Density', size = 20);
The graph above does not show you the probability of events but their probability density. To get the probability of an event within a given range you need to integrate.
Recall that the standard normal table entries are the area under the standard normal curve to the left of z (between negative infinity and z).
To find the area, you need to integrate. Integrating the PDF, gives you the cumulative distribution function (CDF) which is a function that maps values to their percentile rank in a distribution. The values in the table are calculated using the cumulative distribution function of a standard normal distribution with a mean of zero and a standard deviation of one. This can be denoted with the equation below.
This is not an easy integral to calculate by hand so I am going to use Python to calculate it. The code below calculates the probability for Zoe who had a z-score of 1.25 and Mike who had a z-score of 1.00.
def normalProbabilityDensity(x): constant = 1.0 / np.sqrt(2*np.pi) return(constant * np.exp((-x**2) / 2.0) )zoe_percentile, _ = quad(normalProbabilityDensity, np.NINF, 1.25)mike_percentile, _ = quad(normalProbabilityDensity, np.NINF, 1.00)print('Zoe: ', zoe_percentile)print('Mike: ', mike_percentile)
As the code below shows, these calculations can be done to create a z table.
One important point to emphasize is that calculating this table from scratch when needed is inefficient so we usually resort to using a standard normal table from a textbook or online source.
I hope you enjoyed this tutorial. The code used in this tutorial is located on my github. If you any questions or thoughts on the tutorial, feel free to reach out in the comments below or through Twitter. If you want to learn how to utilize the Pandas, Matplotlib, or Seaborn libraries, please consider taking my Python for Data Visualization LinkedIn Learning course. | [
{
"code": null,
"e": 498,
"s": 172,
"text": "To be able to utilize a z-table and answer these questions, you have to turn the scores on the different tests into a standard normal distribution N(mean = 0, std = 1). Since these scores on these tests have a normal distribution, we can convert both of them into standard normal distributions by using the following formula."
},
{
"code": null,
"e": 562,
"s": 498,
"text": "With this formula, you can calculate z-scores for Zoe and Mike."
},
{
"code": null,
"e": 638,
"s": 562,
"text": "Since Zoe has a higher z-score than Mike, Zoe performed better on her test."
},
{
"code": null,
"e": 924,
"s": 638,
"text": "While we know that Zoe performed better, a z-table can tell you in what percentile the test takers are in. The following parital z-table (I cut it off so it wouldn’t take up too much space) can tell you the area underneath the curve to the left of our z-score. This is the probability."
},
{
"code": null,
"e": 945,
"s": 924,
"text": "Zoe (z-score = 1.25)"
},
{
"code": null,
"e": 1229,
"s": 945,
"text": "To use the z-score table, start on the left side of the table go down to 1.2. At the top of the table, go to 0.05 (this corresponds to the value of 1.2 + .05 = 1.25). The value in the table is .8944 which is the probability. Roughly 89.44% of people scored worse than her on the ACT."
},
{
"code": null,
"e": 1250,
"s": 1229,
"text": "Mike (z-score = 1.0)"
},
{
"code": null,
"e": 1541,
"s": 1250,
"text": "To use the z-score table, start on the left side of the table go down to 1.0 and now at the top of the table, go to 0.00 (this corresponds to the value of 1.0 + .00 = 1.00). The value in the table is .8413 which is the probability. Roughly 84.13% of people scored worse than him on the SAT."
},
{
"code": null,
"e": 1670,
"s": 1541,
"text": "It is important to keep in mind that if you have a negative z-score, you can simply use a table that contains negative z-scores."
},
{
"code": null,
"e": 1927,
"s": 1670,
"text": "This section will answer where the values in the z table come from by going through the process of creating a z-score table. Please do not worry if you do not understand this section, it is not important if you just want to know how to use a z-score table."
},
{
"code": null,
"e": 2750,
"s": 1927,
"text": "This part of the post is very similar to the 68–95–99.7 rule article, but adapted for creating a z table. To be able to understand where the values come from, it is important to know about the probability density function (PDF). A PDF is used to specify the probability of the random variable falling within a particular range of values, as opposed to taking on any one value. This probability is given by the integral of this variable’s PDF over that range — that is, it is given by the area under the density function but above the horizontal axis and between the lowest and greatest values of the range. This definition might not make much sense so let’s clear it up by graphing the probability density function for a normal distribution. The equation below is the probability density function for a normal distribution"
},
{
"code": null,
"e": 2870,
"s": 2750,
"text": "Let’s simplify it by assuming we have a mean (μ) of 0 and a standard deviation (σ) of 1 (standard normal distribution)."
},
{
"code": null,
"e": 2945,
"s": 2870,
"text": "This can be graphed using anything, but I choose to graph it using Python."
},
{
"code": null,
"e": 3430,
"s": 2945,
"text": "# Import all libraries for this portion of the blog postfrom scipy.integrate import quadimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd%matplotlib inlinex = np.linspace(-4, 4, num = 100)constant = 1.0 / np.sqrt(2*np.pi)pdf_normal_distribution = constant * np.exp((-x**2) / 2.0)fig, ax = plt.subplots(figsize=(10, 5));ax.plot(x, pdf_normal_distribution);ax.set_ylim(0);ax.set_title('Normal Distribution', size = 20);ax.set_ylabel('Probability Density', size = 20);"
},
{
"code": null,
"e": 3600,
"s": 3430,
"text": "The graph above does not show you the probability of events but their probability density. To get the probability of an event within a given range you need to integrate."
},
{
"code": null,
"e": 3743,
"s": 3600,
"text": "Recall that the standard normal table entries are the area under the standard normal curve to the left of z (between negative infinity and z)."
},
{
"code": null,
"e": 4153,
"s": 3743,
"text": "To find the area, you need to integrate. Integrating the PDF, gives you the cumulative distribution function (CDF) which is a function that maps values to their percentile rank in a distribution. The values in the table are calculated using the cumulative distribution function of a standard normal distribution with a mean of zero and a standard deviation of one. This can be denoted with the equation below."
},
{
"code": null,
"e": 4360,
"s": 4153,
"text": "This is not an easy integral to calculate by hand so I am going to use Python to calculate it. The code below calculates the probability for Zoe who had a z-score of 1.25 and Mike who had a z-score of 1.00."
},
{
"code": null,
"e": 4668,
"s": 4360,
"text": "def normalProbabilityDensity(x): constant = 1.0 / np.sqrt(2*np.pi) return(constant * np.exp((-x**2) / 2.0) )zoe_percentile, _ = quad(normalProbabilityDensity, np.NINF, 1.25)mike_percentile, _ = quad(normalProbabilityDensity, np.NINF, 1.00)print('Zoe: ', zoe_percentile)print('Mike: ', mike_percentile)"
},
{
"code": null,
"e": 4745,
"s": 4668,
"text": "As the code below shows, these calculations can be done to create a z table."
},
{
"code": null,
"e": 4937,
"s": 4745,
"text": "One important point to emphasize is that calculating this table from scratch when needed is inefficient so we usually resort to using a standard normal table from a textbook or online source."
}
]
|
A short tutorial on Fuzzy Time Series — Part III | by Petrônio Silva | Towards Data Science | Hi folks! It was a long time since I published the first and second parts of this tutorial. Meanwhile I had the opportunity to talk with many people that applied FTS methods on several distinct fields, and they helped me to improve pyFTS library by fixing some bugs and expanding its features and usability.
We have been dealing with uncertainty since the beginning of this tutorial. We found ways to model and describe the temporal behavior of the time series using fuzzy sets, but we did not take into account the uncertainty of our forecasts. The forecasting uncertainty is like a fog: if you are looking closer you will see blurred and it may not affect you too much, but if you want to look more ahead...
So, once again it is time to go deeper and explore more forecasting types and also new methods, this time I will focus on non-stationary time series, concept drifts, etc.
All examples of this tutorial are available on Google Colab, on http://bit.ly/short_tutorial_colab3 . Feel free to get in touch, give feedback and ask questions. Now, let’s move!
The greatest majority of the forecasting methods produce point forecasts, i.e., a single scalar forecast. Given a numeric time series Y and its individual values y(t) ∈ Y, a point forecast is usually a conditional expectation ŷ(t+1) = E[Y |y(t), ...]. This number represents the best guess for Y at time t+1 given what we know about Y, its past values t, t-1, ... Regardless how good our estimator is, it is still a guess and not an exact certain value. In other words, behind that number there is uncertainty hidden in it.
The problem with the point forecasting is exactly this: it does not inform the uncertainty around it. A good starting point is the conditional variance Var[ y(t+1) | y(t) ], but it is not usually informed or even known.
There are ways to deal with this limitation of the point forecasts, and they are the interval and probabilistic forecasts.
A prediction interval I is a tuple I = [u, l], where u is the upper uncertainty bound and l is the lower uncertainty bound, asserting that the estimate will probably fall inside this range, ŷ(t+1) ∈ [u, l].
A confidence interval is a value σ associated with a confidence level α ∈ [0,1], where ŷ(t+1) ∈ [ ŷ(t+1)-σ, ŷ(t+1)+σ] with a probability α. The confidence intervals are usually parametric, i.e., they assume that the uncertainty around the predicted value ŷ(t+1) is described by a Gaussian pdf.
There are several ways to measure the accuracy of an interval forecast and the simplest one is the coverage (that indicates the percentage of true values that fell inside the interval), calibration, sharpness, etc. The Winkler Score is known to embody several aspects of the intervals in one measure
S(α,x,I) = (u−l) +2α(l−x)1(x< l) +2α(x−u)1(x>u)
Where I = [u, l], x is the true value, α is the confidence level and 1(condition) = {1 if condition is true, 0 otherwise }.
A probabilistic forecast is a probability distribution P: U →[0, 1], where U is the Universe of Discourse of Y, constrained to ∑P(x) = 1, ∀x ∈ U. It means that we will estimate, for each possible value x of U, a probability π that ŷ(t+1) = x, or in other words: P(ŷ(t+1) = x) = π, 0 ≤ π ≤1 This is the most complete way to represent the uncertainty of a forecast, and give to us the landscape of the possible values that ŷ(t+1) can assume with its degrees of probability.
With the probability distribution P we also can calculate α confidence intervals (using α and 1-α quantiles of the cumulative distribution F) and produce a point forecast using the expected value E[P] = ∑xP(x), ∀x ∈ U.
The main accuracy measure for probabilistic forecasts is the Continuous Rank Probability Score (CRPS). In simple terms, the CRPS measures the area of the forecast probability curve before and after the true value x. This measurement informs how close to the true value the probability distribution was. The CRPS is a generalization of MAE to the case of probabilistic forecasts, then lower values of CRPS are better.
CRPS(F, x) = ∫ (F(y) -1(y>x))2 dy , y = -∞ ..+∞
Where F(x) = P(X ≤ x) is the cumulative distribution function and x is the true value.
First of all, on pyFTS library every model has boolean flags indicating which type of forecasting it is able to make. All models are point forecasting-enabled but not all of them are interval and probabilistic enabled. If you try to use one of these kinds of forecasting on a model without this skill an exception will be raised.
if model.has_interval_forecasting: forecasts = model.predict(data, type=’interval’)
To generate interval forecasts in pyFTS you use the same method for the scalar forecasts — the method predict in the FTS class — and inform the parameter type=’interval’. The interval forecasting type on predict method generates a list of tuples, each tuple with two values corresponding to a prediction interval I = [u, l]. Some models (such as EnsembleFTS and PWFTS) allow the specification of the method of interval.
ifts.IntervalFTS (IFTS): The most basic method for generating prediction intervals, it is an extension of the HighOrderFTS. The generated prediction intervals do not have some probabilistic mean, they just measure the upper and lower bounds of the fuzzy sets that were involved on forecasting process, i.e., the fuzzy uncertainty. The method is described here.
ensemble.AllMethodEnsembleFTS: The EnsembleFTS is a meta model composed by several base models. The AllMethodEnsembleFTS creates one instance of each monovariate FTS method implemented in pyFTS and set them as its base models. The forecasting is computed from the forecasts of the base models. A brief description of the method can be found here. There is basically two ways to compute prediction intervals in EnsembleFTS: extremum and quantile (default). In extremum method the maximum and minimum values between the forecasts of the base models are chosen. On quantile method the alpha parameter must be informed and then the forecasts of the base models will be ordered and the quantile interval will be extracted.
from pyFTS.models.ensemble import ensemblepart = Grid.GridPartitioner(data=train, npart=11)model = ensemble.AllMethodEnsembleFTS(partitioner=part)forecasts = model.predict(test, type='interval', mode='extremum')forecasts2 = model.predict(test, type='interval', mode='quantile', alpha=.1)
pwfts.ProbabilisticWeightedFTS (PWFTS): As its name says, this is the most complex method and still under review (on its way to be published). There is basically two ways to produce prediction intervals on PWFTS: heuristic (default) and quantile. In the heuristic method the interval bounds are calculated as the expected value of the fuzzy sets bounds and its empirical probabilities and the quantile method generates a full probability distribution and then extracts the quantiles (using the alpha parameter).
forecasts1 = model.predict(test, type='interval', method='heuristic')forecasts2 = model.predict(test, type='interval', method='quantile', alpha=.05)
multivariate.mvfts.MVFTS: This multivariate method uses the same approach of IFTS to produce prediction intervals.
multivariate.wmvfts.WeightedMVFTS: This weighted multivariate method uses the same approach of IFTS to produce prediction intervals.
In the module pyFTS.common.Util we can find the function plot_interval which allows us to easily draw the intervals:
The generated intervals try to demonstrate the range of possible variations that the model takes into account. You can see that some models generate wider intervals than others and sometimes (especially on the weighted models that have the thinner intervals) the original values fall outside the interval. The best intervals have balanced widths, neither too wide to show high uncertainty and neither too thin to not cover the real values.
To generate probabilistic forecasts in pyFTS you also use the method predict in the FTS class and inform the parameter type=’distribution’. The predict method will return a list of ProbabilityDistribution objects. Also, like the intervals the probabilistic forecasting has its own boolean flag to indicate which models are enabled to perform it:
if model.has_probabilistic_forecasting: distributions = model.predict(test, type='distribution')
In contrast to interval forecasting, the probabilistic forecasting has its own class to represent a probability distribution — the class pyFTS.probability.ProbabilityDistribution. There are several ways to represent this probability distribution that is, by definition, a discrete probability distribution. Some methods of this class have especial interest for us now: density (returns the probability of the input value(s)), cumulative (returns the cumulative probability of the input value(s)), quantile (returns the quantile value of the input value(s)) and plot (plots the probability distribution on the input matplotlib axis).
Now let’s take a look on some probabilistic forecasting enabled methods on pyFTS:
pwfts.ProbabilisticWeightedFTS (PWFTS): This method was entirely designed for probabilistic forecasting and is the best method for this on pyFTS. Its rules contains empirical probabilities associated with the fuzzy sets and also present a specific defuzzyfication rule that transforms an input (crisp) value on a probability distribution to the future value;
ensemble.EnsembleFTS: The before mentioned ensemble creates probabilistic forecastings using Kernel Density Estimators (KDE) over the point forecasts of the base models. The KDE also requires the specification of the kernel function and the width parameter.
Let’s see how the probability forecasting looks like:
In above pictures the probabilistic forecasting is shown in two different perspectives. The first picture is generated with the method plot_density in the module common.Util, where each probability distribution is plotted as a shade of blue and its intensity corresponds to the probability. This method allows to plot the original time series and the forecast probability distributions on top of it. The second picture shows each probability distribution individually in relation to the universe of discourse using the method plot of the class ProbabilityDistribution.
Of course it is not everything! We have to consider the interval and probabilistic forecasting for many steps ahead, which we expect to tell us how the uncertainty evolve as the prediction horizon increases. Yes! It is fascinating but I still have many things to show, so I will let it as an exercise for you, ok?
Let’s walk now on a trickiest road...
You may remember that old and universally known quote:
“the only certainty is that nothing is certain”.
Yes. Forecasting may be unfair because things change all the time and we have to deal with it. Stationarity means, in layman terms, that the statistical properties of a stochastic process (like their expected value and variance) do not change along the time, whose the ultimate mean is stability. This is awesome for the forecasting models: the test data set will behave exactly as the train data set!
In other hand, the non-stationarity means that the statistical properties change. But not all non-stationarities are created equal. Some of them are predictable as trend and seasonality. Dealing with seasonality is not tricky, you can use High Order, Seasonal or Multivariate methods (you may remember our last tutorial). To deal with trends it is not too complicated either, you can de-trend the data using a difference transformation.
Suppose that we split the above time series in half, and call these subsets training and testing data. You can see that the test subset (after the instance number 2000) have values that did not appear before, in the train subset. This is a drawback for most FTS methods: what happens when the input data fall outside the known Universe of Discourse? The model never saw that region before and doesn’t know how to proceed, than it fails tragically. You can also see on the above image that the differentiated time series is much more well behaved and, indeed, it is stationary.
How can we use the Difference transformation on pyFTS? Just import the Transformations module from pyFTS.common and instantiate it. Don’t forget to inform the transformation to the partitioning method and also add it to the model (with the method append_transformation).
from pyFTS.data import NASDAQfrom pyFTS.models import chenfrom pyFTS.partitioners import Gridfrom pyFTS.common import Transformationsdiff = Transformations.Differential(1)train = data[:2000]test = data[2000:]part = Grid.GridPartitioner(data=train, npart=15, transformation=diff)model = chen.ConventionalFTS(partitioner=part)model.append_transformation(diff)model.fit(train)forecasts = model.predict(test)
Look the behavior of the classical Chen’s model with and without the Differential transformation for the NASDAQ dataset:
While the time series is still fluctuating inside the known Universe of Discourse both models performed well. But when the time series jumped out the Universe of Discourse of the training data, the model without the Differentiate transformation started to deteriorate because it does not know what to do with that unknown data.
Then the transformations help us not only with trending patterns, but also with the unknown ranges of the universe of discourse.
But some non-stationarities are unpredictable, and sometimes they are painful to deal with.
Concept drifts are unforeseen changes (on mean, variance or both) which can happen gradually or suddenly. Some times these drifts occur in cycles (with irregular periods) and, in other scenario, the drift is temporary. There are some questions to answer when a concept drifts happen: Is it temporary? Is the change finished (established) or it will keep changing?
We have also to make the distinction between concept-drift and outlier (or a blip). Outliers are not change, they belong to the known signal but are rare events.
Concept drifts are nightmares — not only FTS methods, other computational intelligence and statistical techniques fear them too — but we need to learn how to live together them. Despite the complexity of the problem there are some simple (somehow expensive unfortunately) techniques to tackle them.
Time Variant Methods
All FTS methods we saw before are time invariant methods, which means that they assume that the future fluctuations of the time series will behave according to patterns already happened before. In other words: the behavior of the time series, which was described by the fuzzy temporal rules of the model, will not change in the future.
This is works fine for many time series (for example the environmental seasonal time series like we studied before) but fails terribly in others (for instance the stock exchange asset prices).
In that cases we need to apply time variant models,
incremental.TimeVariant.Retrainer: The Time Variant model is the simplest (but efficient) approach to tackle concept drifts and non stationarity. This class implement a metamodel, what means that you can choose any FTS method to be its base method, then at each batch_size inputs the metamodel retrain its internal model with the last window_length inputs. These are the main parameters of the model: the window_length and the batch_size. As an meta model you can also specify which FTS method to use (the fts_method parameter) and which partitioner you want to use inside him (the partitioner_method and partitioner_params parameters).
from pyFTS.models.incremental import TimeVariantmodel = TimeVariant.Retrainer( partitioner_method=Grid.GridPartitioner, partitioner_params={'npart': 35}, fts_method=hofts.WeightedHighOrderFTS, fts_params={}, order=2 , batch_size=50, window_length=200)
incremental.IncrementalEnsembleFTS: Works similarly to the TimeVariant but in a EnsembleFTS approach. In TimeVariant there is only one internal model that is recreated after n inputs (which means that the batch_size is the unique memory it has). On IncrementalEnsemble we also have the window_length and the batch_size parameters but also the num_models that says how many internal models to hold. As soon new models are created (with the incoming data) the older ones are dropped from the ensemble.
from pyFTS.models.incremental import IncrementalEnsemblemodel = IncrementalEnsemble.IncrementalEnsembleFTS( partitioner_method=Grid.GridPartitioner, partitioner_params={'npart': 35}, fts_method=hofts.WeightedHighOrderFTS, fts_params={}, order=2 , batch_size=50, window_length=200, num_models=3)
nonstationary.nsfts.NonStationaryFTS (NSFTS): The non-stationary fuzzy sets are fuzzy sets that can be modified along the time, allowing them to adapt to changes in the data by translating and/or scaling its parameters. The NSFTS method is very similitar to time invariant FTS methods, with the exception that their fuzzy sets are not static: for each forecast performed by an NSFTS model the error is calculated and stored and the fuzzy sets are changed to fix that error. For this method, the error is a measure of how much the test data is different from the train data. This method is on this way to be published.
from pyFTS.models.nonstationary import partitioners as nspartfrom pyFTS.models.nonstationary import nsftspart = nspart.simplenonstationary_gridpartitioner_builder( data=train, npart=35, transformation=None)model3 = nsfts.NonStationaryFTS(partitioner=part)
The pyFTS.data module contains a lot of non-stationary and concept drifted time series as NASDAQ, TAIEX, S&P 500, Bitcoin, Ethereum, etc. You can also use the class data.artificial.SignalEmulator to create synthetic and complex patterns. The SignalEmulater is designed to work as an method chain / fluent interface, so you can simulate complex signals by chaining methods that produce specific signals that are added to previous one or replacing it. The method stationary_signal creates a simple stationary signal with constant mean and variance, the method incremental_gaussian creates a signal where the mean and/or variance is incremented at each time, the method periodic_gaussian fluctuate the mead and/or variance in constant periods and the blip method adds an outlier on a random location. Every time one of this methods is called its effects are added to the previous signal except if you inform the start parameter — indicating when (which iteration) the method start to work — or set the boolean parameter additive to False, making the stop the previous signal and start this new one. To render the whole signal you just need to call the function run.
from pyFTS.data import artificialsignal = artificial.SignalEmulator()\.stationary_gaussian(mu=2.5,sigma=.1,length=100,it=10)\.incremental_gaussian(mu=0.02,sigma=0.01,length=500,start=500)\.run()
Now let’s put it all together, create 3 non-stationary time series, with concept drifts and employ the above presented methods to forecast them:
Time Variant methods have to balance some kind of exploitation and exploration when dealing with non-stationarities and concept drifts. To exploit what the model already knows — its memory, the last learned patterns from the data — or to explore new data and learn new patterns. Each method has its own mechanisms: the Retrainer is controlled by the window_length and batch_size, the Incremental Ensemble for the both and the num_models, the NSFTS uses the magnitude of its own errors to adjust the fuzzy sets . After all, the time spent to adapt to concept drifts is one of the most important aspects of the time variant methods. The same principle we saw in previous tutorials apply in this one: each FTS method has its own features and parameters and the best method will depend on the context.
Well guys! That’s enough for today, ok?
In these tutorials we have covered — even superficially — a good portion of the time series forecasting field, with their problems and solutions using FTS methods. We did not finished yet! We will always have problems to solve, new improved methods and optimizations.
In next tutorials I will cover some new approaches, like hyperparameter optimization and how to tackle big time series with distributed computing. See you there guys! | [
{
"code": null,
"e": 479,
"s": 171,
"text": "Hi folks! It was a long time since I published the first and second parts of this tutorial. Meanwhile I had the opportunity to talk with many people that applied FTS methods on several distinct fields, and they helped me to improve pyFTS library by fixing some bugs and expanding its features and usability."
},
{
"code": null,
"e": 881,
"s": 479,
"text": "We have been dealing with uncertainty since the beginning of this tutorial. We found ways to model and describe the temporal behavior of the time series using fuzzy sets, but we did not take into account the uncertainty of our forecasts. The forecasting uncertainty is like a fog: if you are looking closer you will see blurred and it may not affect you too much, but if you want to look more ahead..."
},
{
"code": null,
"e": 1052,
"s": 881,
"text": "So, once again it is time to go deeper and explore more forecasting types and also new methods, this time I will focus on non-stationary time series, concept drifts, etc."
},
{
"code": null,
"e": 1231,
"s": 1052,
"text": "All examples of this tutorial are available on Google Colab, on http://bit.ly/short_tutorial_colab3 . Feel free to get in touch, give feedback and ask questions. Now, let’s move!"
},
{
"code": null,
"e": 1756,
"s": 1231,
"text": "The greatest majority of the forecasting methods produce point forecasts, i.e., a single scalar forecast. Given a numeric time series Y and its individual values y(t) ∈ Y, a point forecast is usually a conditional expectation ŷ(t+1) = E[Y |y(t), ...]. This number represents the best guess for Y at time t+1 given what we know about Y, its past values t, t-1, ... Regardless how good our estimator is, it is still a guess and not an exact certain value. In other words, behind that number there is uncertainty hidden in it."
},
{
"code": null,
"e": 1976,
"s": 1756,
"text": "The problem with the point forecasting is exactly this: it does not inform the uncertainty around it. A good starting point is the conditional variance Var[ y(t+1) | y(t) ], but it is not usually informed or even known."
},
{
"code": null,
"e": 2099,
"s": 1976,
"text": "There are ways to deal with this limitation of the point forecasts, and they are the interval and probabilistic forecasts."
},
{
"code": null,
"e": 2307,
"s": 2099,
"text": "A prediction interval I is a tuple I = [u, l], where u is the upper uncertainty bound and l is the lower uncertainty bound, asserting that the estimate will probably fall inside this range, ŷ(t+1) ∈ [u, l]."
},
{
"code": null,
"e": 2605,
"s": 2307,
"text": "A confidence interval is a value σ associated with a confidence level α ∈ [0,1], where ŷ(t+1) ∈ [ ŷ(t+1)-σ, ŷ(t+1)+σ] with a probability α. The confidence intervals are usually parametric, i.e., they assume that the uncertainty around the predicted value ŷ(t+1) is described by a Gaussian pdf."
},
{
"code": null,
"e": 2905,
"s": 2605,
"text": "There are several ways to measure the accuracy of an interval forecast and the simplest one is the coverage (that indicates the percentage of true values that fell inside the interval), calibration, sharpness, etc. The Winkler Score is known to embody several aspects of the intervals in one measure"
},
{
"code": null,
"e": 2953,
"s": 2905,
"text": "S(α,x,I) = (u−l) +2α(l−x)1(x< l) +2α(x−u)1(x>u)"
},
{
"code": null,
"e": 3077,
"s": 2953,
"text": "Where I = [u, l], x is the true value, α is the confidence level and 1(condition) = {1 if condition is true, 0 otherwise }."
},
{
"code": null,
"e": 3552,
"s": 3077,
"text": "A probabilistic forecast is a probability distribution P: U →[0, 1], where U is the Universe of Discourse of Y, constrained to ∑P(x) = 1, ∀x ∈ U. It means that we will estimate, for each possible value x of U, a probability π that ŷ(t+1) = x, or in other words: P(ŷ(t+1) = x) = π, 0 ≤ π ≤1 This is the most complete way to represent the uncertainty of a forecast, and give to us the landscape of the possible values that ŷ(t+1) can assume with its degrees of probability."
},
{
"code": null,
"e": 3771,
"s": 3552,
"text": "With the probability distribution P we also can calculate α confidence intervals (using α and 1-α quantiles of the cumulative distribution F) and produce a point forecast using the expected value E[P] = ∑xP(x), ∀x ∈ U."
},
{
"code": null,
"e": 4188,
"s": 3771,
"text": "The main accuracy measure for probabilistic forecasts is the Continuous Rank Probability Score (CRPS). In simple terms, the CRPS measures the area of the forecast probability curve before and after the true value x. This measurement informs how close to the true value the probability distribution was. The CRPS is a generalization of MAE to the case of probabilistic forecasts, then lower values of CRPS are better."
},
{
"code": null,
"e": 4236,
"s": 4188,
"text": "CRPS(F, x) = ∫ (F(y) -1(y>x))2 dy , y = -∞ ..+∞"
},
{
"code": null,
"e": 4323,
"s": 4236,
"text": "Where F(x) = P(X ≤ x) is the cumulative distribution function and x is the true value."
},
{
"code": null,
"e": 4653,
"s": 4323,
"text": "First of all, on pyFTS library every model has boolean flags indicating which type of forecasting it is able to make. All models are point forecasting-enabled but not all of them are interval and probabilistic enabled. If you try to use one of these kinds of forecasting on a model without this skill an exception will be raised."
},
{
"code": null,
"e": 4739,
"s": 4653,
"text": "if model.has_interval_forecasting: forecasts = model.predict(data, type=’interval’)"
},
{
"code": null,
"e": 5159,
"s": 4739,
"text": "To generate interval forecasts in pyFTS you use the same method for the scalar forecasts — the method predict in the FTS class — and inform the parameter type=’interval’. The interval forecasting type on predict method generates a list of tuples, each tuple with two values corresponding to a prediction interval I = [u, l]. Some models (such as EnsembleFTS and PWFTS) allow the specification of the method of interval."
},
{
"code": null,
"e": 5520,
"s": 5159,
"text": "ifts.IntervalFTS (IFTS): The most basic method for generating prediction intervals, it is an extension of the HighOrderFTS. The generated prediction intervals do not have some probabilistic mean, they just measure the upper and lower bounds of the fuzzy sets that were involved on forecasting process, i.e., the fuzzy uncertainty. The method is described here."
},
{
"code": null,
"e": 6238,
"s": 5520,
"text": "ensemble.AllMethodEnsembleFTS: The EnsembleFTS is a meta model composed by several base models. The AllMethodEnsembleFTS creates one instance of each monovariate FTS method implemented in pyFTS and set them as its base models. The forecasting is computed from the forecasts of the base models. A brief description of the method can be found here. There is basically two ways to compute prediction intervals in EnsembleFTS: extremum and quantile (default). In extremum method the maximum and minimum values between the forecasts of the base models are chosen. On quantile method the alpha parameter must be informed and then the forecasts of the base models will be ordered and the quantile interval will be extracted."
},
{
"code": null,
"e": 6526,
"s": 6238,
"text": "from pyFTS.models.ensemble import ensemblepart = Grid.GridPartitioner(data=train, npart=11)model = ensemble.AllMethodEnsembleFTS(partitioner=part)forecasts = model.predict(test, type='interval', mode='extremum')forecasts2 = model.predict(test, type='interval', mode='quantile', alpha=.1)"
},
{
"code": null,
"e": 7038,
"s": 6526,
"text": "pwfts.ProbabilisticWeightedFTS (PWFTS): As its name says, this is the most complex method and still under review (on its way to be published). There is basically two ways to produce prediction intervals on PWFTS: heuristic (default) and quantile. In the heuristic method the interval bounds are calculated as the expected value of the fuzzy sets bounds and its empirical probabilities and the quantile method generates a full probability distribution and then extracts the quantiles (using the alpha parameter)."
},
{
"code": null,
"e": 7187,
"s": 7038,
"text": "forecasts1 = model.predict(test, type='interval', method='heuristic')forecasts2 = model.predict(test, type='interval', method='quantile', alpha=.05)"
},
{
"code": null,
"e": 7302,
"s": 7187,
"text": "multivariate.mvfts.MVFTS: This multivariate method uses the same approach of IFTS to produce prediction intervals."
},
{
"code": null,
"e": 7435,
"s": 7302,
"text": "multivariate.wmvfts.WeightedMVFTS: This weighted multivariate method uses the same approach of IFTS to produce prediction intervals."
},
{
"code": null,
"e": 7552,
"s": 7435,
"text": "In the module pyFTS.common.Util we can find the function plot_interval which allows us to easily draw the intervals:"
},
{
"code": null,
"e": 7992,
"s": 7552,
"text": "The generated intervals try to demonstrate the range of possible variations that the model takes into account. You can see that some models generate wider intervals than others and sometimes (especially on the weighted models that have the thinner intervals) the original values fall outside the interval. The best intervals have balanced widths, neither too wide to show high uncertainty and neither too thin to not cover the real values."
},
{
"code": null,
"e": 8338,
"s": 7992,
"text": "To generate probabilistic forecasts in pyFTS you also use the method predict in the FTS class and inform the parameter type=’distribution’. The predict method will return a list of ProbabilityDistribution objects. Also, like the intervals the probabilistic forecasting has its own boolean flag to indicate which models are enabled to perform it:"
},
{
"code": null,
"e": 8437,
"s": 8338,
"text": "if model.has_probabilistic_forecasting: distributions = model.predict(test, type='distribution')"
},
{
"code": null,
"e": 9070,
"s": 8437,
"text": "In contrast to interval forecasting, the probabilistic forecasting has its own class to represent a probability distribution — the class pyFTS.probability.ProbabilityDistribution. There are several ways to represent this probability distribution that is, by definition, a discrete probability distribution. Some methods of this class have especial interest for us now: density (returns the probability of the input value(s)), cumulative (returns the cumulative probability of the input value(s)), quantile (returns the quantile value of the input value(s)) and plot (plots the probability distribution on the input matplotlib axis)."
},
{
"code": null,
"e": 9152,
"s": 9070,
"text": "Now let’s take a look on some probabilistic forecasting enabled methods on pyFTS:"
},
{
"code": null,
"e": 9511,
"s": 9152,
"text": "pwfts.ProbabilisticWeightedFTS (PWFTS): This method was entirely designed for probabilistic forecasting and is the best method for this on pyFTS. Its rules contains empirical probabilities associated with the fuzzy sets and also present a specific defuzzyfication rule that transforms an input (crisp) value on a probability distribution to the future value;"
},
{
"code": null,
"e": 9769,
"s": 9511,
"text": "ensemble.EnsembleFTS: The before mentioned ensemble creates probabilistic forecastings using Kernel Density Estimators (KDE) over the point forecasts of the base models. The KDE also requires the specification of the kernel function and the width parameter."
},
{
"code": null,
"e": 9823,
"s": 9769,
"text": "Let’s see how the probability forecasting looks like:"
},
{
"code": null,
"e": 10392,
"s": 9823,
"text": "In above pictures the probabilistic forecasting is shown in two different perspectives. The first picture is generated with the method plot_density in the module common.Util, where each probability distribution is plotted as a shade of blue and its intensity corresponds to the probability. This method allows to plot the original time series and the forecast probability distributions on top of it. The second picture shows each probability distribution individually in relation to the universe of discourse using the method plot of the class ProbabilityDistribution."
},
{
"code": null,
"e": 10706,
"s": 10392,
"text": "Of course it is not everything! We have to consider the interval and probabilistic forecasting for many steps ahead, which we expect to tell us how the uncertainty evolve as the prediction horizon increases. Yes! It is fascinating but I still have many things to show, so I will let it as an exercise for you, ok?"
},
{
"code": null,
"e": 10744,
"s": 10706,
"text": "Let’s walk now on a trickiest road..."
},
{
"code": null,
"e": 10799,
"s": 10744,
"text": "You may remember that old and universally known quote:"
},
{
"code": null,
"e": 10848,
"s": 10799,
"text": "“the only certainty is that nothing is certain”."
},
{
"code": null,
"e": 11250,
"s": 10848,
"text": "Yes. Forecasting may be unfair because things change all the time and we have to deal with it. Stationarity means, in layman terms, that the statistical properties of a stochastic process (like their expected value and variance) do not change along the time, whose the ultimate mean is stability. This is awesome for the forecasting models: the test data set will behave exactly as the train data set!"
},
{
"code": null,
"e": 11687,
"s": 11250,
"text": "In other hand, the non-stationarity means that the statistical properties change. But not all non-stationarities are created equal. Some of them are predictable as trend and seasonality. Dealing with seasonality is not tricky, you can use High Order, Seasonal or Multivariate methods (you may remember our last tutorial). To deal with trends it is not too complicated either, you can de-trend the data using a difference transformation."
},
{
"code": null,
"e": 12264,
"s": 11687,
"text": "Suppose that we split the above time series in half, and call these subsets training and testing data. You can see that the test subset (after the instance number 2000) have values that did not appear before, in the train subset. This is a drawback for most FTS methods: what happens when the input data fall outside the known Universe of Discourse? The model never saw that region before and doesn’t know how to proceed, than it fails tragically. You can also see on the above image that the differentiated time series is much more well behaved and, indeed, it is stationary."
},
{
"code": null,
"e": 12535,
"s": 12264,
"text": "How can we use the Difference transformation on pyFTS? Just import the Transformations module from pyFTS.common and instantiate it. Don’t forget to inform the transformation to the partitioning method and also add it to the model (with the method append_transformation)."
},
{
"code": null,
"e": 12940,
"s": 12535,
"text": "from pyFTS.data import NASDAQfrom pyFTS.models import chenfrom pyFTS.partitioners import Gridfrom pyFTS.common import Transformationsdiff = Transformations.Differential(1)train = data[:2000]test = data[2000:]part = Grid.GridPartitioner(data=train, npart=15, transformation=diff)model = chen.ConventionalFTS(partitioner=part)model.append_transformation(diff)model.fit(train)forecasts = model.predict(test)"
},
{
"code": null,
"e": 13061,
"s": 12940,
"text": "Look the behavior of the classical Chen’s model with and without the Differential transformation for the NASDAQ dataset:"
},
{
"code": null,
"e": 13389,
"s": 13061,
"text": "While the time series is still fluctuating inside the known Universe of Discourse both models performed well. But when the time series jumped out the Universe of Discourse of the training data, the model without the Differentiate transformation started to deteriorate because it does not know what to do with that unknown data."
},
{
"code": null,
"e": 13518,
"s": 13389,
"text": "Then the transformations help us not only with trending patterns, but also with the unknown ranges of the universe of discourse."
},
{
"code": null,
"e": 13610,
"s": 13518,
"text": "But some non-stationarities are unpredictable, and sometimes they are painful to deal with."
},
{
"code": null,
"e": 13974,
"s": 13610,
"text": "Concept drifts are unforeseen changes (on mean, variance or both) which can happen gradually or suddenly. Some times these drifts occur in cycles (with irregular periods) and, in other scenario, the drift is temporary. There are some questions to answer when a concept drifts happen: Is it temporary? Is the change finished (established) or it will keep changing?"
},
{
"code": null,
"e": 14136,
"s": 13974,
"text": "We have also to make the distinction between concept-drift and outlier (or a blip). Outliers are not change, they belong to the known signal but are rare events."
},
{
"code": null,
"e": 14435,
"s": 14136,
"text": "Concept drifts are nightmares — not only FTS methods, other computational intelligence and statistical techniques fear them too — but we need to learn how to live together them. Despite the complexity of the problem there are some simple (somehow expensive unfortunately) techniques to tackle them."
},
{
"code": null,
"e": 14456,
"s": 14435,
"text": "Time Variant Methods"
},
{
"code": null,
"e": 14792,
"s": 14456,
"text": "All FTS methods we saw before are time invariant methods, which means that they assume that the future fluctuations of the time series will behave according to patterns already happened before. In other words: the behavior of the time series, which was described by the fuzzy temporal rules of the model, will not change in the future."
},
{
"code": null,
"e": 14985,
"s": 14792,
"text": "This is works fine for many time series (for example the environmental seasonal time series like we studied before) but fails terribly in others (for instance the stock exchange asset prices)."
},
{
"code": null,
"e": 15037,
"s": 14985,
"text": "In that cases we need to apply time variant models,"
},
{
"code": null,
"e": 15674,
"s": 15037,
"text": "incremental.TimeVariant.Retrainer: The Time Variant model is the simplest (but efficient) approach to tackle concept drifts and non stationarity. This class implement a metamodel, what means that you can choose any FTS method to be its base method, then at each batch_size inputs the metamodel retrain its internal model with the last window_length inputs. These are the main parameters of the model: the window_length and the batch_size. As an meta model you can also specify which FTS method to use (the fts_method parameter) and which partitioner you want to use inside him (the partitioner_method and partitioner_params parameters)."
},
{
"code": null,
"e": 15977,
"s": 15674,
"text": "from pyFTS.models.incremental import TimeVariantmodel = TimeVariant.Retrainer( partitioner_method=Grid.GridPartitioner, partitioner_params={'npart': 35}, fts_method=hofts.WeightedHighOrderFTS, fts_params={}, order=2 , batch_size=50, window_length=200)"
},
{
"code": null,
"e": 16477,
"s": 15977,
"text": "incremental.IncrementalEnsembleFTS: Works similarly to the TimeVariant but in a EnsembleFTS approach. In TimeVariant there is only one internal model that is recreated after n inputs (which means that the batch_size is the unique memory it has). On IncrementalEnsemble we also have the window_length and the batch_size parameters but also the num_models that says how many internal models to hold. As soon new models are created (with the incoming data) the older ones are dropped from the ensemble."
},
{
"code": null,
"e": 16832,
"s": 16477,
"text": "from pyFTS.models.incremental import IncrementalEnsemblemodel = IncrementalEnsemble.IncrementalEnsembleFTS( partitioner_method=Grid.GridPartitioner, partitioner_params={'npart': 35}, fts_method=hofts.WeightedHighOrderFTS, fts_params={}, order=2 , batch_size=50, window_length=200, num_models=3)"
},
{
"code": null,
"e": 17450,
"s": 16832,
"text": "nonstationary.nsfts.NonStationaryFTS (NSFTS): The non-stationary fuzzy sets are fuzzy sets that can be modified along the time, allowing them to adapt to changes in the data by translating and/or scaling its parameters. The NSFTS method is very similitar to time invariant FTS methods, with the exception that their fuzzy sets are not static: for each forecast performed by an NSFTS model the error is calculated and stored and the fuzzy sets are changed to fix that error. For this method, the error is a measure of how much the test data is different from the train data. This method is on this way to be published."
},
{
"code": null,
"e": 17719,
"s": 17450,
"text": "from pyFTS.models.nonstationary import partitioners as nspartfrom pyFTS.models.nonstationary import nsftspart = nspart.simplenonstationary_gridpartitioner_builder( data=train, npart=35, transformation=None)model3 = nsfts.NonStationaryFTS(partitioner=part)"
},
{
"code": null,
"e": 18882,
"s": 17719,
"text": "The pyFTS.data module contains a lot of non-stationary and concept drifted time series as NASDAQ, TAIEX, S&P 500, Bitcoin, Ethereum, etc. You can also use the class data.artificial.SignalEmulator to create synthetic and complex patterns. The SignalEmulater is designed to work as an method chain / fluent interface, so you can simulate complex signals by chaining methods that produce specific signals that are added to previous one or replacing it. The method stationary_signal creates a simple stationary signal with constant mean and variance, the method incremental_gaussian creates a signal where the mean and/or variance is incremented at each time, the method periodic_gaussian fluctuate the mead and/or variance in constant periods and the blip method adds an outlier on a random location. Every time one of this methods is called its effects are added to the previous signal except if you inform the start parameter — indicating when (which iteration) the method start to work — or set the boolean parameter additive to False, making the stop the previous signal and start this new one. To render the whole signal you just need to call the function run."
},
{
"code": null,
"e": 19077,
"s": 18882,
"text": "from pyFTS.data import artificialsignal = artificial.SignalEmulator()\\.stationary_gaussian(mu=2.5,sigma=.1,length=100,it=10)\\.incremental_gaussian(mu=0.02,sigma=0.01,length=500,start=500)\\.run()"
},
{
"code": null,
"e": 19222,
"s": 19077,
"text": "Now let’s put it all together, create 3 non-stationary time series, with concept drifts and employ the above presented methods to forecast them:"
},
{
"code": null,
"e": 20020,
"s": 19222,
"text": "Time Variant methods have to balance some kind of exploitation and exploration when dealing with non-stationarities and concept drifts. To exploit what the model already knows — its memory, the last learned patterns from the data — or to explore new data and learn new patterns. Each method has its own mechanisms: the Retrainer is controlled by the window_length and batch_size, the Incremental Ensemble for the both and the num_models, the NSFTS uses the magnitude of its own errors to adjust the fuzzy sets . After all, the time spent to adapt to concept drifts is one of the most important aspects of the time variant methods. The same principle we saw in previous tutorials apply in this one: each FTS method has its own features and parameters and the best method will depend on the context."
},
{
"code": null,
"e": 20060,
"s": 20020,
"text": "Well guys! That’s enough for today, ok?"
},
{
"code": null,
"e": 20328,
"s": 20060,
"text": "In these tutorials we have covered — even superficially — a good portion of the time series forecasting field, with their problems and solutions using FTS methods. We did not finished yet! We will always have problems to solve, new improved methods and optimizations."
}
]
|
How to remove all trailing and leading whitespace in a string in Python? | To remove all trailing and leading whitespace in a string, we can use the method strip() in String class that gets rid of both these whitespaces. You can use it as follows:
>>> ' Hello People '.strip()
'Hello People'
If you only want to remove leading or trailing whitespace use lstrip() or rstrip() respectively.
>>> ' Hello People'.lstrip()
'Hello People'
>>> 'Hello People '.rstrip()
'Hello People' | [
{
"code": null,
"e": 1235,
"s": 1062,
"text": "To remove all trailing and leading whitespace in a string, we can use the method strip() in String class that gets rid of both these whitespaces. You can use it as follows:"
},
{
"code": null,
"e": 1283,
"s": 1235,
"text": ">>> ' Hello People '.strip()\n'Hello People'"
},
{
"code": null,
"e": 1380,
"s": 1283,
"text": "If you only want to remove leading or trailing whitespace use lstrip() or rstrip() respectively."
},
{
"code": null,
"e": 1472,
"s": 1380,
"text": ">>> ' Hello People'.lstrip()\n'Hello People'\n>>> 'Hello People '.rstrip()\n'Hello People'"
}
]
|
How to use Git / GitHub with Jupyter Notebook | by Amit Rathi | Towards Data Science | This article is a Git 101 for Jupyter users. Advanced Git users might want to check out integration workflow, real world examples and FAQs for making notebooks play nicely with GitHub.
This is a hands on tutorial for beginners & is meant to be comprehensive. Feel free to skip a section if you’re already familiar with it. At the end you’ll be able to -
Push your notebooks to a GitHub repository
Start versioning your notebooks
Learn how to revert to a specific version
Get feedback & discuss notebook changes with your peers
Easily share your notebooks for others to view
If you don’t have a GitHub account please create one here.
Download and install the latest version of Git.
Setup your name & email in git by running following commands on terminal —
>> git config --global user.name "Mona Lisa">> git config --global user.email "[email protected]"
Connect your local git client with GitHub by caching your password.
A GitHub repository is like your supercharged folder in the cloud. You can store files (notebooks, data, source code), look at historical changes to these files, open issues, discuss changes and much more. People typically create one repository per project.
Let’s go ahead & create a repository on GitHub. Once created, you’ll see a page like below, copy the highlighted repository URL.
Let’s clone the GitHub repository on our machine by running following command on the terminal. It will create projectA directory on our machine which is linked to amit1rrr/projectA repository on GitHub. Replace https://github.com/amit1rrr/projectA.git with your own repository URL from the above step —
>> git clone https://github.com/amit1rrr/projectA.git Cloning into 'projectA'... warning: You appear to have cloned an empty repository.
Our repository is empty right now, let’s push some notebooks to it. We copy two notebooks to the directory where we cloned projectA repository,
>> cp /some/path/analysis1.ipynb /path/of/projectA/>> cp /some/path/scratch.ipynb /path/of/projectA/
Let’s say we want to push analysis1.ipynbto GitHub. We first need to tell local git client to start tracking the file —
>> git add analysis1.ipynb
You can check which files are being tracked with git status,
You can see that analysis1.ipynb is under “Changes to be committed” so it’s being tracked by our local git client. Now let’s commit the changes —
# -m flag provides a human friendly message describing the change>> git commit -m "Adds customer data analysis notebook"
Commit simply creates a checkpoint that you can revert to at any time. Now finally push this commit to GitHub —
>> git push
Now you can visit the repository page on GitHub & see your commits.
Say you are working on a large project spanning multiple days, but you need to periodically push work in progress commits as a backup. The way to do that is by creating a feature branch.
Each repository has a default branch (typically “master” or “main”) that stores most up-to-date versions of completed work. Each member of your team can create their own feature branches to store their WIP commits. When their work in a feature branch is ready to be shared they can create a pull request for peer review & subsequently merge the feature branch into master. Let’s unpack that with concrete steps.
Say I’m about to start working on a new project to analyse customer data. First, I will create a new branch,
>> git checkout -b customer_data_insights
Then I’ll create/edit some notebooks & other files to do the actual analysis. When I’m ready to commit my WIP, I’ll do the usual git add, git commit, git push shown earlier. At git push you will see following error since the branch does not exist on GitHub yet.
Simply push the branch first by copying the command shown in error,
>> git push --set-upstream origin customer_data_insights
And then do git push to push your commits to this newly created branch.
Let’s say you’ve been working on feature branch for a while, and it’s ready for prime time. Most likely, you’d want to first share it with your peers, get their feedback before merging it into master branch. That’s what pull requests are for.
You can create pull requests from GitHub UI. Go to your Project page -> Pull requests tab -> click “New pull request”.
Choose which branch you’d like to merge into master. Verify commits & list of files changed. Click “Create pull request”.
On the next page, provide title & describe your changes in brief, click “Create pull request”.
GitHub pull request are fantastic for peer review as they let you see changes side-by-side & comment on them. But in the case of Jupyter, GitHub shows JSON diffs which are really hard to read (see below).
You can use ReviewNB to solve the notebook diff’ing problem. It shows you rich diffs & lets you comment on any notebook cell to discuss changes with your team.
Once your changes are approved by teammates, you can merge them from GitHub UI.
Or run git merge + git push from command line,
If you want to temporarily go back to a commit, checkout the files, and come back to where you are then you can simply checkout the desired commit. At the end run “git checkout master” to go back to the current state.
If you want to actually revert to an old state and make some changes there, you can start a new branch from that commit —
>> git checkout -b old-state <some-commit-id>
You can also browse old commits on GitHub by going to Your project page -> Commits. Open the desired commit and click “View File” to see the notebook status at that commit.
When you browse notebooks in your repository on GitHub it renders them as HTML. So it’s very convenient to share read-only links to the notebook like this one. If it’s a private repository, the person you are sharing the link with needs to have a GitHub account and have permission to access your repository.
For security reasons, GitHub does not run any Javascript in the notebook. You can use nbviewer or ReviewNB if your notebook contains interactive widgets.
If you are new to Git, it can take some time to get used to all the commands. But it’s a proven way of collaborating on software projects & is widely used in data science work as well. You can combine it with ReviewNB to remove some of the kinks in the workflow.
Happy Hacking!
Originally published at https://blog.reviewnb.com on February 20, 2020. | [
{
"code": null,
"e": 357,
"s": 172,
"text": "This article is a Git 101 for Jupyter users. Advanced Git users might want to check out integration workflow, real world examples and FAQs for making notebooks play nicely with GitHub."
},
{
"code": null,
"e": 526,
"s": 357,
"text": "This is a hands on tutorial for beginners & is meant to be comprehensive. Feel free to skip a section if you’re already familiar with it. At the end you’ll be able to -"
},
{
"code": null,
"e": 569,
"s": 526,
"text": "Push your notebooks to a GitHub repository"
},
{
"code": null,
"e": 601,
"s": 569,
"text": "Start versioning your notebooks"
},
{
"code": null,
"e": 643,
"s": 601,
"text": "Learn how to revert to a specific version"
},
{
"code": null,
"e": 699,
"s": 643,
"text": "Get feedback & discuss notebook changes with your peers"
},
{
"code": null,
"e": 746,
"s": 699,
"text": "Easily share your notebooks for others to view"
},
{
"code": null,
"e": 805,
"s": 746,
"text": "If you don’t have a GitHub account please create one here."
},
{
"code": null,
"e": 853,
"s": 805,
"text": "Download and install the latest version of Git."
},
{
"code": null,
"e": 928,
"s": 853,
"text": "Setup your name & email in git by running following commands on terminal —"
},
{
"code": null,
"e": 1026,
"s": 928,
"text": ">> git config --global user.name \"Mona Lisa\">> git config --global user.email \"[email protected]\""
},
{
"code": null,
"e": 1094,
"s": 1026,
"text": "Connect your local git client with GitHub by caching your password."
},
{
"code": null,
"e": 1352,
"s": 1094,
"text": "A GitHub repository is like your supercharged folder in the cloud. You can store files (notebooks, data, source code), look at historical changes to these files, open issues, discuss changes and much more. People typically create one repository per project."
},
{
"code": null,
"e": 1481,
"s": 1352,
"text": "Let’s go ahead & create a repository on GitHub. Once created, you’ll see a page like below, copy the highlighted repository URL."
},
{
"code": null,
"e": 1784,
"s": 1481,
"text": "Let’s clone the GitHub repository on our machine by running following command on the terminal. It will create projectA directory on our machine which is linked to amit1rrr/projectA repository on GitHub. Replace https://github.com/amit1rrr/projectA.git with your own repository URL from the above step —"
},
{
"code": null,
"e": 1925,
"s": 1784,
"text": ">> git clone https://github.com/amit1rrr/projectA.git Cloning into 'projectA'... warning: You appear to have cloned an empty repository."
},
{
"code": null,
"e": 2069,
"s": 1925,
"text": "Our repository is empty right now, let’s push some notebooks to it. We copy two notebooks to the directory where we cloned projectA repository,"
},
{
"code": null,
"e": 2170,
"s": 2069,
"text": ">> cp /some/path/analysis1.ipynb /path/of/projectA/>> cp /some/path/scratch.ipynb /path/of/projectA/"
},
{
"code": null,
"e": 2290,
"s": 2170,
"text": "Let’s say we want to push analysis1.ipynbto GitHub. We first need to tell local git client to start tracking the file —"
},
{
"code": null,
"e": 2317,
"s": 2290,
"text": ">> git add analysis1.ipynb"
},
{
"code": null,
"e": 2378,
"s": 2317,
"text": "You can check which files are being tracked with git status,"
},
{
"code": null,
"e": 2524,
"s": 2378,
"text": "You can see that analysis1.ipynb is under “Changes to be committed” so it’s being tracked by our local git client. Now let’s commit the changes —"
},
{
"code": null,
"e": 2645,
"s": 2524,
"text": "# -m flag provides a human friendly message describing the change>> git commit -m \"Adds customer data analysis notebook\""
},
{
"code": null,
"e": 2757,
"s": 2645,
"text": "Commit simply creates a checkpoint that you can revert to at any time. Now finally push this commit to GitHub —"
},
{
"code": null,
"e": 2769,
"s": 2757,
"text": ">> git push"
},
{
"code": null,
"e": 2837,
"s": 2769,
"text": "Now you can visit the repository page on GitHub & see your commits."
},
{
"code": null,
"e": 3024,
"s": 2837,
"text": "Say you are working on a large project spanning multiple days, but you need to periodically push work in progress commits as a backup. The way to do that is by creating a feature branch."
},
{
"code": null,
"e": 3436,
"s": 3024,
"text": "Each repository has a default branch (typically “master” or “main”) that stores most up-to-date versions of completed work. Each member of your team can create their own feature branches to store their WIP commits. When their work in a feature branch is ready to be shared they can create a pull request for peer review & subsequently merge the feature branch into master. Let’s unpack that with concrete steps."
},
{
"code": null,
"e": 3545,
"s": 3436,
"text": "Say I’m about to start working on a new project to analyse customer data. First, I will create a new branch,"
},
{
"code": null,
"e": 3587,
"s": 3545,
"text": ">> git checkout -b customer_data_insights"
},
{
"code": null,
"e": 3849,
"s": 3587,
"text": "Then I’ll create/edit some notebooks & other files to do the actual analysis. When I’m ready to commit my WIP, I’ll do the usual git add, git commit, git push shown earlier. At git push you will see following error since the branch does not exist on GitHub yet."
},
{
"code": null,
"e": 3917,
"s": 3849,
"text": "Simply push the branch first by copying the command shown in error,"
},
{
"code": null,
"e": 3974,
"s": 3917,
"text": ">> git push --set-upstream origin customer_data_insights"
},
{
"code": null,
"e": 4046,
"s": 3974,
"text": "And then do git push to push your commits to this newly created branch."
},
{
"code": null,
"e": 4289,
"s": 4046,
"text": "Let’s say you’ve been working on feature branch for a while, and it’s ready for prime time. Most likely, you’d want to first share it with your peers, get their feedback before merging it into master branch. That’s what pull requests are for."
},
{
"code": null,
"e": 4408,
"s": 4289,
"text": "You can create pull requests from GitHub UI. Go to your Project page -> Pull requests tab -> click “New pull request”."
},
{
"code": null,
"e": 4530,
"s": 4408,
"text": "Choose which branch you’d like to merge into master. Verify commits & list of files changed. Click “Create pull request”."
},
{
"code": null,
"e": 4625,
"s": 4530,
"text": "On the next page, provide title & describe your changes in brief, click “Create pull request”."
},
{
"code": null,
"e": 4830,
"s": 4625,
"text": "GitHub pull request are fantastic for peer review as they let you see changes side-by-side & comment on them. But in the case of Jupyter, GitHub shows JSON diffs which are really hard to read (see below)."
},
{
"code": null,
"e": 4990,
"s": 4830,
"text": "You can use ReviewNB to solve the notebook diff’ing problem. It shows you rich diffs & lets you comment on any notebook cell to discuss changes with your team."
},
{
"code": null,
"e": 5070,
"s": 4990,
"text": "Once your changes are approved by teammates, you can merge them from GitHub UI."
},
{
"code": null,
"e": 5117,
"s": 5070,
"text": "Or run git merge + git push from command line,"
},
{
"code": null,
"e": 5335,
"s": 5117,
"text": "If you want to temporarily go back to a commit, checkout the files, and come back to where you are then you can simply checkout the desired commit. At the end run “git checkout master” to go back to the current state."
},
{
"code": null,
"e": 5457,
"s": 5335,
"text": "If you want to actually revert to an old state and make some changes there, you can start a new branch from that commit —"
},
{
"code": null,
"e": 5503,
"s": 5457,
"text": ">> git checkout -b old-state <some-commit-id>"
},
{
"code": null,
"e": 5676,
"s": 5503,
"text": "You can also browse old commits on GitHub by going to Your project page -> Commits. Open the desired commit and click “View File” to see the notebook status at that commit."
},
{
"code": null,
"e": 5985,
"s": 5676,
"text": "When you browse notebooks in your repository on GitHub it renders them as HTML. So it’s very convenient to share read-only links to the notebook like this one. If it’s a private repository, the person you are sharing the link with needs to have a GitHub account and have permission to access your repository."
},
{
"code": null,
"e": 6139,
"s": 5985,
"text": "For security reasons, GitHub does not run any Javascript in the notebook. You can use nbviewer or ReviewNB if your notebook contains interactive widgets."
},
{
"code": null,
"e": 6402,
"s": 6139,
"text": "If you are new to Git, it can take some time to get used to all the commands. But it’s a proven way of collaborating on software projects & is widely used in data science work as well. You can combine it with ReviewNB to remove some of the kinks in the workflow."
},
{
"code": null,
"e": 6417,
"s": 6402,
"text": "Happy Hacking!"
}
]
|
JavaScript Map keys() Method - GeeksforGeeks | 21 Jan, 2022
Below is the basic example of the Map.keys() method.
Javascript
<script> let mp=new Map() mp.set("a",11); mp.set("b",2); mp.set("c",5); console.log(mp.keys());</script>
Output:
MapIterator {"a", "b", "c"}
The Map.keys() method is used to extract the keys from a given map object and return the iterator object of keys. The keys are returned in the order they were inserted.
Syntax:
Map.keys()
Parameters: This method does not accept any parameters.
Returns: This returns the iterator object that contains keys in the map.
Code for the above method is provided below:Program 1:
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <ul class="list"> </ul> <script> // Creating a map using Map object let mp=new Map() // Adding key value pairs to the map mp mp.set("a",1); mp.set("b",2); mp.set("c",22); mp.set("d",12); console.log("Type of mp.keys() is: ",typeof (mp.keys())); console.log("Keys in map mp are: ",mp.keys()); </script></body></html>
Output:
Program 2: Updating the value of the key in the map and printing values using the iterator object.
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <ul class="list"> </ul> <script> // Creating a map using Map object let mp=new Map() // Adding key value pairs to the map mp mp.set("q",1); mp.set("w",2); // Value of key "q" is updated to 22 mp.set("q",22); mp.set("d",22); mp.set("c",12); let it=mp.keys(); // Logginfg iterator object console.log(it); console.log(it.next().value) // Iterator pointing to next key and // printing the value console.log(it.next().value) </script></body></html>
Output:
Supported Browsers:
Chrome 38 and above
Opera 25 and above
Edge 12 and above
Firefox 20 and above
Safari 8 and above
ysachin2314
JavaScript-Methods
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
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
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": 24909,
"s": 24881,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 24962,
"s": 24909,
"text": "Below is the basic example of the Map.keys() method."
},
{
"code": null,
"e": 24973,
"s": 24962,
"text": "Javascript"
},
{
"code": "<script> let mp=new Map() mp.set(\"a\",11); mp.set(\"b\",2); mp.set(\"c\",5); console.log(mp.keys());</script>",
"e": 25083,
"s": 24973,
"text": null
},
{
"code": null,
"e": 25091,
"s": 25083,
"text": "Output:"
},
{
"code": null,
"e": 25119,
"s": 25091,
"text": "MapIterator {\"a\", \"b\", \"c\"}"
},
{
"code": null,
"e": 25288,
"s": 25119,
"text": "The Map.keys() method is used to extract the keys from a given map object and return the iterator object of keys. The keys are returned in the order they were inserted."
},
{
"code": null,
"e": 25297,
"s": 25288,
"text": "Syntax: "
},
{
"code": null,
"e": 25308,
"s": 25297,
"text": "Map.keys()"
},
{
"code": null,
"e": 25364,
"s": 25308,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 25437,
"s": 25364,
"text": "Returns: This returns the iterator object that contains keys in the map."
},
{
"code": null,
"e": 25492,
"s": 25437,
"text": "Code for the above method is provided below:Program 1:"
},
{
"code": null,
"e": 25497,
"s": 25492,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><body> <ul class=\"list\"> </ul> <script> // Creating a map using Map object let mp=new Map() // Adding key value pairs to the map mp mp.set(\"a\",1); mp.set(\"b\",2); mp.set(\"c\",22); mp.set(\"d\",12); console.log(\"Type of mp.keys() is: \",typeof (mp.keys())); console.log(\"Keys in map mp are: \",mp.keys()); </script></body></html>",
"e": 26039,
"s": 25497,
"text": null
},
{
"code": null,
"e": 26047,
"s": 26039,
"text": "Output:"
},
{
"code": null,
"e": 26146,
"s": 26047,
"text": "Program 2: Updating the value of the key in the map and printing values using the iterator object."
},
{
"code": null,
"e": 26151,
"s": 26146,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><body> <ul class=\"list\"> </ul> <script> // Creating a map using Map object let mp=new Map() // Adding key value pairs to the map mp mp.set(\"q\",1); mp.set(\"w\",2); // Value of key \"q\" is updated to 22 mp.set(\"q\",22); mp.set(\"d\",22); mp.set(\"c\",12); let it=mp.keys(); // Logginfg iterator object console.log(it); console.log(it.next().value) // Iterator pointing to next key and // printing the value console.log(it.next().value) </script></body></html>",
"e": 26842,
"s": 26151,
"text": null
},
{
"code": null,
"e": 26851,
"s": 26842,
"text": "Output: "
},
{
"code": null,
"e": 26872,
"s": 26851,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 26892,
"s": 26872,
"text": "Chrome 38 and above"
},
{
"code": null,
"e": 26911,
"s": 26892,
"text": "Opera 25 and above"
},
{
"code": null,
"e": 26929,
"s": 26911,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 26950,
"s": 26929,
"text": "Firefox 20 and above"
},
{
"code": null,
"e": 26969,
"s": 26950,
"text": "Safari 8 and above"
},
{
"code": null,
"e": 26981,
"s": 26969,
"text": "ysachin2314"
},
{
"code": null,
"e": 27000,
"s": 26981,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 27011,
"s": 27000,
"text": "JavaScript"
},
{
"code": null,
"e": 27028,
"s": 27011,
"text": "Web Technologies"
},
{
"code": null,
"e": 27126,
"s": 27028,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27135,
"s": 27126,
"text": "Comments"
},
{
"code": null,
"e": 27148,
"s": 27135,
"text": "Old Comments"
},
{
"code": null,
"e": 27209,
"s": 27148,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27250,
"s": 27209,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27290,
"s": 27250,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27344,
"s": 27290,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27406,
"s": 27344,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27462,
"s": 27406,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27495,
"s": 27462,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27557,
"s": 27495,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27600,
"s": 27557,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Risk Management for Information Security | Set-2 - GeeksforGeeks | 04 Jul, 2018
Prerequisite – Risk Management | Set-12. Risk Assessment –Risk Management is a recurrent activity, on the other hand Risk assessment is executed at discrete points and until the performance of the next assessment. Risk Assessment is the process of evaluating known and postulated threats and vulnerabilities to determine expected loss. It also includes establishing the degree of acceptability to system operations.
Risk Assessment receives input and output from Context establishment phase and output is the list of assessed risk risks, where risks are given priorities as per risk evaluation criteria.
Risk Identification –In this step we identify the following:assetsthreatsexisting and planned security measuresvulnerabilitiesconsequencerelated business processesThus output includes the following:list of asset and related business processes with associated list of threats, existing and planned security measureslist of vulnerabilities unrelated to any identified threatslist of incident scenarios with their consequencesRisk Estimation –There are 2 methods for Risk Assessment:1. Quantitative Risk Assessment – This methodology is not mostly used by the organizations except for the financial institutions and insurance companies. Quantitative risk is mathematically expressed as Annualised Loss Expectancy (ALE). ALE is the expected monetary loss that can be expected for an asset due to a risk being realised over a one-year period.ALE= SLE * AROSingle Loss Expectancy (SLE) is the value of a single loss of the asset. This may or may not be the entire asset. This is the impact of the loss. Annualised Rate of Occurrence (ARO) is how often the loss occurs. This is the likelihood.Theoretically Quantitative risk assessment seems straightforward but there are issues in assigning values to parameters. While the cost of system is easy to define but indirect costs such as value of information, lost production activity and cost to recover are difficult to define accurately. The other element likelihood is not accurately known.Therefore, there is a large margin of error in Quantitative Risk Assessment. Due to unavailability of accurate and complete information it is not cost effective to perform a quantitative risk assessment for a IT System.2. Qualitative Risk Assessment – Qualitative Risk Assessment defines likelihood, impact values and risk in subjective terms, keeping in mind that likelihood and impact values are highly uncertain. Qualitative risk assessments typically give risk results of “High”, “Moderate” and “Low”. Following are the steps in Qualitative Risk Assessment:Identifying Threats: Threats and Threat-Sources must be identified. Threats should include threat-source to ensure accurate estimation. It is important to compile a list of all possible threats that are present across the organization and use this list as the basis for all risk management activities. Some of the examples of threat and threat-source are:Natural Threats- floods, earthquakes etc.Human Threats- virus, worms etc.Environmental Threats- power failure, pollution etc.Identifying Vulnerabilities: Vulnerabilities are identified by numerous means. Some of the tools are:Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures.Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering.Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes.Relating Threats to Vulnerabilities: This is the most difficult and mandatory activity in Risk Assessment. T-V pair list is established by reviewing the vulnerability list and pairing a vulnerability with every threat that applies, then by reviewing the threat list and ensuring that all the vulnerabilities that that threat-action/threat can act against have been identified.Defining Likelihood: Likelihood is the probability that a threat caused by a threat-source will occur against a vulnerability. Sample Likelihood definitions can be like:Low -0-30% chance of successful exercise of Threat during a one year periodModerate – 31-70% chance of successful exercise of Threat during a one year periodHigh – 71-100% chance of successful exercise of Threat during a one year periodThis is just a sample definations. Organization can use their own definitaion like Very Low, Low, Moderate, High, Very High.Defining Impact: Impact is best defined in terms of impact upon confidentiality, integrity and availability. Sample definitions for impact are as follows:ConfidentialityIntegrityAvailabilityLowLoss of Confidentiality leads to Limited effect on organizationLoss of Integrity leads to Limited effect on organizationLoss of Availability leads to Limited effect on organizationMediumLoss of Confidentiality leads to Serious effect on organizationLoss of Integrity leads to Serious effect on organizationLoss of Availability leads to Serious effect on organizationHighLoss of Confidentiality leads to Severe effect on organizationLoss of Integrity leads to Severe effect on organizationLoss of Availability leads to Severe effect on organizationExamples of Organizational Effect is as follows:Effect TypeEffect on Mission CapabilityFinancial LossEffect on Human LifeLimited EffectTemporary loss of one or more minor mission capabilitiesUnder Rs 50, 000Minor HarmSerious EffectLong term loss of one or more minor capabilities or Temporary loss of one or more primary mission capabilities.Rs 50, 000- Rs 1, 00, 000Significant HarmSevere EffectLong term loss of one or more primary mission capabilitiesover Rs 1, 00, 000Loss of lifeAssessing Risk: Assessing risk is the process to determine the likelihood of the threat being exercised against the vulnerability and the resulting impact from a successful compromise. Sample Risk Determination Matrix is as follows:ImpactHighModerateLowLikelihoodHighHighHighModerateModerateHighModerateLowLowModerateLowLow
Risk Identification –In this step we identify the following:assetsthreatsexisting and planned security measuresvulnerabilitiesconsequencerelated business processesThus output includes the following:list of asset and related business processes with associated list of threats, existing and planned security measureslist of vulnerabilities unrelated to any identified threatslist of incident scenarios with their consequences
assets
threats
existing and planned security measures
vulnerabilities
consequence
related business processes
Thus output includes the following:
list of asset and related business processes with associated list of threats, existing and planned security measures
list of vulnerabilities unrelated to any identified threats
list of incident scenarios with their consequences
Risk Estimation –There are 2 methods for Risk Assessment:1. Quantitative Risk Assessment – This methodology is not mostly used by the organizations except for the financial institutions and insurance companies. Quantitative risk is mathematically expressed as Annualised Loss Expectancy (ALE). ALE is the expected monetary loss that can be expected for an asset due to a risk being realised over a one-year period.ALE= SLE * AROSingle Loss Expectancy (SLE) is the value of a single loss of the asset. This may or may not be the entire asset. This is the impact of the loss. Annualised Rate of Occurrence (ARO) is how often the loss occurs. This is the likelihood.Theoretically Quantitative risk assessment seems straightforward but there are issues in assigning values to parameters. While the cost of system is easy to define but indirect costs such as value of information, lost production activity and cost to recover are difficult to define accurately. The other element likelihood is not accurately known.Therefore, there is a large margin of error in Quantitative Risk Assessment. Due to unavailability of accurate and complete information it is not cost effective to perform a quantitative risk assessment for a IT System.2. Qualitative Risk Assessment – Qualitative Risk Assessment defines likelihood, impact values and risk in subjective terms, keeping in mind that likelihood and impact values are highly uncertain. Qualitative risk assessments typically give risk results of “High”, “Moderate” and “Low”. Following are the steps in Qualitative Risk Assessment:Identifying Threats: Threats and Threat-Sources must be identified. Threats should include threat-source to ensure accurate estimation. It is important to compile a list of all possible threats that are present across the organization and use this list as the basis for all risk management activities. Some of the examples of threat and threat-source are:Natural Threats- floods, earthquakes etc.Human Threats- virus, worms etc.Environmental Threats- power failure, pollution etc.Identifying Vulnerabilities: Vulnerabilities are identified by numerous means. Some of the tools are:Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures.Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering.Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes.Relating Threats to Vulnerabilities: This is the most difficult and mandatory activity in Risk Assessment. T-V pair list is established by reviewing the vulnerability list and pairing a vulnerability with every threat that applies, then by reviewing the threat list and ensuring that all the vulnerabilities that that threat-action/threat can act against have been identified.Defining Likelihood: Likelihood is the probability that a threat caused by a threat-source will occur against a vulnerability. Sample Likelihood definitions can be like:Low -0-30% chance of successful exercise of Threat during a one year periodModerate – 31-70% chance of successful exercise of Threat during a one year periodHigh – 71-100% chance of successful exercise of Threat during a one year periodThis is just a sample definations. Organization can use their own definitaion like Very Low, Low, Moderate, High, Very High.Defining Impact: Impact is best defined in terms of impact upon confidentiality, integrity and availability. Sample definitions for impact are as follows:ConfidentialityIntegrityAvailabilityLowLoss of Confidentiality leads to Limited effect on organizationLoss of Integrity leads to Limited effect on organizationLoss of Availability leads to Limited effect on organizationMediumLoss of Confidentiality leads to Serious effect on organizationLoss of Integrity leads to Serious effect on organizationLoss of Availability leads to Serious effect on organizationHighLoss of Confidentiality leads to Severe effect on organizationLoss of Integrity leads to Severe effect on organizationLoss of Availability leads to Severe effect on organizationExamples of Organizational Effect is as follows:Effect TypeEffect on Mission CapabilityFinancial LossEffect on Human LifeLimited EffectTemporary loss of one or more minor mission capabilitiesUnder Rs 50, 000Minor HarmSerious EffectLong term loss of one or more minor capabilities or Temporary loss of one or more primary mission capabilities.Rs 50, 000- Rs 1, 00, 000Significant HarmSevere EffectLong term loss of one or more primary mission capabilitiesover Rs 1, 00, 000Loss of lifeAssessing Risk: Assessing risk is the process to determine the likelihood of the threat being exercised against the vulnerability and the resulting impact from a successful compromise. Sample Risk Determination Matrix is as follows:ImpactHighModerateLowLikelihoodHighHighHighModerateModerateHighModerateLowLowModerateLowLow
1. Quantitative Risk Assessment – This methodology is not mostly used by the organizations except for the financial institutions and insurance companies. Quantitative risk is mathematically expressed as Annualised Loss Expectancy (ALE). ALE is the expected monetary loss that can be expected for an asset due to a risk being realised over a one-year period.
ALE= SLE * ARO
Single Loss Expectancy (SLE) is the value of a single loss of the asset. This may or may not be the entire asset. This is the impact of the loss. Annualised Rate of Occurrence (ARO) is how often the loss occurs. This is the likelihood.
Theoretically Quantitative risk assessment seems straightforward but there are issues in assigning values to parameters. While the cost of system is easy to define but indirect costs such as value of information, lost production activity and cost to recover are difficult to define accurately. The other element likelihood is not accurately known.
Therefore, there is a large margin of error in Quantitative Risk Assessment. Due to unavailability of accurate and complete information it is not cost effective to perform a quantitative risk assessment for a IT System.
2. Qualitative Risk Assessment – Qualitative Risk Assessment defines likelihood, impact values and risk in subjective terms, keeping in mind that likelihood and impact values are highly uncertain. Qualitative risk assessments typically give risk results of “High”, “Moderate” and “Low”. Following are the steps in Qualitative Risk Assessment:
Identifying Threats: Threats and Threat-Sources must be identified. Threats should include threat-source to ensure accurate estimation. It is important to compile a list of all possible threats that are present across the organization and use this list as the basis for all risk management activities. Some of the examples of threat and threat-source are:Natural Threats- floods, earthquakes etc.Human Threats- virus, worms etc.Environmental Threats- power failure, pollution etc.Identifying Vulnerabilities: Vulnerabilities are identified by numerous means. Some of the tools are:Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures.Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering.Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes.Relating Threats to Vulnerabilities: This is the most difficult and mandatory activity in Risk Assessment. T-V pair list is established by reviewing the vulnerability list and pairing a vulnerability with every threat that applies, then by reviewing the threat list and ensuring that all the vulnerabilities that that threat-action/threat can act against have been identified.Defining Likelihood: Likelihood is the probability that a threat caused by a threat-source will occur against a vulnerability. Sample Likelihood definitions can be like:Low -0-30% chance of successful exercise of Threat during a one year periodModerate – 31-70% chance of successful exercise of Threat during a one year periodHigh – 71-100% chance of successful exercise of Threat during a one year periodThis is just a sample definations. Organization can use their own definitaion like Very Low, Low, Moderate, High, Very High.Defining Impact: Impact is best defined in terms of impact upon confidentiality, integrity and availability. Sample definitions for impact are as follows:ConfidentialityIntegrityAvailabilityLowLoss of Confidentiality leads to Limited effect on organizationLoss of Integrity leads to Limited effect on organizationLoss of Availability leads to Limited effect on organizationMediumLoss of Confidentiality leads to Serious effect on organizationLoss of Integrity leads to Serious effect on organizationLoss of Availability leads to Serious effect on organizationHighLoss of Confidentiality leads to Severe effect on organizationLoss of Integrity leads to Severe effect on organizationLoss of Availability leads to Severe effect on organizationExamples of Organizational Effect is as follows:Effect TypeEffect on Mission CapabilityFinancial LossEffect on Human LifeLimited EffectTemporary loss of one or more minor mission capabilitiesUnder Rs 50, 000Minor HarmSerious EffectLong term loss of one or more minor capabilities or Temporary loss of one or more primary mission capabilities.Rs 50, 000- Rs 1, 00, 000Significant HarmSevere EffectLong term loss of one or more primary mission capabilitiesover Rs 1, 00, 000Loss of lifeAssessing Risk: Assessing risk is the process to determine the likelihood of the threat being exercised against the vulnerability and the resulting impact from a successful compromise. Sample Risk Determination Matrix is as follows:ImpactHighModerateLowLikelihoodHighHighHighModerateModerateHighModerateLowLowModerateLowLow
Identifying Threats: Threats and Threat-Sources must be identified. Threats should include threat-source to ensure accurate estimation. It is important to compile a list of all possible threats that are present across the organization and use this list as the basis for all risk management activities. Some of the examples of threat and threat-source are:Natural Threats- floods, earthquakes etc.Human Threats- virus, worms etc.Environmental Threats- power failure, pollution etc.
Natural Threats- floods, earthquakes etc.
Human Threats- virus, worms etc.
Environmental Threats- power failure, pollution etc.
Identifying Vulnerabilities: Vulnerabilities are identified by numerous means. Some of the tools are:Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures.Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering.Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes.
Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures.Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering.Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes.
Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures.
Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering.
Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes.
Relating Threats to Vulnerabilities: This is the most difficult and mandatory activity in Risk Assessment. T-V pair list is established by reviewing the vulnerability list and pairing a vulnerability with every threat that applies, then by reviewing the threat list and ensuring that all the vulnerabilities that that threat-action/threat can act against have been identified.
Defining Likelihood: Likelihood is the probability that a threat caused by a threat-source will occur against a vulnerability. Sample Likelihood definitions can be like:Low -0-30% chance of successful exercise of Threat during a one year periodModerate – 31-70% chance of successful exercise of Threat during a one year periodHigh – 71-100% chance of successful exercise of Threat during a one year periodThis is just a sample definations. Organization can use their own definitaion like Very Low, Low, Moderate, High, Very High.
Low -0-30% chance of successful exercise of Threat during a one year periodModerate – 31-70% chance of successful exercise of Threat during a one year periodHigh – 71-100% chance of successful exercise of Threat during a one year period
This is just a sample definations. Organization can use their own definitaion like Very Low, Low, Moderate, High, Very High.
Defining Impact: Impact is best defined in terms of impact upon confidentiality, integrity and availability. Sample definitions for impact are as follows:ConfidentialityIntegrityAvailabilityLowLoss of Confidentiality leads to Limited effect on organizationLoss of Integrity leads to Limited effect on organizationLoss of Availability leads to Limited effect on organizationMediumLoss of Confidentiality leads to Serious effect on organizationLoss of Integrity leads to Serious effect on organizationLoss of Availability leads to Serious effect on organizationHighLoss of Confidentiality leads to Severe effect on organizationLoss of Integrity leads to Severe effect on organizationLoss of Availability leads to Severe effect on organizationExamples of Organizational Effect is as follows:Effect TypeEffect on Mission CapabilityFinancial LossEffect on Human LifeLimited EffectTemporary loss of one or more minor mission capabilitiesUnder Rs 50, 000Minor HarmSerious EffectLong term loss of one or more minor capabilities or Temporary loss of one or more primary mission capabilities.Rs 50, 000- Rs 1, 00, 000Significant HarmSevere EffectLong term loss of one or more primary mission capabilitiesover Rs 1, 00, 000Loss of life
Examples of Organizational Effect is as follows:
Assessing Risk: Assessing risk is the process to determine the likelihood of the threat being exercised against the vulnerability and the resulting impact from a successful compromise. Sample Risk Determination Matrix is as follows:ImpactHighModerateLowLikelihoodHighHighHighModerateModerateHighModerateLowLowModerateLowLow
3. Risk Evaluation – The risk evaluation process receives as input the output of risk analysis process. It first compares each risk level against the risk acceptance criteria and then prioritise the risk list with risk treatment indications.
3. Risk Mitigation/ Management –Risk Mitigation involves prioritizing, evaluating, and implementing the appropriate risk-reducing controls recommended from the risk assessment process. Since eliminating all risk in an organization is close to impossible thus, it is the responsibility of senior management and functional and business managers to use the least-cost approach and implement the most appropriate controls to decrease risk to an acceptable level.
As per NIST SP 800 30 framework there are 6 steps in Risk Mitigation.
Risk Assumption: This means to accept the risk and continue operating the system but at the same time try to implement the controls toRisk Avoidance: This means to eliminate the risk cause or consequence in order to avoid the risk for example shutdown the system if the risk is identified.Risk Limitation: To limit the risk by implementing controls that minimize the adverse impact of a threat’s exercising a vulnerability (e.g., use of supporting, preventive, detective controls)Risk Planning: To manage risk by developing a risk mitigation plan that prioritizes, implements, and maintains controlsResearch and Acknowledgement: In this step involves acknowledging the vulnerability or flaw and researching controls to correct the vulnerability.Risk Transference: This means to transfer the risk to compensate for the loss for example purchasing insurance guarantees not 100% in all cases but alteast some recovery from the loss.
Risk Assumption: This means to accept the risk and continue operating the system but at the same time try to implement the controls to
Risk Avoidance: This means to eliminate the risk cause or consequence in order to avoid the risk for example shutdown the system if the risk is identified.
Risk Limitation: To limit the risk by implementing controls that minimize the adverse impact of a threat’s exercising a vulnerability (e.g., use of supporting, preventive, detective controls)
Risk Planning: To manage risk by developing a risk mitigation plan that prioritizes, implements, and maintains controls
Research and Acknowledgement: In this step involves acknowledging the vulnerability or flaw and researching controls to correct the vulnerability.
Risk Transference: This means to transfer the risk to compensate for the loss for example purchasing insurance guarantees not 100% in all cases but alteast some recovery from the loss.
4. Risk Communication –The main purpose of this step is to communicate, give an understanding of all aspects of risk to all the stakeholder’s of an organization. Establishing a common understanding is important, since it influences decisions to be taken.
5. Risk Monitoring and Review –Security Measures are regularly reviewed to ensure they work as planned and changes in the environment don’t make them ineffective. With major changes in the work environment security measures should also be updated.Business requirements, vulnerabilities and threats can change over the time. Regular audits should be scheduled and should be conducted by an independent party.
6. IT Evaluation and Assessment –Security controls should be validated. Technical controls are systems that need to tested and verified. Vulnerability assessment and Penetration test are used for verifying status of security controls. Monitoring system events according to a security monitoring strategy, an incident response plan and security validation and metrics are fundamental activities to assure that an optimal level of security is obtained. It is important to keep a check on new vulnerabilities and apply procedural and technical controls for example regularly update software.
Information-Security
Computer Networks
GBlog
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
RSA Algorithm in Cryptography
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Socket Programming in Python
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Top 10 Front End Developer Skills That You Need in 2022
Socket Programming in C/C++
DSA Sheet by Love Babbar
Must Do Coding Questions for Product Based Companies | [
{
"code": null,
"e": 23993,
"s": 23965,
"text": "\n04 Jul, 2018"
},
{
"code": null,
"e": 24409,
"s": 23993,
"text": "Prerequisite – Risk Management | Set-12. Risk Assessment –Risk Management is a recurrent activity, on the other hand Risk assessment is executed at discrete points and until the performance of the next assessment. Risk Assessment is the process of evaluating known and postulated threats and vulnerabilities to determine expected loss. It also includes establishing the degree of acceptability to system operations."
},
{
"code": null,
"e": 24597,
"s": 24409,
"text": "Risk Assessment receives input and output from Context establishment phase and output is the list of assessed risk risks, where risks are given priorities as per risk evaluation criteria."
},
{
"code": null,
"e": 30156,
"s": 24597,
"text": "Risk Identification –In this step we identify the following:assetsthreatsexisting and planned security measuresvulnerabilitiesconsequencerelated business processesThus output includes the following:list of asset and related business processes with associated list of threats, existing and planned security measureslist of vulnerabilities unrelated to any identified threatslist of incident scenarios with their consequencesRisk Estimation –There are 2 methods for Risk Assessment:1. Quantitative Risk Assessment – This methodology is not mostly used by the organizations except for the financial institutions and insurance companies. Quantitative risk is mathematically expressed as Annualised Loss Expectancy (ALE). ALE is the expected monetary loss that can be expected for an asset due to a risk being realised over a one-year period.ALE= SLE * AROSingle Loss Expectancy (SLE) is the value of a single loss of the asset. This may or may not be the entire asset. This is the impact of the loss. Annualised Rate of Occurrence (ARO) is how often the loss occurs. This is the likelihood.Theoretically Quantitative risk assessment seems straightforward but there are issues in assigning values to parameters. While the cost of system is easy to define but indirect costs such as value of information, lost production activity and cost to recover are difficult to define accurately. The other element likelihood is not accurately known.Therefore, there is a large margin of error in Quantitative Risk Assessment. Due to unavailability of accurate and complete information it is not cost effective to perform a quantitative risk assessment for a IT System.2. Qualitative Risk Assessment – Qualitative Risk Assessment defines likelihood, impact values and risk in subjective terms, keeping in mind that likelihood and impact values are highly uncertain. Qualitative risk assessments typically give risk results of “High”, “Moderate” and “Low”. Following are the steps in Qualitative Risk Assessment:Identifying Threats: Threats and Threat-Sources must be identified. Threats should include threat-source to ensure accurate estimation. It is important to compile a list of all possible threats that are present across the organization and use this list as the basis for all risk management activities. Some of the examples of threat and threat-source are:Natural Threats- floods, earthquakes etc.Human Threats- virus, worms etc.Environmental Threats- power failure, pollution etc.Identifying Vulnerabilities: Vulnerabilities are identified by numerous means. Some of the tools are:Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures.Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering.Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes.Relating Threats to Vulnerabilities: This is the most difficult and mandatory activity in Risk Assessment. T-V pair list is established by reviewing the vulnerability list and pairing a vulnerability with every threat that applies, then by reviewing the threat list and ensuring that all the vulnerabilities that that threat-action/threat can act against have been identified.Defining Likelihood: Likelihood is the probability that a threat caused by a threat-source will occur against a vulnerability. Sample Likelihood definitions can be like:Low -0-30% chance of successful exercise of Threat during a one year periodModerate – 31-70% chance of successful exercise of Threat during a one year periodHigh – 71-100% chance of successful exercise of Threat during a one year periodThis is just a sample definations. Organization can use their own definitaion like Very Low, Low, Moderate, High, Very High.Defining Impact: Impact is best defined in terms of impact upon confidentiality, integrity and availability. Sample definitions for impact are as follows:ConfidentialityIntegrityAvailabilityLowLoss of Confidentiality leads to Limited effect on organizationLoss of Integrity leads to Limited effect on organizationLoss of Availability leads to Limited effect on organizationMediumLoss of Confidentiality leads to Serious effect on organizationLoss of Integrity leads to Serious effect on organizationLoss of Availability leads to Serious effect on organizationHighLoss of Confidentiality leads to Severe effect on organizationLoss of Integrity leads to Severe effect on organizationLoss of Availability leads to Severe effect on organizationExamples of Organizational Effect is as follows:Effect TypeEffect on Mission CapabilityFinancial LossEffect on Human LifeLimited EffectTemporary loss of one or more minor mission capabilitiesUnder Rs 50, 000Minor HarmSerious EffectLong term loss of one or more minor capabilities or Temporary loss of one or more primary mission capabilities.Rs 50, 000- Rs 1, 00, 000Significant HarmSevere EffectLong term loss of one or more primary mission capabilitiesover Rs 1, 00, 000Loss of lifeAssessing Risk: Assessing risk is the process to determine the likelihood of the threat being exercised against the vulnerability and the resulting impact from a successful compromise. Sample Risk Determination Matrix is as follows:ImpactHighModerateLowLikelihoodHighHighHighModerateModerateHighModerateLowLowModerateLowLow"
},
{
"code": null,
"e": 30580,
"s": 30156,
"text": "Risk Identification –In this step we identify the following:assetsthreatsexisting and planned security measuresvulnerabilitiesconsequencerelated business processesThus output includes the following:list of asset and related business processes with associated list of threats, existing and planned security measureslist of vulnerabilities unrelated to any identified threatslist of incident scenarios with their consequences"
},
{
"code": null,
"e": 30587,
"s": 30580,
"text": "assets"
},
{
"code": null,
"e": 30595,
"s": 30587,
"text": "threats"
},
{
"code": null,
"e": 30634,
"s": 30595,
"text": "existing and planned security measures"
},
{
"code": null,
"e": 30650,
"s": 30634,
"text": "vulnerabilities"
},
{
"code": null,
"e": 30662,
"s": 30650,
"text": "consequence"
},
{
"code": null,
"e": 30689,
"s": 30662,
"text": "related business processes"
},
{
"code": null,
"e": 30725,
"s": 30689,
"text": "Thus output includes the following:"
},
{
"code": null,
"e": 30842,
"s": 30725,
"text": "list of asset and related business processes with associated list of threats, existing and planned security measures"
},
{
"code": null,
"e": 30902,
"s": 30842,
"text": "list of vulnerabilities unrelated to any identified threats"
},
{
"code": null,
"e": 30953,
"s": 30902,
"text": "list of incident scenarios with their consequences"
},
{
"code": null,
"e": 36089,
"s": 30953,
"text": "Risk Estimation –There are 2 methods for Risk Assessment:1. Quantitative Risk Assessment – This methodology is not mostly used by the organizations except for the financial institutions and insurance companies. Quantitative risk is mathematically expressed as Annualised Loss Expectancy (ALE). ALE is the expected monetary loss that can be expected for an asset due to a risk being realised over a one-year period.ALE= SLE * AROSingle Loss Expectancy (SLE) is the value of a single loss of the asset. This may or may not be the entire asset. This is the impact of the loss. Annualised Rate of Occurrence (ARO) is how often the loss occurs. This is the likelihood.Theoretically Quantitative risk assessment seems straightforward but there are issues in assigning values to parameters. While the cost of system is easy to define but indirect costs such as value of information, lost production activity and cost to recover are difficult to define accurately. The other element likelihood is not accurately known.Therefore, there is a large margin of error in Quantitative Risk Assessment. Due to unavailability of accurate and complete information it is not cost effective to perform a quantitative risk assessment for a IT System.2. Qualitative Risk Assessment – Qualitative Risk Assessment defines likelihood, impact values and risk in subjective terms, keeping in mind that likelihood and impact values are highly uncertain. Qualitative risk assessments typically give risk results of “High”, “Moderate” and “Low”. Following are the steps in Qualitative Risk Assessment:Identifying Threats: Threats and Threat-Sources must be identified. Threats should include threat-source to ensure accurate estimation. It is important to compile a list of all possible threats that are present across the organization and use this list as the basis for all risk management activities. Some of the examples of threat and threat-source are:Natural Threats- floods, earthquakes etc.Human Threats- virus, worms etc.Environmental Threats- power failure, pollution etc.Identifying Vulnerabilities: Vulnerabilities are identified by numerous means. Some of the tools are:Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures.Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering.Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes.Relating Threats to Vulnerabilities: This is the most difficult and mandatory activity in Risk Assessment. T-V pair list is established by reviewing the vulnerability list and pairing a vulnerability with every threat that applies, then by reviewing the threat list and ensuring that all the vulnerabilities that that threat-action/threat can act against have been identified.Defining Likelihood: Likelihood is the probability that a threat caused by a threat-source will occur against a vulnerability. Sample Likelihood definitions can be like:Low -0-30% chance of successful exercise of Threat during a one year periodModerate – 31-70% chance of successful exercise of Threat during a one year periodHigh – 71-100% chance of successful exercise of Threat during a one year periodThis is just a sample definations. Organization can use their own definitaion like Very Low, Low, Moderate, High, Very High.Defining Impact: Impact is best defined in terms of impact upon confidentiality, integrity and availability. Sample definitions for impact are as follows:ConfidentialityIntegrityAvailabilityLowLoss of Confidentiality leads to Limited effect on organizationLoss of Integrity leads to Limited effect on organizationLoss of Availability leads to Limited effect on organizationMediumLoss of Confidentiality leads to Serious effect on organizationLoss of Integrity leads to Serious effect on organizationLoss of Availability leads to Serious effect on organizationHighLoss of Confidentiality leads to Severe effect on organizationLoss of Integrity leads to Severe effect on organizationLoss of Availability leads to Severe effect on organizationExamples of Organizational Effect is as follows:Effect TypeEffect on Mission CapabilityFinancial LossEffect on Human LifeLimited EffectTemporary loss of one or more minor mission capabilitiesUnder Rs 50, 000Minor HarmSerious EffectLong term loss of one or more minor capabilities or Temporary loss of one or more primary mission capabilities.Rs 50, 000- Rs 1, 00, 000Significant HarmSevere EffectLong term loss of one or more primary mission capabilitiesover Rs 1, 00, 000Loss of lifeAssessing Risk: Assessing risk is the process to determine the likelihood of the threat being exercised against the vulnerability and the resulting impact from a successful compromise. Sample Risk Determination Matrix is as follows:ImpactHighModerateLowLikelihoodHighHighHighModerateModerateHighModerateLowLowModerateLowLow"
},
{
"code": null,
"e": 36447,
"s": 36089,
"text": "1. Quantitative Risk Assessment – This methodology is not mostly used by the organizations except for the financial institutions and insurance companies. Quantitative risk is mathematically expressed as Annualised Loss Expectancy (ALE). ALE is the expected monetary loss that can be expected for an asset due to a risk being realised over a one-year period."
},
{
"code": null,
"e": 36462,
"s": 36447,
"text": "ALE= SLE * ARO"
},
{
"code": null,
"e": 36698,
"s": 36462,
"text": "Single Loss Expectancy (SLE) is the value of a single loss of the asset. This may or may not be the entire asset. This is the impact of the loss. Annualised Rate of Occurrence (ARO) is how often the loss occurs. This is the likelihood."
},
{
"code": null,
"e": 37046,
"s": 36698,
"text": "Theoretically Quantitative risk assessment seems straightforward but there are issues in assigning values to parameters. While the cost of system is easy to define but indirect costs such as value of information, lost production activity and cost to recover are difficult to define accurately. The other element likelihood is not accurately known."
},
{
"code": null,
"e": 37266,
"s": 37046,
"text": "Therefore, there is a large margin of error in Quantitative Risk Assessment. Due to unavailability of accurate and complete information it is not cost effective to perform a quantitative risk assessment for a IT System."
},
{
"code": null,
"e": 37609,
"s": 37266,
"text": "2. Qualitative Risk Assessment – Qualitative Risk Assessment defines likelihood, impact values and risk in subjective terms, keeping in mind that likelihood and impact values are highly uncertain. Qualitative risk assessments typically give risk results of “High”, “Moderate” and “Low”. Following are the steps in Qualitative Risk Assessment:"
},
{
"code": null,
"e": 41174,
"s": 37609,
"text": "Identifying Threats: Threats and Threat-Sources must be identified. Threats should include threat-source to ensure accurate estimation. It is important to compile a list of all possible threats that are present across the organization and use this list as the basis for all risk management activities. Some of the examples of threat and threat-source are:Natural Threats- floods, earthquakes etc.Human Threats- virus, worms etc.Environmental Threats- power failure, pollution etc.Identifying Vulnerabilities: Vulnerabilities are identified by numerous means. Some of the tools are:Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures.Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering.Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes.Relating Threats to Vulnerabilities: This is the most difficult and mandatory activity in Risk Assessment. T-V pair list is established by reviewing the vulnerability list and pairing a vulnerability with every threat that applies, then by reviewing the threat list and ensuring that all the vulnerabilities that that threat-action/threat can act against have been identified.Defining Likelihood: Likelihood is the probability that a threat caused by a threat-source will occur against a vulnerability. Sample Likelihood definitions can be like:Low -0-30% chance of successful exercise of Threat during a one year periodModerate – 31-70% chance of successful exercise of Threat during a one year periodHigh – 71-100% chance of successful exercise of Threat during a one year periodThis is just a sample definations. Organization can use their own definitaion like Very Low, Low, Moderate, High, Very High.Defining Impact: Impact is best defined in terms of impact upon confidentiality, integrity and availability. Sample definitions for impact are as follows:ConfidentialityIntegrityAvailabilityLowLoss of Confidentiality leads to Limited effect on organizationLoss of Integrity leads to Limited effect on organizationLoss of Availability leads to Limited effect on organizationMediumLoss of Confidentiality leads to Serious effect on organizationLoss of Integrity leads to Serious effect on organizationLoss of Availability leads to Serious effect on organizationHighLoss of Confidentiality leads to Severe effect on organizationLoss of Integrity leads to Severe effect on organizationLoss of Availability leads to Severe effect on organizationExamples of Organizational Effect is as follows:Effect TypeEffect on Mission CapabilityFinancial LossEffect on Human LifeLimited EffectTemporary loss of one or more minor mission capabilitiesUnder Rs 50, 000Minor HarmSerious EffectLong term loss of one or more minor capabilities or Temporary loss of one or more primary mission capabilities.Rs 50, 000- Rs 1, 00, 000Significant HarmSevere EffectLong term loss of one or more primary mission capabilitiesover Rs 1, 00, 000Loss of lifeAssessing Risk: Assessing risk is the process to determine the likelihood of the threat being exercised against the vulnerability and the resulting impact from a successful compromise. Sample Risk Determination Matrix is as follows:ImpactHighModerateLowLikelihoodHighHighHighModerateModerateHighModerateLowLowModerateLowLow"
},
{
"code": null,
"e": 41655,
"s": 41174,
"text": "Identifying Threats: Threats and Threat-Sources must be identified. Threats should include threat-source to ensure accurate estimation. It is important to compile a list of all possible threats that are present across the organization and use this list as the basis for all risk management activities. Some of the examples of threat and threat-source are:Natural Threats- floods, earthquakes etc.Human Threats- virus, worms etc.Environmental Threats- power failure, pollution etc."
},
{
"code": null,
"e": 41697,
"s": 41655,
"text": "Natural Threats- floods, earthquakes etc."
},
{
"code": null,
"e": 41730,
"s": 41697,
"text": "Human Threats- virus, worms etc."
},
{
"code": null,
"e": 41783,
"s": 41730,
"text": "Environmental Threats- power failure, pollution etc."
},
{
"code": null,
"e": 42416,
"s": 41783,
"text": "Identifying Vulnerabilities: Vulnerabilities are identified by numerous means. Some of the tools are:Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures.Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering.Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes."
},
{
"code": null,
"e": 42948,
"s": 42416,
"text": "Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures.Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering.Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes."
},
{
"code": null,
"e": 43086,
"s": 42948,
"text": "Vulnerability Scanners – This is the software the compare the operating system or code for flaws against the database of flaw signatures."
},
{
"code": null,
"e": 43235,
"s": 43086,
"text": "Penetration Testing – Human Security analyst will exercise threats against the system including operational vulnerabilities like Social Engineering."
},
{
"code": null,
"e": 43482,
"s": 43235,
"text": "Audit of Operational and Management Controls – Operational and management controls are reviewed by comparing the current documentation to best practices for example ISO 17799 and by comparing actual practices against current documented processes."
},
{
"code": null,
"e": 43859,
"s": 43482,
"text": "Relating Threats to Vulnerabilities: This is the most difficult and mandatory activity in Risk Assessment. T-V pair list is established by reviewing the vulnerability list and pairing a vulnerability with every threat that applies, then by reviewing the threat list and ensuring that all the vulnerabilities that that threat-action/threat can act against have been identified."
},
{
"code": null,
"e": 44389,
"s": 43859,
"text": "Defining Likelihood: Likelihood is the probability that a threat caused by a threat-source will occur against a vulnerability. Sample Likelihood definitions can be like:Low -0-30% chance of successful exercise of Threat during a one year periodModerate – 31-70% chance of successful exercise of Threat during a one year periodHigh – 71-100% chance of successful exercise of Threat during a one year periodThis is just a sample definations. Organization can use their own definitaion like Very Low, Low, Moderate, High, Very High."
},
{
"code": null,
"e": 44626,
"s": 44389,
"text": "Low -0-30% chance of successful exercise of Threat during a one year periodModerate – 31-70% chance of successful exercise of Threat during a one year periodHigh – 71-100% chance of successful exercise of Threat during a one year period"
},
{
"code": null,
"e": 44751,
"s": 44626,
"text": "This is just a sample definations. Organization can use their own definitaion like Very Low, Low, Moderate, High, Very High."
},
{
"code": null,
"e": 45976,
"s": 44751,
"text": "Defining Impact: Impact is best defined in terms of impact upon confidentiality, integrity and availability. Sample definitions for impact are as follows:ConfidentialityIntegrityAvailabilityLowLoss of Confidentiality leads to Limited effect on organizationLoss of Integrity leads to Limited effect on organizationLoss of Availability leads to Limited effect on organizationMediumLoss of Confidentiality leads to Serious effect on organizationLoss of Integrity leads to Serious effect on organizationLoss of Availability leads to Serious effect on organizationHighLoss of Confidentiality leads to Severe effect on organizationLoss of Integrity leads to Severe effect on organizationLoss of Availability leads to Severe effect on organizationExamples of Organizational Effect is as follows:Effect TypeEffect on Mission CapabilityFinancial LossEffect on Human LifeLimited EffectTemporary loss of one or more minor mission capabilitiesUnder Rs 50, 000Minor HarmSerious EffectLong term loss of one or more minor capabilities or Temporary loss of one or more primary mission capabilities.Rs 50, 000- Rs 1, 00, 000Significant HarmSevere EffectLong term loss of one or more primary mission capabilitiesover Rs 1, 00, 000Loss of life"
},
{
"code": null,
"e": 46025,
"s": 45976,
"text": "Examples of Organizational Effect is as follows:"
},
{
"code": null,
"e": 46349,
"s": 46025,
"text": "Assessing Risk: Assessing risk is the process to determine the likelihood of the threat being exercised against the vulnerability and the resulting impact from a successful compromise. Sample Risk Determination Matrix is as follows:ImpactHighModerateLowLikelihoodHighHighHighModerateModerateHighModerateLowLowModerateLowLow"
},
{
"code": null,
"e": 46591,
"s": 46349,
"text": "3. Risk Evaluation – The risk evaluation process receives as input the output of risk analysis process. It first compares each risk level against the risk acceptance criteria and then prioritise the risk list with risk treatment indications."
},
{
"code": null,
"e": 47050,
"s": 46591,
"text": "3. Risk Mitigation/ Management –Risk Mitigation involves prioritizing, evaluating, and implementing the appropriate risk-reducing controls recommended from the risk assessment process. Since eliminating all risk in an organization is close to impossible thus, it is the responsibility of senior management and functional and business managers to use the least-cost approach and implement the most appropriate controls to decrease risk to an acceptable level."
},
{
"code": null,
"e": 47120,
"s": 47050,
"text": "As per NIST SP 800 30 framework there are 6 steps in Risk Mitigation."
},
{
"code": null,
"e": 48050,
"s": 47120,
"text": "Risk Assumption: This means to accept the risk and continue operating the system but at the same time try to implement the controls toRisk Avoidance: This means to eliminate the risk cause or consequence in order to avoid the risk for example shutdown the system if the risk is identified.Risk Limitation: To limit the risk by implementing controls that minimize the adverse impact of a threat’s exercising a vulnerability (e.g., use of supporting, preventive, detective controls)Risk Planning: To manage risk by developing a risk mitigation plan that prioritizes, implements, and maintains controlsResearch and Acknowledgement: In this step involves acknowledging the vulnerability or flaw and researching controls to correct the vulnerability.Risk Transference: This means to transfer the risk to compensate for the loss for example purchasing insurance guarantees not 100% in all cases but alteast some recovery from the loss."
},
{
"code": null,
"e": 48185,
"s": 48050,
"text": "Risk Assumption: This means to accept the risk and continue operating the system but at the same time try to implement the controls to"
},
{
"code": null,
"e": 48341,
"s": 48185,
"text": "Risk Avoidance: This means to eliminate the risk cause or consequence in order to avoid the risk for example shutdown the system if the risk is identified."
},
{
"code": null,
"e": 48533,
"s": 48341,
"text": "Risk Limitation: To limit the risk by implementing controls that minimize the adverse impact of a threat’s exercising a vulnerability (e.g., use of supporting, preventive, detective controls)"
},
{
"code": null,
"e": 48653,
"s": 48533,
"text": "Risk Planning: To manage risk by developing a risk mitigation plan that prioritizes, implements, and maintains controls"
},
{
"code": null,
"e": 48800,
"s": 48653,
"text": "Research and Acknowledgement: In this step involves acknowledging the vulnerability or flaw and researching controls to correct the vulnerability."
},
{
"code": null,
"e": 48985,
"s": 48800,
"text": "Risk Transference: This means to transfer the risk to compensate for the loss for example purchasing insurance guarantees not 100% in all cases but alteast some recovery from the loss."
},
{
"code": null,
"e": 49240,
"s": 48985,
"text": "4. Risk Communication –The main purpose of this step is to communicate, give an understanding of all aspects of risk to all the stakeholder’s of an organization. Establishing a common understanding is important, since it influences decisions to be taken."
},
{
"code": null,
"e": 49648,
"s": 49240,
"text": "5. Risk Monitoring and Review –Security Measures are regularly reviewed to ensure they work as planned and changes in the environment don’t make them ineffective. With major changes in the work environment security measures should also be updated.Business requirements, vulnerabilities and threats can change over the time. Regular audits should be scheduled and should be conducted by an independent party."
},
{
"code": null,
"e": 50237,
"s": 49648,
"text": "6. IT Evaluation and Assessment –Security controls should be validated. Technical controls are systems that need to tested and verified. Vulnerability assessment and Penetration test are used for verifying status of security controls. Monitoring system events according to a security monitoring strategy, an incident response plan and security validation and metrics are fundamental activities to assure that an optimal level of security is obtained. It is important to keep a check on new vulnerabilities and apply procedural and technical controls for example regularly update software."
},
{
"code": null,
"e": 50258,
"s": 50237,
"text": "Information-Security"
},
{
"code": null,
"e": 50276,
"s": 50258,
"text": "Computer Networks"
},
{
"code": null,
"e": 50282,
"s": 50276,
"text": "GBlog"
},
{
"code": null,
"e": 50300,
"s": 50282,
"text": "Computer Networks"
},
{
"code": null,
"e": 50398,
"s": 50300,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 50407,
"s": 50398,
"text": "Comments"
},
{
"code": null,
"e": 50420,
"s": 50407,
"text": "Old Comments"
},
{
"code": null,
"e": 50458,
"s": 50420,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 50488,
"s": 50458,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 50520,
"s": 50488,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 50559,
"s": 50520,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 50588,
"s": 50559,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 50662,
"s": 50588,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 50718,
"s": 50662,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 50746,
"s": 50718,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 50771,
"s": 50746,
"text": "DSA Sheet by Love Babbar"
}
]
|
Print an array with numbers having 1, 2 and 3 as a digit in ascending order | Here, the task is to print those number in an array having 1, 2 and 3 as digits in their numbers and if their is no such number than the output must be -1
Input : arr[] = {320,123,124,125,14532,126,340,123400,100032,13,32,3123,1100}
Output : 123 3123 14532 100032 123400
Since the array have values with digits 1, 2 and 3 it wouldn’t return -1 and print 5 values that
Contain 1, 2 and 3 in their respective numbers.
START
Step 1 -> Declare array with elements of int type as arr
Step 2 -> store size of array in int n
Step 3 -> declare int variable as one, two, three
Step 4 -> call sort functions with parameters as arr and arr+n
Step 5 -> declare variable of type osrtingstream as st and string as num
Step 6 -> Loop For i=0 and i<n and ++i
Set one=two=three=1
Print arr[i]
Set num=st.str()
Set one=num.find("1")
Set two=num.find("2")
Set three=num.find("3")
IF((one!=-1)&&(two!=-1)&&(three!=-1))
Print num
End
Call st.str(‘’”)
end
STOP
#include <bits/stdc++.h>
#include<string.h>
#include<sstream>
using namespace std;
int main() {
int arr[] = {320,123,124,125,14532,126,340,123400,100032,13,32,3123,1100};
int n = sizeof(arr)/sizeof(arr[0]);
int one,two,three;
sort(arr, arr+n);
ostringstream st;
string num;
for (int i = 0; i < n; ++i) {
one=two=three=-1;
st << arr[i];
num=st.str();
one=num.find("1");
two=num.find("2");
three=num.find("3");
if((one!=-1)&&(two!=-1)&&(three!=-1)) {
cout<<num<<" ";
}
st.str("");
}
}
if we run the above program then it will generate the following output
123 3123 14532 100032 123400 | [
{
"code": null,
"e": 1217,
"s": 1062,
"text": "Here, the task is to print those number in an array having 1, 2 and 3 as digits in their numbers and if their is no such number than the output must be -1"
},
{
"code": null,
"e": 1479,
"s": 1217,
"text": "Input : arr[] = {320,123,124,125,14532,126,340,123400,100032,13,32,3123,1100}\nOutput : 123 3123 14532 100032 123400\n\nSince the array have values with digits 1, 2 and 3 it wouldn’t return -1 and print 5 values that\nContain 1, 2 and 3 in their respective numbers."
},
{
"code": null,
"e": 2035,
"s": 1479,
"text": "START\nStep 1 -> Declare array with elements of int type as arr\nStep 2 -> store size of array in int n\nStep 3 -> declare int variable as one, two, three\nStep 4 -> call sort functions with parameters as arr and arr+n\nStep 5 -> declare variable of type osrtingstream as st and string as num\nStep 6 -> Loop For i=0 and i<n and ++i\n Set one=two=three=1\n Print arr[i]\n Set num=st.str()\n Set one=num.find(\"1\")\n Set two=num.find(\"2\")\n Set three=num.find(\"3\")\n IF((one!=-1)&&(two!=-1)&&(three!=-1))\n Print num\n End\n Call st.str(‘’”)\nend\nSTOP"
},
{
"code": null,
"e": 2605,
"s": 2035,
"text": "#include <bits/stdc++.h>\n#include<string.h>\n#include<sstream>\nusing namespace std;\nint main() {\n int arr[] = {320,123,124,125,14532,126,340,123400,100032,13,32,3123,1100};\n int n = sizeof(arr)/sizeof(arr[0]);\n int one,two,three;\n sort(arr, arr+n);\n ostringstream st;\n string num;\n for (int i = 0; i < n; ++i) {\n one=two=three=-1;\n st << arr[i];\n num=st.str();\n one=num.find(\"1\");\n two=num.find(\"2\");\n three=num.find(\"3\");\n if((one!=-1)&&(two!=-1)&&(three!=-1)) {\n cout<<num<<\" \";\n }\n st.str(\"\");\n }\n}"
},
{
"code": null,
"e": 2676,
"s": 2605,
"text": "if we run the above program then it will generate the following output"
},
{
"code": null,
"e": 2705,
"s": 2676,
"text": "123 3123 14532 100032 123400"
}
]
|
Convert an unbalanced bracket sequence to a balanced sequence - GeeksforGeeks | 13 May, 2021
Given an unbalanced bracket sequence of ‘(‘ and ‘)’, convert it into a balanced sequence by adding the minimum number of ‘(‘ at the beginning of the string and ‘)’ at the end of the string.
Examples:
Input: str = “)))()” Output: “((()))()”
Input: str = “())())(())())” Output: “(((())())(())())”
Approach:
Let us assume that whenever we encounter with opening bracket the depth increases by one and with a closing bracket the depth decreases by one.
Find the maximum negative depth in minDep and add that number of ‘(‘ at the beginning.
Then loop the new sequence to find the number of ‘)’s needed at the end of the string and add them.
Finally, return the string.
Below is the implementation of the approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return balancedBrackets stringstring balancedBrackets(string str){ // Initializing dep to 0 int dep = 0; // Stores maximum negative depth int minDep = 0; for (int i = 0; i < str.length(); i++) { if (str[i] == '(') dep++; else dep--; // if dep is less than minDep if (minDep > dep) minDep = dep; } // if minDep is less than 0 then there // is need to add '(' at the front if (minDep < 0) { for (int i = 0; i < abs(minDep); i++) str = '(' + str; } // Reinitializing to check the updated string dep = 0; for (int i = 0; i < str.length(); i++) { if (str[i] == '(') dep++; else dep--; } // if dep is not 0 then there // is need to add ')' at the back if (dep != 0) { for (int i = 0; i < dep; i++) str = str + ')'; } return str;} // Driver codeint main(){ string str = ")))()"; cout << balancedBrackets(str);}
// Java implementation of the approachimport java.util.*; class GFG { // Function to return balancedBrackets string static String balancedBrackets(String str) { // Initializing dep to 0 int dep = 0; // Stores maximum negative depth int minDep = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(') dep++; else dep--; // if dep is less than minDep if (minDep > dep) minDep = dep; } // if minDep is less than 0 then there // is need to add '(' at the front if (minDep < 0) { for (int i = 0; i < Math.abs(minDep); i++) str = '(' + str; } // Reinitializing to check the updated string dep = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(') dep++; else dep--; } // if dep is not 0 then there // is need to add ')' at the back if (dep != 0) { for (int i = 0; i < dep; i++) str = str + ')'; } return str; } // Driver code public static void main(String[] args) { String str = ")))()"; System.out.println(balancedBrackets(str)); }} // This code is contributed by ihritik
# Python3 implementation of the approach # Function to return balancedBrackets String def balancedBrackets(Str): # Initializing dep to 0 dep = 0 # Stores maximum negative depth minDep = 0 for i in Str: if (i == '('): dep += 1 else: dep -= 1 # if dep is less than minDep if (minDep > dep): minDep = dep # if minDep is less than 0 then there # is need to add '(' at the front if (minDep < 0): for i in range(abs(minDep)): Str = '(' + Str # Reinitializing to check the updated String dep = 0 for i in Str: if (i == '('): dep += 1 else: dep -= 1 # if dep is not 0 then there # is need to add ')' at the back if (dep != 0): for i in range(dep): Str = Str + ')' return Str # Driver codeStr = ")))()"print(balancedBrackets(Str)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG { // Function to return balancedBrackets string static string balancedBrackets(string str) { // Initializing dep to 0 int dep = 0; // Stores maximum negative depth int minDep = 0; for (int i = 0; i < str.Length; i++) { if (str[i] == '(') dep++; else dep--; // if dep is less than minDep if (minDep > dep) minDep = dep; } // if minDep is less than 0 then there // is need to add '(' at the front if (minDep < 0) { for (int i = 0; i < Math.Abs(minDep); i++) str = '(' + str; } // Reinitializing to check the updated string dep = 0; for (int i = 0; i < str.Length; i++) { if (str[i] == '(') dep++; else dep--; } // if dep is not 0 then there // is need to add ')' at the back if (dep != 0) { for (int i = 0; i < dep; i++) str = str + ')'; } return str; } // Driver code public static void Main() { String str = ")))()"; Console.WriteLine(balancedBrackets(str)); }} // This code is contributed by ihritik
<script> // JavaScript implementation of the approach // Function to return balancedBrackets string function balancedBrackets(str) { // Initializing dep to 0 var dep = 0; // Stores maximum negative depth var minDep = 0; for (var i = 0; i < str.length; i++) { if (str[i] === "(") dep++; else dep--; // if dep is less than minDep if (minDep > dep) minDep = dep; } // if minDep is less than 0 then there // is need to add '(' at the front if (minDep < 0) { for (var i = 0; i < Math.abs(minDep); i++) str = "(" + str; } // Reinitializing to check the updated string dep = 0; for (var i = 0; i < str.length; i++) { if (str[i] === "(") dep++; else dep--; } // if dep is not 0 then there // is need to add ')' at the back if (dep !== 0) { for (var i = 0; i < dep; i++) str = str + ")"; } return str; } // Driver code var str = ")))()"; document.write(balancedBrackets(str)); </script>
((()))()
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
ihritik
nidhi_biet
ujjwalgoel1103
rdtank
Constructive Algorithms
Competitive Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Pairs with same Manhattan and Euclidean distance
Breadth First Traversal ( BFS ) on a 2D array
Shortest path in a directed graph by Dijkstra’s algorithm
Multistage Graph (Shortest Path)
Runtime Errors
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 24968,
"s": 24940,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 25158,
"s": 24968,
"text": "Given an unbalanced bracket sequence of ‘(‘ and ‘)’, convert it into a balanced sequence by adding the minimum number of ‘(‘ at the beginning of the string and ‘)’ at the end of the string."
},
{
"code": null,
"e": 25169,
"s": 25158,
"text": "Examples: "
},
{
"code": null,
"e": 25209,
"s": 25169,
"text": "Input: str = “)))()” Output: “((()))()”"
},
{
"code": null,
"e": 25265,
"s": 25209,
"text": "Input: str = “())())(())())” Output: “(((())())(())())”"
},
{
"code": null,
"e": 25276,
"s": 25265,
"text": "Approach: "
},
{
"code": null,
"e": 25420,
"s": 25276,
"text": "Let us assume that whenever we encounter with opening bracket the depth increases by one and with a closing bracket the depth decreases by one."
},
{
"code": null,
"e": 25507,
"s": 25420,
"text": "Find the maximum negative depth in minDep and add that number of ‘(‘ at the beginning."
},
{
"code": null,
"e": 25607,
"s": 25507,
"text": "Then loop the new sequence to find the number of ‘)’s needed at the end of the string and add them."
},
{
"code": null,
"e": 25635,
"s": 25607,
"text": "Finally, return the string."
},
{
"code": null,
"e": 25681,
"s": 25635,
"text": "Below is the implementation of the approach: "
},
{
"code": null,
"e": 25685,
"s": 25681,
"text": "C++"
},
{
"code": null,
"e": 25690,
"s": 25685,
"text": "Java"
},
{
"code": null,
"e": 25698,
"s": 25690,
"text": "Python3"
},
{
"code": null,
"e": 25701,
"s": 25698,
"text": "C#"
},
{
"code": null,
"e": 25712,
"s": 25701,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return balancedBrackets stringstring balancedBrackets(string str){ // Initializing dep to 0 int dep = 0; // Stores maximum negative depth int minDep = 0; for (int i = 0; i < str.length(); i++) { if (str[i] == '(') dep++; else dep--; // if dep is less than minDep if (minDep > dep) minDep = dep; } // if minDep is less than 0 then there // is need to add '(' at the front if (minDep < 0) { for (int i = 0; i < abs(minDep); i++) str = '(' + str; } // Reinitializing to check the updated string dep = 0; for (int i = 0; i < str.length(); i++) { if (str[i] == '(') dep++; else dep--; } // if dep is not 0 then there // is need to add ')' at the back if (dep != 0) { for (int i = 0; i < dep; i++) str = str + ')'; } return str;} // Driver codeint main(){ string str = \")))()\"; cout << balancedBrackets(str);}",
"e": 26828,
"s": 25712,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG { // Function to return balancedBrackets string static String balancedBrackets(String str) { // Initializing dep to 0 int dep = 0; // Stores maximum negative depth int minDep = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(') dep++; else dep--; // if dep is less than minDep if (minDep > dep) minDep = dep; } // if minDep is less than 0 then there // is need to add '(' at the front if (minDep < 0) { for (int i = 0; i < Math.abs(minDep); i++) str = '(' + str; } // Reinitializing to check the updated string dep = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(') dep++; else dep--; } // if dep is not 0 then there // is need to add ')' at the back if (dep != 0) { for (int i = 0; i < dep; i++) str = str + ')'; } return str; } // Driver code public static void main(String[] args) { String str = \")))()\"; System.out.println(balancedBrackets(str)); }} // This code is contributed by ihritik",
"e": 28230,
"s": 26828,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return balancedBrackets String def balancedBrackets(Str): # Initializing dep to 0 dep = 0 # Stores maximum negative depth minDep = 0 for i in Str: if (i == '('): dep += 1 else: dep -= 1 # if dep is less than minDep if (minDep > dep): minDep = dep # if minDep is less than 0 then there # is need to add '(' at the front if (minDep < 0): for i in range(abs(minDep)): Str = '(' + Str # Reinitializing to check the updated String dep = 0 for i in Str: if (i == '('): dep += 1 else: dep -= 1 # if dep is not 0 then there # is need to add ')' at the back if (dep != 0): for i in range(dep): Str = Str + ')' return Str # Driver codeStr = \")))()\"print(balancedBrackets(Str)) # This code is contributed by Mohit Kumar",
"e": 29183,
"s": 28230,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG { // Function to return balancedBrackets string static string balancedBrackets(string str) { // Initializing dep to 0 int dep = 0; // Stores maximum negative depth int minDep = 0; for (int i = 0; i < str.Length; i++) { if (str[i] == '(') dep++; else dep--; // if dep is less than minDep if (minDep > dep) minDep = dep; } // if minDep is less than 0 then there // is need to add '(' at the front if (minDep < 0) { for (int i = 0; i < Math.Abs(minDep); i++) str = '(' + str; } // Reinitializing to check the updated string dep = 0; for (int i = 0; i < str.Length; i++) { if (str[i] == '(') dep++; else dep--; } // if dep is not 0 then there // is need to add ')' at the back if (dep != 0) { for (int i = 0; i < dep; i++) str = str + ')'; } return str; } // Driver code public static void Main() { String str = \")))()\"; Console.WriteLine(balancedBrackets(str)); }} // This code is contributed by ihritik",
"e": 30545,
"s": 29183,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return balancedBrackets string function balancedBrackets(str) { // Initializing dep to 0 var dep = 0; // Stores maximum negative depth var minDep = 0; for (var i = 0; i < str.length; i++) { if (str[i] === \"(\") dep++; else dep--; // if dep is less than minDep if (minDep > dep) minDep = dep; } // if minDep is less than 0 then there // is need to add '(' at the front if (minDep < 0) { for (var i = 0; i < Math.abs(minDep); i++) str = \"(\" + str; } // Reinitializing to check the updated string dep = 0; for (var i = 0; i < str.length; i++) { if (str[i] === \"(\") dep++; else dep--; } // if dep is not 0 then there // is need to add ')' at the back if (dep !== 0) { for (var i = 0; i < dep; i++) str = str + \")\"; } return str; } // Driver code var str = \")))()\"; document.write(balancedBrackets(str)); </script>",
"e": 31674,
"s": 30545,
"text": null
},
{
"code": null,
"e": 31683,
"s": 31674,
"text": "((()))()"
},
{
"code": null,
"e": 31726,
"s": 31683,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 31741,
"s": 31726,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31749,
"s": 31741,
"text": "ihritik"
},
{
"code": null,
"e": 31760,
"s": 31749,
"text": "nidhi_biet"
},
{
"code": null,
"e": 31775,
"s": 31760,
"text": "ujjwalgoel1103"
},
{
"code": null,
"e": 31782,
"s": 31775,
"text": "rdtank"
},
{
"code": null,
"e": 31806,
"s": 31782,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 31830,
"s": 31806,
"text": "Competitive Programming"
},
{
"code": null,
"e": 31838,
"s": 31830,
"text": "Strings"
},
{
"code": null,
"e": 31846,
"s": 31838,
"text": "Strings"
},
{
"code": null,
"e": 31944,
"s": 31846,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31953,
"s": 31944,
"text": "Comments"
},
{
"code": null,
"e": 31966,
"s": 31953,
"text": "Old Comments"
},
{
"code": null,
"e": 32015,
"s": 31966,
"text": "Pairs with same Manhattan and Euclidean distance"
},
{
"code": null,
"e": 32061,
"s": 32015,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 32119,
"s": 32061,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 32152,
"s": 32119,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 32167,
"s": 32152,
"text": "Runtime Errors"
},
{
"code": null,
"e": 32192,
"s": 32167,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32238,
"s": 32192,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 32272,
"s": 32238,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 32287,
"s": 32272,
"text": "C++ Data Types"
}
]
|
Apache Pig - Split Operator | The SPLIT operator is used to split a relation into two or more relations.
Given below is the syntax of the SPLIT operator.
grunt> SPLIT Relation1_name INTO Relation2_name IF (condition1), Relation2_name (condition2),
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
002,siddarth,Battacharya,22,9848022338,Kolkata
003,Rajesh,Khanna,22,9848022339,Delhi
004,Preethi,Agarwal,21,9848022330,Pune
005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar
006,Archana,Mishra,23,9848022335,Chennai
007,Komal,Nayak,24,9848022334,trivendram
008,Bharathi,Nambiayar,24,9848022333,Chennai
And we have loaded this file into Pig with the relation name student_details as shown below.
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);
Let us now split the relation into two, one listing the employees of age less than 23, and the other listing the employees having the age between 22 and 25.
SPLIT student_details into student_details1 if age<23, student_details2 if (22<age and age>25);
Verify the relations student_details1 and student_details2 using the DUMP operator as shown below.
grunt> Dump student_details1;
grunt> Dump student_details2;
It will produce the following output, displaying the contents of the relations student_details1 and student_details2 respectively.
grunt> Dump student_details1;
(1,Rajiv,Reddy,21,9848022337,Hyderabad)
(2,siddarth,Battacharya,22,9848022338,Kolkata)
(3,Rajesh,Khanna,22,9848022339,Delhi)
(4,Preethi,Agarwal,21,9848022330,Pune)
grunt> Dump student_details2;
(5,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar)
(6,Archana,Mishra,23,9848022335,Chennai)
(7,Komal,Nayak,24,9848022334,trivendram)
(8,Bharathi,Nambiayar,24,9848022333,Chennai)
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": 2759,
"s": 2684,
"text": "The SPLIT operator is used to split a relation into two or more relations."
},
{
"code": null,
"e": 2808,
"s": 2759,
"text": "Given below is the syntax of the SPLIT operator."
},
{
"code": null,
"e": 2903,
"s": 2808,
"text": "grunt> SPLIT Relation1_name INTO Relation2_name IF (condition1), Relation2_name (condition2),\n"
},
{
"code": null,
"e": 3005,
"s": 2903,
"text": "Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below."
},
{
"code": null,
"e": 3025,
"s": 3005,
"text": "student_details.txt"
},
{
"code": null,
"e": 3370,
"s": 3025,
"text": "001,Rajiv,Reddy,21,9848022337,Hyderabad\n002,siddarth,Battacharya,22,9848022338,Kolkata\n003,Rajesh,Khanna,22,9848022339,Delhi \n004,Preethi,Agarwal,21,9848022330,Pune \n005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar \n006,Archana,Mishra,23,9848022335,Chennai \n007,Komal,Nayak,24,9848022334,trivendram \n008,Bharathi,Nambiayar,24,9848022333,Chennai\n"
},
{
"code": null,
"e": 3463,
"s": 3370,
"text": "And we have loaded this file into Pig with the relation name student_details as shown below."
},
{
"code": null,
"e": 3661,
"s": 3463,
"text": "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); "
},
{
"code": null,
"e": 3818,
"s": 3661,
"text": "Let us now split the relation into two, one listing the employees of age less than 23, and the other listing the employees having the age between 22 and 25."
},
{
"code": null,
"e": 3914,
"s": 3818,
"text": "SPLIT student_details into student_details1 if age<23, student_details2 if (22<age and age>25);"
},
{
"code": null,
"e": 4013,
"s": 3914,
"text": "Verify the relations student_details1 and student_details2 using the DUMP operator as shown below."
},
{
"code": null,
"e": 4077,
"s": 4013,
"text": "grunt> Dump student_details1; \n\ngrunt> Dump student_details2; "
},
{
"code": null,
"e": 4208,
"s": 4077,
"text": "It will produce the following output, displaying the contents of the relations student_details1 and student_details2 respectively."
},
{
"code": null,
"e": 4618,
"s": 4208,
"text": "grunt> Dump student_details1; \n(1,Rajiv,Reddy,21,9848022337,Hyderabad) \n(2,siddarth,Battacharya,22,9848022338,Kolkata)\n(3,Rajesh,Khanna,22,9848022339,Delhi) \n(4,Preethi,Agarwal,21,9848022330,Pune)\n \ngrunt> Dump student_details2; \n(5,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar) \n(6,Archana,Mishra,23,9848022335,Chennai) \n(7,Komal,Nayak,24,9848022334,trivendram) \n(8,Bharathi,Nambiayar,24,9848022333,Chennai)\n"
},
{
"code": null,
"e": 4653,
"s": 4618,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4672,
"s": 4653,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4707,
"s": 4672,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4728,
"s": 4707,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 4761,
"s": 4728,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4774,
"s": 4761,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 4809,
"s": 4774,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4827,
"s": 4809,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4860,
"s": 4827,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4878,
"s": 4860,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4911,
"s": 4878,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4929,
"s": 4911,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4936,
"s": 4929,
"text": " Print"
},
{
"code": null,
"e": 4947,
"s": 4936,
"text": " Add Notes"
}
]
|
How to Remove Characters from a String in Arduino? | The remove function in Arduino helps you remove one or more characters from within a string.
myString.remove(index, count)
Here, index refers to the index from where removal has to start. Note that indexing in Arduino starts with 0. Thus, within string "Hello", 'H' is at index 0, 'e' is at index 1, and so on.
The count argument is optional, and it specifies the number of characters to remove. If you don’t specify the count, then all characters starting from index till the end of the string will be removed. If you specify count as say, 3, then 3 characters starting from index position will be removed.
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
String s1 = "Mississippi";
String s2 = "Mississippi";
String s3 = "Mississippi";
Serial.println(s1);
Serial.println(s2);
Serial.println(s3);
Serial.println();
s1.remove(3,6); //Remove 6 characters starting from position 3
s2.remove(3); //Remove all characters starting from position 3
s3.remove(3,1); //Remove 1 character starting from position 3
Serial.println(s1);
Serial.println(s2);
Serial.println(s3);
}
void loop() {
// put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, the removal of characters happens exactly as described in the comments of the code. | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "The remove function in Arduino helps you remove one or more characters from within a string."
},
{
"code": null,
"e": 1185,
"s": 1155,
"text": "myString.remove(index, count)"
},
{
"code": null,
"e": 1373,
"s": 1185,
"text": "Here, index refers to the index from where removal has to start. Note that indexing in Arduino starts with 0. Thus, within string \"Hello\", 'H' is at index 0, 'e' is at index 1, and so on."
},
{
"code": null,
"e": 1670,
"s": 1373,
"text": "The count argument is optional, and it specifies the number of characters to remove. If you don’t specify the count, then all characters starting from index till the end of the string will be removed. If you specify count as say, 3, then 3 characters starting from index position will be removed."
},
{
"code": null,
"e": 2292,
"s": 1670,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n String s1 = \"Mississippi\";\n String s2 = \"Mississippi\";\n String s3 = \"Mississippi\";\n\n Serial.println(s1);\n Serial.println(s2);\n Serial.println(s3);\n Serial.println();\n\n s1.remove(3,6); //Remove 6 characters starting from position 3\n s2.remove(3); //Remove all characters starting from position 3\n s3.remove(3,1); //Remove 1 character starting from position 3\n\n Serial.println(s1);\n Serial.println(s2);\n Serial.println(s3);\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}"
},
{
"code": null,
"e": 2335,
"s": 2292,
"text": "The Serial Monitor output is shown below −"
},
{
"code": null,
"e": 2435,
"s": 2335,
"text": "As you can see, the removal of characters happens exactly as described in the comments of the code."
}
]
|
CBSE 12th class Paper Solved - 2015-16 session - GeeksforGeeks | 24 Feb, 2022
Sample Question Paper – Set II Computer Science (083) Class- XII (2015-16) Time: 3hrs M.M: 70Instructions: i. All Questions are Compulsory. ii. Programming Language: Section A : C++ iii. Programming Language: Section B: Python iv. Answer either Section A or B, and Section C is compulsory
Q1 a. Define Macro with suitable example. 2Ans: Macros are preprocessor directive created using # define that serve as symbolic constants. They are a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. They are created to simplify and reduce the amount of repetitive coding. For instance,
CPP
#define sum (a, b) a + b
Defines the macro sum, taking two arguments a and b. This macro may be called like any function. Therefore, after preprocessing:
CPP
z = sum(x, y);is replaced with Z = x + y;
b. Which C++ header file (s) will be included to run /execute the following C++ code? 1
CPP
void main(){ int Last = 26.5698742658; cout << setw(5) << setprecision(9) << Last;}
Ans: The two header files that need to be included are: iostream: iostream stands for standard input output stream. This header file contains definitions to objects like cin, cout etc. iomanip: iomanip stands for input output manipulators. The methods declared in this files are used for manipulating streams. This file contains definitions of setw, setprecision etc. c. Rewrite the following program after removing any syntactical errors. Underline each correction made. 2
CPP
#include<iostream.h>void main() int A[10];A = [ 3, 2, 5, 4, 7, 9, 10 ];for (p = 0; p <= 6; p++) { if (A[p] % 2 = 0) int S = S + A[p];}cout << S;}
Ans: In the above code, curly bracket after main() is missing, the elements of the array are wrongly declared, variable p is not declared and S can’t be declared inside the block. So, the following corrections are made:
#include <iostream.h>
void main() {
int A[10] = { 3, 2, 5, 4, 7, 9, 10 };
int S = 0, p;
for (p = 0; p <= 6; p++) {
if (A[p] % 2 == 0)
S = S + A[p];
}
cout << S;
}
d. Find the output of the following C++ program: 2
CPP
#include <iostream.h>void repch(char s[]){ for (int i = 0; s[i] != '\0'; i++) { if (((i % 2) != 0) && (s[i] != s[i + 1])) { s[i] = '@'; } else if (s[i] == s[i + 1]) { s[i + 1] = '!'; i++; } }}void main(){ char str[] = "SUCCESS"; cout << "Original String" << str repch(str); cout << "Changed String" << str;}
Ans: Output: Replace ‘@’ in place of U, ‘!’ in place of second C and ‘!’ in place of third S
Original String SUCCESS
Changed String S@C!ES!
e. Find the output of the following : 3
CPP
#include <iostream.h> void switchover(int A[], int N, int split){ for (int K = 0; K < N; K++) if (K < split) A[K] += K; else A[K] *= K;} void display(int A[], int N){ for (int K = 0; K < N; K++) (K % 2 == 0) ? cout << A[K] << "%" : cout << A[K] << endl;}void main(){ int H[] = { 30, 40, 50, 20, 10, 5 }; switchover(H, 6, 3); display(H, 6);}
Ans: In the above program, when switchover () function is called by passing the address of array, size of array and split = 3. In this function for K = 0, 1, 2, if condition is executed and K is added to the array elements i.e. 30+0 = 30, 40+1 = 41, 50+2 = 52 and after that else condition is followed and array elements are multiplied, 20*3 = 60, 10*4 = 40, 5*5 = 25. Display () prints the value of the modified array and the output is:
30%41
52%60
40%25
f. Observe the following C++ code and find out, which out of the given options i) to iv) are the expected correct output. Also assign the maximum and minimum value that can be assigned to the variable ‘Go’. 2
CPP
void main(){ int X[4] = { 100, 75, 10, 125 }; int Go = random(2) + 2; for (int i = Go; i < 4; i++) cout << X[i] << "$$";}
i. 100$$75 ii. 75$$10$$125$$ iii. 75$$10$$ iv.10$$125$$Ans: Option (iv) can be the only correct answer if Go=2. In this case 10$$125$$ will be printed. Minimum value of Go = 2 (when random(2) = 0) Maximum value of Go = 3 (when random(2) = 1)Q2 a. Differentiate between data abstraction and data hiding. 2 Ans: Data hiding can be defined as the mechanism of hiding the data of a class from the outside world. This is done to protect the data from any accidental or intentional access. Data hiding is achieved by making the members of the class private. Data abstraction refers to, providing only essential information to the outside world and hiding their background details. Members defined with a public label are accessible to all parts of the program. The data abstraction view of a type is defined by its public members. b. Answer the questions (i) and (ii) after going through the following class : 2
CPP
class Exam { int Rollno; char Cname[25]; float Marks; public: Exam() // Function 1 { Rollno = 0; Cname =""; Marks = 0.0; } Exam(int Rno, char candname) // Function 2 { Rollno = Rno; strcpy(Cname, candname); } ~Exam() // Function 3 { cout << "Result will be intimated shortly" << endl; } void Display() // Function 4 { cout << "Roll no :"<< Rollno; cout <<"Name :" << Cname; cout <<" Marks :"<< Marks; }};
(i) Which OOP concept does Function 1 and Function 2 implement. Explain? Ans: Function 1 and Function 2 are Constructor, which implement the concept Overloading and Polymorphism, as multiple definitions for Constructors are given in the same scope. Function 1 is a Default constructor and function 2 is a Parameterized constructor.(ii) What is Function 3 called? When will it be invoked? Ans: Function 3 is a Destructor which is invoked when the object goes out of scope. c. Define a class Candidate in C++ with the following specification : 4 Private Members :
A data members Rno(Registration Number) type long
A data member Cname of type string
A data members Agg_marks (Aggregate Marks) of type float
A data members Grade of type char
A member function setGrade () to find the grade as per the aggregate marks obtained by the student. Equivalent aggregate marks range and the respective grade as shown below:
Public members:
A constructor to assign default values to data members: Rno=0, Cname=”N.A”, Agg_marks=0.0
A function Getdata () to allow users to enter values for Rno. Cname, Agg_marks and call function setGrade () to find the grade.
A function dispResult( ) to allow user to view the content of all the data members.
Ans: :
CPP
class Candidate { long Rno; char Cname[20]; float Agg_marks; char Grade; void setGrade() { if (Agg_marks >= 80) Grade = ‘A’; else if (Agg_marks < 80 && Agg_marks >= 65) Grade = ‘B’; else if (Agg_marks < 65 && Agg_marks >= 50) Grade =’C’; else Grade =’D’; } public: Candidate() { Rno = 0; Strcpy(Cname, "N.A."); Agg_marks = 0.0; } void Getdata() { cout << "Registration No"; cin >> Rno; cout << "Name"; cin >> Cname; cout << Aggregate Marks "; cin >> Agg_marks; setGrade(); } void dispResult() { cout << "Registration No" << Rno; cout << "Name" << Cname; cout << Aggregate Marks "<< Agg_marks; }
d. Give the following class definition answer the question that is follows: 4
CPP
class University { char name[20]; protected: char vc[20]; public: void estd(); void inputdata(); void outputdata();} class College : protected University { int regno; protected char principal() public : int no_of_students; void readdata(); void dispdata ( );}; class Department : public College { char name[20];public: void fetchdata(int); void displaydata(); };
i) Name the base class and derived class of college. 1 Ans: Base class: University Derived class: Department ii) Name the data member(s) that can be accessed from function displaydata(). Ans: char name[20], char HOD[20], char principal(), int no_of_students, char vc[20]iii) What type of inheritance is depicted in the above class definition? Ans: Multilevel Inheritance iv) What will be the size of an object (in bytes) of class Department? Ans: 85 bytes Q3 a. An integer array A [30][40] is stored along the column in the memory. If the element A[20][25] is stored at 50000, find out the location of A[25][30]. 3 Ans: A[i][j] = B + W[No.of rows x (I – Lr) + (J – Lc)] A[20][25] = B + 2[30 x (20 – 0) + (25 – 0)] 50000 = B + 2[30 x (20 – 0) + (25 – 0)] B = 48750A[7][10] = 48750 + 2[30 x (7 – 0) + (10 – 0)] A[7][10] = 49190 b. Write the definition of functions for the linked implemented queue containing passenger information as follows: 4
CPP
struct NODE { int Ticketno; char PName[20]; NODE* NEXT;};class Queueofbus { NODE *Rear, *Front; public: Queueofbus() { Rear = NULL; Front = NULL; }; void Insert(); void Delete(); ~Queueofbus() { cout << "Object destroyed"; }};
Ans:
CPP
void Queueofbus::Insert(){ NODE* p = new NODE; cout << "Enter Ticket no"; cin >> p->Ticketno; cout << "Enter Name"; cin >> p->PName; p->NEXT = NULL; if (rear == NULL) { Rear = p; Front = Rear; } else { Rear->NEXT = p; Rear = Rear->NEXT; }}
c. Write a function to sort any array of n elements using insertion sort. Array should be passed as argument to the function. 3Ans:
CPP
void insertsort(int a[], int n){ int p, ptr; // Assuming a[0] = int_min i.e. smallest integer for (p = 1; p <= n; p++) { temp = a[p]; ptr = p - 1; while (temp <= a[ptr]) { a[ptr + 1] = a[ptr]; // Move Element Forward ptr--; } a[ptr + 1] = temp; // Insert Element in Proper Place }
d. Write a function NewMAT(int A[][], int r, int c ) in C++, which accepts a 2d array of integer and its size as parameters divide all those array elements by 6 which are not in the range 60 to 600(both values inclusive) in the 2d Array . 2Ans:
CPP
void NewMAT(int A[][], int r, int c){ for (int i = 0; i < r; i++) for (j = 0; j < c; j++) if ((A[i][j] >= 60) && (A[i][j] <= 600)) A[i][j] /= 6; or A[i][j] = A[i][j] / 6;}
e. Evaluate the following postfix expression using stack and show the contents after execution of each Operations : 470, 5, 4, ^, 25, /, 6, * 2Ans:
Q4 a. Consider a file F containing objects E of class Emp. 1i) Write statement to position the file pointer to the end of the file Ans: F.seekg(0, ios::end);ii) Write statement to return the number of bytes from the beginning of the file to the current position of the file pointer. Ans: F.tellg();b. Write a function RevText() to read a text file ” Input.txt ” and Print only word starting with ‘I’ in reverse order . 2 Example: If value in text file is: INDIA IS MY COUNTRY Output will be: AIDNI SI MY COUNTRY Ans:
CPP
void RevText(){ ifstream in("Input.txt"); char word[25]; while (in) { in >> word; if (word[0] ==’I’) cout << rrev(word); else cout << word;
c. Write a function in C++ to search and display details, whose destination is “Chandigarh” from binary file “Flight.Data”. Assuming the binary file is containing the objects of the following class: 3
CPP
class FLIGHT { int Fno; // Flight Number char From[20]; // Flight Starting Point char To[20]; // Flight Destinationpublic: char* GetFrom(); { return from; } char* GetTo(); { return To; } void input() { cin >> Fno >> ; gets(From); get(To); } void show() { cout Fno << ": " From ":" To endl; }};
Ans:
CPP
void Dispdetails(){ ifstream fin("Flight.Dat"); Flight F; while (fin) { fin.read((char*)&F, sizeof(F)) if (strcmp(F.GetTo(), "Chandigarh")) F.show(); }}
Section : B (Python)
Q1 a. List one similarity and one difference between List and Dictionary datatype. 2 Ans: Similarity: Both List and Dictionary are mutable datatypes. Dissimilarity: List is a sequential data type i.e. they are indexed. Dictionary is a mapping datatype. It consists of key: value pair. Eg: L =[1, 2, 3, 4, 5] is a list D= {1:”Ajay”, 2:”Prashant, 4:”Himani”} is a dictionary where 1, 2, 4 are keys and “Ajay”, Prashant, “Himani” are their corresponding values.b. Observe the following Python functions and write the name(s) of the module(s) to which they belong: 1 i) uniform() ii) findall()Ans: i) random ii) re c. Rewrite the following Python program after removing all the syntactical errors (if any), underlining each correction: 2
Python
def checkval : x = raw_input("Enter a number")if x % 2 = 0 :print x, "is even"else if x < 0 :print x, "should be positive"else;print x, "is odd"
Ans:
def checkval():
x = raw_input("Enter a number")
if x % 2 == 0:
print x, "is even"
elif x < 0 :
print x, "should be positive"
else:
print x, "is odd"
d. Find the output of the following Python program: 3
Python3
def makenew(mystr): newstr = " " count = 0 for i in mystr: if(count % 2 != 0): newstr = newstr + str(count) else: if(i.islower()): newstr = newstr + i.upper() else: newstr = newstr + i count += 1 newstr = newstr + mystr[:1] print("The new string is :", newstr)makenew("sTUdeNT")
Ans: The new string is: S1U3E5Ts e. Find the output of the following program 2
CPP
def calcresult(): i = 9 while i > 1: if (i % 2 == 0): x = i % 2 i = i - 1 else: i = i - 2 x = i print x * *2
Ans: Output:
49
25
9
1
f. Observe the following Python code and find out, which out of the given options i) to iv) are the expected correct output(s). Also assign the maximum and minimum value that can be assigned to the variable ‘Go’. 2
Python3
import random X =[100, 75, 10, 125]Go = random.randint(0, 3)for i in range(Go) :print X[i], "$$",
i. 100$$75$$10$$ ii. 75$$10$$125$$ iii. 75$$10$$ iv.10$$125$$100
Ans: i. 100$$75$$10$$ Minimum Value that can be assigned to Go is 0 Maximum Value that can be assigned to Go is 3 Q2 a. Discuss the strategies employed by python for memory allocation? 2Ans: Python uses two strategies for memory allocation- Reference counting and Automatic garbage collection: Reference Counting: works by counting the number of times an object is referenced by other objects in the system. When an object’s reference count reaches zero, Python collects it automatically. Automatic Garbage Collection: Python schedules garbage collection based upon a threshold of object allocations and object de-allocations. When the number of allocations minus the number of deallocations are greater than the threshold number, the garbage collector is run and the unused block of memory is reclaimed.b. Answer the questions (i) and (ii) after going through the following class definition: 2
class Toy :
tid =0;
tcat = " "
def __init__(self):// Function1
10
..................................... // Blank 2
i. Explain relevance of Function 1.Ans: __init__ function is used to initialize the members of a class. It is automatically invoked when the object of the class is created.ii (a). Fill in the blanks with a statement to create object of the class TOY.Ans: T=Toy()(b). Write statement to check whether tprice is an attribute of class TOY.Ans: hasattr(T, tprice) c. Define a class Train in PYTHON with following description: 4Data Members src of type string Tnm of type string dest of type string charges of float • A member function Getdata to assign the following values for Charges
Public Members: • A constructor to initialize the data members. • A function InputData() to allow the user to enter the values • A function displaydata() to display all and call getdata functionAns:
Python3
class train : def __init__(self): _src = "" _tnm = "" _dest = "" _charges = 0.0 def getdata(self): if self._dest == "mumbai" or self._dest == "MUMBAI": self._charges = 1000 elif self._dest == "chennai" or self._dest == "CHENNAI" : self._charges = 2000 elif self._dest == "kolkata" or self._dest == "KOLKATA" : self._charges = 2500 def inputdata(self): self._src = raw_input("enter the source of journey") self._tnm = raw_input("enter the train name") self._dest = raw_input("enter the destination")
d. Observe the following class definition and answer the question that follow: 2
i. Explain the relevance of Line1..Ans: super() function is used to call the methods of base class which have been extended in derived class. Also, it is the importance of derived class __init__() to invoke the base class __init__(). ii. What type of inheritance is being demonstrated in the above code?Ans: single level inheritance in Pythone. Write a user defined function findname(name) where name is an argument in Python to delete phone number from a dictionary phonebook on the basis of the name, where name is the key. Ans:
Q3 a. Explain try..except...else ... with the help of user defined function def divide(x, y) which raises an error when the denominator is zero while dividing x by y and displays the quotient otherwise. 3Ans:
Python
def divide(x, y): try: result = x / y except ZeroDivisionError: print "division by zero!" else: print "result is", result
In the above example: try block consists of code that can raise an error. When y(denominator) gets a 0 value, ZeroDivisionError is raised which is handled by except clause. In case of no exception else statement is executed. In case there is no error the statement(s) in else clause are executedb. Write a user defined function arrangelements(X), that accepts a list X of integers and sets all the negative elements to the left and all positive elements to the right of the list. Eg: if L =[1, -2, 3, 4, -5, 7], the output should be: [-2, -5, 3, 4, 7] 3 Eg: if L =[1, -2, 3, 4, -5, 7], the output should be: [-2, -5, 3, 4, 7] 3Ans:
Python
def arrangelements(X): L = len(X) for i in range(L): if a[i] < 0 and i != 0: j = i while j != 0 and a[j - 1] > 0: a[j], [j - 1] = a[j - 1], a[j] j = j - 1
c. Consider the following class definition:- 3
Python
class book (): bk = [] def _ init _ (self, bno): self .bno = bno def addbook (self): ............... def removebook (self): ...............
The class book is implemented using Queue. Keeping the same in mind, complete the function definitions for adding a book addbook() and deleting a book removebook(). Ans:
Python3
def addbook(self): a = input("enter book number: ") book.bk.append(a) def removebook (self): if (book.bk ==[]): print "Queue empty" else: print "deleted element is: ", book.bk[0]del book.bk[0]
d. Write a python function generate fibo(n) where n is the limit using a generator function Fibonacci (max) where max is the limit n that produces Fibonacci series. 3Ans:
Python3
def Fibonacci (max): a, b = 0, 1 while a <= max: yield a a, b = b, a + b def generatefibo(n) for i in Fibonacci (n): print i
e. Evaluate the following postfix using stack & show the content of the stack after the execution of each: 220, 4, +, 3, -, 7, 1Ans:
Q4 a. Consider the following code: 1
Explain statement 1 and give output of 2.Ans: Statement 1 uses seek()method can be used to position the file object at a particular place in the file. It’s syntax is :fileobject.seek(offset [, from_what]). So, f.seek(-3, 2) positions the fileobject to 3 bytes before the end of the file.Output of 2 is: de (It reads 2 bytes from where the file object is placed.) b. Write a user defined function in Python that displays the number of lines starting with ‘H’ in the file Para.txt.Eg: if the file contains: 2Whose woods these are I think I know. His house is in the village though; He will not see me stopping here To watch his woods fill up with snow. Then the line count should be 2.Ans:
Python3
def countH(): f = open ("Para.txt", "r") lines = 0 l = f.readlines() for i in l: if i[0] == 'H': lines += 1print "no. of lines is", lines
c. Consider a binary file Employee.dat containing details such as empno: ename: salary (separator ‘ :’). Write a python function to display details of those employees who are earning between 20000 and 40000.(both values inclusive) 3Ans:
Section : C
Q5 a. Differentiate between cardinality and degree of a table with the help of an example. 2Ans: Cardinality is defined as the number of rows in a table. Degree is the number of columns in a table.b) Consider the following tables FACULTY and COURSES. Write SQL commands for the statements (i) to (v) and give outputs for SQL queries (vi) to (vii) 6
i) To display details of those Faculties whose salary is greater than 12000.Ans:
Select * from faculty
where salary > 12000
ii) To display the details of courses whose fees is in the range of 15000 to 50000 (both values included).Ans:
Select * from Courses
where fees between 15000 and 50000
iii) To increase the fees of all courses by 500 of “System Design” Course. Ans:
Update courses set fees = fees + 500
where Cname = "System Design"
iv) To display details of those courses which are taught by ‘Sulekha’ in descending order ofcourses.Ans:
Select *from faculty fac, courses cour
where fac.f_id = cour.f_id and
fac.fname = 'Sulekha' order by cname desc
v) Select COUNT(DISTINCT F_ID) from COURSES; Ans: 4vi) Select MIN(Salary) from FACULTY, COURSES where COURSES.F_ID = FACULTY.F_ID; Ans: 6000Q6 a. State and Verify Absorption law algebraically. 2Ans:Absorption law states that: A + AB = A and A.(A + B) = AAlgebraic method: Taking LHS : A + AB = (A.1) + (A.B) by Identity = A. (1+B) by Distribution = A.1 by Null Element = A b. Draw a logic circuit for the following Boolean expression: A.B+C.D’. 2 Ans:
c. Write the SOP form of a Boolean function F, which is represented in a truth table as follows: 1 A B C F 0 0 0 0 0 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 0 1 1 1 1 0 0 1 1 1 0Ans: A’B’C + A’BC’ + AB’C’ + AB’Cd. Obtain a simplified from for a Boolean expression: F (U, V, W, Z) = II (0, 1, 3, 5, 6, 7, 15)Ans: (u + v + w).(u + z’).(v’ + w’).(u’ + w’ + z) Q7 a. Write any 1 advantage and 1 disadvantage of Bus topology. 1Ans: Advantage: Since there is a single common data path connecting all the nodes, the bus topology uses a very short cable length which considerably reduces the installation cost. Disadvantage: Fault detection and isolation is difficult. This is because control of the network is not centralized in any particular node. If a node is faulty on the bus, detection of fault may have to be performed at many points on the network. The faulty node has then to be rectified at that connection point.b. SunRise Pvt. Ltd. is setting up the network in the Ahmadabad. There are four departments named as MrktDept, FunDept, LegalDept, SalesDept. 4
Distance between various buildings is given as follows:
Number of Computers in the buildings:
i) Suggest a cable layout of connections between the Departments and specify topology.Ans:
ii) Suggest the most suitable building to place the server with a suitable reason. Ans: As per 80 – 20 rule, MrktDept because it has maximum no. of computers. iii) Suggest the placement of i) modem ii) Hub /Switch in the network.Ans: Each building should have a hub/switch and Modem in case Internet connection is requirediv) The organization is planning to link its sale counter situated in various part of the same city/ which type of network out of LAN, WAN, MAN will be formed??Justify.Ans: MAN (Metropolitan Area Network) c. Name the protocol 1i. Used to transfer voice using packet switched network.Ans: VOIP (Voice Over Internet Protocol), is used for the transmission of voice traffic over Internet-based networks.ii. Used for chatting between 2 groups or between 2 individuals.Ans: Internet Relay Chat is an open protocol that allows users to chat with each other online. It operates on a client/server model.d. What is an IP Address? 1 Ans: Internet Protocol (IP) Address is an address that uniquely identifies a device on the Internet. It allows a system to be recognized by other systems that are present on the world wide web. There are two primary types of IP address formats used — IPv4 and IPv6. Data transmission and routing over the internet requires the IP address of both the sender and receiver computer.e. What is HTTP? 1Ans: Hyper Text Transfer Protocol(HTTP) is an application-level protocol used to transfer data like text, graphic, images, sound, video, and other multimedia files over the web. HTTP is a part of the Internet protocol suite and uses a server-client paradigm for transmitting data.f. Explain the importance of Cookies. 1Ans: Cookies are small text files stored in the user’s browser directory or data folder to retain the browsing information of a user like the login credentials, browsed web pages to identify customers and customize their browsing experience. The main purpose of a cookie is to identify users and possibly prepare customized Web pages or to save site login information for the user.g. How is 4G different from 3G? 1Ans: 3G stands for 3rd Generation and 4G is the 4th Generation of mobile broadband internet. The basic difference between the 3G and the 4G is the speed of transmission of mobile data. The average 3G speed is considered to be 3 MBps while in 4G, it is upto 15 MBps in India.
varshagumber28
CBSE - Class 12
Programming Basics
school-programming
C++
Python
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
List in C++ Standard Template Library (STL)
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": 23707,
"s": 23679,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 23997,
"s": 23707,
"text": "Sample Question Paper – Set II Computer Science (083) Class- XII (2015-16) Time: 3hrs M.M: 70Instructions: i. All Questions are Compulsory. ii. Programming Language: Section A : C++ iii. Programming Language: Section B: Python iv. Answer either Section A or B, and Section C is compulsory "
},
{
"code": null,
"e": 24354,
"s": 23997,
"text": "Q1 a. Define Macro with suitable example. 2Ans: Macros are preprocessor directive created using # define that serve as symbolic constants. They are a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. They are created to simplify and reduce the amount of repetitive coding. For instance, "
},
{
"code": null,
"e": 24358,
"s": 24354,
"text": "CPP"
},
{
"code": "#define sum (a, b) a + b",
"e": 24383,
"s": 24358,
"text": null
},
{
"code": null,
"e": 24514,
"s": 24383,
"text": "Defines the macro sum, taking two arguments a and b. This macro may be called like any function. Therefore, after preprocessing: "
},
{
"code": null,
"e": 24518,
"s": 24514,
"text": "CPP"
},
{
"code": "z = sum(x, y);is replaced with Z = x + y;",
"e": 24560,
"s": 24518,
"text": null
},
{
"code": null,
"e": 24650,
"s": 24560,
"text": "b. Which C++ header file (s) will be included to run /execute the following C++ code? 1 "
},
{
"code": null,
"e": 24654,
"s": 24650,
"text": "CPP"
},
{
"code": "void main(){ int Last = 26.5698742658; cout << setw(5) << setprecision(9) << Last;}",
"e": 24744,
"s": 24654,
"text": null
},
{
"code": null,
"e": 25220,
"s": 24744,
"text": "Ans: The two header files that need to be included are: iostream: iostream stands for standard input output stream. This header file contains definitions to objects like cin, cout etc. iomanip: iomanip stands for input output manipulators. The methods declared in this files are used for manipulating streams. This file contains definitions of setw, setprecision etc. c. Rewrite the following program after removing any syntactical errors. Underline each correction made. 2 "
},
{
"code": null,
"e": 25224,
"s": 25220,
"text": "CPP"
},
{
"code": "#include<iostream.h>void main() int A[10];A = [ 3, 2, 5, 4, 7, 9, 10 ];for (p = 0; p <= 6; p++) { if (A[p] % 2 = 0) int S = S + A[p];}cout << S;}",
"e": 25380,
"s": 25224,
"text": null
},
{
"code": null,
"e": 25602,
"s": 25380,
"text": "Ans: In the above code, curly bracket after main() is missing, the elements of the array are wrongly declared, variable p is not declared and S can’t be declared inside the block. So, the following corrections are made: "
},
{
"code": null,
"e": 25808,
"s": 25602,
"text": "#include <iostream.h>\nvoid main() { \n\n int A[10] = { 3, 2, 5, 4, 7, 9, 10 };\n int S = 0, p;\n for (p = 0; p <= 6; p++) {\n if (A[p] % 2 == 0)\n S = S + A[p];\n }\n cout << S;\n}"
},
{
"code": null,
"e": 25861,
"s": 25808,
"text": "d. Find the output of the following C++ program: 2 "
},
{
"code": null,
"e": 25865,
"s": 25861,
"text": "CPP"
},
{
"code": "#include <iostream.h>void repch(char s[]){ for (int i = 0; s[i] != '\\0'; i++) { if (((i % 2) != 0) && (s[i] != s[i + 1])) { s[i] = '@'; } else if (s[i] == s[i + 1]) { s[i + 1] = '!'; i++; } }}void main(){ char str[] = \"SUCCESS\"; cout << \"Original String\" << str repch(str); cout << \"Changed String\" << str;}",
"e": 26252,
"s": 25865,
"text": null
},
{
"code": null,
"e": 26347,
"s": 26252,
"text": "Ans: Output: Replace ‘@’ in place of U, ‘!’ in place of second C and ‘!’ in place of third S "
},
{
"code": null,
"e": 26395,
"s": 26347,
"text": "Original String SUCCESS\nChanged String S@C!ES! "
},
{
"code": null,
"e": 26437,
"s": 26395,
"text": "e. Find the output of the following : 3 "
},
{
"code": null,
"e": 26441,
"s": 26437,
"text": "CPP"
},
{
"code": "#include <iostream.h> void switchover(int A[], int N, int split){ for (int K = 0; K < N; K++) if (K < split) A[K] += K; else A[K] *= K;} void display(int A[], int N){ for (int K = 0; K < N; K++) (K % 2 == 0) ? cout << A[K] << \"%\" : cout << A[K] << endl;}void main(){ int H[] = { 30, 40, 50, 20, 10, 5 }; switchover(H, 6, 3); display(H, 6);}",
"e": 26841,
"s": 26441,
"text": null
},
{
"code": null,
"e": 27281,
"s": 26841,
"text": "Ans: In the above program, when switchover () function is called by passing the address of array, size of array and split = 3. In this function for K = 0, 1, 2, if condition is executed and K is added to the array elements i.e. 30+0 = 30, 40+1 = 41, 50+2 = 52 and after that else condition is followed and array elements are multiplied, 20*3 = 60, 10*4 = 40, 5*5 = 25. Display () prints the value of the modified array and the output is: "
},
{
"code": null,
"e": 27299,
"s": 27281,
"text": "30%41\n52%60\n40%25"
},
{
"code": null,
"e": 27510,
"s": 27299,
"text": "f. Observe the following C++ code and find out, which out of the given options i) to iv) are the expected correct output. Also assign the maximum and minimum value that can be assigned to the variable ‘Go’. 2 "
},
{
"code": null,
"e": 27514,
"s": 27510,
"text": "CPP"
},
{
"code": "void main(){ int X[4] = { 100, 75, 10, 125 }; int Go = random(2) + 2; for (int i = Go; i < 4; i++) cout << X[i] << \"$$\";}",
"e": 27652,
"s": 27514,
"text": null
},
{
"code": null,
"e": 28560,
"s": 27652,
"text": "i. 100$$75 ii. 75$$10$$125$$ iii. 75$$10$$ iv.10$$125$$Ans: Option (iv) can be the only correct answer if Go=2. In this case 10$$125$$ will be printed. Minimum value of Go = 2 (when random(2) = 0) Maximum value of Go = 3 (when random(2) = 1)Q2 a. Differentiate between data abstraction and data hiding. 2 Ans: Data hiding can be defined as the mechanism of hiding the data of a class from the outside world. This is done to protect the data from any accidental or intentional access. Data hiding is achieved by making the members of the class private. Data abstraction refers to, providing only essential information to the outside world and hiding their background details. Members defined with a public label are accessible to all parts of the program. The data abstraction view of a type is defined by its public members. b. Answer the questions (i) and (ii) after going through the following class : 2 "
},
{
"code": null,
"e": 28564,
"s": 28560,
"text": "CPP"
},
{
"code": "class Exam { int Rollno; char Cname[25]; float Marks; public: Exam() // Function 1 { Rollno = 0; Cname =\"\"; Marks = 0.0; } Exam(int Rno, char candname) // Function 2 { Rollno = Rno; strcpy(Cname, candname); } ~Exam() // Function 3 { cout << \"Result will be intimated shortly\" << endl; } void Display() // Function 4 { cout << \"Roll no :\"<< Rollno; cout <<\"Name :\" << Cname; cout <<\" Marks :\"<< Marks; }};",
"e": 29077,
"s": 28564,
"text": null
},
{
"code": null,
"e": 29641,
"s": 29077,
"text": "(i) Which OOP concept does Function 1 and Function 2 implement. Explain? Ans: Function 1 and Function 2 are Constructor, which implement the concept Overloading and Polymorphism, as multiple definitions for Constructors are given in the same scope. Function 1 is a Default constructor and function 2 is a Parameterized constructor.(ii) What is Function 3 called? When will it be invoked? Ans: Function 3 is a Destructor which is invoked when the object goes out of scope. c. Define a class Candidate in C++ with the following specification : 4 Private Members : "
},
{
"code": null,
"e": 29691,
"s": 29641,
"text": "A data members Rno(Registration Number) type long"
},
{
"code": null,
"e": 29726,
"s": 29691,
"text": "A data member Cname of type string"
},
{
"code": null,
"e": 29783,
"s": 29726,
"text": "A data members Agg_marks (Aggregate Marks) of type float"
},
{
"code": null,
"e": 29817,
"s": 29783,
"text": "A data members Grade of type char"
},
{
"code": null,
"e": 29992,
"s": 29817,
"text": "A member function setGrade () to find the grade as per the aggregate marks obtained by the student. Equivalent aggregate marks range and the respective grade as shown below: "
},
{
"code": null,
"e": 30014,
"s": 29996,
"text": "Public members: "
},
{
"code": null,
"e": 30104,
"s": 30014,
"text": "A constructor to assign default values to data members: Rno=0, Cname=”N.A”, Agg_marks=0.0"
},
{
"code": null,
"e": 30232,
"s": 30104,
"text": "A function Getdata () to allow users to enter values for Rno. Cname, Agg_marks and call function setGrade () to find the grade."
},
{
"code": null,
"e": 30316,
"s": 30232,
"text": "A function dispResult( ) to allow user to view the content of all the data members."
},
{
"code": null,
"e": 30325,
"s": 30316,
"text": "Ans: : "
},
{
"code": null,
"e": 30329,
"s": 30325,
"text": "CPP"
},
{
"code": "class Candidate { long Rno; char Cname[20]; float Agg_marks; char Grade; void setGrade() { if (Agg_marks >= 80) Grade = ‘A’; else if (Agg_marks < 80 && Agg_marks >= 65) Grade = ‘B’; else if (Agg_marks < 65 && Agg_marks >= 50) Grade =’C’; else Grade =’D’; } public: Candidate() { Rno = 0; Strcpy(Cname, \"N.A.\"); Agg_marks = 0.0; } void Getdata() { cout << \"Registration No\"; cin >> Rno; cout << \"Name\"; cin >> Cname; cout << Aggregate Marks \"; cin >> Agg_marks; setGrade(); } void dispResult() { cout << \"Registration No\" << Rno; cout << \"Name\" << Cname; cout << Aggregate Marks \"<< Agg_marks; }",
"e": 31135,
"s": 30329,
"text": null
},
{
"code": null,
"e": 31215,
"s": 31135,
"text": "d. Give the following class definition answer the question that is follows: 4 "
},
{
"code": null,
"e": 31219,
"s": 31215,
"text": "CPP"
},
{
"code": "class University { char name[20]; protected: char vc[20]; public: void estd(); void inputdata(); void outputdata();} class College : protected University { int regno; protected char principal() public : int no_of_students; void readdata(); void dispdata ( );}; class Department : public College { char name[20];public: void fetchdata(int); void displaydata(); };",
"e": 31654,
"s": 31219,
"text": null
},
{
"code": null,
"e": 32599,
"s": 31654,
"text": "i) Name the base class and derived class of college. 1 Ans: Base class: University Derived class: Department ii) Name the data member(s) that can be accessed from function displaydata(). Ans: char name[20], char HOD[20], char principal(), int no_of_students, char vc[20]iii) What type of inheritance is depicted in the above class definition? Ans: Multilevel Inheritance iv) What will be the size of an object (in bytes) of class Department? Ans: 85 bytes Q3 a. An integer array A [30][40] is stored along the column in the memory. If the element A[20][25] is stored at 50000, find out the location of A[25][30]. 3 Ans: A[i][j] = B + W[No.of rows x (I – Lr) + (J – Lc)] A[20][25] = B + 2[30 x (20 – 0) + (25 – 0)] 50000 = B + 2[30 x (20 – 0) + (25 – 0)] B = 48750A[7][10] = 48750 + 2[30 x (7 – 0) + (10 – 0)] A[7][10] = 49190 b. Write the definition of functions for the linked implemented queue containing passenger information as follows: 4 "
},
{
"code": null,
"e": 32603,
"s": 32599,
"text": "CPP"
},
{
"code": "struct NODE { int Ticketno; char PName[20]; NODE* NEXT;};class Queueofbus { NODE *Rear, *Front; public: Queueofbus() { Rear = NULL; Front = NULL; }; void Insert(); void Delete(); ~Queueofbus() { cout << \"Object destroyed\"; }};",
"e": 32887,
"s": 32603,
"text": null
},
{
"code": null,
"e": 32894,
"s": 32887,
"text": "Ans: "
},
{
"code": null,
"e": 32898,
"s": 32894,
"text": "CPP"
},
{
"code": "void Queueofbus::Insert(){ NODE* p = new NODE; cout << \"Enter Ticket no\"; cin >> p->Ticketno; cout << \"Enter Name\"; cin >> p->PName; p->NEXT = NULL; if (rear == NULL) { Rear = p; Front = Rear; } else { Rear->NEXT = p; Rear = Rear->NEXT; }}",
"e": 33196,
"s": 32898,
"text": null
},
{
"code": null,
"e": 33330,
"s": 33196,
"text": "c. Write a function to sort any array of n elements using insertion sort. Array should be passed as argument to the function. 3Ans: "
},
{
"code": null,
"e": 33334,
"s": 33330,
"text": "CPP"
},
{
"code": "void insertsort(int a[], int n){ int p, ptr; // Assuming a[0] = int_min i.e. smallest integer for (p = 1; p <= n; p++) { temp = a[p]; ptr = p - 1; while (temp <= a[ptr]) { a[ptr + 1] = a[ptr]; // Move Element Forward ptr--; } a[ptr + 1] = temp; // Insert Element in Proper Place }",
"e": 33684,
"s": 33334,
"text": null
},
{
"code": null,
"e": 33931,
"s": 33684,
"text": "d. Write a function NewMAT(int A[][], int r, int c ) in C++, which accepts a 2d array of integer and its size as parameters divide all those array elements by 6 which are not in the range 60 to 600(both values inclusive) in the 2d Array . 2Ans: "
},
{
"code": null,
"e": 33935,
"s": 33931,
"text": "CPP"
},
{
"code": "void NewMAT(int A[][], int r, int c){ for (int i = 0; i < r; i++) for (j = 0; j < c; j++) if ((A[i][j] >= 60) && (A[i][j] <= 600)) A[i][j] /= 6; or A[i][j] = A[i][j] / 6;}",
"e": 34146,
"s": 33935,
"text": null
},
{
"code": null,
"e": 34306,
"s": 34146,
"text": "e. Evaluate the following postfix expression using stack and show the contents after execution of each Operations : 470, 5, 4, ^, 25, /, 6, * 2Ans: "
},
{
"code": null,
"e": 34825,
"s": 34306,
"text": "Q4 a. Consider a file F containing objects E of class Emp. 1i) Write statement to position the file pointer to the end of the file Ans: F.seekg(0, ios::end);ii) Write statement to return the number of bytes from the beginning of the file to the current position of the file pointer. Ans: F.tellg();b. Write a function RevText() to read a text file ” Input.txt ” and Print only word starting with ‘I’ in reverse order . 2 Example: If value in text file is: INDIA IS MY COUNTRY Output will be: AIDNI SI MY COUNTRY Ans: "
},
{
"code": null,
"e": 34829,
"s": 34825,
"text": "CPP"
},
{
"code": "void RevText(){ ifstream in(\"Input.txt\"); char word[25]; while (in) { in >> word; if (word[0] ==’I’) cout << rrev(word); else cout << word;",
"e": 35021,
"s": 34829,
"text": null
},
{
"code": null,
"e": 35223,
"s": 35021,
"text": "c. Write a function in C++ to search and display details, whose destination is “Chandigarh” from binary file “Flight.Data”. Assuming the binary file is containing the objects of the following class: 3 "
},
{
"code": null,
"e": 35227,
"s": 35223,
"text": "CPP"
},
{
"code": "class FLIGHT { int Fno; // Flight Number char From[20]; // Flight Starting Point char To[20]; // Flight Destinationpublic: char* GetFrom(); { return from; } char* GetTo(); { return To; } void input() { cin >> Fno >> ; gets(From); get(To); } void show() { cout Fno << \": \" From \":\" To endl; }};",
"e": 35613,
"s": 35227,
"text": null
},
{
"code": null,
"e": 35619,
"s": 35613,
"text": "Ans: "
},
{
"code": null,
"e": 35623,
"s": 35619,
"text": "CPP"
},
{
"code": "void Dispdetails(){ ifstream fin(\"Flight.Dat\"); Flight F; while (fin) { fin.read((char*)&F, sizeof(F)) if (strcmp(F.GetTo(), \"Chandigarh\")) F.show(); }}",
"e": 35806,
"s": 35623,
"text": null
},
{
"code": null,
"e": 35827,
"s": 35806,
"text": "Section : B (Python)"
},
{
"code": null,
"e": 36563,
"s": 35827,
"text": "Q1 a. List one similarity and one difference between List and Dictionary datatype. 2 Ans: Similarity: Both List and Dictionary are mutable datatypes. Dissimilarity: List is a sequential data type i.e. they are indexed. Dictionary is a mapping datatype. It consists of key: value pair. Eg: L =[1, 2, 3, 4, 5] is a list D= {1:”Ajay”, 2:”Prashant, 4:”Himani”} is a dictionary where 1, 2, 4 are keys and “Ajay”, Prashant, “Himani” are their corresponding values.b. Observe the following Python functions and write the name(s) of the module(s) to which they belong: 1 i) uniform() ii) findall()Ans: i) random ii) re c. Rewrite the following Python program after removing all the syntactical errors (if any), underlining each correction: 2 "
},
{
"code": null,
"e": 36570,
"s": 36563,
"text": "Python"
},
{
"code": "def checkval : x = raw_input(\"Enter a number\")if x % 2 = 0 :print x, \"is even\"else if x < 0 :print x, \"should be positive\"else;print x, \"is odd\"",
"e": 36715,
"s": 36570,
"text": null
},
{
"code": null,
"e": 36722,
"s": 36715,
"text": "Ans: "
},
{
"code": null,
"e": 36906,
"s": 36722,
"text": "def checkval():\n x = raw_input(\"Enter a number\")\n if x % 2 == 0:\n print x, \"is even\" \n elif x < 0 : \n print x, \"should be positive\" \nelse:\n print x, \"is odd\""
},
{
"code": null,
"e": 36962,
"s": 36906,
"text": "d. Find the output of the following Python program: 3 "
},
{
"code": null,
"e": 36970,
"s": 36962,
"text": "Python3"
},
{
"code": "def makenew(mystr): newstr = \" \" count = 0 for i in mystr: if(count % 2 != 0): newstr = newstr + str(count) else: if(i.islower()): newstr = newstr + i.upper() else: newstr = newstr + i count += 1 newstr = newstr + mystr[:1] print(\"The new string is :\", newstr)makenew(\"sTUdeNT\")",
"e": 37340,
"s": 36970,
"text": null
},
{
"code": null,
"e": 37420,
"s": 37340,
"text": "Ans: The new string is: S1U3E5Ts e. Find the output of the following program 2 "
},
{
"code": null,
"e": 37424,
"s": 37420,
"text": "CPP"
},
{
"code": "def calcresult(): i = 9 while i > 1: if (i % 2 == 0): x = i % 2 i = i - 1 else: i = i - 2 x = i print x * *2",
"e": 37593,
"s": 37424,
"text": null
},
{
"code": null,
"e": 37608,
"s": 37593,
"text": "Ans: Output: "
},
{
"code": null,
"e": 37619,
"s": 37608,
"text": "49\n25\n9\n1 "
},
{
"code": null,
"e": 37835,
"s": 37619,
"text": "f. Observe the following Python code and find out, which out of the given options i) to iv) are the expected correct output(s). Also assign the maximum and minimum value that can be assigned to the variable ‘Go’. 2 "
},
{
"code": null,
"e": 37843,
"s": 37835,
"text": "Python3"
},
{
"code": "import random X =[100, 75, 10, 125]Go = random.randint(0, 3)for i in range(Go) :print X[i], \"$$\",",
"e": 37941,
"s": 37843,
"text": null
},
{
"code": null,
"e": 38006,
"s": 37941,
"text": "i. 100$$75$$10$$ ii. 75$$10$$125$$ iii. 75$$10$$ iv.10$$125$$100"
},
{
"code": null,
"e": 38903,
"s": 38006,
"text": "Ans: i. 100$$75$$10$$ Minimum Value that can be assigned to Go is 0 Maximum Value that can be assigned to Go is 3 Q2 a. Discuss the strategies employed by python for memory allocation? 2Ans: Python uses two strategies for memory allocation- Reference counting and Automatic garbage collection: Reference Counting: works by counting the number of times an object is referenced by other objects in the system. When an object’s reference count reaches zero, Python collects it automatically. Automatic Garbage Collection: Python schedules garbage collection based upon a threshold of object allocations and object de-allocations. When the number of allocations minus the number of deallocations are greater than the threshold number, the garbage collector is run and the unused block of memory is reclaimed.b. Answer the questions (i) and (ii) after going through the following class definition: 2 "
},
{
"code": null,
"e": 39019,
"s": 38903,
"text": "class Toy :\ntid =0;\ntcat = \" \"\ndef __init__(self):// Function1 \n10\n..................................... // Blank 2"
},
{
"code": null,
"e": 39602,
"s": 39019,
"text": "i. Explain relevance of Function 1.Ans: __init__ function is used to initialize the members of a class. It is automatically invoked when the object of the class is created.ii (a). Fill in the blanks with a statement to create object of the class TOY.Ans: T=Toy()(b). Write statement to check whether tprice is an attribute of class TOY.Ans: hasattr(T, tprice) c. Define a class Train in PYTHON with following description: 4Data Members src of type string Tnm of type string dest of type string charges of float • A member function Getdata to assign the following values for Charges "
},
{
"code": null,
"e": 39805,
"s": 39604,
"text": "Public Members: • A constructor to initialize the data members. • A function InputData() to allow the user to enter the values • A function displaydata() to display all and call getdata functionAns: "
},
{
"code": null,
"e": 39813,
"s": 39805,
"text": "Python3"
},
{
"code": "class train : def __init__(self): _src = \"\" _tnm = \"\" _dest = \"\" _charges = 0.0 def getdata(self): if self._dest == \"mumbai\" or self._dest == \"MUMBAI\": self._charges = 1000 elif self._dest == \"chennai\" or self._dest == \"CHENNAI\" : self._charges = 2000 elif self._dest == \"kolkata\" or self._dest == \"KOLKATA\" : self._charges = 2500 def inputdata(self): self._src = raw_input(\"enter the source of journey\") self._tnm = raw_input(\"enter the train name\") self._dest = raw_input(\"enter the destination\") ",
"e": 40480,
"s": 39813,
"text": null
},
{
"code": null,
"e": 40563,
"s": 40480,
"text": "d. Observe the following class definition and answer the question that follow: 2 "
},
{
"code": null,
"e": 41096,
"s": 40563,
"text": "i. Explain the relevance of Line1..Ans: super() function is used to call the methods of base class which have been extended in derived class. Also, it is the importance of derived class __init__() to invoke the base class __init__(). ii. What type of inheritance is being demonstrated in the above code?Ans: single level inheritance in Pythone. Write a user defined function findname(name) where name is an argument in Python to delete phone number from a dictionary phonebook on the basis of the name, where name is the key. Ans: "
},
{
"code": null,
"e": 41306,
"s": 41096,
"text": "Q3 a. Explain try..except...else ... with the help of user defined function def divide(x, y) which raises an error when the denominator is zero while dividing x by y and displays the quotient otherwise. 3Ans: "
},
{
"code": null,
"e": 41313,
"s": 41306,
"text": "Python"
},
{
"code": "def divide(x, y): try: result = x / y except ZeroDivisionError: print \"division by zero!\" else: print \"result is\", result",
"e": 41447,
"s": 41313,
"text": null
},
{
"code": null,
"e": 42095,
"s": 41447,
"text": "In the above example: try block consists of code that can raise an error. When y(denominator) gets a 0 value, ZeroDivisionError is raised which is handled by except clause. In case of no exception else statement is executed. In case there is no error the statement(s) in else clause are executedb. Write a user defined function arrangelements(X), that accepts a list X of integers and sets all the negative elements to the left and all positive elements to the right of the list. Eg: if L =[1, -2, 3, 4, -5, 7], the output should be: [-2, -5, 3, 4, 7] 3 Eg: if L =[1, -2, 3, 4, -5, 7], the output should be: [-2, -5, 3, 4, 7] 3Ans: "
},
{
"code": null,
"e": 42102,
"s": 42095,
"text": "Python"
},
{
"code": "def arrangelements(X): L = len(X) for i in range(L): if a[i] < 0 and i != 0: j = i while j != 0 and a[j - 1] > 0: a[j], [j - 1] = a[j - 1], a[j] j = j - 1",
"e": 42298,
"s": 42102,
"text": null
},
{
"code": null,
"e": 42354,
"s": 42298,
"text": "c. Consider the following class definition:- 3 "
},
{
"code": null,
"e": 42361,
"s": 42354,
"text": "Python"
},
{
"code": "class book (): bk = [] def _ init _ (self, bno): self .bno = bno def addbook (self): ............... def removebook (self): ...............",
"e": 42534,
"s": 42361,
"text": null
},
{
"code": null,
"e": 42705,
"s": 42534,
"text": "The class book is implemented using Queue. Keeping the same in mind, complete the function definitions for adding a book addbook() and deleting a book removebook(). Ans: "
},
{
"code": null,
"e": 42713,
"s": 42705,
"text": "Python3"
},
{
"code": "def addbook(self): a = input(\"enter book number: \") book.bk.append(a) def removebook (self): if (book.bk ==[]): print \"Queue empty\" else: print \"deleted element is: \", book.bk[0]del book.bk[0]",
"e": 42951,
"s": 42713,
"text": null
},
{
"code": null,
"e": 43124,
"s": 42951,
"text": "d. Write a python function generate fibo(n) where n is the limit using a generator function Fibonacci (max) where max is the limit n that produces Fibonacci series. 3Ans: "
},
{
"code": null,
"e": 43132,
"s": 43124,
"text": "Python3"
},
{
"code": "def Fibonacci (max): a, b = 0, 1 while a <= max: yield a a, b = b, a + b def generatefibo(n) for i in Fibonacci (n): print i",
"e": 43272,
"s": 43132,
"text": null
},
{
"code": null,
"e": 43414,
"s": 43272,
"text": "e. Evaluate the following postfix using stack & show the content of the stack after the execution of each: 220, 4, +, 3, -, 7, 1Ans: "
},
{
"code": null,
"e": 43452,
"s": 43414,
"text": "Q4 a. Consider the following code: 1 "
},
{
"code": null,
"e": 44141,
"s": 43452,
"text": "Explain statement 1 and give output of 2.Ans: Statement 1 uses seek()method can be used to position the file object at a particular place in the file. It’s syntax is :fileobject.seek(offset [, from_what]). So, f.seek(-3, 2) positions the fileobject to 3 bytes before the end of the file.Output of 2 is: de (It reads 2 bytes from where the file object is placed.) b. Write a user defined function in Python that displays the number of lines starting with ‘H’ in the file Para.txt.Eg: if the file contains: 2Whose woods these are I think I know. His house is in the village though; He will not see me stopping here To watch his woods fill up with snow. Then the line count should be 2.Ans: "
},
{
"code": null,
"e": 44149,
"s": 44141,
"text": "Python3"
},
{
"code": "def countH(): f = open (\"Para.txt\", \"r\") lines = 0 l = f.readlines() for i in l: if i[0] == 'H': lines += 1print \"no. of lines is\", lines",
"e": 44300,
"s": 44149,
"text": null
},
{
"code": null,
"e": 44538,
"s": 44300,
"text": "c. Consider a binary file Employee.dat containing details such as empno: ename: salary (separator ‘ :’). Write a python function to display details of those employees who are earning between 20000 and 40000.(both values inclusive) 3Ans: "
},
{
"code": null,
"e": 44550,
"s": 44538,
"text": "Section : C"
},
{
"code": null,
"e": 44900,
"s": 44550,
"text": "Q5 a. Differentiate between cardinality and degree of a table with the help of an example. 2Ans: Cardinality is defined as the number of rows in a table. Degree is the number of columns in a table.b) Consider the following tables FACULTY and COURSES. Write SQL commands for the statements (i) to (v) and give outputs for SQL queries (vi) to (vii) 6 "
},
{
"code": null,
"e": 44983,
"s": 44900,
"text": "i) To display details of those Faculties whose salary is greater than 12000.Ans: "
},
{
"code": null,
"e": 45028,
"s": 44983,
"text": "Select * from faculty\n where salary > 12000"
},
{
"code": null,
"e": 45141,
"s": 45028,
"text": "ii) To display the details of courses whose fees is in the range of 15000 to 50000 (both values included).Ans: "
},
{
"code": null,
"e": 45200,
"s": 45141,
"text": "Select * from Courses\n where fees between 15000 and 50000"
},
{
"code": null,
"e": 45282,
"s": 45200,
"text": "iii) To increase the fees of all courses by 500 of “System Design” Course. Ans: "
},
{
"code": null,
"e": 45355,
"s": 45282,
"text": "Update courses set fees = fees + 500\n where Cname = \"System Design\" "
},
{
"code": null,
"e": 45462,
"s": 45355,
"text": "iv) To display details of those courses which are taught by ‘Sulekha’ in descending order ofcourses.Ans: "
},
{
"code": null,
"e": 45582,
"s": 45462,
"text": "Select *from faculty fac, courses cour \n where fac.f_id = cour.f_id and \n fac.fname = 'Sulekha' order by cname desc"
},
{
"code": null,
"e": 46036,
"s": 45582,
"text": "v) Select COUNT(DISTINCT F_ID) from COURSES; Ans: 4vi) Select MIN(Salary) from FACULTY, COURSES where COURSES.F_ID = FACULTY.F_ID; Ans: 6000Q6 a. State and Verify Absorption law algebraically. 2Ans:Absorption law states that: A + AB = A and A.(A + B) = AAlgebraic method: Taking LHS : A + AB = (A.1) + (A.B) by Identity = A. (1+B) by Distribution = A.1 by Null Element = A b. Draw a logic circuit for the following Boolean expression: A.B+C.D’. 2 Ans: "
},
{
"code": null,
"e": 47089,
"s": 46036,
"text": "c. Write the SOP form of a Boolean function F, which is represented in a truth table as follows: 1 A B C F 0 0 0 0 0 0 1 1 0 1 0 1 0 1 1 0 1 0 0 1 1 0 1 1 1 1 0 0 1 1 1 0Ans: A’B’C + A’BC’ + AB’C’ + AB’Cd. Obtain a simplified from for a Boolean expression: F (U, V, W, Z) = II (0, 1, 3, 5, 6, 7, 15)Ans: (u + v + w).(u + z’).(v’ + w’).(u’ + w’ + z) Q7 a. Write any 1 advantage and 1 disadvantage of Bus topology. 1Ans: Advantage: Since there is a single common data path connecting all the nodes, the bus topology uses a very short cable length which considerably reduces the installation cost. Disadvantage: Fault detection and isolation is difficult. This is because control of the network is not centralized in any particular node. If a node is faulty on the bus, detection of fault may have to be performed at many points on the network. The faulty node has then to be rectified at that connection point.b. SunRise Pvt. Ltd. is setting up the network in the Ahmadabad. There are four departments named as MrktDept, FunDept, LegalDept, SalesDept. 4 "
},
{
"code": null,
"e": 47146,
"s": 47089,
"text": "Distance between various buildings is given as follows: "
},
{
"code": null,
"e": 47186,
"s": 47148,
"text": "Number of Computers in the buildings:"
},
{
"code": null,
"e": 47280,
"s": 47188,
"text": "i) Suggest a cable layout of connections between the Departments and specify topology.Ans: "
},
{
"code": null,
"e": 49632,
"s": 47280,
"text": "ii) Suggest the most suitable building to place the server with a suitable reason. Ans: As per 80 – 20 rule, MrktDept because it has maximum no. of computers. iii) Suggest the placement of i) modem ii) Hub /Switch in the network.Ans: Each building should have a hub/switch and Modem in case Internet connection is requirediv) The organization is planning to link its sale counter situated in various part of the same city/ which type of network out of LAN, WAN, MAN will be formed??Justify.Ans: MAN (Metropolitan Area Network) c. Name the protocol 1i. Used to transfer voice using packet switched network.Ans: VOIP (Voice Over Internet Protocol), is used for the transmission of voice traffic over Internet-based networks.ii. Used for chatting between 2 groups or between 2 individuals.Ans: Internet Relay Chat is an open protocol that allows users to chat with each other online. It operates on a client/server model.d. What is an IP Address? 1 Ans: Internet Protocol (IP) Address is an address that uniquely identifies a device on the Internet. It allows a system to be recognized by other systems that are present on the world wide web. There are two primary types of IP address formats used — IPv4 and IPv6. Data transmission and routing over the internet requires the IP address of both the sender and receiver computer.e. What is HTTP? 1Ans: Hyper Text Transfer Protocol(HTTP) is an application-level protocol used to transfer data like text, graphic, images, sound, video, and other multimedia files over the web. HTTP is a part of the Internet protocol suite and uses a server-client paradigm for transmitting data.f. Explain the importance of Cookies. 1Ans: Cookies are small text files stored in the user’s browser directory or data folder to retain the browsing information of a user like the login credentials, browsed web pages to identify customers and customize their browsing experience. The main purpose of a cookie is to identify users and possibly prepare customized Web pages or to save site login information for the user.g. How is 4G different from 3G? 1Ans: 3G stands for 3rd Generation and 4G is the 4th Generation of mobile broadband internet. The basic difference between the 3G and the 4G is the speed of transmission of mobile data. The average 3G speed is considered to be 3 MBps while in 4G, it is upto 15 MBps in India. "
},
{
"code": null,
"e": 49647,
"s": 49632,
"text": "varshagumber28"
},
{
"code": null,
"e": 49663,
"s": 49647,
"text": "CBSE - Class 12"
},
{
"code": null,
"e": 49682,
"s": 49663,
"text": "Programming Basics"
},
{
"code": null,
"e": 49701,
"s": 49682,
"text": "school-programming"
},
{
"code": null,
"e": 49705,
"s": 49701,
"text": "C++"
},
{
"code": null,
"e": 49712,
"s": 49705,
"text": "Python"
},
{
"code": null,
"e": 49731,
"s": 49712,
"text": "School Programming"
},
{
"code": null,
"e": 49735,
"s": 49731,
"text": "CPP"
},
{
"code": null,
"e": 49833,
"s": 49735,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49842,
"s": 49833,
"text": "Comments"
},
{
"code": null,
"e": 49855,
"s": 49842,
"text": "Old Comments"
},
{
"code": null,
"e": 49883,
"s": 49855,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 49907,
"s": 49883,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 49927,
"s": 49907,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 49960,
"s": 49927,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 50004,
"s": 49960,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 50032,
"s": 50004,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 50082,
"s": 50032,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 50104,
"s": 50082,
"text": "Python map() function"
}
]
|
ArrayDeque pop() Method in Java - GeeksforGeeks | 10 Dec, 2018
The Java.util.ArrayDeque.pop() method in Java is used to pop an element from the deque. The element is popped from the top of the deque and is removed from the same.
Syntax:
Array_Deque.pop()
Parameters: The method does not take any parameters.
Return Value: This method returns the element present at the front of the Deque.
Exceptions: The method throws NoSuchElementException is thrown if the deque is empty.
Below programs illustrate the Java.util.ArrayDeque.pop() method:Program 1:
// Java code to illustrate pop()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("For"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using pop() method System.out.println("Popped element: " + de_que.pop()); System.out.println("Popped element: " + de_que.pop()); // Displaying the ArrayDeque after pop System.out.println("Deque after operation " + de_que); }}
Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]
Popped element: Welcome
Popped element: To
Deque after operation [Geeks, For, Geeks]
Program 2:
// Java code to illustrate pop()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using pop() method System.out.println("Popped element: " + de_que.pop()); System.out.println("Popped element: " + de_que.pop()); // Displaying the ArrayDeque after pop System.out.println("Deque after operation " + de_que); }}
Initial ArrayDeque: [10, 15, 30, 20, 5]
Popped element: 10
Popped element: 15
Deque after operation [30, 20, 5]
Java - util package
Java-ArrayDeque
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java | [
{
"code": null,
"e": 23770,
"s": 23742,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 23936,
"s": 23770,
"text": "The Java.util.ArrayDeque.pop() method in Java is used to pop an element from the deque. The element is popped from the top of the deque and is removed from the same."
},
{
"code": null,
"e": 23944,
"s": 23936,
"text": "Syntax:"
},
{
"code": null,
"e": 23962,
"s": 23944,
"text": "Array_Deque.pop()"
},
{
"code": null,
"e": 24015,
"s": 23962,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 24096,
"s": 24015,
"text": "Return Value: This method returns the element present at the front of the Deque."
},
{
"code": null,
"e": 24182,
"s": 24096,
"text": "Exceptions: The method throws NoSuchElementException is thrown if the deque is empty."
},
{
"code": null,
"e": 24257,
"s": 24182,
"text": "Below programs illustrate the Java.util.ArrayDeque.pop() method:Program 1:"
},
{
"code": "// Java code to illustrate pop()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"For\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using pop() method System.out.println(\"Popped element: \" + de_que.pop()); System.out.println(\"Popped element: \" + de_que.pop()); // Displaying the ArrayDeque after pop System.out.println(\"Deque after operation \" + de_que); }}",
"e": 25077,
"s": 24257,
"text": null
},
{
"code": null,
"e": 25216,
"s": 25077,
"text": "Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]\nPopped element: Welcome\nPopped element: To\nDeque after operation [Geeks, For, Geeks]\n"
},
{
"code": null,
"e": 25227,
"s": 25216,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate pop()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using pop() method System.out.println(\"Popped element: \" + de_que.pop()); System.out.println(\"Popped element: \" + de_que.pop()); // Displaying the ArrayDeque after pop System.out.println(\"Deque after operation \" + de_que); }}",
"e": 26041,
"s": 25227,
"text": null
},
{
"code": null,
"e": 26154,
"s": 26041,
"text": "Initial ArrayDeque: [10, 15, 30, 20, 5]\nPopped element: 10\nPopped element: 15\nDeque after operation [30, 20, 5]\n"
},
{
"code": null,
"e": 26174,
"s": 26154,
"text": "Java - util package"
},
{
"code": null,
"e": 26190,
"s": 26174,
"text": "Java-ArrayDeque"
},
{
"code": null,
"e": 26207,
"s": 26190,
"text": "Java-Collections"
},
{
"code": null,
"e": 26222,
"s": 26207,
"text": "Java-Functions"
},
{
"code": null,
"e": 26227,
"s": 26222,
"text": "Java"
},
{
"code": null,
"e": 26232,
"s": 26227,
"text": "Java"
},
{
"code": null,
"e": 26249,
"s": 26232,
"text": "Java-Collections"
},
{
"code": null,
"e": 26347,
"s": 26249,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26362,
"s": 26347,
"text": "Arrays in Java"
},
{
"code": null,
"e": 26406,
"s": 26362,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 26428,
"s": 26406,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 26464,
"s": 26428,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 26489,
"s": 26464,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 26521,
"s": 26489,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26572,
"s": 26521,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26602,
"s": 26572,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26621,
"s": 26602,
"text": "Interfaces in Java"
}
]
|
How to Highlight 3D Brain Regions | by Matt.0 | Towards Data Science | Recently, I was reading Howard et. al., (2018) “Genome-wide meta-analysis of depression in 807,553 individuals identifies 102 independent variants with replication in a further 1,507,153 individuals” and saw a really cool 3D visualization of highlighted brain regions associated with depression:
After an exhaustive search I couldn’t find any reference to how this was done in the methods or supplementary information so I reached out to the authors. While I was awaiting a response, I also reached out to the Twitterverse to see if anyone knew of tools which could be used to create such a visualization.
Helmet Karim suggested that perhaps these images were created using BrainNet Viewer in MATLABso this was the first method I tried out.
Note: All of the methods covered in this article use what is called a brain Atlas overlayed as a maskon a normalized T1 MRI image. I’ve chosen to highlight the left hippocampus across these methods so that they are comparable.
First follow the install instructions for BrainNet Viewer here then start the graphical user interface (GUI) up from the terminal.
Next select load file and choose a surface template surface template and a mapping file (i.e. a brain atlas). The package provides samples so I chose BrainMesh_ICBMI52_smoothed.nv and the [AAL90](http://neuro.imm.dtu.dk/wiki/Automated_Anatomical_Labeling) brain atlas which has labeled volumes for 90 brain regions.
Next there’s a pop-up with 7-sections of which layout, surface and volume are of interest to us.
In layout select which view you would like, I’ve chosen full view which will show eight different viewpoints.
In the surface tab you can select the transparency of the surface map — I’ve set it to 0.75.
In the volume tab select ROI drawing, deselect draw all and in the custom box put 37 (the code for hippocampus_L). Then select Ok.
I am currently in discussion with the Howard laboratory trying to get the exact methodology they used to create the image in their figure, but this how I believe they did it with [Mango].
Mango has good video tutorials, user guide and forum but for those of us whose sole interest is creating a highlighted 3D brain image it’s a lot of material to go through. Therefore, I decided to create a detailed protocol of this process to save others time.
I decided to download the Hammers brain atlas to use as the mask/overlay and the sample image provided with Mango
Next select Add Overlay and choose the hippocampus_L.
Now select Image > Build Surface to create a 3D representation of the brain.
In this new pop-up GUI there’s a few things we want to do. First, change the background to white so this can be published in a manuscript. Second, change the transparency of this image to 0.75.
Under the View tab deselect the Crosshairs.
In the other panel select Analysis > Create Logical Overlays then in the surface panel select Shapes > Add Logical.
Then under Surface > Views you can select any orientation you like then Surface > Create Snapshot to save as a .png.
Here are three views of the hippocampus_L: anterior, left and superior:
John Muschelli, an Assistant Scientist at Johns Hopkins Bloomberg School of Public Health who has authored numerous R packages (e.g. fslr) responded a couple weeks later to my tweet. He whipped up a gist to highlight a 3D brain image in R.
library(rgl)library(misc3d)library(neurobase)if (!requireNamespace("aal")) { devtools::install_github("muschellij2/aal")} else { library(aal)}if (!requireNamespace("MNITemplate")) { devtools::install_github("jfortin1/MNITemplate")} else { library(MNITemplate)}img = aal_image()template = readMNI(res = "2mm")cut <- 4500dtemp <- dim(template)# All of the sections you can labellabs = aal_get_labels()# Pick the region of the brain you would like to highlight - in this case the hippocamus_Lhippocampus = labs$index[grep("Hippocampus_L", labs$name)]mask = remake_img(vec = img %in% hippocampus, img = img)### this would be the ``activation'' or surface you want to render contour3d(template, x=1:dtemp[1], y=1:dtemp[2], z=1:dtemp[3], level = cut, alpha = 0.1, draw = TRUE)contour3d(mask, level = c(0.5), alpha = c(0.5), add = TRUE, color=c("red") )### add texttext3d(x=dtemp[1]/2, y=dtemp[2]/2, z = dtemp[3]*0.98, text="Top")text3d(x=-0.98, y=dtemp[2]/2, z = dtemp[3]/2, text="Right")rglwidget()
John Muschelli also teaches a couple of short courses on imaging in R and I’m currently taking his [Neurohacking] course. I really appreciate him taking the time to do this.
If your interested in learning more about medical imaging in R be sure to check out Neuroconductor
If you find this article useful feel free to share it with others or recommend this article! 😃
As always, if you have any questions or comments feel free to leave your feedback below or you can always reach me on LinkedIn. Till then, see you in the next post! 😄 | [
{
"code": null,
"e": 468,
"s": 172,
"text": "Recently, I was reading Howard et. al., (2018) “Genome-wide meta-analysis of depression in 807,553 individuals identifies 102 independent variants with replication in a further 1,507,153 individuals” and saw a really cool 3D visualization of highlighted brain regions associated with depression:"
},
{
"code": null,
"e": 778,
"s": 468,
"text": "After an exhaustive search I couldn’t find any reference to how this was done in the methods or supplementary information so I reached out to the authors. While I was awaiting a response, I also reached out to the Twitterverse to see if anyone knew of tools which could be used to create such a visualization."
},
{
"code": null,
"e": 913,
"s": 778,
"text": "Helmet Karim suggested that perhaps these images were created using BrainNet Viewer in MATLABso this was the first method I tried out."
},
{
"code": null,
"e": 1140,
"s": 913,
"text": "Note: All of the methods covered in this article use what is called a brain Atlas overlayed as a maskon a normalized T1 MRI image. I’ve chosen to highlight the left hippocampus across these methods so that they are comparable."
},
{
"code": null,
"e": 1271,
"s": 1140,
"text": "First follow the install instructions for BrainNet Viewer here then start the graphical user interface (GUI) up from the terminal."
},
{
"code": null,
"e": 1587,
"s": 1271,
"text": "Next select load file and choose a surface template surface template and a mapping file (i.e. a brain atlas). The package provides samples so I chose BrainMesh_ICBMI52_smoothed.nv and the [AAL90](http://neuro.imm.dtu.dk/wiki/Automated_Anatomical_Labeling) brain atlas which has labeled volumes for 90 brain regions."
},
{
"code": null,
"e": 1684,
"s": 1587,
"text": "Next there’s a pop-up with 7-sections of which layout, surface and volume are of interest to us."
},
{
"code": null,
"e": 1794,
"s": 1684,
"text": "In layout select which view you would like, I’ve chosen full view which will show eight different viewpoints."
},
{
"code": null,
"e": 1887,
"s": 1794,
"text": "In the surface tab you can select the transparency of the surface map — I’ve set it to 0.75."
},
{
"code": null,
"e": 2018,
"s": 1887,
"text": "In the volume tab select ROI drawing, deselect draw all and in the custom box put 37 (the code for hippocampus_L). Then select Ok."
},
{
"code": null,
"e": 2206,
"s": 2018,
"text": "I am currently in discussion with the Howard laboratory trying to get the exact methodology they used to create the image in their figure, but this how I believe they did it with [Mango]."
},
{
"code": null,
"e": 2466,
"s": 2206,
"text": "Mango has good video tutorials, user guide and forum but for those of us whose sole interest is creating a highlighted 3D brain image it’s a lot of material to go through. Therefore, I decided to create a detailed protocol of this process to save others time."
},
{
"code": null,
"e": 2580,
"s": 2466,
"text": "I decided to download the Hammers brain atlas to use as the mask/overlay and the sample image provided with Mango"
},
{
"code": null,
"e": 2634,
"s": 2580,
"text": "Next select Add Overlay and choose the hippocampus_L."
},
{
"code": null,
"e": 2711,
"s": 2634,
"text": "Now select Image > Build Surface to create a 3D representation of the brain."
},
{
"code": null,
"e": 2905,
"s": 2711,
"text": "In this new pop-up GUI there’s a few things we want to do. First, change the background to white so this can be published in a manuscript. Second, change the transparency of this image to 0.75."
},
{
"code": null,
"e": 2949,
"s": 2905,
"text": "Under the View tab deselect the Crosshairs."
},
{
"code": null,
"e": 3065,
"s": 2949,
"text": "In the other panel select Analysis > Create Logical Overlays then in the surface panel select Shapes > Add Logical."
},
{
"code": null,
"e": 3182,
"s": 3065,
"text": "Then under Surface > Views you can select any orientation you like then Surface > Create Snapshot to save as a .png."
},
{
"code": null,
"e": 3254,
"s": 3182,
"text": "Here are three views of the hippocampus_L: anterior, left and superior:"
},
{
"code": null,
"e": 3494,
"s": 3254,
"text": "John Muschelli, an Assistant Scientist at Johns Hopkins Bloomberg School of Public Health who has authored numerous R packages (e.g. fslr) responded a couple weeks later to my tweet. He whipped up a gist to highlight a 3D brain image in R."
},
{
"code": null,
"e": 4492,
"s": 3494,
"text": "library(rgl)library(misc3d)library(neurobase)if (!requireNamespace(\"aal\")) { devtools::install_github(\"muschellij2/aal\")} else { library(aal)}if (!requireNamespace(\"MNITemplate\")) { devtools::install_github(\"jfortin1/MNITemplate\")} else { library(MNITemplate)}img = aal_image()template = readMNI(res = \"2mm\")cut <- 4500dtemp <- dim(template)# All of the sections you can labellabs = aal_get_labels()# Pick the region of the brain you would like to highlight - in this case the hippocamus_Lhippocampus = labs$index[grep(\"Hippocampus_L\", labs$name)]mask = remake_img(vec = img %in% hippocampus, img = img)### this would be the ``activation'' or surface you want to render contour3d(template, x=1:dtemp[1], y=1:dtemp[2], z=1:dtemp[3], level = cut, alpha = 0.1, draw = TRUE)contour3d(mask, level = c(0.5), alpha = c(0.5), add = TRUE, color=c(\"red\") )### add texttext3d(x=dtemp[1]/2, y=dtemp[2]/2, z = dtemp[3]*0.98, text=\"Top\")text3d(x=-0.98, y=dtemp[2]/2, z = dtemp[3]/2, text=\"Right\")rglwidget()"
},
{
"code": null,
"e": 4666,
"s": 4492,
"text": "John Muschelli also teaches a couple of short courses on imaging in R and I’m currently taking his [Neurohacking] course. I really appreciate him taking the time to do this."
},
{
"code": null,
"e": 4765,
"s": 4666,
"text": "If your interested in learning more about medical imaging in R be sure to check out Neuroconductor"
},
{
"code": null,
"e": 4860,
"s": 4765,
"text": "If you find this article useful feel free to share it with others or recommend this article! 😃"
}
]
|
How to find the counts of categories in categorical columns in an R data frame? | If we have two categorical columns in an R data frame then we can find the frequency/count of each category with respect to each category in the other column. This will help us to compare the frequencies for all categories. To find the counts of categories, we can use table function as shown in the below examples.
Live Demo
Consider the below data frame −
x1<−sample(c("Child","Teen","Adult","Old"),20,replace=TRUE)
x2<−sample(c("Unemployed","Employed"),20,replace=TRUE)
df1<−data.frame(x1,x2)
df1
x1 x2
1 Old Unemployed
2 Child Unemployed
3 Adult Employed
4 Adult Unemployed
5 Adult Employed
6 Teen Employed
7 Old Employed
8 Child Unemployed
9 Child Employed
10 Adult Unemployed
11 Child Unemployed
12 Old Employed
13 Child Unemployed
14 Child Employed
15 Teen Employed
16 Adult Employed
17 Adult Unemployed
18 Old Employed
19 Adult Unemployed
20 Child Employed
Finding the counts of categories in both columns of df1 −
table(df1$x1,df1$x2)
Employed Unemployed
Adult 3 4
Child 3 4
Old 3 1
Teen 2 0
Live Demo
y1<−sample(c("Married","Unmarried"),20,replace=TRUE)
y2<−sample(c("Satisfied","Not-Satisfied"),20,replace=TRUE)
df2<−data.frame(y1,y2)
df2
y1 y2
1 Married Not-Satisfied
2 Unmarried Not-Satisfied
3 Married Not-Satisfied
4 Unmarried Not-Satisfied
5 Married Satisfied
6 Married Not-Satisfied
7 Unmarried Satisfied
8 Married Satisfied
9 Unmarried Not-Satisfied
10 Unmarried Not-Satisfied
11 Unmarried Not-Satisfied
12 Unmarried Not-Satisfied
13 Married Satisfied
14 Married Satisfied
15 Married Satisfied
16 Married Not-Satisfied
17 Married Satisfied
18 Unmarried Satisfied
19 Married Satisfied
20 Married Satisfied
Finding the counts of categories in both columns of df2 −
table(df2$y1,df2$y2)
Not−Satisfied Satisfied
Married 4 8
Unmarried 6 2 | [
{
"code": null,
"e": 1378,
"s": 1062,
"text": "If we have two categorical columns in an R data frame then we can find the frequency/count of each category with respect to each category in the other column. This will help us to compare the frequencies for all categories. To find the counts of categories, we can use table function as shown in the below examples."
},
{
"code": null,
"e": 1389,
"s": 1378,
"text": " Live Demo"
},
{
"code": null,
"e": 1421,
"s": 1389,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1563,
"s": 1421,
"text": "x1<−sample(c(\"Child\",\"Teen\",\"Adult\",\"Old\"),20,replace=TRUE)\nx2<−sample(c(\"Unemployed\",\"Employed\"),20,replace=TRUE)\ndf1<−data.frame(x1,x2)\ndf1"
},
{
"code": null,
"e": 1928,
"s": 1563,
"text": "x1 x2\n1 Old Unemployed\n2 Child Unemployed\n3 Adult Employed\n4 Adult Unemployed\n5 Adult Employed\n6 Teen Employed\n7 Old Employed\n8 Child Unemployed\n9 Child Employed\n10 Adult Unemployed\n11 Child Unemployed\n12 Old Employed\n13 Child Unemployed\n14 Child Employed\n15 Teen Employed\n16 Adult Employed\n17 Adult Unemployed\n18 Old Employed\n19 Adult Unemployed\n20 Child Employed"
},
{
"code": null,
"e": 1986,
"s": 1928,
"text": "Finding the counts of categories in both columns of df1 −"
},
{
"code": null,
"e": 2007,
"s": 1986,
"text": "table(df1$x1,df1$x2)"
},
{
"code": null,
"e": 2064,
"s": 2007,
"text": "Employed Unemployed\nAdult 3 4\nChild 3 4\nOld 3 1\nTeen 2 0"
},
{
"code": null,
"e": 2075,
"s": 2064,
"text": " Live Demo"
},
{
"code": null,
"e": 2214,
"s": 2075,
"text": "y1<−sample(c(\"Married\",\"Unmarried\"),20,replace=TRUE)\ny2<−sample(c(\"Satisfied\",\"Not-Satisfied\"),20,replace=TRUE)\ndf2<−data.frame(y1,y2)\ndf2"
},
{
"code": null,
"e": 2687,
"s": 2214,
"text": "y1 y2\n1 Married Not-Satisfied\n2 Unmarried Not-Satisfied\n3 Married Not-Satisfied\n4 Unmarried Not-Satisfied\n5 Married Satisfied\n6 Married Not-Satisfied\n7 Unmarried Satisfied\n8 Married Satisfied\n9 Unmarried Not-Satisfied\n10 Unmarried Not-Satisfied\n11 Unmarried Not-Satisfied\n12 Unmarried Not-Satisfied\n13 Married Satisfied\n14 Married Satisfied\n15 Married Satisfied\n16 Married Not-Satisfied\n17 Married Satisfied\n18 Unmarried Satisfied\n19 Married Satisfied\n20 Married Satisfied"
},
{
"code": null,
"e": 2745,
"s": 2687,
"text": "Finding the counts of categories in both columns of df2 −"
},
{
"code": null,
"e": 2766,
"s": 2745,
"text": "table(df2$y1,df2$y2)"
},
{
"code": null,
"e": 2816,
"s": 2766,
"text": "Not−Satisfied Satisfied\nMarried 4 8\nUnmarried 6 2"
}
]
|
Clojure - Vectors | A Vector is a collection of values indexed by contiguous integers. A vector is created by using the vector method in Clojure.
Following is an example of creating a vector in Clojure.
(ns clojure.examples.example
(:require [clojure.set :as set])
(:gen-class))
(defn example []
(println (vector 1 2 3)))
(example)
The above code produces the following output.
[1 2 3]
Following are the methods available in Clojure.
Creates a new vector of a single primitive type ‘t’, where ‘t’ is one of :int :long :float :double :byte :short :char or :boolean.
This function returns the item in the nth position in the vector.
Returns the element at the index position in the vector.
Appends an element to the vector and returns the new set of vector elements.
For a list or queue, returns a new list/queue without the first item, for a vector, returns a new vector without the last item.
Returns a sub vector from a starting and ending index.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2500,
"s": 2374,
"text": "A Vector is a collection of values indexed by contiguous integers. A vector is created by using the vector method in Clojure."
},
{
"code": null,
"e": 2557,
"s": 2500,
"text": "Following is an example of creating a vector in Clojure."
},
{
"code": null,
"e": 2695,
"s": 2557,
"text": "(ns clojure.examples.example\n (:require [clojure.set :as set])\n (:gen-class))\n(defn example []\n (println (vector 1 2 3)))\n(example)"
},
{
"code": null,
"e": 2741,
"s": 2695,
"text": "The above code produces the following output."
},
{
"code": null,
"e": 2750,
"s": 2741,
"text": "[1 2 3]\n"
},
{
"code": null,
"e": 2798,
"s": 2750,
"text": "Following are the methods available in Clojure."
},
{
"code": null,
"e": 2929,
"s": 2798,
"text": "Creates a new vector of a single primitive type ‘t’, where ‘t’ is one of :int :long :float :double :byte :short :char or :boolean."
},
{
"code": null,
"e": 2995,
"s": 2929,
"text": "This function returns the item in the nth position in the vector."
},
{
"code": null,
"e": 3052,
"s": 2995,
"text": "Returns the element at the index position in the vector."
},
{
"code": null,
"e": 3129,
"s": 3052,
"text": "Appends an element to the vector and returns the new set of vector elements."
},
{
"code": null,
"e": 3257,
"s": 3129,
"text": "For a list or queue, returns a new list/queue without the first item, for a vector, returns a new vector without the last item."
},
{
"code": null,
"e": 3312,
"s": 3257,
"text": "Returns a sub vector from a starting and ending index."
},
{
"code": null,
"e": 3319,
"s": 3312,
"text": " Print"
},
{
"code": null,
"e": 3330,
"s": 3319,
"text": " Add Notes"
}
]
|
Selenium - Mouse Actions | Listed below are some of the key mouse actions that one would come across in most of the applications -
Click − Performs a Click. We can also perform a click based on coordinates.
Click − Performs a Click. We can also perform a click based on coordinates.
contextClick − Performs a context click/right-click on an element or based on the coordinates
contextClick − Performs a context click/right-click on an element or based on the coordinates
doubleClick − Performs a double-click on the webelement or based on the coordinates. If left empty, it performs double-click on the current location.
doubleClick − Performs a double-click on the webelement or based on the coordinates. If left empty, it performs double-click on the current location.
mouseDown − Performs a mouse-down action on an element or based on coordinates.
mouseDown − Performs a mouse-down action on an element or based on coordinates.
mouseMove − Performs a mouse-move action on an element or based on coordinates.
mouseMove − Performs a mouse-move action on an element or based on coordinates.
mouseUp − Releases the mouse usually followed by mouse-down and acts based on co-ordinates.
mouseUp − Releases the mouse usually followed by mouse-down and acts based on co-ordinates.
Here are the syntax to call mouse actions using Selenium WebDriver -
void click(WebElement onElement)
void contextClick(WebElement onElement)
void doubleClick(WebElement onElement)
void mouseDown(WebElement onElement)
void mouseUp(WebElement onElement)
void mouseMove(WebElement toElement)
void mouseMove(WebElement toElement, long xOffset, long yOffset)
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1979,
"s": 1875,
"text": "Listed below are some of the key mouse actions that one would come across in most of the applications -"
},
{
"code": null,
"e": 2055,
"s": 1979,
"text": "Click − Performs a Click. We can also perform a click based on coordinates."
},
{
"code": null,
"e": 2131,
"s": 2055,
"text": "Click − Performs a Click. We can also perform a click based on coordinates."
},
{
"code": null,
"e": 2225,
"s": 2131,
"text": "contextClick − Performs a context click/right-click on an element or based on the coordinates"
},
{
"code": null,
"e": 2319,
"s": 2225,
"text": "contextClick − Performs a context click/right-click on an element or based on the coordinates"
},
{
"code": null,
"e": 2469,
"s": 2319,
"text": "doubleClick − Performs a double-click on the webelement or based on the coordinates. If left empty, it performs double-click on the current location."
},
{
"code": null,
"e": 2619,
"s": 2469,
"text": "doubleClick − Performs a double-click on the webelement or based on the coordinates. If left empty, it performs double-click on the current location."
},
{
"code": null,
"e": 2699,
"s": 2619,
"text": "mouseDown − Performs a mouse-down action on an element or based on coordinates."
},
{
"code": null,
"e": 2779,
"s": 2699,
"text": "mouseDown − Performs a mouse-down action on an element or based on coordinates."
},
{
"code": null,
"e": 2859,
"s": 2779,
"text": "mouseMove − Performs a mouse-move action on an element or based on coordinates."
},
{
"code": null,
"e": 2939,
"s": 2859,
"text": "mouseMove − Performs a mouse-move action on an element or based on coordinates."
},
{
"code": null,
"e": 3031,
"s": 2939,
"text": "mouseUp − Releases the mouse usually followed by mouse-down and acts based on co-ordinates."
},
{
"code": null,
"e": 3123,
"s": 3031,
"text": "mouseUp − Releases the mouse usually followed by mouse-down and acts based on co-ordinates."
},
{
"code": null,
"e": 3192,
"s": 3123,
"text": "Here are the syntax to call mouse actions using Selenium WebDriver -"
},
{
"code": null,
"e": 3478,
"s": 3192,
"text": "void click(WebElement onElement)\nvoid contextClick(WebElement onElement)\nvoid doubleClick(WebElement onElement)\nvoid mouseDown(WebElement onElement)\nvoid mouseUp(WebElement onElement)\nvoid mouseMove(WebElement toElement)\nvoid mouseMove(WebElement toElement, long xOffset, long yOffset)"
},
{
"code": null,
"e": 3513,
"s": 3478,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3525,
"s": 3513,
"text": " Aditya Dua"
},
{
"code": null,
"e": 3561,
"s": 3525,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 3575,
"s": 3561,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3612,
"s": 3575,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 3634,
"s": 3612,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3667,
"s": 3634,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3681,
"s": 3667,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3716,
"s": 3681,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3730,
"s": 3716,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3767,
"s": 3730,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 3781,
"s": 3767,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3788,
"s": 3781,
"text": " Print"
},
{
"code": null,
"e": 3799,
"s": 3788,
"text": " Add Notes"
}
]
|
addgroup command in Linux with Examples - GeeksforGeeks | 22 Jun, 2020
addgroup command in Linux is used to add a new group to your current Linux machine. This command allows you to modify the configurations of the group which is to be created. It is similar to the groupadd command in Linux. The addgroup command is much interactive as compared to groupadd command.
To install addgroup tool use the following commands as per your Linux distribution.
In case of Debian/Ubuntu
$sudo apt-get install addgroup
In case of CentOS/RedHat
$sudo yum install addgroup
In case of Fedora OS
$sudo dnf install addgroup
1. To add a new group
sudo addgroup groupname
This command will create a new group for your Linux machine.
2. To add a new group with specified group id
sudo addgroup groupname --gid 12345
This command will add a new group with the specified group id.
3. To create a group with a specific shell
sudo addgroup groupname --shell /bin/sh
This command will allocate the /bin/sh shell to the newly create group.
4. To enter verbose mode
sudo addgroup groupname --debug
This command will execute the command in the verbose mode that means it will print all details of the tasks it is executing.
5. To display help related to addgroup command.
addgroup --help
This command will display the help section of the addgroup command.
6. To display version
addgroup --version
This command will display the version details of the addgroup command.
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples | [
{
"code": null,
"e": 24015,
"s": 23987,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 24311,
"s": 24015,
"text": "addgroup command in Linux is used to add a new group to your current Linux machine. This command allows you to modify the configurations of the group which is to be created. It is similar to the groupadd command in Linux. The addgroup command is much interactive as compared to groupadd command."
},
{
"code": null,
"e": 24395,
"s": 24311,
"text": "To install addgroup tool use the following commands as per your Linux distribution."
},
{
"code": null,
"e": 24420,
"s": 24395,
"text": "In case of Debian/Ubuntu"
},
{
"code": null,
"e": 24451,
"s": 24420,
"text": "$sudo apt-get install addgroup"
},
{
"code": null,
"e": 24476,
"s": 24451,
"text": "In case of CentOS/RedHat"
},
{
"code": null,
"e": 24503,
"s": 24476,
"text": "$sudo yum install addgroup"
},
{
"code": null,
"e": 24524,
"s": 24503,
"text": "In case of Fedora OS"
},
{
"code": null,
"e": 24551,
"s": 24524,
"text": "$sudo dnf install addgroup"
},
{
"code": null,
"e": 24573,
"s": 24551,
"text": "1. To add a new group"
},
{
"code": null,
"e": 24597,
"s": 24573,
"text": "sudo addgroup groupname"
},
{
"code": null,
"e": 24658,
"s": 24597,
"text": "This command will create a new group for your Linux machine."
},
{
"code": null,
"e": 24704,
"s": 24658,
"text": "2. To add a new group with specified group id"
},
{
"code": null,
"e": 24740,
"s": 24704,
"text": "sudo addgroup groupname --gid 12345"
},
{
"code": null,
"e": 24803,
"s": 24740,
"text": "This command will add a new group with the specified group id."
},
{
"code": null,
"e": 24846,
"s": 24803,
"text": "3. To create a group with a specific shell"
},
{
"code": null,
"e": 24886,
"s": 24846,
"text": "sudo addgroup groupname --shell /bin/sh"
},
{
"code": null,
"e": 24958,
"s": 24886,
"text": "This command will allocate the /bin/sh shell to the newly create group."
},
{
"code": null,
"e": 24983,
"s": 24958,
"text": "4. To enter verbose mode"
},
{
"code": null,
"e": 25015,
"s": 24983,
"text": "sudo addgroup groupname --debug"
},
{
"code": null,
"e": 25140,
"s": 25015,
"text": "This command will execute the command in the verbose mode that means it will print all details of the tasks it is executing."
},
{
"code": null,
"e": 25188,
"s": 25140,
"text": "5. To display help related to addgroup command."
},
{
"code": null,
"e": 25204,
"s": 25188,
"text": "addgroup --help"
},
{
"code": null,
"e": 25272,
"s": 25204,
"text": "This command will display the help section of the addgroup command."
},
{
"code": null,
"e": 25294,
"s": 25272,
"text": "6. To display version"
},
{
"code": null,
"e": 25313,
"s": 25294,
"text": "addgroup --version"
},
{
"code": null,
"e": 25384,
"s": 25313,
"text": "This command will display the version details of the addgroup command."
},
{
"code": null,
"e": 25398,
"s": 25384,
"text": "linux-command"
},
{
"code": null,
"e": 25409,
"s": 25398,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25507,
"s": 25409,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25516,
"s": 25507,
"text": "Comments"
},
{
"code": null,
"e": 25529,
"s": 25516,
"text": "Old Comments"
},
{
"code": null,
"e": 25564,
"s": 25529,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 25601,
"s": 25564,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 25635,
"s": 25601,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 25661,
"s": 25635,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 25687,
"s": 25661,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 25724,
"s": 25687,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 25764,
"s": 25724,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 25793,
"s": 25764,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 25835,
"s": 25793,
"text": "Named Pipe or FIFO with example C program"
}
]
|
What e.preventDefault() method really does in jQuery? | The preventDefault() method stops the default action of a selected element from happening by a user. This method does not accept any parameter and works in two ways:
It prevents a link from following the URL so that the browser can't go another page.
It prevents a submit button from submitting a form.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("a").click(function(event) {
event.preventDefault();
});
});
</script>
</head>
<body>
<a href="https://www.tutorialspoint.com/">Tutorialspoint.com</a>
<p>Click the link and it wont work.</p>
</body>
</html> | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "The preventDefault() method stops the default action of a selected element from happening by a user. This method does not accept any parameter and works in two ways:"
},
{
"code": null,
"e": 1313,
"s": 1228,
"text": "It prevents a link from following the URL so that the browser can't go another page."
},
{
"code": null,
"e": 1365,
"s": 1313,
"text": "It prevents a submit button from submitting a form."
},
{
"code": null,
"e": 1774,
"s": 1365,
"text": "<html>\n<head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function() {\n $(\"a\").click(function(event) {\n event.preventDefault();\n });\n });\n </script>\n</head>\n<body>\n <a href=\"https://www.tutorialspoint.com/\">Tutorialspoint.com</a>\n <p>Click the link and it wont work.</p>\n</body>\n</html>"
}
]
|
Simple Diamond Pattern in Python - GeeksforGeeks | 29 May, 2021
Given an integer n, the task is to write a python program to print diamond using loops and mathematical formulations. The minimum value of n should be greater than 4.
Examples :
For size = 5
* * *
* * * * *
* * *
*
For size = 8
* * * * * *
* * * * * * * *
* * * * * *
* * * *
* *
For size = 11
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Approach :
The following steps are used :
Form the worksheet of (size/2+2) x size using two loops.
Apply the if-else conditions for printing stars.
Apply else condition for rest spaces.
Below is the implementation of the above approach :
Example 1:
Python3
# define the size (no. of columns)# must be odd to draw proper diamond shapesize = 8 # initialize the spacesspaces = size # loops for iterations to create worksheetfor i in range(size//2+2): for j in range(size): # condition to left space # condition to right space # condition for making diamond # else print * if j < i-1: print(' ', end=" ") elif j > spaces: print(' ', end=" ") elif (i == 0 and j == 0) | (i == 0 and j == size-1): print(' ', end=" ") else: print('*', end=" ") # increase space area by decreasing spaces spaces -= 1 # for line change print()
Output :
* * * * * *
* * * * * * * *
* * * * * *
* * * *
* *
Example 2:
Python3
# define the size (no. of columns)# must be odd to draw proper diamond shapesize = 11 # initialize the spacesspaces = size # loops for iterations to create worksheetfor i in range(size//2+2): for j in range(size): # condition to left space # condition to right space # condition for making diamond # else print ^ if j < i-1: print(' ', end=" ") elif j > spaces: print(' ', end=" ") elif (i == 0 and j == 0) | (i == 0 and j == size-1): print(' ', end=" ") else: print('*', end=" ") # increase space area by decreasing spaces spaces -= 1 # for line change print()
Output :
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Akanksha_Rai
Python Pattern-printing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 24379,
"s": 24212,
"text": "Given an integer n, the task is to write a python program to print diamond using loops and mathematical formulations. The minimum value of n should be greater than 4."
},
{
"code": null,
"e": 24390,
"s": 24379,
"text": "Examples :"
},
{
"code": null,
"e": 24747,
"s": 24390,
"text": "For size = 5\n\n * * * \n* * * * * \n * * * \n * \n \nFor size = 8\n\n * * * * * * \n* * * * * * * * \n * * * * * * \n * * * * \n * * \n \n\nFor size = 11\n\n * * * * * * * * * \n* * * * * * * * * * * \n * * * * * * * * * \n * * * * * * * \n * * * * * \n * * * \n * "
},
{
"code": null,
"e": 24758,
"s": 24747,
"text": "Approach :"
},
{
"code": null,
"e": 24789,
"s": 24758,
"text": "The following steps are used :"
},
{
"code": null,
"e": 24846,
"s": 24789,
"text": "Form the worksheet of (size/2+2) x size using two loops."
},
{
"code": null,
"e": 24895,
"s": 24846,
"text": "Apply the if-else conditions for printing stars."
},
{
"code": null,
"e": 24933,
"s": 24895,
"text": "Apply else condition for rest spaces."
},
{
"code": null,
"e": 24985,
"s": 24933,
"text": "Below is the implementation of the above approach :"
},
{
"code": null,
"e": 24996,
"s": 24985,
"text": "Example 1:"
},
{
"code": null,
"e": 25004,
"s": 24996,
"text": "Python3"
},
{
"code": "# define the size (no. of columns)# must be odd to draw proper diamond shapesize = 8 # initialize the spacesspaces = size # loops for iterations to create worksheetfor i in range(size//2+2): for j in range(size): # condition to left space # condition to right space # condition for making diamond # else print * if j < i-1: print(' ', end=\" \") elif j > spaces: print(' ', end=\" \") elif (i == 0 and j == 0) | (i == 0 and j == size-1): print(' ', end=\" \") else: print('*', end=\" \") # increase space area by decreasing spaces spaces -= 1 # for line change print()",
"e": 25705,
"s": 25004,
"text": null
},
{
"code": null,
"e": 25714,
"s": 25705,
"text": "Output :"
},
{
"code": null,
"e": 25799,
"s": 25714,
"text": " * * * * * * \n* * * * * * * * \n * * * * * * \n * * * * \n * * "
},
{
"code": null,
"e": 25810,
"s": 25799,
"text": "Example 2:"
},
{
"code": null,
"e": 25818,
"s": 25810,
"text": "Python3"
},
{
"code": "# define the size (no. of columns)# must be odd to draw proper diamond shapesize = 11 # initialize the spacesspaces = size # loops for iterations to create worksheetfor i in range(size//2+2): for j in range(size): # condition to left space # condition to right space # condition for making diamond # else print ^ if j < i-1: print(' ', end=\" \") elif j > spaces: print(' ', end=\" \") elif (i == 0 and j == 0) | (i == 0 and j == size-1): print(' ', end=\" \") else: print('*', end=\" \") # increase space area by decreasing spaces spaces -= 1 # for line change print()",
"e": 26520,
"s": 25818,
"text": null
},
{
"code": null,
"e": 26529,
"s": 26520,
"text": "Output :"
},
{
"code": null,
"e": 26689,
"s": 26529,
"text": " * * * * * * * * * \n* * * * * * * * * * * \n * * * * * * * * * \n * * * * * * * \n * * * * * \n * * * \n * "
},
{
"code": null,
"e": 26702,
"s": 26689,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26726,
"s": 26702,
"text": "Python Pattern-printing"
},
{
"code": null,
"e": 26733,
"s": 26726,
"text": "Python"
},
{
"code": null,
"e": 26831,
"s": 26733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26840,
"s": 26831,
"text": "Comments"
},
{
"code": null,
"e": 26853,
"s": 26840,
"text": "Old Comments"
},
{
"code": null,
"e": 26885,
"s": 26853,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26941,
"s": 26885,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26962,
"s": 26941,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 27001,
"s": 26962,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27043,
"s": 27001,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27070,
"s": 27043,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27101,
"s": 27070,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27143,
"s": 27101,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27179,
"s": 27143,
"text": "Python | Pandas dataframe.groupby()"
}
]
|
How to implement an interface using an anonymous inner class in Java? | An anonymous inner class is a class which doesn't have a name, we will directly define it at the instantiation line.
In the following program, we are implementing the toString() method of TutorialsPoint interface using Anonymous inner class and, print its return value.
interface TutorialsPoint{
public String toString();
}
public class Main implements TutorialsPoint {
public static void main(String[] args) {
System.out.print(new TutorialsPoint() {
public String toString() {
return "Welcome to Tutorials Point";
}
});
}
}
Welcome to Tutorials Point | [
{
"code": null,
"e": 1179,
"s": 1062,
"text": "An anonymous inner class is a class which doesn't have a name, we will directly define it at the instantiation line."
},
{
"code": null,
"e": 1332,
"s": 1179,
"text": "In the following program, we are implementing the toString() method of TutorialsPoint interface using Anonymous inner class and, print its return value."
},
{
"code": null,
"e": 1638,
"s": 1332,
"text": "interface TutorialsPoint{\n public String toString();\n}\npublic class Main implements TutorialsPoint {\n public static void main(String[] args) {\n System.out.print(new TutorialsPoint() {\n public String toString() {\n return \"Welcome to Tutorials Point\";\n }\n });\n }\n}"
},
{
"code": null,
"e": 1665,
"s": 1638,
"text": "Welcome to Tutorials Point"
}
]
|
GATE | GATE-CS-2015 (Set 3) | Question 23 - GeeksforGeeks | 10 Sep, 2018
While inserting the elements 71, 65, 84, 69, 67, 83 in an empty binary search tree (BST) in the sequence shown, the element in the lowest level is
(A) 65(B) 67(C) 69(D) 83Answer: (B)Explanation: Here is The Insertion Algorithm For a Binary Search Tree :
Insert(Root,key)
{
if(Root is NULL)
Create a Node with value as key and return
Else if(Root.key >= key)
Insert(Root.left,key)
Else
Insert(Root.right,key)
}
Creating the BST one by one using the above algorithm in the below given image :
This solution is contributed by Pranjul Ahuja.Quiz of this Question
Parmod Jangra
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65 | [
{
"code": null,
"e": 24542,
"s": 24514,
"text": "\n10 Sep, 2018"
},
{
"code": null,
"e": 24689,
"s": 24542,
"text": "While inserting the elements 71, 65, 84, 69, 67, 83 in an empty binary search tree (BST) in the sequence shown, the element in the lowest level is"
},
{
"code": null,
"e": 24796,
"s": 24689,
"text": "(A) 65(B) 67(C) 69(D) 83Answer: (B)Explanation: Here is The Insertion Algorithm For a Binary Search Tree :"
},
{
"code": null,
"e": 24989,
"s": 24796,
"text": "Insert(Root,key)\n{\n if(Root is NULL)\n Create a Node with value as key and return\n Else if(Root.key >= key)\n Insert(Root.left,key)\n Else\n Insert(Root.right,key)\n}\n"
},
{
"code": null,
"e": 25070,
"s": 24989,
"text": "Creating the BST one by one using the above algorithm in the below given image :"
},
{
"code": null,
"e": 25138,
"s": 25070,
"text": "This solution is contributed by Pranjul Ahuja.Quiz of this Question"
},
{
"code": null,
"e": 25152,
"s": 25138,
"text": "Parmod Jangra"
},
{
"code": null,
"e": 25173,
"s": 25152,
"text": "GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 25199,
"s": 25173,
"text": "GATE-GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 25204,
"s": 25199,
"text": "GATE"
},
{
"code": null,
"e": 25302,
"s": 25204,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25311,
"s": 25302,
"text": "Comments"
},
{
"code": null,
"e": 25324,
"s": 25311,
"text": "Old Comments"
},
{
"code": null,
"e": 25358,
"s": 25324,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25391,
"s": 25358,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25433,
"s": 25391,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25475,
"s": 25433,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25517,
"s": 25475,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 25551,
"s": 25517,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 25593,
"s": 25551,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 25627,
"s": 25593,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 25669,
"s": 25627,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
}
]
|
How to Efficiently Fine-Tune your Machine Learning Models | by Khuyen Tran | Towards Data Science | Have you ever wanted to experiment with different parameters for your model but find it really time-consuming to do so? Let’s say you want to use support vector machines (SVM) to train and predict the model.
You debate what could be the best value for C so you keep experimenting with different values of C manually and hopefully get good results. That is time-consuming but still not so bad.
But what if you want to first use sklearn.feature_extraction.text.TfidfVectorizer to extract important texts, then use sklearn.feature_selection.SelectKBest to find the best features, and finally use sklearn.SVM.LinearSVCto train and predict the model? There would be so many parameters to tune in. Plus you need to find a way to record the results for comparison. So your notebook can look like a mess!
Is there a better way to select the parameters, shorten the code, as well as save the results for comparison? Yes, of course! Our method will be like a delicious cake with three simple ingredients:
Pipeline to combine different models
Grid search to find the best parameters for each model
MLflow to record the results
Have all the ingredients you need? Awesome! Now we are ready to put them together.
What is pipeline? sklearn.pipeline.Pipeline allows us to combine a list of transforms and a final estimator into a chain.
For example, to predict whether a tweet is aggressive or not, after processing the text, we usetfidf_vectorizer, and SelectKBest as the transformers and svm.LinearSVC as a final estimator.
The codes above could be combined into a pipeline with a list of steps represented as tuples. In each tuple, the first parameter is the name of the class, and the second parameter is the class.
Much shorter and organized! We could easily switch any of the steps to another transformer or estimator. Make sure the classes in the pipeline are from sklearn. If they are not, you could easily create customized sklearn classes with def __init__, def fit(), and def transform() like this.
So we got the pipeline ready to transform and predict our data. But how about parameter tuning? We could easily find the best parameters for transformers and estimator in our pipeline with sklearn.model_selection.GridSearchCV.
Let’s say we want to find the best value of k for SelectKBest, the best value of C for svm.LinearSVC, best values of analyzer, ngram_range, and binary for TfidfVectorizer. We could give our grid several parameters to search for. The parameters are represented as lists nested inside a dictionary.
To set the parameters of a particular class, we use class_name__parameter = [para_1, para_2, para_3]. Make sure to have two underscores between class’s name and parameter.
grid_search.fit(X_train, y_train) creates several runs using different parameters with specified transformations, and estimator. The combination of parameters yielding the best result will be chosen for the transformation step.
We could also create other pipelines with different transformers and estimators and again use GridSearchCV to find the best parameters! But how could we save the results of all the runs we perform?
It is possible to observe the results by scrolling up and down the screen or taking photos of the results. But that is time-consuming, not taking into account that we might want to look at the results later for future projects. Is there a better way to track our results? That is when we need a tracking tool like MLflow
MLflow is a tool for managing the end-to-end machine learning lifecycle including tracking experiments, packaging ML code in a reproducible form for sharing, and deployment. We will utilize this tool to keep the log of our results.
Installation of MLflow can be just simple as this
pip install mlflow
Let’s combine what we have done so far and MLflow tracking tool
In this code, we just add three elements to log the results:
mlflow.set_experiment('name_of_experiment') to create a new experiment
mlflow.start_run() inside which the codes we want to run the experiment are in
mlflow.log_param() and mlflow.log_metric() to log the parameters and metrics
Save the file above as train.py. The last step is to run the file
python train.py
After the code finish running, we could find the log of MLflow by running
mlflow ui
Access to the link http://localhost:5000 and we should see this
As we can see from above, the metrics and the parameters of the experiments are logged! We could create several experiments and log the results of those experiments for easy and efficient comparison.
Congratulations! You have learned how to tune parameters for your machine learning models efficiently with Pipeline, GridSearchCV, and MLflow. You could find similar example codes for this article here. I encourage you to try out these methods with your existing machine learning projects. Just a little change in your coding approach can make a big difference in the long run. Experimenting and tracking the results efficiently will not only save you time but also make it much easier to find the best parameters and learn from your experiments.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: | [
{
"code": null,
"e": 380,
"s": 172,
"text": "Have you ever wanted to experiment with different parameters for your model but find it really time-consuming to do so? Let’s say you want to use support vector machines (SVM) to train and predict the model."
},
{
"code": null,
"e": 565,
"s": 380,
"text": "You debate what could be the best value for C so you keep experimenting with different values of C manually and hopefully get good results. That is time-consuming but still not so bad."
},
{
"code": null,
"e": 969,
"s": 565,
"text": "But what if you want to first use sklearn.feature_extraction.text.TfidfVectorizer to extract important texts, then use sklearn.feature_selection.SelectKBest to find the best features, and finally use sklearn.SVM.LinearSVCto train and predict the model? There would be so many parameters to tune in. Plus you need to find a way to record the results for comparison. So your notebook can look like a mess!"
},
{
"code": null,
"e": 1167,
"s": 969,
"text": "Is there a better way to select the parameters, shorten the code, as well as save the results for comparison? Yes, of course! Our method will be like a delicious cake with three simple ingredients:"
},
{
"code": null,
"e": 1204,
"s": 1167,
"text": "Pipeline to combine different models"
},
{
"code": null,
"e": 1259,
"s": 1204,
"text": "Grid search to find the best parameters for each model"
},
{
"code": null,
"e": 1288,
"s": 1259,
"text": "MLflow to record the results"
},
{
"code": null,
"e": 1371,
"s": 1288,
"text": "Have all the ingredients you need? Awesome! Now we are ready to put them together."
},
{
"code": null,
"e": 1493,
"s": 1371,
"text": "What is pipeline? sklearn.pipeline.Pipeline allows us to combine a list of transforms and a final estimator into a chain."
},
{
"code": null,
"e": 1682,
"s": 1493,
"text": "For example, to predict whether a tweet is aggressive or not, after processing the text, we usetfidf_vectorizer, and SelectKBest as the transformers and svm.LinearSVC as a final estimator."
},
{
"code": null,
"e": 1876,
"s": 1682,
"text": "The codes above could be combined into a pipeline with a list of steps represented as tuples. In each tuple, the first parameter is the name of the class, and the second parameter is the class."
},
{
"code": null,
"e": 2166,
"s": 1876,
"text": "Much shorter and organized! We could easily switch any of the steps to another transformer or estimator. Make sure the classes in the pipeline are from sklearn. If they are not, you could easily create customized sklearn classes with def __init__, def fit(), and def transform() like this."
},
{
"code": null,
"e": 2393,
"s": 2166,
"text": "So we got the pipeline ready to transform and predict our data. But how about parameter tuning? We could easily find the best parameters for transformers and estimator in our pipeline with sklearn.model_selection.GridSearchCV."
},
{
"code": null,
"e": 2690,
"s": 2393,
"text": "Let’s say we want to find the best value of k for SelectKBest, the best value of C for svm.LinearSVC, best values of analyzer, ngram_range, and binary for TfidfVectorizer. We could give our grid several parameters to search for. The parameters are represented as lists nested inside a dictionary."
},
{
"code": null,
"e": 2862,
"s": 2690,
"text": "To set the parameters of a particular class, we use class_name__parameter = [para_1, para_2, para_3]. Make sure to have two underscores between class’s name and parameter."
},
{
"code": null,
"e": 3090,
"s": 2862,
"text": "grid_search.fit(X_train, y_train) creates several runs using different parameters with specified transformations, and estimator. The combination of parameters yielding the best result will be chosen for the transformation step."
},
{
"code": null,
"e": 3288,
"s": 3090,
"text": "We could also create other pipelines with different transformers and estimators and again use GridSearchCV to find the best parameters! But how could we save the results of all the runs we perform?"
},
{
"code": null,
"e": 3609,
"s": 3288,
"text": "It is possible to observe the results by scrolling up and down the screen or taking photos of the results. But that is time-consuming, not taking into account that we might want to look at the results later for future projects. Is there a better way to track our results? That is when we need a tracking tool like MLflow"
},
{
"code": null,
"e": 3841,
"s": 3609,
"text": "MLflow is a tool for managing the end-to-end machine learning lifecycle including tracking experiments, packaging ML code in a reproducible form for sharing, and deployment. We will utilize this tool to keep the log of our results."
},
{
"code": null,
"e": 3891,
"s": 3841,
"text": "Installation of MLflow can be just simple as this"
},
{
"code": null,
"e": 3910,
"s": 3891,
"text": "pip install mlflow"
},
{
"code": null,
"e": 3974,
"s": 3910,
"text": "Let’s combine what we have done so far and MLflow tracking tool"
},
{
"code": null,
"e": 4035,
"s": 3974,
"text": "In this code, we just add three elements to log the results:"
},
{
"code": null,
"e": 4106,
"s": 4035,
"text": "mlflow.set_experiment('name_of_experiment') to create a new experiment"
},
{
"code": null,
"e": 4185,
"s": 4106,
"text": "mlflow.start_run() inside which the codes we want to run the experiment are in"
},
{
"code": null,
"e": 4262,
"s": 4185,
"text": "mlflow.log_param() and mlflow.log_metric() to log the parameters and metrics"
},
{
"code": null,
"e": 4328,
"s": 4262,
"text": "Save the file above as train.py. The last step is to run the file"
},
{
"code": null,
"e": 4344,
"s": 4328,
"text": "python train.py"
},
{
"code": null,
"e": 4418,
"s": 4344,
"text": "After the code finish running, we could find the log of MLflow by running"
},
{
"code": null,
"e": 4428,
"s": 4418,
"text": "mlflow ui"
},
{
"code": null,
"e": 4492,
"s": 4428,
"text": "Access to the link http://localhost:5000 and we should see this"
},
{
"code": null,
"e": 4692,
"s": 4492,
"text": "As we can see from above, the metrics and the parameters of the experiments are logged! We could create several experiments and log the results of those experiments for easy and efficient comparison."
},
{
"code": null,
"e": 5239,
"s": 4692,
"text": "Congratulations! You have learned how to tune parameters for your machine learning models efficiently with Pipeline, GridSearchCV, and MLflow. You could find similar example codes for this article here. I encourage you to try out these methods with your existing machine learning projects. Just a little change in your coding approach can make a big difference in the long run. Experimenting and tracking the results efficiently will not only save you time but also make it much easier to find the best parameters and learn from your experiments."
},
{
"code": null,
"e": 5399,
"s": 5239,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
]
|
jMeter - Quick Guide | Before going into the details of JMeter, let us first understand a few jargons associated with the testing of any application.
Performance Test − This test sets the best possible performance expectation under a given configuration of infrastructure. It also highlights early in the testing process if any changes need to be made before the application goes into production.
Performance Test − This test sets the best possible performance expectation under a given configuration of infrastructure. It also highlights early in the testing process if any changes need to be made before the application goes into production.
Load Test − This test is basically used for testing the system under the top load it was designed to operate under.
Load Test − This test is basically used for testing the system under the top load it was designed to operate under.
Stress Test − This test is an attempt to break the system by overwhelming its resources.
Stress Test − This test is an attempt to break the system by overwhelming its resources.
JMeter is a software that can perform load test, performance-oriented business (functional) test, regression test, etc., on different protocols or technologies.
Stefano Mazzocchi of the Apache Software Foundation was the original developer of JMeter. He wrote it primarily to test the performance of Apache JServ (now called as Apache Tomcat project). Apache later redesigned JMeter to enhance the GUI and to add functional testing capabilities.
JMeter is a Java desktop application with a graphical interface that uses the Swing graphical API. It can therefore run on any environment / workstation that accepts a Java virtual machine, for example − Windows, Linux, Mac, etc.
The protocols supported by JMeter are −
Web − HTTP, HTTPS sites 'web 1.0' web 2.0 (ajax, flex and flex-ws-amf)
Web − HTTP, HTTPS sites 'web 1.0' web 2.0 (ajax, flex and flex-ws-amf)
Web Services − SOAP / XML-RPC
Web Services − SOAP / XML-RPC
Database via JDBC drivers
Database via JDBC drivers
Directory − LDAP
Directory − LDAP
Messaging Oriented service via JMS
Messaging Oriented service via JMS
Service − POP3, IMAP, SMTP
Service − POP3, IMAP, SMTP
FTP Service
FTP Service
Following are some of the features of JMeter −
Being an open source software, it is freely available.
Being an open source software, it is freely available.
It has a simple and intuitive GUI.
It has a simple and intuitive GUI.
JMeter can conduct load and performance test for many different server types − Web - HTTP, HTTPS, SOAP, Database via JDBC, LDAP, JMS, Mail - POP3, etc.
JMeter can conduct load and performance test for many different server types − Web - HTTP, HTTPS, SOAP, Database via JDBC, LDAP, JMS, Mail - POP3, etc.
It is a platform-independent tool. On Linux/Unix, JMeter can be invoked by clicking on JMeter shell script. On Windows, it can be invoked by starting the jmeter.bat file.
It is a platform-independent tool. On Linux/Unix, JMeter can be invoked by clicking on JMeter shell script. On Windows, it can be invoked by starting the jmeter.bat file.
It has full Swing and lightweight component support (precompiled JAR uses packages javax.swing.* ).
It has full Swing and lightweight component support (precompiled JAR uses packages javax.swing.* ).
JMeter store its test plans in XML format. This means you can generate a test plan using a text editor.
JMeter store its test plans in XML format. This means you can generate a test plan using a text editor.
Its full multi-threading framework allows concurrent sampling by many threads and simultaneous sampling of different functions by separate thread groups.
Its full multi-threading framework allows concurrent sampling by many threads and simultaneous sampling of different functions by separate thread groups.
It is highly extensible.
It is highly extensible.
It can also be used to perform automated and functional testing of the applications.
It can also be used to perform automated and functional testing of the applications.
JMeter simulates a group of users sending requests to a target server, and returns statistics that show the performance/functionality of the target server/application via tables, graphs, etc.
Take a look at the following figure that depicts how JMeter works −
JMeter is a framework for Java, so the very first requirement is to have JDK installed in your machine.
First of all, verify whether you have Java installed in your system. Open your console and execute one of the following java commands based on the operating system you are working on.
If you have Java installed in your system, you would get an appropriate output based on the OS you are working on.
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)
If you do not have Java installed, install the Java Software Development Kit (SDK) from www.oracle.com/technetwork/java/javase/downloads/index.html. We are assuming Java 1.7.0_25 as the installed version for this tutorial.
Set the JAVA_HOME environment variable to point to the base directory location, where Java is installed on your machine. For example −
Append Java compiler location to System Path.
Verify Java Installation using java -version command as explained above.
Download the latest version of JMeter from https://jmeter.apache.org/download_jmeter.cgi. For this tutorial, we downloaded apache-jmeter-2.9 and copied it into C:\>JMeter folder.
The directory structure should look like as shown below −
apache-jmeter-2.9
apache-jmeter-2.9\bin
apache-jmeter-2.9\docs
apache-jmeter-2.9\extras
apache-jmeter-2.9\lib\
apache-jmeter-2.9\lib\ext
apache-jmeter-2.9\lib\junit
apache-jmeter-2.9\printable_docs
You can rename the parent directory (i.e. apache-jmeter-2.9) if you want, but do not change any of the sub-directory names.
After downloading JMeter, go to the bin directory. In this case, it is /home/manisha/apache-jmeter-2.9/bin. Now click on the following −
After a short pause, the JMeter GUI should appear, which is a Swing application, as seen in the following screenshot −
This is the main page and the default page of the tool.
A Test Plan can be viewed as a container for running tests. It defines what to test and how to go about it. A complete test plan consists of one or more elements such as thread groups, logic controllers, sample-generating controllers, listeners, timers, assertions, and configuration elements. A test plan must have at least one thread group.
Follow the steps given below to write a test plan −
Open the JMeter window by clicking /home/manisha/apache-jmeter-2.9/bin/jmeter.sh. The JMeter window will appear as below −
This is a plain and blank JMeter window without any additional elements added to it. It contains two nodes −
Test Plan node − is where the real test plan is kept.
Test Plan node − is where the real test plan is kept.
Workbench node − It simply provides a place to temporarily store test elements while not in use, for copy/paste purposes. When you save your test plan, Workbench items are not saved with it.
Workbench node − It simply provides a place to temporarily store test elements while not in use, for copy/paste purposes. When you save your test plan, Workbench items are not saved with it.
Elements (which will be discussed in the next chapter Test Plan Elements) can be added to a test plan by right-clicking on the Test Plan node and choosing a new element from the "add" list.
Alternatively, you can load an element from a file and add it by choosing the "merge" or "open" option.
For example, let us add a Thread Group element to a Test Plan as shown below −
To remove an element, make sure the element is selected, right-click on the element, and choose the "remove" option.
To load an element from file −
Right-click on the existing tree element to which you want to add the loaded element.
Select Merge.
Choose the file where you saved the elements.
JMeter will merge the elements into the tree.
By default, JMeter does not save the element, you need to explicitly save it.
To save tree elements −
Right-click on the element.
Choose the Save Selection As ... option.
JMeter will save the element selected, plus all the child elements beneath it. By default, JMeter doesn't save the elements, you need to explicitly save it as mentioned earlier.
Any element in the Test Plan can be configured using the controls present in JMeter's right-hand side frame. These controls allow you to configure the behavior of that particular test element. For example, the Thread Group can be configured for a number of users, ramp up periods, etc., as shown below −
You can save an entire Test Plan by using either Save or "Save Test Plan As ..." from the File menu.
You can run the Test Plan by clicking Start(Control + r) from the Run menu item. When JMeter starts running, it shows a small green box at the right-hand end of the section just under the menubar.
The numbers to the left of the green box are the number of active threads / total number of threads. These only apply to a locally run test; they do not include any threads started on remote systems when using client-server mode.
You can stop your test in two ways −
Using Stop (Control + '.'). It stops the threads immediately if possible.
Using Stop (Control + '.'). It stops the threads immediately if possible.
Using Shutdown (Control + ','). It requests the threads to stop at the end of any current work.
Using Shutdown (Control + ','). It requests the threads to stop at the end of any current work.
A JMeter Test Plan comprises of test elements discussed below. A Test Plan comprises of at least one Thread Group. Within each Thread Group, we may place a combination of one or more of other elements − Sampler, Logic Controller, Configuration Element, Listener, and Timer. Each Sampler can be preceded by one or more Pre-processor element, followed by Post-processor element, and/or Assertion element. Let us see each of these elements in detail −
Thread Group elements are the beginning points of your test plan. As the name suggests, the thread group elements control the number of threads JMeter will use during the test. We can also control the following via the Thread Group −
Setting the number of threads
Setting the number of threads
Setting the ramp-up time
Setting the ramp-up time
Setting the number of test iterations
Setting the number of test iterations
The Thread Group Control Panel looks like this −
The Thread Group Panel holds the following components −
Action to be taken after a Sampler error − In case any error occurs during test execution, you may let the test either −
Continue to the next element in the test
Stop Thread to stop the current Thread.
Stop Test completely, in case you want to inspect the error before it continues running.
Action to be taken after a Sampler error − In case any error occurs during test execution, you may let the test either −
Continue to the next element in the test
Continue to the next element in the test
Stop Thread to stop the current Thread.
Stop Thread to stop the current Thread.
Stop Test completely, in case you want to inspect the error before it continues running.
Stop Test completely, in case you want to inspect the error before it continues running.
Number of Threads − Simulates the number of users or connections to your server application.
Number of Threads − Simulates the number of users or connections to your server application.
Ramp-Up Period Defines how long it will take JMeter to get all threads running.
Ramp-Up Period Defines how long it will take JMeter to get all threads running.
Loop Count − Defines the number of times to execute the test.
Loop Count − Defines the number of times to execute the test.
Scheduler checkbox − Once selected, the Scheduler Configuration section appears at the bottom of the control panel.
Scheduler checkbox − Once selected, the Scheduler Configuration section appears at the bottom of the control panel.
Scheduler Configuration − You can configure the start and end time of running the test.
Scheduler Configuration − You can configure the start and end time of running the test.
JMeter has two types of Controllers − Samplers and Logic Controllers.
Samplers allow JMeter to send specific types of requests to a server. They simulate a user request for a page from the target server. For example, you can add a HTTP Request sampler if you need to perform a POST, GET, or DELETE on a HTTP service.
Some useful samplers are −
HTTP Request
FTP Request
JDBC Request
Java Request
SOAP/XML Request
RPC Requests
The following screenshot shows an HTTP Request Sampler Control Panel −
Logic Controllers let you control the order of processing of Samplers in a Thread. Logic controllers can change the order of a request coming from any of their child elements. Some examples are − ForEach Controller, While Controller, Loop Controller, IF Controller, Run Time Controller, Interleave Controller, Throughput Controller, and Run Once Controller.
The following screenshot shows a Loop Controller Control Panel −
The following list consists of all the Logic Controllers JMeter provides −
Simple Controller
Loop Controller
Once Only Controller
Interleave Controller
Random Controller
Random Order Controller
Throughput Controller
Runtime Controller
If Controller
While Controller
Switch Controller
ForEach Controller
Module Controller
Include Controller
Transaction Controller
Recording Controller
A Test Fragment is a special type of element placed at the same level as the Thread Group element. It is distinguished from a Thread Group in that it is not executed unless it is referenced by either a Module Controller or an Include_Controller. This element is purely for code re-use within Test Plans.
Listeners let you view the results of Samplers in the form of tables, graphs, trees, or simple text in some log files. They provide visual access to the data gathered by JMeter about the test cases as a Sampler component of JMeter is executed.
Listeners can be added anywhere in the test, including directly under the test plan. They will collect data only from elements at or below their level. The following list consists of all the Listeners JMeter provides −
Sample Result Save Configuration
Graph Full Results
Graph Results
Spline Visualizer
Assertion Results
View Results Tree
Aggregate Report
View Results in Table
Simple Data Writer
Monitor Results
Distribution Graph (alpha)
Aggregate Graph
Mailer Visualizer
BeanShell Listener
Summary Report
By default, a JMeter thread sends requests without pausing between each sampler. This may not be what you want. You can add a timer element which allows you to define a period to wait between each request.
The following list shows all the timers that JMeter provides −
Constant Timer
Gaussian Random Timer
Uniform Random Timer
Constant Throughput Timer
Synchronizing Timer
JSR223 Time
BeanShell Time
BSF Time
Poisson Random Time
The following screenshot shows a Constant Timer Control Panel −
Assertions allow you to include some validation test on the response of your request made using a Sampler. Using assertions you can prove that your application is returning the correct data. JMeter highlights when an assertion fails.
The following list consists of all the assertions JMeter provides −
Beanshell Assertion
BSF Assertion
Compare Assertion
JSR223 Assertion
Response Assertion
Duration Assertion
Size Assertion
XML Assertion
BeanShell Assertion
MD5Hex Assertion
HTML Assertion
XPath Assertion
XML Schema Assertion
The following screenshot shows a Response Assertion Control Panel −
Configuration Elements allow you to create defaults and variables to be used by Samplers. They are used to add or modify requests made by Samplers.
They are executed at the start of the scope of which they are part, before any Samplers that are located in the same scope. Therefore, a Configuration Element is accessed only from inside the branch where it is placed.
The following list consists of all the Configuration Elements that JMeter provides −
Counter
CSV Data Set Config
FTP Request Defaults
HTTP Authorization Manager
HTTP Cache Manager
HTTP Cookie Manager
HTTP Proxy Server
HTTP Request Defaults
HTTP Header Manager
Java Request Defaults
Keystore Configuration
JDBC Connection Configuration
Login Config Element
LDAP Request Defaults
LDAP Extended Request Defaults
TCP Sampler Config
User Defined Variables
Simple Config Element
Random Variable
A pre-processor element is something that runs just before a sampler executes. They are often used to modify the settings of a Sample Request just before it runs, or to update variables that are not extracted from response text.
The following list consists of all the pre-processor elements that JMeter provides −
HTML Link Parser
HTTP URL Re-writing Modifier
HTTP User Parameter Modifier
User Parameters
JDBC PreProcessor
JSR223 PreProcessor
RegEx User Parameters
BeanShell PreProcessor
BSF PreProcessor
A post-processor executes after a sampler finishes its execution. This element is most often used to process the response data, for example, to retrieve a particular value for later use.
The following list consists of all the Post-Processor Elements JMeter provides −
Regular Expression Extractor
XPath Extractor
Result Status Action Handler
JSR223 PostProcessor
JDBC PostProcessor
BSF PostProcessor
CSS/JQuery Extractor
BeanShell PostProcessor
Debug PostProcessor
Following is the execution order of the test plan elements −
Configuration elements
Pre-Processors
Timers
Sampler
Post-Processors (unless SampleResult is null)
Assertions (unless SampleResult is null)
Listeners (unless SampleResult is null)
Let us build a simple test plan which tests a web page. We write a test plan in Apache JMeter so that we can test the performance of the web page shown by the URL − www.tutorialspoint.com.
Open the JMeter window by clicking on /home/manisha/apache-jmeter-2.9/bin/jmeter.sh. The JMeter window appear as below −
Change the name of test plan node to Sample Test in the Name text box. You need to change the focus to workbench node and back to the Test Plan node to see the name getting reflected.
Now we add our first element in the window. We add one Thread Group, which is a placeholder for all other elements like Samplers, Controllers, and Listeners. We need one so we can configure number of users to simulate.
In JMeter, all the node elements are added by using the context menu.
Right-click the element where you want to add a child element node.
Right-click the element where you want to add a child element node.
Choose the appropriate option to add.
Choose the appropriate option to add.
Right-click on the Sample Test (our Test Plan) → Add → Threads (Users) → Thread Group. Thus, the Thread Group gets added under the Test Plan (Sample Test) node.
Right-click on the Sample Test (our Test Plan) → Add → Threads (Users) → Thread Group. Thus, the Thread Group gets added under the Test Plan (Sample Test) node.
Name the Thread Group as Users. For us, this element means users visiting the TutorialsPoint Home Page.
Name the Thread Group as Users. For us, this element means users visiting the TutorialsPoint Home Page.
We need to add one Sampler in our Thread Group (Users). As done earlier for adding Thread group, this time we will open the context menu of the Thread Group (Users) node by right-clicking and we will add HTTP Request Sampler by choosing Add → Sampler → HTTP request option.
It will add one empty HTTP Request Sampler under the Thread Group (Users) node. Let us configure this node element −
Name − We will change the name to reflect the action what we want to achieve. We will name it as Visit TutorialsPoint Home Page
Name − We will change the name to reflect the action what we want to achieve. We will name it as Visit TutorialsPoint Home Page
Server Name or IP − Here, we have to type the web server name. In our case it is www.tutorialspoint.com. (http:// part is not written this is only the name of the server or its IP)
Server Name or IP − Here, we have to type the web server name. In our case it is www.tutorialspoint.com. (http:// part is not written this is only the name of the server or its IP)
Protocol − We will keep this blank, which means we want HTTP as the protocol.
Protocol − We will keep this blank, which means we want HTTP as the protocol.
Path − We will type path as / (slash). It means we want the root page of the server.
Path − We will type path as / (slash). It means we want the root page of the server.
We will now add a listener. Let us add View Results Tree Listener under the Thread Group (User) node. It will ensure that the results of the Sampler will be available to view in this Listener node element.
To add a listener −
Open the context menu
Open the context menu
Right-click the Thread Group (Users)
Right-click the Thread Group (Users)
Choose Add → Listener → View Results Tree option
Choose Add → Listener → View Results Tree option
Now with all the setup, let us execute the test plan. With the configuration of the Thread Group (Users), we keep all the default values. It means JMeter will execute the sampler only once. It is similar to a single user, only once.
This is similar to a user visiting a web page through browser, with JMeter sampler. To execute the test plan, Select Run from the menu and select Start option.
Apache JMeter asks us to save the test plan in a disk file before actually starting the test. This is important if you want to run the test plan multiple times. You can opt for running it without saving too.
We have kept the setting of the thread group as single thread (one user only) and loop for 1 time (run only one time), hence we will get the result of one single transaction in the View Result Tree Listener.
Details of the above result are −
Green color against the name Visit TutorialsPoint Home Page indicates success.
Green color against the name Visit TutorialsPoint Home Page indicates success.
JMeter has stored all the headers and the responses sent by the web server and ready to show us the result in many ways.
JMeter has stored all the headers and the responses sent by the web server and ready to show us the result in many ways.
The first tab is Sampler Results. It shows JMeter data as well as data returned by the web server.
The first tab is Sampler Results. It shows JMeter data as well as data returned by the web server.
The second tab is Request, which shows all the data sent to the web server as part of the request.
The second tab is Request, which shows all the data sent to the web server as part of the request.
The last tab is Response data. In this tab, the listener shows the data received from server in text format.
This is just a simple test plan which executes only one request. But JMeter's real strength is in sending the same request, as if many users are sending it. To test the web servers with multiple users, we need to change the Thread Group (Users) settings.
In this chapter, we will see how to create a simple test plan to test the database server. For our test purpose we use the MYSQL database server. You can use any other database for testing. For installation and table creation in MYSQL please refer MYSQL Tutorial.
Once MYSQL is installed, follow the steps below to setup the database −
Create a database with name "tutorial".
Create a database with name "tutorial".
Create a table tutorials_tbl.
Create a table tutorials_tbl.
Insert records into tutorials_tbl as shown below −
Insert records into tutorials_tbl as shown below −
mysql> use TUTORIALS;
Database changed
mysql> INSERT INTO tutorials_tbl
->(tutorial_title, tutorial_author, submission_date)
->VALUES
->("Learn PHP", "John Poul", NOW());
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO tutorials_tbl
->(tutorial_title, tutorial_author, submission_date)
->VALUES
->("Learn MySQL", "Abdul S", NOW());
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO tutorials_tbl
->(tutorial_title, tutorial_author, submission_date)
->VALUES
->("JAVA Tutorial", "Sanjay", '2007-05-06');
Query OK, 1 row affected (0.01 sec)
mysql>
Copy the appropriate JDBC driver to /home/manisha/apache-jmeter-2.9/lib.
Copy the appropriate JDBC driver to /home/manisha/apache-jmeter-2.9/lib.
Let us start the JMeter from /home/manisha/apache-jmeter-2.9/bin/jmeter.sh.
To create a Thread group,
Right-click on Test Plan.
Right-click on Test Plan.
Select Add → Threads (Users) → Thread Group.
Select Add → Threads (Users) → Thread Group.
Thus, thread group gets added under the Test Plan node.
Thus, thread group gets added under the Test Plan node.
Rename this Thread Group as JDBC Users.
Rename this Thread Group as JDBC Users.
We will not change the default properties of the Thread Group.
Now that we defined our users, it is time to define the tasks that they will be performing. In this section, specify the JDBC requests to perform.
Right-click on the JDBC Users element.
Right-click on the JDBC Users element.
Select Add → Config Element → JDBC Connection Configuration.
Select Add → Config Element → JDBC Connection Configuration.
Set up the following fields (we are using MySQL database called tutorial) −
Variable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test.
Database URL − jdbc:mysql://localhost:3306/tutorial.
JDBC Driver class: com.mysql.jdbc.Driver.
Username: root.
Password: password for root.
Set up the following fields (we are using MySQL database called tutorial) −
Variable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test.
Variable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test.
Database URL − jdbc:mysql://localhost:3306/tutorial.
Database URL − jdbc:mysql://localhost:3306/tutorial.
JDBC Driver class: com.mysql.jdbc.Driver.
JDBC Driver class: com.mysql.jdbc.Driver.
Username: root.
Username: root.
Password: password for root.
Password: password for root.
The other fields on the screen are left as defaults as shown below −
Now add a JDBC Request which refers to the JDBC Configuration pool defined above. Select JDBC Users element.
Click your right mouse button to get the Add menu
Click your right mouse button to get the Add menu
Select Add → Sampler → JDBC Request.
Select Add → Sampler → JDBC Request.
Select this new element to view its Control Panel.
Select this new element to view its Control Panel.
Edit the properties as shown below −
Variable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test.
Name − Learn.
Enter the Pool Name − test (same as in the configuration element).
Query Type − Select statement.
Enter the SQL Query String field.
Edit the properties as shown below −
Variable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test.
Variable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test.
Name − Learn.
Name − Learn.
Enter the Pool Name − test (same as in the configuration element).
Enter the Pool Name − test (same as in the configuration element).
Query Type − Select statement.
Query Type − Select statement.
Enter the SQL Query String field.
Enter the SQL Query String field.
Now add the Listener element. This element is responsible for storing all of the results of your JDBC requests in a file and presenting a visual model of the data.
Select the JDBC Users element
Select the JDBC Users element
Add a View Results Tree listener (Add → Listener → View Results Tree).
Add a View Results Tree listener (Add → Listener → View Results Tree).
Now save the above test plan as db_test.jmx. Execute this test plan using Run → Start option.
In the last image, you can see that two records are selected.
In this chapter, we will see how to test a FTP site using JMeter. Let us create a Test Plan to test the FTP site.
Open the JMeter window by clicking /home/manisha/apache-jmeter-2.9/bin/jmeter.sh
Open the JMeter window by clicking /home/manisha/apache-jmeter-2.9/bin/jmeter.sh
Click on the Test Plan node.
Click on the Test Plan node.
Rename this Test Plan node as TestFTPSite.
Rename this Test Plan node as TestFTPSite.
Add one Thread Group, which is placeholder for all other elements like Samplers, Controllers, and Listeners.
Right click on TestFTPSite (our Test Plan)
Right click on TestFTPSite (our Test Plan)
Select Add → Threads(Users) → Thread Group. Thread Group will get added under the Test Plan (TestFTPSite) node.
Select Add → Threads(Users) → Thread Group. Thread Group will get added under the Test Plan (TestFTPSite) node.
Modify the default properties of the Thread Group to suit our testing as follows −
Name − FTPusers
Number of Threads (Users) − 4
Ramp-Up Period − leave the the default value of 0 seconds.
Loop Count − 1
Modify the default properties of the Thread Group to suit our testing as follows −
Name − FTPusers
Name − FTPusers
Number of Threads (Users) − 4
Number of Threads (Users) − 4
Ramp-Up Period − leave the the default value of 0 seconds.
Ramp-Up Period − leave the the default value of 0 seconds.
Loop Count − 1
Loop Count − 1
Now that we have defined our users, it is time to define the tasks that they will be performing. Add FTP Request elements. We add two FTP request elements, one which retrieves a file and the other which puts a file on the ftp site.
Select the FTP users element.
Select the FTP users element.
Right-click the mouse button to get the Add menu
Right-click the mouse button to get the Add menu
Select Add → Sampler → FTP Request.
Select Add → Sampler → FTP Request.
Select the FTP Request element in the tree.
Select the FTP Request element in the tree.
Edit the following properties as shown below −
Edit the following properties as shown below −
The following details are entered in this element −
Name − FTP Request Get
Name − FTP Request Get
Server Name or IP − 184.168.74.29
Server Name or IP − 184.168.74.29
Remote File − /home/manisha/sample_ftp.txt
Remote File − /home/manisha/sample_ftp.txt
Local File − sample_ftp.txt
Local File − sample_ftp.txt
Select get(RETR)
Select get(RETR)
Username − manisha
Username − manisha
Password − manisha123
Password − manisha123
Now add another FTP request as above and edit the properties as shown in the following screenshot −
The following details are entered in this element −
Name − FTP Request Put
Name − FTP Request Put
Server Name or IP − 184.168.74.29
Server Name or IP − 184.168.74.29
Remote File − /home/manisha/examplefile.txt
Remote File − /home/manisha/examplefile.txt
Local File − /home/manisha/work/examplefile.txt
Local File − /home/manisha/work/examplefile.txt
Select put(STOR)
Select put(STOR)
Username − manisha
Username − manisha
Password − manisha123
Password − manisha123
The final element you need to add to your Test Plan is a Listener. This element is responsible for storing all of the results of your FTP requests in a file and presenting a visual model of the data.
Select the FTP users element.
Select the FTP users element.
Add a View Results Tree listener by selecting Add > Listener > View Results Tree.
Add a View Results Tree listener by selecting Add > Listener > View Results Tree.
Now save the above test plan as ftpsite_test.jmx. Execute this test plan using Run → Start option.
The following output can be seen in the listener.
You can see that four requests are made for each FTP request and the test is successful. The retrieved file for GET request is stored in the /bin folder. In our case, it is /home/manisha/apache-jmeter-2.9/bin/. For PUT request, the file is uploaded at the path /home/manisha/.
In this chapter, we will learn how to create a Test Plan to test a WebService. For our test purpose, we have created a simple webservice project and deployed it on the Tomcat server locally.
To create a webservice project, we have used Eclipse IDE. First write the Service Endpoint Interface HelloWorld under the package com.tutorialspoint.ws. The contents of the HelloWorld.java are as follows −
package com.tutorialspoint.ws;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld {
@WebMethod String getHelloWorldMessage(String string);
}
This service has a method getHelloWorldMessage which takes a String parameter.
Next, create the implementation class HelloWorldImpl.java under the package com.tutorialspoint.ws.
package com.tutorialspoint.ws;
import javax.jws.WebService;
@WebService(endpointInterface="com.tutorialspoint.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
@Override
public String getHelloWorldMessage(String myName) {
return("Hello "+myName+" to JAX WS world");
}
}
Let us now publish this web service locally by creating the Endpoint publisher and expose the service on the server.
The publish method takes two parameters −
Endpoint URL String.
Endpoint URL String.
Implementor object, in this case the HelloWorld implementation class, which is exposed as a Web Service at the endpoint identified by the URL mentioned in the parameter above.
Implementor object, in this case the HelloWorld implementation class, which is exposed as a Web Service at the endpoint identified by the URL mentioned in the parameter above.
The contents of HelloWorldPublisher.java are as follows −
package com.tutorialspoint.endpoint;
import javax.xml.ws.Endpoint;
import com.tutorialspoint.ws.HelloWorldImpl;
public class HelloWorldPublisher {
public static void main(String[] args) {
Endpoint.publish("http://localhost:9000/ws/hello", new HelloWorldImpl());
}
}
Modify the web.xml contents as shown below −
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems,
Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<listener>
<listener-class>
com.sun.xml.ws.transport.http.servlet.WSServletContextListener
</listener-class>
</listener>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>120</session-timeout>
</session-config>
</web-app>
To deploy this application as a webservice, we would need another configuration file sun-jaxws.xml. The contents of this file are as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
<endpoints
xmlns = "http://java.sun.com/xml/ns/jax-ws/ri/runtime"
version = "2.0">
<endpoint name = "HelloWorld"
implementation = "com.tutorialspoint.ws.HelloWorldImpl"
url-pattern = "/hello"/>
</endpoints>
Now that all the files are ready, the directory structure would look as shown in the following screenshot −
Now create a WAR file of this application.
Now create a WAR file of this application.
Choose the project → right click → Export → WAR file.
Choose the project → right click → Export → WAR file.
Save this as hello.war file under the webapps folder of Tomcat server.
Save this as hello.war file under the webapps folder of Tomcat server.
Now start the Tomcat server.
Now start the Tomcat server.
Once the server is started, you should be able to access the webservice with the URL − http://localhost:8080/hello/hello
Once the server is started, you should be able to access the webservice with the URL − http://localhost:8080/hello/hello
Now let us create a test plan to test the above webservice.
Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh.
Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh.
Click the Test Plan node.
Click the Test Plan node.
Rename this Test Plan node as WebserviceTest.
Rename this Test Plan node as WebserviceTest.
Add one Thread Group, which is placeholder for all other elements like Samplers, Controllers, and Listeners.
Right click on WebserviceTest (our Test Plan) → Add → Threads (Users) → Thread Group. Thread Group will get added under the Test Plan (WebserviceTest) node.
Right click on WebserviceTest (our Test Plan) → Add → Threads (Users) → Thread Group. Thread Group will get added under the Test Plan (WebserviceTest) node.
Next, let us modify the default properties of the Thread Group to suit our testing. Following properties are changed −
Name − webservice user
Number of Threads (Users) − 2
Ramp-Up Period − leave the the default value of 0 seconds.
Loop Count − 2
Next, let us modify the default properties of the Thread Group to suit our testing. Following properties are changed −
Name − webservice user
Name − webservice user
Number of Threads (Users) − 2
Number of Threads (Users) − 2
Ramp-Up Period − leave the the default value of 0 seconds.
Ramp-Up Period − leave the the default value of 0 seconds.
Loop Count − 2
Loop Count − 2
Now that we have defined the users, it is time to define the tasks that they will be performing.
We will add SOAP/XML-RPC Request element −
Right-click mouse button to get the Add menu.
Right-click mouse button to get the Add menu.
Select Add → Sampler → SOAP/XML-RPC Request.
Select Add → Sampler → SOAP/XML-RPC Request.
Select the SOAP/XML-RPC Request element in the tree
Select the SOAP/XML-RPC Request element in the tree
Edit the following properties as in the image below −
Edit the following properties as in the image below −
The following details are entered in this element −
Name − SOAP/XML-RPC Request
URL − http://localhost:8080/hello/hello?wsdl
Soap/XML-RPC Data − Enter the below contents
The following details are entered in this element −
Name − SOAP/XML-RPC Request
Name − SOAP/XML-RPC Request
URL − http://localhost:8080/hello/hello?wsdl
URL − http://localhost:8080/hello/hello?wsdl
Soap/XML-RPC Data − Enter the below contents
Soap/XML-RPC Data − Enter the below contents
<soapenv:Envelope xmlns:soapenv = "http://schemas.xmlsoap.org/soap/envelope/"
xmlns:web = "http://ws.tutorialspoint.com/">
<soapenv:Header/>
<soapenv:Body>
<web:getHelloWorldMessage>
<arg0>Manisha</arg0>
</web:getHelloWorldMessage>
</soapenv:Body>
</soapenv:Envelope>
The final element you need to add to your Test Plan is a Listener. This element is responsible for storing all of the results of your HTTP requests in a file and presenting a visual model of the data.
Select the webservice user element.
Select the webservice user element.
Add a View Results Tree listener by selecting Add → Listener → View Results Tree.
Add a View Results Tree listener by selecting Add → Listener → View Results Tree.
Now save the above test plan as test_webservice.jmx. Execute this test plan using Run → Start option.
The following output can be seen in the listener.
In the last image, you can see the response message "Hello Manisha to JAX WS world".
In this chapter, we will learn how to write a simple test plan to test Java Messaging Service (JMS). JMS supports two types of messaging −
Point-to-Point messaging − Queue messaging is generally used for transactions where the sender expects a response. Messaging systems are quite different from normal HTTP requests. In HTTP, a single user sends a request and gets a response.
Point-to-Point messaging − Queue messaging is generally used for transactions where the sender expects a response. Messaging systems are quite different from normal HTTP requests. In HTTP, a single user sends a request and gets a response.
Topic messaging − Topic messages are commonly known as pub/sub messaging. Topic messaging is generally used in cases where a message is published by a producer and consumed by multiple subscribers.
Topic messaging − Topic messages are commonly known as pub/sub messaging. Topic messaging is generally used in cases where a message is published by a producer and consumed by multiple subscribers.
Let us see a test example for each of these. The pre-requisites for testing JMS are −
We use Apache ActiveMQ in the example. There are various JMS servers like IBM WebSphere MQ (formerly MQSeries), Tibco, etc. Download it from the binaries from the Apache ActiveMQ website.
We use Apache ActiveMQ in the example. There are various JMS servers like IBM WebSphere MQ (formerly MQSeries), Tibco, etc. Download it from the binaries from the Apache ActiveMQ website.
Unzip the archive, go to the decompressed directory, and run the following command from the command console to start the ActiveMQ server −
Unzip the archive, go to the decompressed directory, and run the following command from the command console to start the ActiveMQ server −
.\bin\activemq start
You can verify if the ActiveMQ server has started by visiting the admin interface at the following address http://localhost:8161/admin/. If it asks for authentication, then enter the userid and password as admin. The screen is similar as shown below −
Now copy the activemq-all-x.x.x.jar (XXX depending on the version) from the ActiveMQ unzipped directory to /home/manisha/apache-jmeter-2.9/lib.
Now copy the activemq-all-x.x.x.jar (XXX depending on the version) from the ActiveMQ unzipped directory to /home/manisha/apache-jmeter-2.9/lib.
With the above setup, let us build the test plan for −
JMS Point-to-Point Test Plan
JMS Point-to-Point Test Plan
JMS Topic Test Plan
JMS Topic Test Plan
In this chapter, we will discuss how to create a Test Plan using JMeter to monitor webservers. The uses of monitor tests are as follows −
Monitors are useful for a stress testing and system management.
Monitors are useful for a stress testing and system management.
Used with stress testing, the monitor provides additional information about server performance.
Used with stress testing, the monitor provides additional information about server performance.
Monitors make it easier to see the relationship between server performance and response time on the client side.
Monitors make it easier to see the relationship between server performance and response time on the client side.
As a system administration tool, the monitor provides an easy way to monitor multiple servers from one console.
As a system administration tool, the monitor provides an easy way to monitor multiple servers from one console.
We need Tomcat 5 or above for monitoring. For our test purpose, we will monitor Tomcat 7.0.42 server. You can test any servlet container that supports Java Management Extension (JMX). Let us write a test case to monitor the Tomcat server. Let us first set up our tomcat server.
We start with opening the Tomcat service status. To do this, edit the configuration file for users, <TOMCAT_HOME>/conf/tomcat-users.xml. This file contains a tomcat-users section (commented) as shown −
<tomcat-users>
<!--
<role rolename = "tomcat"/>
<role rolename = "role1"/>
<user username = "tomcat" password = "tomcat" roles = "tomcat"/>
<user username = "both" password = "tomcat" roles = "tomcat,role1"/>
<user username = "role1" password = "tomcat" roles = "role1"/>
-->
</tomcat-users>
We need to change this section to add the admin roles, manager, manager-gui and assign the user "admin". The revised file is as follows −
<tomcat-users>
<role rolename = "manager-gui"/>
<role rolename = "manager-script"/>
<role rolename = "manager-jmx"/>
<role rolename = "manager-status"/>
<user username = "admin" password = "admin" roles = "manager-gui,manager-script,manager-jmx,manager-status"/>
</tomcat-users>
Now start the tomcat server <TOMCAT_HOME>/bin/startup.sh for Linux and <TOMCAT_HOME>/bin/startup.bat for windows. Once started, check that the Tomcat supervision works by entering the following link in your browser −
http://localhost:8080/manager/status?XML=true
An authentication window appears in the browser. Enter the tomcat login and password associated (in our case it is admin). Then, the browser shows the execution status of Tomcat as below −
From the above screenshot, we can note a few things −
In the URL, note that XML = true (note the case sensitivity) allows a clean display of the supervisory Tomcat necessary for the JMeter functioning.
In the URL, note that XML = true (note the case sensitivity) allows a clean display of the supervisory Tomcat necessary for the JMeter functioning.
Also note that there are default two connectors. The AJP connector used in general coupled with the mod_jk Apache HTTPD front module and the HTTP connector which is commonly used connector for direct access to Tomcat via port 8080.
Also note that there are default two connectors. The AJP connector used in general coupled with the mod_jk Apache HTTPD front module and the HTTP connector which is commonly used connector for direct access to Tomcat via port 8080.
Let us monitor the Tomcat server by writing a test plan −
Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh.
Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh.
Click the Test Plan node.
Click the Test Plan node.
Add a thread group as explained in the next step.
Add a thread group as explained in the next step.
Right-click on Test Plan → Add → Threads(Users) → Thread Group. Thread Group will get added under the Test Plan node.
Right-click on Test Plan → Add → Threads(Users) → Thread Group. Thread Group will get added under the Test Plan node.
Change the loop count to forever (or some large number) so that enough samples are generated.
Change the loop count to forever (or some large number) so that enough samples are generated.
Add HTTP Authorization Manager to the Thread Group element by selecting Add → Config element → HTTP Authorization Manager. This element manages authentication requested by the browser to see the Tomcat server status.
Add HTTP Authorization Manager to the Thread Group element by selecting Add → Config element → HTTP Authorization Manager. This element manages authentication requested by the browser to see the Tomcat server status.
Select the HTTP Authorization Manager.
Select the HTTP Authorization Manager.
Edit the following details −
Username − admin (depending on the configuration in tomcat-users.xml file)
Password − admin (depending on the configuration in the tomcatusers.xml file)
The other fields are left empty.
Edit the following details −
Username − admin (depending on the configuration in tomcat-users.xml file)
Username − admin (depending on the configuration in tomcat-users.xml file)
Password − admin (depending on the configuration in the tomcatusers.xml file)
Password − admin (depending on the configuration in the tomcatusers.xml file)
The other fields are left empty.
The other fields are left empty.
Now that we have defined our users, it is time to define the tasks that they will be performing. We add HTTP Request element.
Right click the mouse button to get the Add menu.
Right click the mouse button to get the Add menu.
Select Add → Sampler → HTTP Request.
Select Add → Sampler → HTTP Request.
Then, select the HTTP Request element in the tree.
Then, select the HTTP Request element in the tree.
Edit the following properties as in the image below −
Edit the following properties as in the image below −
The following details are entered in this element −
Name − Server Status
Server Name or IP − localhost
Port − 8080
Path − /manager/status
Parameters − Add a request parameter named "XML" in uppercase. Give it a value of "true" in lowercase.
Optional Tasks − Check "Use as Monitor" at the bottom of the sampler.
The following details are entered in this element −
Name − Server Status
Name − Server Status
Server Name or IP − localhost
Server Name or IP − localhost
Port − 8080
Port − 8080
Path − /manager/status
Path − /manager/status
Parameters − Add a request parameter named "XML" in uppercase. Give it a value of "true" in lowercase.
Parameters − Add a request parameter named "XML" in uppercase. Give it a value of "true" in lowercase.
Optional Tasks − Check "Use as Monitor" at the bottom of the sampler.
Optional Tasks − Check "Use as Monitor" at the bottom of the sampler.
To request the status of the server periodically, add a Constant Timer which will allow a time interval between each request. Add a timer to this thread group by selecting Add → Timer → Constant Timer.
Enter 5000 milliseconds in the Thread Delay box. In general, using intervals shorter than 5 seconds may add stress to your server. Find out what is an acceptable interval before you deploy the monitor in your production environment.
The final element you need to add to your Test Plan is a Listener. We add two types of listeners. One that stores results in a file and second that shows the graphical view of the results.
Select the thread group element.
Select the thread group element.
Add a Simple Data Writer listener Add → Listener → Simple Data Writer.
Add a Simple Data Writer listener Add → Listener → Simple Data Writer.
Specify a directory and filename of the output file (in our case, it is /home/manisha/work/sample.csv)
Specify a directory and filename of the output file (in our case, it is /home/manisha/work/sample.csv)
Let us add another listener by selecting the test plan element Add → Listener → Monitor Results.
Let us add another listener by selecting the test plan element Add → Listener → Monitor Results.
Now save the above test plan as monitor_test.jmx. Execute this test plan using Run → Start option.
Results will be saved in /home/manisha/work/sample.csv file. You can also see a graphical result in the Monitor result listener as in the image below.
Note the graph has captions on both sides of the graph. On the left is percent and the right is dead/healthy. If the memory line spikes up and down rapidly, it could indicate memory thrashing. In those situations, it is a good idea to profile the application with Borland OptimizeIt or JProbe. What you want to see is a regular pattern for load, memory and threads. Any erratic behavior usually indicates poor performance or a bug of some sort.
Listeners provide access to the information JMeter gathers about the test cases while JMeter runs. The results or information gathered by listeners can be shown in the form of −
tree
tables
graphs
log file
All listeners write the same raw data to the output file when one is specified.
The default items to be saved can be defined in one of the following two ways −
In the jmeter.properties (or user.properties) file. This file is present in the /bin folder of JMeter.To change the default format, find the following line in jmeter.properties −
In the jmeter.properties (or user.properties) file. This file is present in the /bin folder of JMeter.To change the default format, find the following line in jmeter.properties −
jmeter.save.saveservice.output_format=
By using the Config popup as shown in the following screenshot −
By using the Config popup as shown in the following screenshot −
JMeter creates results of a test run as JMeter Text Logs(JTL). These are normally called JTL files, as that is the default extension − but any extension can be used.
If multiple tests are run using the same output file name, then JMeter automatically appends new data at the end of the file.
The listener can record results to a file but not to the UI. It is meant to provide an efficient means of recording data by eliminating GUI overhead.
When running in −
GUI mode − use the listener Simple Data Writer
GUI mode − use the listener Simple Data Writer
non-GUI mode − the -l flag can be used to create a data file.
non-GUI mode − the -l flag can be used to create a data file.
Listeners can use a lot of memory if there are a lot of samples. To minimize the amount of memory needed, use the Simple Data Write with CSV format.
The CSV log format depends on which data items are selected in the configuration. Only the specified data items are recorded in the file. The order of appearance of columns is fixed, and is as follows −
The response data can be saved in the XML log file if required. However it does not allow to save large files and images. In such cases, use the Post-Processor Save_Responses_to_a_file. This generates a new file for each sample, and saves the file name with the sample. The file name can then be included in the sample log output. The data will be retrieved from the file if necessary when the sample log file is reloaded.
To view an existing results file, you can use the file "Browse..." button to select a file. If necessary, just create a dummy testplan with the appropriate Listener in it.
JMeter is capable of saving any listener as a PNG file. To do so,
Select the listener in the left panel by selecting Edit → Save As Image. A file dialog appears.
Select the listener in the left panel by selecting Edit → Save As Image. A file dialog appears.
Enter the desired name.
Enter the desired name.
Save the listener.
Save the listener.
JMeter functions are special values that can populate fields of any Sampler or other element in a test tree.
A function call looks like this −
A function call looks like this −
${__functionName(var1,var2,var3)}
_functionName matches the name of a function. For example ${__threadNum}.
_functionName matches the name of a function. For example ${__threadNum}.
If a function parameter contains a comma, then make sure you escape this with "\" as shown below −
If a function parameter contains a comma, then make sure you escape this with "\" as shown below −
${__time(EEE\, d MMM yyyy)}
Variables are referenced as −
Variables are referenced as −
${VARIABLE}
Following table lists a group of functions loosely grouped into types −
There are two kinds of functions −
User-defined static values (or variables)
Built-in functions
There are two kinds of functions −
User-defined static values (or variables)
User-defined static values (or variables)
Built-in functions
Built-in functions
User-defined static values allow the user to define variables to be replaced with their static value when a test tree is compiled and submitted to be run.
User-defined static values allow the user to define variables to be replaced with their static value when a test tree is compiled and submitted to be run.
The variables cannot be nested; i.e ${Var${N}} does not work.
The variables cannot be nested; i.e ${Var${N}} does not work.
The __V (variable) function (versions after 2.2) can be used to do this − ${__V(Var${N})}.
The __V (variable) function (versions after 2.2) can be used to do this − ${__V(Var${N})}.
This type of replacement is possible without functions, but it is less convenient and less intuitive.
This type of replacement is possible without functions, but it is less convenient and less intuitive.
Functions and variables can be written into any field of any test component.
The following functions should work well in a test plan −
intSum
longSum
machineName
BeanShell
javaScript
jexl
random
time
property functions
log functions
Functions which are used on the Test Plan have some restrictions. JMeter thread variables will have not been fully set up when the functions are processed, so variable names passed as parameters will not be set up and variable references will not work. Hence, split() and regex() and the variable evaluation functions will not work. The threadNum() function will not work and it does not make sense at test plan level.
Referencing a variable in a test element is done by bracketing the variable name with '${' and '}'.
Referencing a variable in a test element is done by bracketing the variable name with '${' and '}'.
Functions are referenced in the same manner, but by convention, the names of functions begin with "__" to avoid conflict with user value names.
Functions are referenced in the same manner, but by convention, the names of functions begin with "__" to avoid conflict with user value names.
Some functions take arguments to configure them, and these go in parentheses, comma-delimited. If the function takes no arguments, the parentheses can be omitted. For example −
Some functions take arguments to configure them, and these go in parentheses, comma-delimited. If the function takes no arguments, the parentheses can be omitted. For example −
${__BeanShell(vars.put("name"\,"value"))}
Alternatively, you can define your script as a variable, e.g. on the Test Plan −
Alternatively, you can define your script as a variable, e.g. on the Test Plan −
SCRIPT vars.put("name","value")
The script can then be referenced as follows −
The script can then be referenced as follows −
${__BeanShell(${SCRIPT})}
The Function Helper Dialog is available from JMeter's Options tab.
Using the Function Helper, you can select a function from the pull down, and assign values for its arguments. The left column in the table provides a brief description of the argument, and the right column is where you write the value for that argument. Different functions take different arguments.
Using the Function Helper, you can select a function from the pull down, and assign values for its arguments. The left column in the table provides a brief description of the argument, and the right column is where you write the value for that argument. Different functions take different arguments.
Once you have done this, click the “Generate" button, and the appropriate string is generated, which you can copy-paste into the test plan wherever you need to.
Once you have done this, click the “Generate" button, and the appropriate string is generated, which you can copy-paste into the test plan wherever you need to.
Some variables are defined internally by JMeter. They are −
COOKIE_cookiename − contains the cookie value.
COOKIE_cookiename − contains the cookie value.
JMeterThread.last_sample_ok − whether or not the last sample was OK − true/false. Note − this is updated after PostProcessors and Assertions have been run.
JMeterThread.last_sample_ok − whether or not the last sample was OK − true/false. Note − this is updated after PostProcessors and Assertions have been run.
START variables.
START variables.
Some built-in properties are defined by JMeter. These are listed below. For convenience, the START properties are also copied to variables with the same names.
START.MS − JMeter start time in milliseconds.
START.MS − JMeter start time in milliseconds.
START.YMD − JMeter start time as yyyyMMdd.
START.YMD − JMeter start time as yyyyMMdd.
START.HMS − JMeter start time as HHmmss.
START.HMS − JMeter start time as HHmmss.
TESTSTART.MS − test start time in milliseconds.
TESTSTART.MS − test start time in milliseconds.
Note that the START variables / properties represent JMeter startup time, not the test start time. They are mainly intended for use in file names etc.
Regular expressions are used to search and manipulate text, based on patterns. JMeter interprets forms of regular expressions or patterns being used throughout a JMeter test plan, by including the pattern matching software Apache Jakarta ORO.
With the use of regular expressions, we can certainly save a lot of time and achieve greater flexibility as we create or enhance a Test Plan. Regular expressions provide a simple method to get information from pages when it is impossible or very hard to predict an outcome.
To use regular expressions in your test plan, you need to use the Regular Expression Extractor of JMeter. You can place regular expressions in any component in a Test Plan.
It is worth stressing the difference between contains and matches, as used on the Response Assertion test element −
contains means that the regular expression matched at least some part of the target, so 'alphabet' "contains" 'ph.b.' because the regular expression matches the substring 'phabe'.
contains means that the regular expression matched at least some part of the target, so 'alphabet' "contains" 'ph.b.' because the regular expression matches the substring 'phabe'.
matches means that the regular expression matched the whole target. Hence the 'alphabet' is "matched" by 'al.*t'.
matches means that the regular expression matched the whole target. Hence the 'alphabet' is "matched" by 'al.*t'.
Suppose you want to match the following portion of a web-page −
name = "file" value = "readme.txt"
And you want to extract readme.txt. A suitable regular expression would be −
name = "file" value = "(.+?)">
The special characters above are −
( and ) − these enclose the portion of the match string to be returned
( and ) − these enclose the portion of the match string to be returned
. − match any character
. − match any character
+ − one or more times
+ − one or more times
? − stop when first match succeeds
? − stop when first match succeeds
Let us understand the use of Regular expressions in the Regular Expression Extractor—a Post-Processor Element by writing a test plan. This element extracts text from the current page using a Regular Expression to identify the text pattern that a desired element conforms with.
First we write an HTML page which a list of people and their email IDs. We deploy it to our tomcat server. The contents of html (index.html) are as follows −
<html>
<head>
</head>
<body>
<table style = "border: 1px solid #000000;">
<th style = "border: 1px solid #000000;">ID</th>
<th style = "border: 1px solid #000000;">name</th>
<th style = "border: 1px solid #000000;">Email</th>
<tr>
<td id = "ID" style = "border: 1px solid #000000;">3</td>
<td id = "Name" style = "border: 1px solid #000000;">Manisha</td>
<td id = "Email" style = "border: 1px solid #000000;">[email protected]</td>
</tr>
<tr>
<td id = "ID" style = "border: 1px solid #000000;">4</td>
<td id = "Name" style = "border: 1px solid #000000;">joe</td>
<td id = "Email" style = "border: 1px solid #000000;">[email protected]</td>
</tr>
</table>
</body>
</html>
On deploying it on the tomcat server, this page would look like as shown in the following screenshot −
In our test plan, we will select the person in the first row of the person table seen in the person list page above. To capture the ID of this person, let us first determine the pattern where we will find the person in the second row.
As can be seen in the following snapshot, the ID of the second person is surrounded by <td id = "ID"> and </td >, and it is the second row of data having this pattern. We can use this to match the exact pattern that we want to extract information from. As we want to extract two pieces of information from this page, the person ID and the person name, the fields are defined as follows −
Start JMeter, add a Thread group Test Plan → Add→ Threads(Users)→ Thread Group.
Next add a sampler HTTP Request, select the test plan, right click Add → Sampler → HTTP Request and enter the details as shown below −
Name − Manage
Name − Manage
Server Name or IP − localhost
Server Name or IP − localhost
Port Number − 8080
Port Number − 8080
Protocol − We will keep this blank, which means we want HTTP as the protocol.
Protocol − We will keep this blank, which means we want HTTP as the protocol.
Path − jmeter/index.html
Path − jmeter/index.html
Next, add a Regular Expression Extractor. Select the HTTP Request Sampler (Manage), right click Add → Post Processor → Regular Expression Extractor.
The following table provides a description of the fields used in the above screenshot −
Reference Name
The name of the variable in which the extracted test will be stored (refname).
Regular Expression
The pattern against which the text to be extracted will be matched. The text groups that will extracted are enclosed by the characters '(' and ')'. We use '.+?' to indicate a single instance of the text enclosed by the <td..>..</td> tags. In our example the expression is − <td id = "ID">(+?)</td>\s*<td id = "Name">(+?)</td>\s*
Template
Each group of extracted text placed as a member of the variable Person, following the order of each group of pattern enclosed by '(' and ')'. Each group is stored as refname_g#, where refname is the string you entered as the reference name, and # is the group number. $1$ to refers to group 1, $2$ to refers to group 2, etc. $0$ refers to whatever the entire expression matches. In this example, the ID we extract is maintained in Person_g1, while the Name value is stored in Person_g2.
Match No.
Since we plan to extract only the second occurrence of this pattern, matching the second volunteer, we use value 2. Value 0 would make a random matching, while a negative value needs to be used with the ForEach Controller.
Default
If the item is not found, this will be the default value. This is an optional field. You may leave it blank.
Add a listener to capture the result of this Test Plan. Right-click the Thread Group and select Add → Listener → View Results Tree option to add the listener.
Save the test plan as reg_express_test.jmx and run the test. The output would be a success as shown in the following screenshot −
JMeter has some limitations especially when it is run in a distributed environment. Following these guidelines will assist in creating a real and continuous load −
Use multiple instances of JMeter in case, the number of threads are more.
Use multiple instances of JMeter in case, the number of threads are more.
Check the Scoping Rules and design accordingly.
Check the Scoping Rules and design accordingly.
Use naming conventions always for all elements.
Use naming conventions always for all elements.
Check the default browser Connectivity settings, before executing scripts.
Check the default browser Connectivity settings, before executing scripts.
Add Listeners appropriately.
Add Listeners appropriately.
Here are some suggestion to reduce resource requirements −
Here are some suggestion to reduce resource requirements −
Use non-GUI mode: jmeter -n -t test.jmx -l test.jtl.
Use non-GUI mode: jmeter -n -t test.jmx -l test.jtl.
Use as few Listeners as possible; if using the -l flag as above, they can all be deleted or disabled.
Use as few Listeners as possible; if using the -l flag as above, they can all be deleted or disabled.
Disable the “View Result Tree” listener as it consumes a lot of memory and can result in the console freezing or JMeter running out of memory. It is, however, safe to use the “View Result Tree” listener with only “Errors” checked.
Disable the “View Result Tree” listener as it consumes a lot of memory and can result in the console freezing or JMeter running out of memory. It is, however, safe to use the “View Result Tree” listener with only “Errors” checked.
Rather than using lots of similar samplers, use the same sampler in a loop, and use variables (CSV Data Set) to vary the sample. Or perhaps use the Access Log Sampler.
Rather than using lots of similar samplers, use the same sampler in a loop, and use variables (CSV Data Set) to vary the sample. Or perhaps use the Access Log Sampler.
Do not use functional mode.
Do not use functional mode.
Use CSV output rather than XML.
Use CSV output rather than XML.
Only save the data that you need.
Only save the data that you need.
Use as few Assertions as possible.
Use as few Assertions as possible.
Disable all JMeter graphs as they consume a lot of memory. You can view all of the real time graphs using the JTLs tab in your web interface.
Disable all JMeter graphs as they consume a lot of memory. You can view all of the real time graphs using the JTLs tab in your web interface.
Do not forget to erase the local path from CSV Data Set Config if used.
Do not forget to erase the local path from CSV Data Set Config if used.
Clean the Files tab prior to every test run.
Clean the Files tab prior to every test run.
59 Lectures
9.5 hours
Rahul Shetty
54 Lectures
13.5 hours
Wallace Tauriac
23 Lectures
1.5 hours
Anuja Jain
12 Lectures
1 hours
Spotle Learn
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2032,
"s": 1905,
"text": "Before going into the details of JMeter, let us first understand a few jargons associated with the testing of any application."
},
{
"code": null,
"e": 2279,
"s": 2032,
"text": "Performance Test − This test sets the best possible performance expectation under a given configuration of infrastructure. It also highlights early in the testing process if any changes need to be made before the application goes into production."
},
{
"code": null,
"e": 2526,
"s": 2279,
"text": "Performance Test − This test sets the best possible performance expectation under a given configuration of infrastructure. It also highlights early in the testing process if any changes need to be made before the application goes into production."
},
{
"code": null,
"e": 2642,
"s": 2526,
"text": "Load Test − This test is basically used for testing the system under the top load it was designed to operate under."
},
{
"code": null,
"e": 2758,
"s": 2642,
"text": "Load Test − This test is basically used for testing the system under the top load it was designed to operate under."
},
{
"code": null,
"e": 2847,
"s": 2758,
"text": "Stress Test − This test is an attempt to break the system by overwhelming its resources."
},
{
"code": null,
"e": 2936,
"s": 2847,
"text": "Stress Test − This test is an attempt to break the system by overwhelming its resources."
},
{
"code": null,
"e": 3097,
"s": 2936,
"text": "JMeter is a software that can perform load test, performance-oriented business (functional) test, regression test, etc., on different protocols or technologies."
},
{
"code": null,
"e": 3382,
"s": 3097,
"text": "Stefano Mazzocchi of the Apache Software Foundation was the original developer of JMeter. He wrote it primarily to test the performance of Apache JServ (now called as Apache Tomcat project). Apache later redesigned JMeter to enhance the GUI and to add functional testing capabilities."
},
{
"code": null,
"e": 3612,
"s": 3382,
"text": "JMeter is a Java desktop application with a graphical interface that uses the Swing graphical API. It can therefore run on any environment / workstation that accepts a Java virtual machine, for example − Windows, Linux, Mac, etc."
},
{
"code": null,
"e": 3652,
"s": 3612,
"text": "The protocols supported by JMeter are −"
},
{
"code": null,
"e": 3723,
"s": 3652,
"text": "Web − HTTP, HTTPS sites 'web 1.0' web 2.0 (ajax, flex and flex-ws-amf)"
},
{
"code": null,
"e": 3794,
"s": 3723,
"text": "Web − HTTP, HTTPS sites 'web 1.0' web 2.0 (ajax, flex and flex-ws-amf)"
},
{
"code": null,
"e": 3824,
"s": 3794,
"text": "Web Services − SOAP / XML-RPC"
},
{
"code": null,
"e": 3854,
"s": 3824,
"text": "Web Services − SOAP / XML-RPC"
},
{
"code": null,
"e": 3880,
"s": 3854,
"text": "Database via JDBC drivers"
},
{
"code": null,
"e": 3906,
"s": 3880,
"text": "Database via JDBC drivers"
},
{
"code": null,
"e": 3923,
"s": 3906,
"text": "Directory − LDAP"
},
{
"code": null,
"e": 3940,
"s": 3923,
"text": "Directory − LDAP"
},
{
"code": null,
"e": 3975,
"s": 3940,
"text": "Messaging Oriented service via JMS"
},
{
"code": null,
"e": 4010,
"s": 3975,
"text": "Messaging Oriented service via JMS"
},
{
"code": null,
"e": 4037,
"s": 4010,
"text": "Service − POP3, IMAP, SMTP"
},
{
"code": null,
"e": 4064,
"s": 4037,
"text": "Service − POP3, IMAP, SMTP"
},
{
"code": null,
"e": 4076,
"s": 4064,
"text": "FTP Service"
},
{
"code": null,
"e": 4088,
"s": 4076,
"text": "FTP Service"
},
{
"code": null,
"e": 4135,
"s": 4088,
"text": "Following are some of the features of JMeter −"
},
{
"code": null,
"e": 4190,
"s": 4135,
"text": "Being an open source software, it is freely available."
},
{
"code": null,
"e": 4245,
"s": 4190,
"text": "Being an open source software, it is freely available."
},
{
"code": null,
"e": 4280,
"s": 4245,
"text": "It has a simple and intuitive GUI."
},
{
"code": null,
"e": 4315,
"s": 4280,
"text": "It has a simple and intuitive GUI."
},
{
"code": null,
"e": 4467,
"s": 4315,
"text": "JMeter can conduct load and performance test for many different server types − Web - HTTP, HTTPS, SOAP, Database via JDBC, LDAP, JMS, Mail - POP3, etc."
},
{
"code": null,
"e": 4619,
"s": 4467,
"text": "JMeter can conduct load and performance test for many different server types − Web - HTTP, HTTPS, SOAP, Database via JDBC, LDAP, JMS, Mail - POP3, etc."
},
{
"code": null,
"e": 4790,
"s": 4619,
"text": "It is a platform-independent tool. On Linux/Unix, JMeter can be invoked by clicking on JMeter shell script. On Windows, it can be invoked by starting the jmeter.bat file."
},
{
"code": null,
"e": 4961,
"s": 4790,
"text": "It is a platform-independent tool. On Linux/Unix, JMeter can be invoked by clicking on JMeter shell script. On Windows, it can be invoked by starting the jmeter.bat file."
},
{
"code": null,
"e": 5061,
"s": 4961,
"text": "It has full Swing and lightweight component support (precompiled JAR uses packages javax.swing.* )."
},
{
"code": null,
"e": 5161,
"s": 5061,
"text": "It has full Swing and lightweight component support (precompiled JAR uses packages javax.swing.* )."
},
{
"code": null,
"e": 5265,
"s": 5161,
"text": "JMeter store its test plans in XML format. This means you can generate a test plan using a text editor."
},
{
"code": null,
"e": 5369,
"s": 5265,
"text": "JMeter store its test plans in XML format. This means you can generate a test plan using a text editor."
},
{
"code": null,
"e": 5523,
"s": 5369,
"text": "Its full multi-threading framework allows concurrent sampling by many threads and simultaneous sampling of different functions by separate thread groups."
},
{
"code": null,
"e": 5677,
"s": 5523,
"text": "Its full multi-threading framework allows concurrent sampling by many threads and simultaneous sampling of different functions by separate thread groups."
},
{
"code": null,
"e": 5702,
"s": 5677,
"text": "It is highly extensible."
},
{
"code": null,
"e": 5727,
"s": 5702,
"text": "It is highly extensible."
},
{
"code": null,
"e": 5812,
"s": 5727,
"text": "It can also be used to perform automated and functional testing of the applications."
},
{
"code": null,
"e": 5897,
"s": 5812,
"text": "It can also be used to perform automated and functional testing of the applications."
},
{
"code": null,
"e": 6089,
"s": 5897,
"text": "JMeter simulates a group of users sending requests to a target server, and returns statistics that show the performance/functionality of the target server/application via tables, graphs, etc."
},
{
"code": null,
"e": 6157,
"s": 6089,
"text": "Take a look at the following figure that depicts how JMeter works −"
},
{
"code": null,
"e": 6261,
"s": 6157,
"text": "JMeter is a framework for Java, so the very first requirement is to have JDK installed in your machine."
},
{
"code": null,
"e": 6445,
"s": 6261,
"text": "First of all, verify whether you have Java installed in your system. Open your console and execute one of the following java commands based on the operating system you are working on."
},
{
"code": null,
"e": 6560,
"s": 6445,
"text": "If you have Java installed in your system, you would get an appropriate output based on the OS you are working on."
},
{
"code": null,
"e": 6584,
"s": 6560,
"text": "java version \"1.7.0_25\""
},
{
"code": null,
"e": 6637,
"s": 6584,
"text": "Java(TM) SE Runtime Environment (build 1.7.0_25-b15)"
},
{
"code": null,
"e": 6701,
"s": 6637,
"text": "Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)"
},
{
"code": null,
"e": 6725,
"s": 6701,
"text": "java version \"1.7.0_25\""
},
{
"code": null,
"e": 6778,
"s": 6725,
"text": "Java(TM) SE Runtime Environment (build 1.7.0_25-b15)"
},
{
"code": null,
"e": 6842,
"s": 6778,
"text": "Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)"
},
{
"code": null,
"e": 6866,
"s": 6842,
"text": "java version \"1.7.0_25\""
},
{
"code": null,
"e": 6919,
"s": 6866,
"text": "Java(TM) SE Runtime Environment (build 1.7.0_25-b15)"
},
{
"code": null,
"e": 6983,
"s": 6919,
"text": "Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)"
},
{
"code": null,
"e": 7206,
"s": 6983,
"text": "If you do not have Java installed, install the Java Software Development Kit (SDK) from www.oracle.com/technetwork/java/javase/downloads/index.html. We are assuming Java 1.7.0_25 as the installed version for this tutorial."
},
{
"code": null,
"e": 7341,
"s": 7206,
"text": "Set the JAVA_HOME environment variable to point to the base directory location, where Java is installed on your machine. For example −"
},
{
"code": null,
"e": 7387,
"s": 7341,
"text": "Append Java compiler location to System Path."
},
{
"code": null,
"e": 7460,
"s": 7387,
"text": "Verify Java Installation using java -version command as explained above."
},
{
"code": null,
"e": 7639,
"s": 7460,
"text": "Download the latest version of JMeter from https://jmeter.apache.org/download_jmeter.cgi. For this tutorial, we downloaded apache-jmeter-2.9 and copied it into C:\\>JMeter folder."
},
{
"code": null,
"e": 7697,
"s": 7639,
"text": "The directory structure should look like as shown below −"
},
{
"code": null,
"e": 7715,
"s": 7697,
"text": "apache-jmeter-2.9"
},
{
"code": null,
"e": 7737,
"s": 7715,
"text": "apache-jmeter-2.9\\bin"
},
{
"code": null,
"e": 7760,
"s": 7737,
"text": "apache-jmeter-2.9\\docs"
},
{
"code": null,
"e": 7785,
"s": 7760,
"text": "apache-jmeter-2.9\\extras"
},
{
"code": null,
"e": 7808,
"s": 7785,
"text": "apache-jmeter-2.9\\lib\\"
},
{
"code": null,
"e": 7834,
"s": 7808,
"text": "apache-jmeter-2.9\\lib\\ext"
},
{
"code": null,
"e": 7862,
"s": 7834,
"text": "apache-jmeter-2.9\\lib\\junit"
},
{
"code": null,
"e": 7895,
"s": 7862,
"text": "apache-jmeter-2.9\\printable_docs"
},
{
"code": null,
"e": 8019,
"s": 7895,
"text": "You can rename the parent directory (i.e. apache-jmeter-2.9) if you want, but do not change any of the sub-directory names."
},
{
"code": null,
"e": 8156,
"s": 8019,
"text": "After downloading JMeter, go to the bin directory. In this case, it is /home/manisha/apache-jmeter-2.9/bin. Now click on the following −"
},
{
"code": null,
"e": 8275,
"s": 8156,
"text": "After a short pause, the JMeter GUI should appear, which is a Swing application, as seen in the following screenshot −"
},
{
"code": null,
"e": 8331,
"s": 8275,
"text": "This is the main page and the default page of the tool."
},
{
"code": null,
"e": 8674,
"s": 8331,
"text": "A Test Plan can be viewed as a container for running tests. It defines what to test and how to go about it. A complete test plan consists of one or more elements such as thread groups, logic controllers, sample-generating controllers, listeners, timers, assertions, and configuration elements. A test plan must have at least one thread group."
},
{
"code": null,
"e": 8726,
"s": 8674,
"text": "Follow the steps given below to write a test plan −"
},
{
"code": null,
"e": 8849,
"s": 8726,
"text": "Open the JMeter window by clicking /home/manisha/apache-jmeter-2.9/bin/jmeter.sh. The JMeter window will appear as below −"
},
{
"code": null,
"e": 8958,
"s": 8849,
"text": "This is a plain and blank JMeter window without any additional elements added to it. It contains two nodes −"
},
{
"code": null,
"e": 9012,
"s": 8958,
"text": "Test Plan node − is where the real test plan is kept."
},
{
"code": null,
"e": 9066,
"s": 9012,
"text": "Test Plan node − is where the real test plan is kept."
},
{
"code": null,
"e": 9257,
"s": 9066,
"text": "Workbench node − It simply provides a place to temporarily store test elements while not in use, for copy/paste purposes. When you save your test plan, Workbench items are not saved with it."
},
{
"code": null,
"e": 9448,
"s": 9257,
"text": "Workbench node − It simply provides a place to temporarily store test elements while not in use, for copy/paste purposes. When you save your test plan, Workbench items are not saved with it."
},
{
"code": null,
"e": 9638,
"s": 9448,
"text": "Elements (which will be discussed in the next chapter Test Plan Elements) can be added to a test plan by right-clicking on the Test Plan node and choosing a new element from the \"add\" list."
},
{
"code": null,
"e": 9742,
"s": 9638,
"text": "Alternatively, you can load an element from a file and add it by choosing the \"merge\" or \"open\" option."
},
{
"code": null,
"e": 9821,
"s": 9742,
"text": "For example, let us add a Thread Group element to a Test Plan as shown below −"
},
{
"code": null,
"e": 9938,
"s": 9821,
"text": "To remove an element, make sure the element is selected, right-click on the element, and choose the \"remove\" option."
},
{
"code": null,
"e": 9969,
"s": 9938,
"text": "To load an element from file −"
},
{
"code": null,
"e": 10055,
"s": 9969,
"text": "Right-click on the existing tree element to which you want to add the loaded element."
},
{
"code": null,
"e": 10069,
"s": 10055,
"text": "Select Merge."
},
{
"code": null,
"e": 10115,
"s": 10069,
"text": "Choose the file where you saved the elements."
},
{
"code": null,
"e": 10161,
"s": 10115,
"text": "JMeter will merge the elements into the tree."
},
{
"code": null,
"e": 10239,
"s": 10161,
"text": "By default, JMeter does not save the element, you need to explicitly save it."
},
{
"code": null,
"e": 10263,
"s": 10239,
"text": "To save tree elements −"
},
{
"code": null,
"e": 10291,
"s": 10263,
"text": "Right-click on the element."
},
{
"code": null,
"e": 10332,
"s": 10291,
"text": "Choose the Save Selection As ... option."
},
{
"code": null,
"e": 10510,
"s": 10332,
"text": "JMeter will save the element selected, plus all the child elements beneath it. By default, JMeter doesn't save the elements, you need to explicitly save it as mentioned earlier."
},
{
"code": null,
"e": 10814,
"s": 10510,
"text": "Any element in the Test Plan can be configured using the controls present in JMeter's right-hand side frame. These controls allow you to configure the behavior of that particular test element. For example, the Thread Group can be configured for a number of users, ramp up periods, etc., as shown below −"
},
{
"code": null,
"e": 10915,
"s": 10814,
"text": "You can save an entire Test Plan by using either Save or \"Save Test Plan As ...\" from the File menu."
},
{
"code": null,
"e": 11112,
"s": 10915,
"text": "You can run the Test Plan by clicking Start(Control + r) from the Run menu item. When JMeter starts running, it shows a small green box at the right-hand end of the section just under the menubar."
},
{
"code": null,
"e": 11342,
"s": 11112,
"text": "The numbers to the left of the green box are the number of active threads / total number of threads. These only apply to a locally run test; they do not include any threads started on remote systems when using client-server mode."
},
{
"code": null,
"e": 11379,
"s": 11342,
"text": "You can stop your test in two ways −"
},
{
"code": null,
"e": 11454,
"s": 11379,
"text": "Using Stop (Control + '.'). It stops the threads immediately if possible. "
},
{
"code": null,
"e": 11529,
"s": 11454,
"text": "Using Stop (Control + '.'). It stops the threads immediately if possible. "
},
{
"code": null,
"e": 11625,
"s": 11529,
"text": "Using Shutdown (Control + ','). It requests the threads to stop at the end of any current work."
},
{
"code": null,
"e": 11721,
"s": 11625,
"text": "Using Shutdown (Control + ','). It requests the threads to stop at the end of any current work."
},
{
"code": null,
"e": 12170,
"s": 11721,
"text": "A JMeter Test Plan comprises of test elements discussed below. A Test Plan comprises of at least one Thread Group. Within each Thread Group, we may place a combination of one or more of other elements − Sampler, Logic Controller, Configuration Element, Listener, and Timer. Each Sampler can be preceded by one or more Pre-processor element, followed by Post-processor element, and/or Assertion element. Let us see each of these elements in detail −"
},
{
"code": null,
"e": 12404,
"s": 12170,
"text": "Thread Group elements are the beginning points of your test plan. As the name suggests, the thread group elements control the number of threads JMeter will use during the test. We can also control the following via the Thread Group −"
},
{
"code": null,
"e": 12434,
"s": 12404,
"text": "Setting the number of threads"
},
{
"code": null,
"e": 12464,
"s": 12434,
"text": "Setting the number of threads"
},
{
"code": null,
"e": 12489,
"s": 12464,
"text": "Setting the ramp-up time"
},
{
"code": null,
"e": 12514,
"s": 12489,
"text": "Setting the ramp-up time"
},
{
"code": null,
"e": 12552,
"s": 12514,
"text": "Setting the number of test iterations"
},
{
"code": null,
"e": 12590,
"s": 12552,
"text": "Setting the number of test iterations"
},
{
"code": null,
"e": 12639,
"s": 12590,
"text": "The Thread Group Control Panel looks like this −"
},
{
"code": null,
"e": 12695,
"s": 12639,
"text": "The Thread Group Panel holds the following components −"
},
{
"code": null,
"e": 12989,
"s": 12695,
"text": "Action to be taken after a Sampler error − In case any error occurs during test execution, you may let the test either −\n\nContinue to the next element in the test\nStop Thread to stop the current Thread.\nStop Test completely, in case you want to inspect the error before it continues running.\n\n"
},
{
"code": null,
"e": 13110,
"s": 12989,
"text": "Action to be taken after a Sampler error − In case any error occurs during test execution, you may let the test either −"
},
{
"code": null,
"e": 13151,
"s": 13110,
"text": "Continue to the next element in the test"
},
{
"code": null,
"e": 13192,
"s": 13151,
"text": "Continue to the next element in the test"
},
{
"code": null,
"e": 13232,
"s": 13192,
"text": "Stop Thread to stop the current Thread."
},
{
"code": null,
"e": 13272,
"s": 13232,
"text": "Stop Thread to stop the current Thread."
},
{
"code": null,
"e": 13361,
"s": 13272,
"text": "Stop Test completely, in case you want to inspect the error before it continues running."
},
{
"code": null,
"e": 13450,
"s": 13361,
"text": "Stop Test completely, in case you want to inspect the error before it continues running."
},
{
"code": null,
"e": 13543,
"s": 13450,
"text": "Number of Threads − Simulates the number of users or connections to your server application."
},
{
"code": null,
"e": 13636,
"s": 13543,
"text": "Number of Threads − Simulates the number of users or connections to your server application."
},
{
"code": null,
"e": 13716,
"s": 13636,
"text": "Ramp-Up Period Defines how long it will take JMeter to get all threads running."
},
{
"code": null,
"e": 13796,
"s": 13716,
"text": "Ramp-Up Period Defines how long it will take JMeter to get all threads running."
},
{
"code": null,
"e": 13858,
"s": 13796,
"text": "Loop Count − Defines the number of times to execute the test."
},
{
"code": null,
"e": 13920,
"s": 13858,
"text": "Loop Count − Defines the number of times to execute the test."
},
{
"code": null,
"e": 14036,
"s": 13920,
"text": "Scheduler checkbox − Once selected, the Scheduler Configuration section appears at the bottom of the control panel."
},
{
"code": null,
"e": 14152,
"s": 14036,
"text": "Scheduler checkbox − Once selected, the Scheduler Configuration section appears at the bottom of the control panel."
},
{
"code": null,
"e": 14240,
"s": 14152,
"text": "Scheduler Configuration − You can configure the start and end time of running the test."
},
{
"code": null,
"e": 14328,
"s": 14240,
"text": "Scheduler Configuration − You can configure the start and end time of running the test."
},
{
"code": null,
"e": 14398,
"s": 14328,
"text": "JMeter has two types of Controllers − Samplers and Logic Controllers."
},
{
"code": null,
"e": 14645,
"s": 14398,
"text": "Samplers allow JMeter to send specific types of requests to a server. They simulate a user request for a page from the target server. For example, you can add a HTTP Request sampler if you need to perform a POST, GET, or DELETE on a HTTP service."
},
{
"code": null,
"e": 14672,
"s": 14645,
"text": "Some useful samplers are −"
},
{
"code": null,
"e": 14685,
"s": 14672,
"text": "HTTP Request"
},
{
"code": null,
"e": 14697,
"s": 14685,
"text": "FTP Request"
},
{
"code": null,
"e": 14710,
"s": 14697,
"text": "JDBC Request"
},
{
"code": null,
"e": 14723,
"s": 14710,
"text": "Java Request"
},
{
"code": null,
"e": 14740,
"s": 14723,
"text": "SOAP/XML Request"
},
{
"code": null,
"e": 14753,
"s": 14740,
"text": "RPC Requests"
},
{
"code": null,
"e": 14824,
"s": 14753,
"text": "The following screenshot shows an HTTP Request Sampler Control Panel −"
},
{
"code": null,
"e": 15182,
"s": 14824,
"text": "Logic Controllers let you control the order of processing of Samplers in a Thread. Logic controllers can change the order of a request coming from any of their child elements. Some examples are − ForEach Controller, While Controller, Loop Controller, IF Controller, Run Time Controller, Interleave Controller, Throughput Controller, and Run Once Controller."
},
{
"code": null,
"e": 15247,
"s": 15182,
"text": "The following screenshot shows a Loop Controller Control Panel −"
},
{
"code": null,
"e": 15322,
"s": 15247,
"text": "The following list consists of all the Logic Controllers JMeter provides −"
},
{
"code": null,
"e": 15340,
"s": 15322,
"text": "Simple Controller"
},
{
"code": null,
"e": 15356,
"s": 15340,
"text": "Loop Controller"
},
{
"code": null,
"e": 15377,
"s": 15356,
"text": "Once Only Controller"
},
{
"code": null,
"e": 15399,
"s": 15377,
"text": "Interleave Controller"
},
{
"code": null,
"e": 15417,
"s": 15399,
"text": "Random Controller"
},
{
"code": null,
"e": 15441,
"s": 15417,
"text": "Random Order Controller"
},
{
"code": null,
"e": 15463,
"s": 15441,
"text": "Throughput Controller"
},
{
"code": null,
"e": 15482,
"s": 15463,
"text": "Runtime Controller"
},
{
"code": null,
"e": 15496,
"s": 15482,
"text": "If Controller"
},
{
"code": null,
"e": 15513,
"s": 15496,
"text": "While Controller"
},
{
"code": null,
"e": 15531,
"s": 15513,
"text": "Switch Controller"
},
{
"code": null,
"e": 15550,
"s": 15531,
"text": "ForEach Controller"
},
{
"code": null,
"e": 15568,
"s": 15550,
"text": "Module Controller"
},
{
"code": null,
"e": 15587,
"s": 15568,
"text": "Include Controller"
},
{
"code": null,
"e": 15610,
"s": 15587,
"text": "Transaction Controller"
},
{
"code": null,
"e": 15631,
"s": 15610,
"text": "Recording Controller"
},
{
"code": null,
"e": 15935,
"s": 15631,
"text": "A Test Fragment is a special type of element placed at the same level as the Thread Group element. It is distinguished from a Thread Group in that it is not executed unless it is referenced by either a Module Controller or an Include_Controller. This element is purely for code re-use within Test Plans."
},
{
"code": null,
"e": 16179,
"s": 15935,
"text": "Listeners let you view the results of Samplers in the form of tables, graphs, trees, or simple text in some log files. They provide visual access to the data gathered by JMeter about the test cases as a Sampler component of JMeter is executed."
},
{
"code": null,
"e": 16398,
"s": 16179,
"text": "Listeners can be added anywhere in the test, including directly under the test plan. They will collect data only from elements at or below their level. The following list consists of all the Listeners JMeter provides −"
},
{
"code": null,
"e": 16431,
"s": 16398,
"text": "Sample Result Save Configuration"
},
{
"code": null,
"e": 16450,
"s": 16431,
"text": "Graph Full Results"
},
{
"code": null,
"e": 16464,
"s": 16450,
"text": "Graph Results"
},
{
"code": null,
"e": 16482,
"s": 16464,
"text": "Spline Visualizer"
},
{
"code": null,
"e": 16500,
"s": 16482,
"text": "Assertion Results"
},
{
"code": null,
"e": 16518,
"s": 16500,
"text": "View Results Tree"
},
{
"code": null,
"e": 16535,
"s": 16518,
"text": "Aggregate Report"
},
{
"code": null,
"e": 16557,
"s": 16535,
"text": "View Results in Table"
},
{
"code": null,
"e": 16576,
"s": 16557,
"text": "Simple Data Writer"
},
{
"code": null,
"e": 16592,
"s": 16576,
"text": "Monitor Results"
},
{
"code": null,
"e": 16619,
"s": 16592,
"text": "Distribution Graph (alpha)"
},
{
"code": null,
"e": 16635,
"s": 16619,
"text": "Aggregate Graph"
},
{
"code": null,
"e": 16653,
"s": 16635,
"text": "Mailer Visualizer"
},
{
"code": null,
"e": 16672,
"s": 16653,
"text": "BeanShell Listener"
},
{
"code": null,
"e": 16687,
"s": 16672,
"text": "Summary Report"
},
{
"code": null,
"e": 16893,
"s": 16687,
"text": "By default, a JMeter thread sends requests without pausing between each sampler. This may not be what you want. You can add a timer element which allows you to define a period to wait between each request."
},
{
"code": null,
"e": 16956,
"s": 16893,
"text": "The following list shows all the timers that JMeter provides −"
},
{
"code": null,
"e": 16971,
"s": 16956,
"text": "Constant Timer"
},
{
"code": null,
"e": 16993,
"s": 16971,
"text": "Gaussian Random Timer"
},
{
"code": null,
"e": 17014,
"s": 16993,
"text": "Uniform Random Timer"
},
{
"code": null,
"e": 17040,
"s": 17014,
"text": "Constant Throughput Timer"
},
{
"code": null,
"e": 17060,
"s": 17040,
"text": "Synchronizing Timer"
},
{
"code": null,
"e": 17072,
"s": 17060,
"text": "JSR223 Time"
},
{
"code": null,
"e": 17087,
"s": 17072,
"text": "BeanShell Time"
},
{
"code": null,
"e": 17096,
"s": 17087,
"text": "BSF Time"
},
{
"code": null,
"e": 17116,
"s": 17096,
"text": "Poisson Random Time"
},
{
"code": null,
"e": 17180,
"s": 17116,
"text": "The following screenshot shows a Constant Timer Control Panel −"
},
{
"code": null,
"e": 17414,
"s": 17180,
"text": "Assertions allow you to include some validation test on the response of your request made using a Sampler. Using assertions you can prove that your application is returning the correct data. JMeter highlights when an assertion fails."
},
{
"code": null,
"e": 17482,
"s": 17414,
"text": "The following list consists of all the assertions JMeter provides −"
},
{
"code": null,
"e": 17502,
"s": 17482,
"text": "Beanshell Assertion"
},
{
"code": null,
"e": 17516,
"s": 17502,
"text": "BSF Assertion"
},
{
"code": null,
"e": 17534,
"s": 17516,
"text": "Compare Assertion"
},
{
"code": null,
"e": 17551,
"s": 17534,
"text": "JSR223 Assertion"
},
{
"code": null,
"e": 17570,
"s": 17551,
"text": "Response Assertion"
},
{
"code": null,
"e": 17589,
"s": 17570,
"text": "Duration Assertion"
},
{
"code": null,
"e": 17604,
"s": 17589,
"text": "Size Assertion"
},
{
"code": null,
"e": 17618,
"s": 17604,
"text": "XML Assertion"
},
{
"code": null,
"e": 17638,
"s": 17618,
"text": "BeanShell Assertion"
},
{
"code": null,
"e": 17655,
"s": 17638,
"text": "MD5Hex Assertion"
},
{
"code": null,
"e": 17670,
"s": 17655,
"text": "HTML Assertion"
},
{
"code": null,
"e": 17686,
"s": 17670,
"text": "XPath Assertion"
},
{
"code": null,
"e": 17707,
"s": 17686,
"text": "XML Schema Assertion"
},
{
"code": null,
"e": 17775,
"s": 17707,
"text": "The following screenshot shows a Response Assertion Control Panel −"
},
{
"code": null,
"e": 17923,
"s": 17775,
"text": "Configuration Elements allow you to create defaults and variables to be used by Samplers. They are used to add or modify requests made by Samplers."
},
{
"code": null,
"e": 18142,
"s": 17923,
"text": "They are executed at the start of the scope of which they are part, before any Samplers that are located in the same scope. Therefore, a Configuration Element is accessed only from inside the branch where it is placed."
},
{
"code": null,
"e": 18227,
"s": 18142,
"text": "The following list consists of all the Configuration Elements that JMeter provides −"
},
{
"code": null,
"e": 18235,
"s": 18227,
"text": "Counter"
},
{
"code": null,
"e": 18255,
"s": 18235,
"text": "CSV Data Set Config"
},
{
"code": null,
"e": 18276,
"s": 18255,
"text": "FTP Request Defaults"
},
{
"code": null,
"e": 18303,
"s": 18276,
"text": "HTTP Authorization Manager"
},
{
"code": null,
"e": 18322,
"s": 18303,
"text": "HTTP Cache Manager"
},
{
"code": null,
"e": 18342,
"s": 18322,
"text": "HTTP Cookie Manager"
},
{
"code": null,
"e": 18360,
"s": 18342,
"text": "HTTP Proxy Server"
},
{
"code": null,
"e": 18382,
"s": 18360,
"text": "HTTP Request Defaults"
},
{
"code": null,
"e": 18402,
"s": 18382,
"text": "HTTP Header Manager"
},
{
"code": null,
"e": 18424,
"s": 18402,
"text": "Java Request Defaults"
},
{
"code": null,
"e": 18447,
"s": 18424,
"text": "Keystore Configuration"
},
{
"code": null,
"e": 18477,
"s": 18447,
"text": "JDBC Connection Configuration"
},
{
"code": null,
"e": 18498,
"s": 18477,
"text": "Login Config Element"
},
{
"code": null,
"e": 18520,
"s": 18498,
"text": "LDAP Request Defaults"
},
{
"code": null,
"e": 18551,
"s": 18520,
"text": "LDAP Extended Request Defaults"
},
{
"code": null,
"e": 18570,
"s": 18551,
"text": "TCP Sampler Config"
},
{
"code": null,
"e": 18593,
"s": 18570,
"text": "User Defined Variables"
},
{
"code": null,
"e": 18615,
"s": 18593,
"text": "Simple Config Element"
},
{
"code": null,
"e": 18631,
"s": 18615,
"text": "Random Variable"
},
{
"code": null,
"e": 18860,
"s": 18631,
"text": "A pre-processor element is something that runs just before a sampler executes. They are often used to modify the settings of a Sample Request just before it runs, or to update variables that are not extracted from response text."
},
{
"code": null,
"e": 18945,
"s": 18860,
"text": "The following list consists of all the pre-processor elements that JMeter provides −"
},
{
"code": null,
"e": 18962,
"s": 18945,
"text": "HTML Link Parser"
},
{
"code": null,
"e": 18991,
"s": 18962,
"text": "HTTP URL Re-writing Modifier"
},
{
"code": null,
"e": 19020,
"s": 18991,
"text": "HTTP User Parameter Modifier"
},
{
"code": null,
"e": 19036,
"s": 19020,
"text": "User Parameters"
},
{
"code": null,
"e": 19054,
"s": 19036,
"text": "JDBC PreProcessor"
},
{
"code": null,
"e": 19074,
"s": 19054,
"text": "JSR223 PreProcessor"
},
{
"code": null,
"e": 19096,
"s": 19074,
"text": "RegEx User Parameters"
},
{
"code": null,
"e": 19119,
"s": 19096,
"text": "BeanShell PreProcessor"
},
{
"code": null,
"e": 19136,
"s": 19119,
"text": "BSF PreProcessor"
},
{
"code": null,
"e": 19323,
"s": 19136,
"text": "A post-processor executes after a sampler finishes its execution. This element is most often used to process the response data, for example, to retrieve a particular value for later use."
},
{
"code": null,
"e": 19404,
"s": 19323,
"text": "The following list consists of all the Post-Processor Elements JMeter provides −"
},
{
"code": null,
"e": 19433,
"s": 19404,
"text": "Regular Expression Extractor"
},
{
"code": null,
"e": 19449,
"s": 19433,
"text": "XPath Extractor"
},
{
"code": null,
"e": 19478,
"s": 19449,
"text": "Result Status Action Handler"
},
{
"code": null,
"e": 19499,
"s": 19478,
"text": "JSR223 PostProcessor"
},
{
"code": null,
"e": 19518,
"s": 19499,
"text": "JDBC PostProcessor"
},
{
"code": null,
"e": 19536,
"s": 19518,
"text": "BSF PostProcessor"
},
{
"code": null,
"e": 19557,
"s": 19536,
"text": "CSS/JQuery Extractor"
},
{
"code": null,
"e": 19581,
"s": 19557,
"text": "BeanShell PostProcessor"
},
{
"code": null,
"e": 19601,
"s": 19581,
"text": "Debug PostProcessor"
},
{
"code": null,
"e": 19662,
"s": 19601,
"text": "Following is the execution order of the test plan elements −"
},
{
"code": null,
"e": 19685,
"s": 19662,
"text": "Configuration elements"
},
{
"code": null,
"e": 19700,
"s": 19685,
"text": "Pre-Processors"
},
{
"code": null,
"e": 19707,
"s": 19700,
"text": "Timers"
},
{
"code": null,
"e": 19715,
"s": 19707,
"text": "Sampler"
},
{
"code": null,
"e": 19761,
"s": 19715,
"text": "Post-Processors (unless SampleResult is null)"
},
{
"code": null,
"e": 19802,
"s": 19761,
"text": "Assertions (unless SampleResult is null)"
},
{
"code": null,
"e": 19842,
"s": 19802,
"text": "Listeners (unless SampleResult is null)"
},
{
"code": null,
"e": 20031,
"s": 19842,
"text": "Let us build a simple test plan which tests a web page. We write a test plan in Apache JMeter so that we can test the performance of the web page shown by the URL − www.tutorialspoint.com."
},
{
"code": null,
"e": 20152,
"s": 20031,
"text": "Open the JMeter window by clicking on /home/manisha/apache-jmeter-2.9/bin/jmeter.sh. The JMeter window appear as below −"
},
{
"code": null,
"e": 20336,
"s": 20152,
"text": "Change the name of test plan node to Sample Test in the Name text box. You need to change the focus to workbench node and back to the Test Plan node to see the name getting reflected."
},
{
"code": null,
"e": 20555,
"s": 20336,
"text": "Now we add our first element in the window. We add one Thread Group, which is a placeholder for all other elements like Samplers, Controllers, and Listeners. We need one so we can configure number of users to simulate."
},
{
"code": null,
"e": 20625,
"s": 20555,
"text": "In JMeter, all the node elements are added by using the context menu."
},
{
"code": null,
"e": 20693,
"s": 20625,
"text": "Right-click the element where you want to add a child element node."
},
{
"code": null,
"e": 20761,
"s": 20693,
"text": "Right-click the element where you want to add a child element node."
},
{
"code": null,
"e": 20799,
"s": 20761,
"text": "Choose the appropriate option to add."
},
{
"code": null,
"e": 20837,
"s": 20799,
"text": "Choose the appropriate option to add."
},
{
"code": null,
"e": 20998,
"s": 20837,
"text": "Right-click on the Sample Test (our Test Plan) → Add → Threads (Users) → Thread Group. Thus, the Thread Group gets added under the Test Plan (Sample Test) node."
},
{
"code": null,
"e": 21159,
"s": 20998,
"text": "Right-click on the Sample Test (our Test Plan) → Add → Threads (Users) → Thread Group. Thus, the Thread Group gets added under the Test Plan (Sample Test) node."
},
{
"code": null,
"e": 21263,
"s": 21159,
"text": "Name the Thread Group as Users. For us, this element means users visiting the TutorialsPoint Home Page."
},
{
"code": null,
"e": 21367,
"s": 21263,
"text": "Name the Thread Group as Users. For us, this element means users visiting the TutorialsPoint Home Page."
},
{
"code": null,
"e": 21641,
"s": 21367,
"text": "We need to add one Sampler in our Thread Group (Users). As done earlier for adding Thread group, this time we will open the context menu of the Thread Group (Users) node by right-clicking and we will add HTTP Request Sampler by choosing Add → Sampler → HTTP request option."
},
{
"code": null,
"e": 21758,
"s": 21641,
"text": "It will add one empty HTTP Request Sampler under the Thread Group (Users) node. Let us configure this node element −"
},
{
"code": null,
"e": 21886,
"s": 21758,
"text": "Name − We will change the name to reflect the action what we want to achieve. We will name it as Visit TutorialsPoint Home Page"
},
{
"code": null,
"e": 22014,
"s": 21886,
"text": "Name − We will change the name to reflect the action what we want to achieve. We will name it as Visit TutorialsPoint Home Page"
},
{
"code": null,
"e": 22195,
"s": 22014,
"text": "Server Name or IP − Here, we have to type the web server name. In our case it is www.tutorialspoint.com. (http:// part is not written this is only the name of the server or its IP)"
},
{
"code": null,
"e": 22376,
"s": 22195,
"text": "Server Name or IP − Here, we have to type the web server name. In our case it is www.tutorialspoint.com. (http:// part is not written this is only the name of the server or its IP)"
},
{
"code": null,
"e": 22454,
"s": 22376,
"text": "Protocol − We will keep this blank, which means we want HTTP as the protocol."
},
{
"code": null,
"e": 22532,
"s": 22454,
"text": "Protocol − We will keep this blank, which means we want HTTP as the protocol."
},
{
"code": null,
"e": 22617,
"s": 22532,
"text": "Path − We will type path as / (slash). It means we want the root page of the server."
},
{
"code": null,
"e": 22702,
"s": 22617,
"text": "Path − We will type path as / (slash). It means we want the root page of the server."
},
{
"code": null,
"e": 22908,
"s": 22702,
"text": "We will now add a listener. Let us add View Results Tree Listener under the Thread Group (User) node. It will ensure that the results of the Sampler will be available to view in this Listener node element."
},
{
"code": null,
"e": 22928,
"s": 22908,
"text": "To add a listener −"
},
{
"code": null,
"e": 22950,
"s": 22928,
"text": "Open the context menu"
},
{
"code": null,
"e": 22972,
"s": 22950,
"text": "Open the context menu"
},
{
"code": null,
"e": 23009,
"s": 22972,
"text": "Right-click the Thread Group (Users)"
},
{
"code": null,
"e": 23046,
"s": 23009,
"text": "Right-click the Thread Group (Users)"
},
{
"code": null,
"e": 23095,
"s": 23046,
"text": "Choose Add → Listener → View Results Tree option"
},
{
"code": null,
"e": 23144,
"s": 23095,
"text": "Choose Add → Listener → View Results Tree option"
},
{
"code": null,
"e": 23377,
"s": 23144,
"text": "Now with all the setup, let us execute the test plan. With the configuration of the Thread Group (Users), we keep all the default values. It means JMeter will execute the sampler only once. It is similar to a single user, only once."
},
{
"code": null,
"e": 23537,
"s": 23377,
"text": "This is similar to a user visiting a web page through browser, with JMeter sampler. To execute the test plan, Select Run from the menu and select Start option."
},
{
"code": null,
"e": 23745,
"s": 23537,
"text": "Apache JMeter asks us to save the test plan in a disk file before actually starting the test. This is important if you want to run the test plan multiple times. You can opt for running it without saving too."
},
{
"code": null,
"e": 23953,
"s": 23745,
"text": "We have kept the setting of the thread group as single thread (one user only) and loop for 1 time (run only one time), hence we will get the result of one single transaction in the View Result Tree Listener."
},
{
"code": null,
"e": 23987,
"s": 23953,
"text": "Details of the above result are −"
},
{
"code": null,
"e": 24066,
"s": 23987,
"text": "Green color against the name Visit TutorialsPoint Home Page indicates success."
},
{
"code": null,
"e": 24145,
"s": 24066,
"text": "Green color against the name Visit TutorialsPoint Home Page indicates success."
},
{
"code": null,
"e": 24266,
"s": 24145,
"text": "JMeter has stored all the headers and the responses sent by the web server and ready to show us the result in many ways."
},
{
"code": null,
"e": 24387,
"s": 24266,
"text": "JMeter has stored all the headers and the responses sent by the web server and ready to show us the result in many ways."
},
{
"code": null,
"e": 24486,
"s": 24387,
"text": "The first tab is Sampler Results. It shows JMeter data as well as data returned by the web server."
},
{
"code": null,
"e": 24585,
"s": 24486,
"text": "The first tab is Sampler Results. It shows JMeter data as well as data returned by the web server."
},
{
"code": null,
"e": 24684,
"s": 24585,
"text": "The second tab is Request, which shows all the data sent to the web server as part of the request."
},
{
"code": null,
"e": 24783,
"s": 24684,
"text": "The second tab is Request, which shows all the data sent to the web server as part of the request."
},
{
"code": null,
"e": 24892,
"s": 24783,
"text": "The last tab is Response data. In this tab, the listener shows the data received from server in text format."
},
{
"code": null,
"e": 25147,
"s": 24892,
"text": "This is just a simple test plan which executes only one request. But JMeter's real strength is in sending the same request, as if many users are sending it. To test the web servers with multiple users, we need to change the Thread Group (Users) settings."
},
{
"code": null,
"e": 25411,
"s": 25147,
"text": "In this chapter, we will see how to create a simple test plan to test the database server. For our test purpose we use the MYSQL database server. You can use any other database for testing. For installation and table creation in MYSQL please refer MYSQL Tutorial."
},
{
"code": null,
"e": 25483,
"s": 25411,
"text": "Once MYSQL is installed, follow the steps below to setup the database −"
},
{
"code": null,
"e": 25523,
"s": 25483,
"text": "Create a database with name \"tutorial\"."
},
{
"code": null,
"e": 25563,
"s": 25523,
"text": "Create a database with name \"tutorial\"."
},
{
"code": null,
"e": 25593,
"s": 25563,
"text": "Create a table tutorials_tbl."
},
{
"code": null,
"e": 25623,
"s": 25593,
"text": "Create a table tutorials_tbl."
},
{
"code": null,
"e": 25674,
"s": 25623,
"text": "Insert records into tutorials_tbl as shown below −"
},
{
"code": null,
"e": 25725,
"s": 25674,
"text": "Insert records into tutorials_tbl as shown below −"
},
{
"code": null,
"e": 26318,
"s": 25725,
"text": "mysql> use TUTORIALS;\nDatabase changed\nmysql> INSERT INTO tutorials_tbl \n ->(tutorial_title, tutorial_author, submission_date)\n ->VALUES\n ->(\"Learn PHP\", \"John Poul\", NOW());\n \nQuery OK, 1 row affected (0.01 sec)\nmysql> INSERT INTO tutorials_tbl\n ->(tutorial_title, tutorial_author, submission_date)\n ->VALUES\n ->(\"Learn MySQL\", \"Abdul S\", NOW());\n \nQuery OK, 1 row affected (0.01 sec)\nmysql> INSERT INTO tutorials_tbl\n ->(tutorial_title, tutorial_author, submission_date)\n ->VALUES\n ->(\"JAVA Tutorial\", \"Sanjay\", '2007-05-06');\n\nQuery OK, 1 row affected (0.01 sec)\nmysql>\n"
},
{
"code": null,
"e": 26391,
"s": 26318,
"text": "Copy the appropriate JDBC driver to /home/manisha/apache-jmeter-2.9/lib."
},
{
"code": null,
"e": 26464,
"s": 26391,
"text": "Copy the appropriate JDBC driver to /home/manisha/apache-jmeter-2.9/lib."
},
{
"code": null,
"e": 26540,
"s": 26464,
"text": "Let us start the JMeter from /home/manisha/apache-jmeter-2.9/bin/jmeter.sh."
},
{
"code": null,
"e": 26566,
"s": 26540,
"text": "To create a Thread group,"
},
{
"code": null,
"e": 26592,
"s": 26566,
"text": "Right-click on Test Plan."
},
{
"code": null,
"e": 26618,
"s": 26592,
"text": "Right-click on Test Plan."
},
{
"code": null,
"e": 26663,
"s": 26618,
"text": "Select Add → Threads (Users) → Thread Group."
},
{
"code": null,
"e": 26708,
"s": 26663,
"text": "Select Add → Threads (Users) → Thread Group."
},
{
"code": null,
"e": 26764,
"s": 26708,
"text": "Thus, thread group gets added under the Test Plan node."
},
{
"code": null,
"e": 26820,
"s": 26764,
"text": "Thus, thread group gets added under the Test Plan node."
},
{
"code": null,
"e": 26860,
"s": 26820,
"text": "Rename this Thread Group as JDBC Users."
},
{
"code": null,
"e": 26900,
"s": 26860,
"text": "Rename this Thread Group as JDBC Users."
},
{
"code": null,
"e": 26963,
"s": 26900,
"text": "We will not change the default properties of the Thread Group."
},
{
"code": null,
"e": 27110,
"s": 26963,
"text": "Now that we defined our users, it is time to define the tasks that they will be performing. In this section, specify the JDBC requests to perform."
},
{
"code": null,
"e": 27149,
"s": 27110,
"text": "Right-click on the JDBC Users element."
},
{
"code": null,
"e": 27188,
"s": 27149,
"text": "Right-click on the JDBC Users element."
},
{
"code": null,
"e": 27249,
"s": 27188,
"text": "Select Add → Config Element → JDBC Connection Configuration."
},
{
"code": null,
"e": 27310,
"s": 27249,
"text": "Select Add → Config Element → JDBC Connection Configuration."
},
{
"code": null,
"e": 27708,
"s": 27310,
"text": "Set up the following fields (we are using MySQL database called tutorial) −\n\nVariable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test.\nDatabase URL − jdbc:mysql://localhost:3306/tutorial.\nJDBC Driver class: com.mysql.jdbc.Driver.\nUsername: root.\nPassword: password for root.\n\n"
},
{
"code": null,
"e": 27784,
"s": 27708,
"text": "Set up the following fields (we are using MySQL database called tutorial) −"
},
{
"code": null,
"e": 27963,
"s": 27784,
"text": "Variable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test."
},
{
"code": null,
"e": 28142,
"s": 27963,
"text": "Variable name bound to pool. This needs to identify the configuration uniquely. It is used by the JDBC Sampler to identify the configuration to be used. We have named it as test."
},
{
"code": null,
"e": 28195,
"s": 28142,
"text": "Database URL − jdbc:mysql://localhost:3306/tutorial."
},
{
"code": null,
"e": 28248,
"s": 28195,
"text": "Database URL − jdbc:mysql://localhost:3306/tutorial."
},
{
"code": null,
"e": 28290,
"s": 28248,
"text": "JDBC Driver class: com.mysql.jdbc.Driver."
},
{
"code": null,
"e": 28332,
"s": 28290,
"text": "JDBC Driver class: com.mysql.jdbc.Driver."
},
{
"code": null,
"e": 28348,
"s": 28332,
"text": "Username: root."
},
{
"code": null,
"e": 28364,
"s": 28348,
"text": "Username: root."
},
{
"code": null,
"e": 28393,
"s": 28364,
"text": "Password: password for root."
},
{
"code": null,
"e": 28422,
"s": 28393,
"text": "Password: password for root."
},
{
"code": null,
"e": 28491,
"s": 28422,
"text": "The other fields on the screen are left as defaults as shown below −"
},
{
"code": null,
"e": 28600,
"s": 28491,
"text": "Now add a JDBC Request which refers to the JDBC Configuration pool defined above. Select JDBC Users element."
},
{
"code": null,
"e": 28650,
"s": 28600,
"text": "Click your right mouse button to get the Add menu"
},
{
"code": null,
"e": 28700,
"s": 28650,
"text": "Click your right mouse button to get the Add menu"
},
{
"code": null,
"e": 28737,
"s": 28700,
"text": "Select Add → Sampler → JDBC Request."
},
{
"code": null,
"e": 28774,
"s": 28737,
"text": "Select Add → Sampler → JDBC Request."
},
{
"code": null,
"e": 28825,
"s": 28774,
"text": "Select this new element to view its Control Panel."
},
{
"code": null,
"e": 28876,
"s": 28825,
"text": "Select this new element to view its Control Panel."
},
{
"code": null,
"e": 29233,
"s": 28876,
"text": "Edit the properties as shown below −\n\nVariable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test.\nName − Learn.\nEnter the Pool Name − test (same as in the configuration element).\nQuery Type − Select statement.\nEnter the SQL Query String field.\n\n"
},
{
"code": null,
"e": 29270,
"s": 29233,
"text": "Edit the properties as shown below −"
},
{
"code": null,
"e": 29441,
"s": 29270,
"text": "Variable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test."
},
{
"code": null,
"e": 29612,
"s": 29441,
"text": "Variable name bound to pool. This needs to uniquely identify the configuration. It is used by the JDBC Sampler to identify the configuration to be used. Named it as test."
},
{
"code": null,
"e": 29626,
"s": 29612,
"text": "Name − Learn."
},
{
"code": null,
"e": 29640,
"s": 29626,
"text": "Name − Learn."
},
{
"code": null,
"e": 29707,
"s": 29640,
"text": "Enter the Pool Name − test (same as in the configuration element)."
},
{
"code": null,
"e": 29774,
"s": 29707,
"text": "Enter the Pool Name − test (same as in the configuration element)."
},
{
"code": null,
"e": 29805,
"s": 29774,
"text": "Query Type − Select statement."
},
{
"code": null,
"e": 29836,
"s": 29805,
"text": "Query Type − Select statement."
},
{
"code": null,
"e": 29870,
"s": 29836,
"text": "Enter the SQL Query String field."
},
{
"code": null,
"e": 29904,
"s": 29870,
"text": "Enter the SQL Query String field."
},
{
"code": null,
"e": 30068,
"s": 29904,
"text": "Now add the Listener element. This element is responsible for storing all of the results of your JDBC requests in a file and presenting a visual model of the data."
},
{
"code": null,
"e": 30098,
"s": 30068,
"text": "Select the JDBC Users element"
},
{
"code": null,
"e": 30128,
"s": 30098,
"text": "Select the JDBC Users element"
},
{
"code": null,
"e": 30199,
"s": 30128,
"text": "Add a View Results Tree listener (Add → Listener → View Results Tree)."
},
{
"code": null,
"e": 30270,
"s": 30199,
"text": "Add a View Results Tree listener (Add → Listener → View Results Tree)."
},
{
"code": null,
"e": 30364,
"s": 30270,
"text": "Now save the above test plan as db_test.jmx. Execute this test plan using Run → Start option."
},
{
"code": null,
"e": 30426,
"s": 30364,
"text": "In the last image, you can see that two records are selected."
},
{
"code": null,
"e": 30540,
"s": 30426,
"text": "In this chapter, we will see how to test a FTP site using JMeter. Let us create a Test Plan to test the FTP site."
},
{
"code": null,
"e": 30621,
"s": 30540,
"text": "Open the JMeter window by clicking /home/manisha/apache-jmeter-2.9/bin/jmeter.sh"
},
{
"code": null,
"e": 30702,
"s": 30621,
"text": "Open the JMeter window by clicking /home/manisha/apache-jmeter-2.9/bin/jmeter.sh"
},
{
"code": null,
"e": 30731,
"s": 30702,
"text": "Click on the Test Plan node."
},
{
"code": null,
"e": 30760,
"s": 30731,
"text": "Click on the Test Plan node."
},
{
"code": null,
"e": 30803,
"s": 30760,
"text": "Rename this Test Plan node as TestFTPSite."
},
{
"code": null,
"e": 30846,
"s": 30803,
"text": "Rename this Test Plan node as TestFTPSite."
},
{
"code": null,
"e": 30955,
"s": 30846,
"text": "Add one Thread Group, which is placeholder for all other elements like Samplers, Controllers, and Listeners."
},
{
"code": null,
"e": 30998,
"s": 30955,
"text": "Right click on TestFTPSite (our Test Plan)"
},
{
"code": null,
"e": 31041,
"s": 30998,
"text": "Right click on TestFTPSite (our Test Plan)"
},
{
"code": null,
"e": 31153,
"s": 31041,
"text": "Select Add → Threads(Users) → Thread Group. Thread Group will get added under the Test Plan (TestFTPSite) node."
},
{
"code": null,
"e": 31265,
"s": 31153,
"text": "Select Add → Threads(Users) → Thread Group. Thread Group will get added under the Test Plan (TestFTPSite) node."
},
{
"code": null,
"e": 31471,
"s": 31265,
"text": "Modify the default properties of the Thread Group to suit our testing as follows −\n\nName − FTPusers\nNumber of Threads (Users) − 4\nRamp-Up Period − leave the the default value of 0 seconds.\nLoop Count − 1\n\n"
},
{
"code": null,
"e": 31554,
"s": 31471,
"text": "Modify the default properties of the Thread Group to suit our testing as follows −"
},
{
"code": null,
"e": 31570,
"s": 31554,
"text": "Name − FTPusers"
},
{
"code": null,
"e": 31586,
"s": 31570,
"text": "Name − FTPusers"
},
{
"code": null,
"e": 31616,
"s": 31586,
"text": "Number of Threads (Users) − 4"
},
{
"code": null,
"e": 31646,
"s": 31616,
"text": "Number of Threads (Users) − 4"
},
{
"code": null,
"e": 31705,
"s": 31646,
"text": "Ramp-Up Period − leave the the default value of 0 seconds."
},
{
"code": null,
"e": 31764,
"s": 31705,
"text": "Ramp-Up Period − leave the the default value of 0 seconds."
},
{
"code": null,
"e": 31779,
"s": 31764,
"text": "Loop Count − 1"
},
{
"code": null,
"e": 31794,
"s": 31779,
"text": "Loop Count − 1"
},
{
"code": null,
"e": 32026,
"s": 31794,
"text": "Now that we have defined our users, it is time to define the tasks that they will be performing. Add FTP Request elements. We add two FTP request elements, one which retrieves a file and the other which puts a file on the ftp site."
},
{
"code": null,
"e": 32056,
"s": 32026,
"text": "Select the FTP users element."
},
{
"code": null,
"e": 32086,
"s": 32056,
"text": "Select the FTP users element."
},
{
"code": null,
"e": 32135,
"s": 32086,
"text": "Right-click the mouse button to get the Add menu"
},
{
"code": null,
"e": 32184,
"s": 32135,
"text": "Right-click the mouse button to get the Add menu"
},
{
"code": null,
"e": 32220,
"s": 32184,
"text": "Select Add → Sampler → FTP Request."
},
{
"code": null,
"e": 32256,
"s": 32220,
"text": "Select Add → Sampler → FTP Request."
},
{
"code": null,
"e": 32300,
"s": 32256,
"text": "Select the FTP Request element in the tree."
},
{
"code": null,
"e": 32344,
"s": 32300,
"text": "Select the FTP Request element in the tree."
},
{
"code": null,
"e": 32391,
"s": 32344,
"text": "Edit the following properties as shown below −"
},
{
"code": null,
"e": 32438,
"s": 32391,
"text": "Edit the following properties as shown below −"
},
{
"code": null,
"e": 32490,
"s": 32438,
"text": "The following details are entered in this element −"
},
{
"code": null,
"e": 32513,
"s": 32490,
"text": "Name − FTP Request Get"
},
{
"code": null,
"e": 32536,
"s": 32513,
"text": "Name − FTP Request Get"
},
{
"code": null,
"e": 32570,
"s": 32536,
"text": "Server Name or IP − 184.168.74.29"
},
{
"code": null,
"e": 32604,
"s": 32570,
"text": "Server Name or IP − 184.168.74.29"
},
{
"code": null,
"e": 32647,
"s": 32604,
"text": "Remote File − /home/manisha/sample_ftp.txt"
},
{
"code": null,
"e": 32690,
"s": 32647,
"text": "Remote File − /home/manisha/sample_ftp.txt"
},
{
"code": null,
"e": 32718,
"s": 32690,
"text": "Local File − sample_ftp.txt"
},
{
"code": null,
"e": 32746,
"s": 32718,
"text": "Local File − sample_ftp.txt"
},
{
"code": null,
"e": 32763,
"s": 32746,
"text": "Select get(RETR)"
},
{
"code": null,
"e": 32780,
"s": 32763,
"text": "Select get(RETR)"
},
{
"code": null,
"e": 32799,
"s": 32780,
"text": "Username − manisha"
},
{
"code": null,
"e": 32818,
"s": 32799,
"text": "Username − manisha"
},
{
"code": null,
"e": 32840,
"s": 32818,
"text": "Password − manisha123"
},
{
"code": null,
"e": 32862,
"s": 32840,
"text": "Password − manisha123"
},
{
"code": null,
"e": 32962,
"s": 32862,
"text": "Now add another FTP request as above and edit the properties as shown in the following screenshot −"
},
{
"code": null,
"e": 33014,
"s": 32962,
"text": "The following details are entered in this element −"
},
{
"code": null,
"e": 33037,
"s": 33014,
"text": "Name − FTP Request Put"
},
{
"code": null,
"e": 33060,
"s": 33037,
"text": "Name − FTP Request Put"
},
{
"code": null,
"e": 33094,
"s": 33060,
"text": "Server Name or IP − 184.168.74.29"
},
{
"code": null,
"e": 33128,
"s": 33094,
"text": "Server Name or IP − 184.168.74.29"
},
{
"code": null,
"e": 33172,
"s": 33128,
"text": "Remote File − /home/manisha/examplefile.txt"
},
{
"code": null,
"e": 33216,
"s": 33172,
"text": "Remote File − /home/manisha/examplefile.txt"
},
{
"code": null,
"e": 33264,
"s": 33216,
"text": "Local File − /home/manisha/work/examplefile.txt"
},
{
"code": null,
"e": 33312,
"s": 33264,
"text": "Local File − /home/manisha/work/examplefile.txt"
},
{
"code": null,
"e": 33329,
"s": 33312,
"text": "Select put(STOR)"
},
{
"code": null,
"e": 33346,
"s": 33329,
"text": "Select put(STOR)"
},
{
"code": null,
"e": 33365,
"s": 33346,
"text": "Username − manisha"
},
{
"code": null,
"e": 33384,
"s": 33365,
"text": "Username − manisha"
},
{
"code": null,
"e": 33406,
"s": 33384,
"text": "Password − manisha123"
},
{
"code": null,
"e": 33428,
"s": 33406,
"text": "Password − manisha123"
},
{
"code": null,
"e": 33628,
"s": 33428,
"text": "The final element you need to add to your Test Plan is a Listener. This element is responsible for storing all of the results of your FTP requests in a file and presenting a visual model of the data."
},
{
"code": null,
"e": 33658,
"s": 33628,
"text": "Select the FTP users element."
},
{
"code": null,
"e": 33688,
"s": 33658,
"text": "Select the FTP users element."
},
{
"code": null,
"e": 33770,
"s": 33688,
"text": "Add a View Results Tree listener by selecting Add > Listener > View Results Tree."
},
{
"code": null,
"e": 33852,
"s": 33770,
"text": "Add a View Results Tree listener by selecting Add > Listener > View Results Tree."
},
{
"code": null,
"e": 33951,
"s": 33852,
"text": "Now save the above test plan as ftpsite_test.jmx. Execute this test plan using Run → Start option."
},
{
"code": null,
"e": 34001,
"s": 33951,
"text": "The following output can be seen in the listener."
},
{
"code": null,
"e": 34278,
"s": 34001,
"text": "You can see that four requests are made for each FTP request and the test is successful. The retrieved file for GET request is stored in the /bin folder. In our case, it is /home/manisha/apache-jmeter-2.9/bin/. For PUT request, the file is uploaded at the path /home/manisha/."
},
{
"code": null,
"e": 34469,
"s": 34278,
"text": "In this chapter, we will learn how to create a Test Plan to test a WebService. For our test purpose, we have created a simple webservice project and deployed it on the Tomcat server locally."
},
{
"code": null,
"e": 34675,
"s": 34469,
"text": "To create a webservice project, we have used Eclipse IDE. First write the Service Endpoint Interface HelloWorld under the package com.tutorialspoint.ws. The contents of the HelloWorld.java are as follows −"
},
{
"code": null,
"e": 35005,
"s": 34675,
"text": "package com.tutorialspoint.ws;\n\nimport javax.jws.WebMethod;\nimport javax.jws.WebService;\nimport javax.jws.soap.SOAPBinding;\nimport javax.jws.soap.SOAPBinding.Style;\n\n//Service Endpoint Interface\n@WebService\n@SOAPBinding(style = Style.RPC)\n\npublic interface HelloWorld {\n @WebMethod String getHelloWorldMessage(String string);\n}"
},
{
"code": null,
"e": 35084,
"s": 35005,
"text": "This service has a method getHelloWorldMessage which takes a String parameter."
},
{
"code": null,
"e": 35183,
"s": 35084,
"text": "Next, create the implementation class HelloWorldImpl.java under the package com.tutorialspoint.ws."
},
{
"code": null,
"e": 35490,
"s": 35183,
"text": "package com.tutorialspoint.ws;\n\nimport javax.jws.WebService;\n\n@WebService(endpointInterface=\"com.tutorialspoint.ws.HelloWorld\")\npublic class HelloWorldImpl implements HelloWorld {\n @Override\n public String getHelloWorldMessage(String myName) {\n return(\"Hello \"+myName+\" to JAX WS world\");\n }\n}"
},
{
"code": null,
"e": 35607,
"s": 35490,
"text": "Let us now publish this web service locally by creating the Endpoint publisher and expose the service on the server."
},
{
"code": null,
"e": 35649,
"s": 35607,
"text": "The publish method takes two parameters −"
},
{
"code": null,
"e": 35670,
"s": 35649,
"text": "Endpoint URL String."
},
{
"code": null,
"e": 35691,
"s": 35670,
"text": "Endpoint URL String."
},
{
"code": null,
"e": 35867,
"s": 35691,
"text": "Implementor object, in this case the HelloWorld implementation class, which is exposed as a Web Service at the endpoint identified by the URL mentioned in the parameter above."
},
{
"code": null,
"e": 36043,
"s": 35867,
"text": "Implementor object, in this case the HelloWorld implementation class, which is exposed as a Web Service at the endpoint identified by the URL mentioned in the parameter above."
},
{
"code": null,
"e": 36101,
"s": 36043,
"text": "The contents of HelloWorldPublisher.java are as follows −"
},
{
"code": null,
"e": 36381,
"s": 36101,
"text": "package com.tutorialspoint.endpoint;\n\nimport javax.xml.ws.Endpoint;\nimport com.tutorialspoint.ws.HelloWorldImpl;\n\npublic class HelloWorldPublisher {\n public static void main(String[] args) {\n Endpoint.publish(\"http://localhost:9000/ws/hello\", new HelloWorldImpl());\n }\n}"
},
{
"code": null,
"e": 36426,
"s": 36381,
"text": "Modify the web.xml contents as shown below −"
},
{
"code": null,
"e": 37188,
"s": 36426,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE web-app PUBLIC \"-//Sun Microsystems, \n Inc.//DTD Web Application 2.3//EN\" \"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd\">\n\n<web-app>\n <listener>\n <listener-class>\n com.sun.xml.ws.transport.http.servlet.WSServletContextListener\n </listener-class>\n </listener>\n\t\n <servlet>\n <servlet-name>hello</servlet-name>\n <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\t\n <servlet-mapping>\n <servlet-name>hello</servlet-name>\n <url-pattern>/hello</url-pattern>\n </servlet-mapping>\n\t\n <session-config>\n <session-timeout>120</session-timeout>\n </session-config>\n\t\n</web-app>"
},
{
"code": null,
"e": 37331,
"s": 37188,
"text": "To deploy this application as a webservice, we would need another configuration file sun-jaxws.xml. The contents of this file are as follows −"
},
{
"code": null,
"e": 37608,
"s": 37331,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<endpoints\n xmlns = \"http://java.sun.com/xml/ns/jax-ws/ri/runtime\"\n version = \"2.0\">\n \n <endpoint name = \"HelloWorld\" \n implementation = \"com.tutorialspoint.ws.HelloWorldImpl\" \n url-pattern = \"/hello\"/>\n</endpoints>"
},
{
"code": null,
"e": 37716,
"s": 37608,
"text": "Now that all the files are ready, the directory structure would look as shown in the following screenshot −"
},
{
"code": null,
"e": 37759,
"s": 37716,
"text": "Now create a WAR file of this application."
},
{
"code": null,
"e": 37802,
"s": 37759,
"text": "Now create a WAR file of this application."
},
{
"code": null,
"e": 37856,
"s": 37802,
"text": "Choose the project → right click → Export → WAR file."
},
{
"code": null,
"e": 37910,
"s": 37856,
"text": "Choose the project → right click → Export → WAR file."
},
{
"code": null,
"e": 37981,
"s": 37910,
"text": "Save this as hello.war file under the webapps folder of Tomcat server."
},
{
"code": null,
"e": 38052,
"s": 37981,
"text": "Save this as hello.war file under the webapps folder of Tomcat server."
},
{
"code": null,
"e": 38081,
"s": 38052,
"text": "Now start the Tomcat server."
},
{
"code": null,
"e": 38110,
"s": 38081,
"text": "Now start the Tomcat server."
},
{
"code": null,
"e": 38231,
"s": 38110,
"text": "Once the server is started, you should be able to access the webservice with the URL − http://localhost:8080/hello/hello"
},
{
"code": null,
"e": 38352,
"s": 38231,
"text": "Once the server is started, you should be able to access the webservice with the URL − http://localhost:8080/hello/hello"
},
{
"code": null,
"e": 38412,
"s": 38352,
"text": "Now let us create a test plan to test the above webservice."
},
{
"code": null,
"e": 38493,
"s": 38412,
"text": "Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh."
},
{
"code": null,
"e": 38574,
"s": 38493,
"text": "Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh."
},
{
"code": null,
"e": 38600,
"s": 38574,
"text": "Click the Test Plan node."
},
{
"code": null,
"e": 38626,
"s": 38600,
"text": "Click the Test Plan node."
},
{
"code": null,
"e": 38672,
"s": 38626,
"text": "Rename this Test Plan node as WebserviceTest."
},
{
"code": null,
"e": 38718,
"s": 38672,
"text": "Rename this Test Plan node as WebserviceTest."
},
{
"code": null,
"e": 38827,
"s": 38718,
"text": "Add one Thread Group, which is placeholder for all other elements like Samplers, Controllers, and Listeners."
},
{
"code": null,
"e": 38984,
"s": 38827,
"text": "Right click on WebserviceTest (our Test Plan) → Add → Threads (Users) → Thread Group. Thread Group will get added under the Test Plan (WebserviceTest) node."
},
{
"code": null,
"e": 39141,
"s": 38984,
"text": "Right click on WebserviceTest (our Test Plan) → Add → Threads (Users) → Thread Group. Thread Group will get added under the Test Plan (WebserviceTest) node."
},
{
"code": null,
"e": 39390,
"s": 39141,
"text": "Next, let us modify the default properties of the Thread Group to suit our testing. Following properties are changed −\n\nName − webservice user\nNumber of Threads (Users) − 2\nRamp-Up Period − leave the the default value of 0 seconds.\nLoop Count − 2\n\n"
},
{
"code": null,
"e": 39509,
"s": 39390,
"text": "Next, let us modify the default properties of the Thread Group to suit our testing. Following properties are changed −"
},
{
"code": null,
"e": 39532,
"s": 39509,
"text": "Name − webservice user"
},
{
"code": null,
"e": 39555,
"s": 39532,
"text": "Name − webservice user"
},
{
"code": null,
"e": 39585,
"s": 39555,
"text": "Number of Threads (Users) − 2"
},
{
"code": null,
"e": 39615,
"s": 39585,
"text": "Number of Threads (Users) − 2"
},
{
"code": null,
"e": 39674,
"s": 39615,
"text": "Ramp-Up Period − leave the the default value of 0 seconds."
},
{
"code": null,
"e": 39733,
"s": 39674,
"text": "Ramp-Up Period − leave the the default value of 0 seconds."
},
{
"code": null,
"e": 39748,
"s": 39733,
"text": "Loop Count − 2"
},
{
"code": null,
"e": 39763,
"s": 39748,
"text": "Loop Count − 2"
},
{
"code": null,
"e": 39860,
"s": 39763,
"text": "Now that we have defined the users, it is time to define the tasks that they will be performing."
},
{
"code": null,
"e": 39903,
"s": 39860,
"text": "We will add SOAP/XML-RPC Request element −"
},
{
"code": null,
"e": 39949,
"s": 39903,
"text": "Right-click mouse button to get the Add menu."
},
{
"code": null,
"e": 39995,
"s": 39949,
"text": "Right-click mouse button to get the Add menu."
},
{
"code": null,
"e": 40040,
"s": 39995,
"text": "Select Add → Sampler → SOAP/XML-RPC Request."
},
{
"code": null,
"e": 40085,
"s": 40040,
"text": "Select Add → Sampler → SOAP/XML-RPC Request."
},
{
"code": null,
"e": 40137,
"s": 40085,
"text": "Select the SOAP/XML-RPC Request element in the tree"
},
{
"code": null,
"e": 40189,
"s": 40137,
"text": "Select the SOAP/XML-RPC Request element in the tree"
},
{
"code": null,
"e": 40243,
"s": 40189,
"text": "Edit the following properties as in the image below −"
},
{
"code": null,
"e": 40297,
"s": 40243,
"text": "Edit the following properties as in the image below −"
},
{
"code": null,
"e": 40470,
"s": 40297,
"text": "The following details are entered in this element −\n\nName − SOAP/XML-RPC Request\nURL − http://localhost:8080/hello/hello?wsdl\nSoap/XML-RPC Data − Enter the below contents\n\n"
},
{
"code": null,
"e": 40522,
"s": 40470,
"text": "The following details are entered in this element −"
},
{
"code": null,
"e": 40550,
"s": 40522,
"text": "Name − SOAP/XML-RPC Request"
},
{
"code": null,
"e": 40578,
"s": 40550,
"text": "Name − SOAP/XML-RPC Request"
},
{
"code": null,
"e": 40623,
"s": 40578,
"text": "URL − http://localhost:8080/hello/hello?wsdl"
},
{
"code": null,
"e": 40668,
"s": 40623,
"text": "URL − http://localhost:8080/hello/hello?wsdl"
},
{
"code": null,
"e": 40713,
"s": 40668,
"text": "Soap/XML-RPC Data − Enter the below contents"
},
{
"code": null,
"e": 40758,
"s": 40713,
"text": "Soap/XML-RPC Data − Enter the below contents"
},
{
"code": null,
"e": 41066,
"s": 40758,
"text": "<soapenv:Envelope xmlns:soapenv = \"http://schemas.xmlsoap.org/soap/envelope/\" \n xmlns:web = \"http://ws.tutorialspoint.com/\">\n <soapenv:Header/>\n\t\n <soapenv:Body>\n <web:getHelloWorldMessage>\n <arg0>Manisha</arg0>\n </web:getHelloWorldMessage>\n </soapenv:Body>\n \n</soapenv:Envelope>"
},
{
"code": null,
"e": 41267,
"s": 41066,
"text": "The final element you need to add to your Test Plan is a Listener. This element is responsible for storing all of the results of your HTTP requests in a file and presenting a visual model of the data."
},
{
"code": null,
"e": 41303,
"s": 41267,
"text": "Select the webservice user element."
},
{
"code": null,
"e": 41339,
"s": 41303,
"text": "Select the webservice user element."
},
{
"code": null,
"e": 41421,
"s": 41339,
"text": "Add a View Results Tree listener by selecting Add → Listener → View Results Tree."
},
{
"code": null,
"e": 41503,
"s": 41421,
"text": "Add a View Results Tree listener by selecting Add → Listener → View Results Tree."
},
{
"code": null,
"e": 41605,
"s": 41503,
"text": "Now save the above test plan as test_webservice.jmx. Execute this test plan using Run → Start option."
},
{
"code": null,
"e": 41655,
"s": 41605,
"text": "The following output can be seen in the listener."
},
{
"code": null,
"e": 41740,
"s": 41655,
"text": "In the last image, you can see the response message \"Hello Manisha to JAX WS world\"."
},
{
"code": null,
"e": 41879,
"s": 41740,
"text": "In this chapter, we will learn how to write a simple test plan to test Java Messaging Service (JMS). JMS supports two types of messaging −"
},
{
"code": null,
"e": 42119,
"s": 41879,
"text": "Point-to-Point messaging − Queue messaging is generally used for transactions where the sender expects a response. Messaging systems are quite different from normal HTTP requests. In HTTP, a single user sends a request and gets a response."
},
{
"code": null,
"e": 42359,
"s": 42119,
"text": "Point-to-Point messaging − Queue messaging is generally used for transactions where the sender expects a response. Messaging systems are quite different from normal HTTP requests. In HTTP, a single user sends a request and gets a response."
},
{
"code": null,
"e": 42557,
"s": 42359,
"text": "Topic messaging − Topic messages are commonly known as pub/sub messaging. Topic messaging is generally used in cases where a message is published by a producer and consumed by multiple subscribers."
},
{
"code": null,
"e": 42755,
"s": 42557,
"text": "Topic messaging − Topic messages are commonly known as pub/sub messaging. Topic messaging is generally used in cases where a message is published by a producer and consumed by multiple subscribers."
},
{
"code": null,
"e": 42841,
"s": 42755,
"text": "Let us see a test example for each of these. The pre-requisites for testing JMS are −"
},
{
"code": null,
"e": 43030,
"s": 42841,
"text": "We use Apache ActiveMQ in the example. There are various JMS servers like IBM WebSphere MQ (formerly MQSeries), Tibco, etc. Download it from the binaries from the Apache ActiveMQ website."
},
{
"code": null,
"e": 43219,
"s": 43030,
"text": "We use Apache ActiveMQ in the example. There are various JMS servers like IBM WebSphere MQ (formerly MQSeries), Tibco, etc. Download it from the binaries from the Apache ActiveMQ website."
},
{
"code": null,
"e": 43358,
"s": 43219,
"text": "Unzip the archive, go to the decompressed directory, and run the following command from the command console to start the ActiveMQ server −"
},
{
"code": null,
"e": 43497,
"s": 43358,
"text": "Unzip the archive, go to the decompressed directory, and run the following command from the command console to start the ActiveMQ server −"
},
{
"code": null,
"e": 43520,
"s": 43497,
"text": ".\\bin\\activemq start\n"
},
{
"code": null,
"e": 43772,
"s": 43520,
"text": "You can verify if the ActiveMQ server has started by visiting the admin interface at the following address http://localhost:8161/admin/. If it asks for authentication, then enter the userid and password as admin. The screen is similar as shown below −"
},
{
"code": null,
"e": 43916,
"s": 43772,
"text": "Now copy the activemq-all-x.x.x.jar (XXX depending on the version) from the ActiveMQ unzipped directory to /home/manisha/apache-jmeter-2.9/lib."
},
{
"code": null,
"e": 44060,
"s": 43916,
"text": "Now copy the activemq-all-x.x.x.jar (XXX depending on the version) from the ActiveMQ unzipped directory to /home/manisha/apache-jmeter-2.9/lib."
},
{
"code": null,
"e": 44115,
"s": 44060,
"text": "With the above setup, let us build the test plan for −"
},
{
"code": null,
"e": 44144,
"s": 44115,
"text": "JMS Point-to-Point Test Plan"
},
{
"code": null,
"e": 44173,
"s": 44144,
"text": "JMS Point-to-Point Test Plan"
},
{
"code": null,
"e": 44193,
"s": 44173,
"text": "JMS Topic Test Plan"
},
{
"code": null,
"e": 44213,
"s": 44193,
"text": "JMS Topic Test Plan"
},
{
"code": null,
"e": 44351,
"s": 44213,
"text": "In this chapter, we will discuss how to create a Test Plan using JMeter to monitor webservers. The uses of monitor tests are as follows −"
},
{
"code": null,
"e": 44415,
"s": 44351,
"text": "Monitors are useful for a stress testing and system management."
},
{
"code": null,
"e": 44479,
"s": 44415,
"text": "Monitors are useful for a stress testing and system management."
},
{
"code": null,
"e": 44575,
"s": 44479,
"text": "Used with stress testing, the monitor provides additional information about server performance."
},
{
"code": null,
"e": 44671,
"s": 44575,
"text": "Used with stress testing, the monitor provides additional information about server performance."
},
{
"code": null,
"e": 44784,
"s": 44671,
"text": "Monitors make it easier to see the relationship between server performance and response time on the client side."
},
{
"code": null,
"e": 44897,
"s": 44784,
"text": "Monitors make it easier to see the relationship between server performance and response time on the client side."
},
{
"code": null,
"e": 45009,
"s": 44897,
"text": "As a system administration tool, the monitor provides an easy way to monitor multiple servers from one console."
},
{
"code": null,
"e": 45121,
"s": 45009,
"text": "As a system administration tool, the monitor provides an easy way to monitor multiple servers from one console."
},
{
"code": null,
"e": 45399,
"s": 45121,
"text": "We need Tomcat 5 or above for monitoring. For our test purpose, we will monitor Tomcat 7.0.42 server. You can test any servlet container that supports Java Management Extension (JMX). Let us write a test case to monitor the Tomcat server. Let us first set up our tomcat server."
},
{
"code": null,
"e": 45601,
"s": 45399,
"text": "We start with opening the Tomcat service status. To do this, edit the configuration file for users, <TOMCAT_HOME>/conf/tomcat-users.xml. This file contains a tomcat-users section (commented) as shown −"
},
{
"code": null,
"e": 45910,
"s": 45601,
"text": "<tomcat-users>\n\n<!--\n <role rolename = \"tomcat\"/>\n <role rolename = \"role1\"/>\n <user username = \"tomcat\" password = \"tomcat\" roles = \"tomcat\"/>\n <user username = \"both\" password = \"tomcat\" roles = \"tomcat,role1\"/>\n <user username = \"role1\" password = \"tomcat\" roles = \"role1\"/>\n-->\n\n</tomcat-users>"
},
{
"code": null,
"e": 46048,
"s": 45910,
"text": "We need to change this section to add the admin roles, manager, manager-gui and assign the user \"admin\". The revised file is as follows −"
},
{
"code": null,
"e": 46344,
"s": 46048,
"text": "<tomcat-users>\n\n <role rolename = \"manager-gui\"/>\n <role rolename = \"manager-script\"/>\n <role rolename = \"manager-jmx\"/>\n <role rolename = \"manager-status\"/>\n <user username = \"admin\" password = \"admin\" roles = \"manager-gui,manager-script,manager-jmx,manager-status\"/>\n\n</tomcat-users>"
},
{
"code": null,
"e": 46561,
"s": 46344,
"text": "Now start the tomcat server <TOMCAT_HOME>/bin/startup.sh for Linux and <TOMCAT_HOME>/bin/startup.bat for windows. Once started, check that the Tomcat supervision works by entering the following link in your browser −"
},
{
"code": null,
"e": 46608,
"s": 46561,
"text": "http://localhost:8080/manager/status?XML=true\n"
},
{
"code": null,
"e": 46797,
"s": 46608,
"text": "An authentication window appears in the browser. Enter the tomcat login and password associated (in our case it is admin). Then, the browser shows the execution status of Tomcat as below −"
},
{
"code": null,
"e": 46851,
"s": 46797,
"text": "From the above screenshot, we can note a few things −"
},
{
"code": null,
"e": 46999,
"s": 46851,
"text": "In the URL, note that XML = true (note the case sensitivity) allows a clean display of the supervisory Tomcat necessary for the JMeter functioning."
},
{
"code": null,
"e": 47147,
"s": 46999,
"text": "In the URL, note that XML = true (note the case sensitivity) allows a clean display of the supervisory Tomcat necessary for the JMeter functioning."
},
{
"code": null,
"e": 47379,
"s": 47147,
"text": "Also note that there are default two connectors. The AJP connector used in general coupled with the mod_jk Apache HTTPD front module and the HTTP connector which is commonly used connector for direct access to Tomcat via port 8080."
},
{
"code": null,
"e": 47611,
"s": 47379,
"text": "Also note that there are default two connectors. The AJP connector used in general coupled with the mod_jk Apache HTTPD front module and the HTTP connector which is commonly used connector for direct access to Tomcat via port 8080."
},
{
"code": null,
"e": 47669,
"s": 47611,
"text": "Let us monitor the Tomcat server by writing a test plan −"
},
{
"code": null,
"e": 47750,
"s": 47669,
"text": "Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh."
},
{
"code": null,
"e": 47831,
"s": 47750,
"text": "Open the JMeter window by clicking /home/manisha/apache-jmeter2.9/bin/jmeter.sh."
},
{
"code": null,
"e": 47857,
"s": 47831,
"text": "Click the Test Plan node."
},
{
"code": null,
"e": 47883,
"s": 47857,
"text": "Click the Test Plan node."
},
{
"code": null,
"e": 47933,
"s": 47883,
"text": "Add a thread group as explained in the next step."
},
{
"code": null,
"e": 47983,
"s": 47933,
"text": "Add a thread group as explained in the next step."
},
{
"code": null,
"e": 48101,
"s": 47983,
"text": "Right-click on Test Plan → Add → Threads(Users) → Thread Group. Thread Group will get added under the Test Plan node."
},
{
"code": null,
"e": 48219,
"s": 48101,
"text": "Right-click on Test Plan → Add → Threads(Users) → Thread Group. Thread Group will get added under the Test Plan node."
},
{
"code": null,
"e": 48313,
"s": 48219,
"text": "Change the loop count to forever (or some large number) so that enough samples are generated."
},
{
"code": null,
"e": 48407,
"s": 48313,
"text": "Change the loop count to forever (or some large number) so that enough samples are generated."
},
{
"code": null,
"e": 48624,
"s": 48407,
"text": "Add HTTP Authorization Manager to the Thread Group element by selecting Add → Config element → HTTP Authorization Manager. This element manages authentication requested by the browser to see the Tomcat server status."
},
{
"code": null,
"e": 48841,
"s": 48624,
"text": "Add HTTP Authorization Manager to the Thread Group element by selecting Add → Config element → HTTP Authorization Manager. This element manages authentication requested by the browser to see the Tomcat server status."
},
{
"code": null,
"e": 48880,
"s": 48841,
"text": "Select the HTTP Authorization Manager."
},
{
"code": null,
"e": 48919,
"s": 48880,
"text": "Select the HTTP Authorization Manager."
},
{
"code": null,
"e": 49137,
"s": 48919,
"text": "Edit the following details −\n\nUsername − admin (depending on the configuration in tomcat-users.xml file)\nPassword − admin (depending on the configuration in the tomcatusers.xml file)\nThe other fields are left empty.\n\n"
},
{
"code": null,
"e": 49166,
"s": 49137,
"text": "Edit the following details −"
},
{
"code": null,
"e": 49241,
"s": 49166,
"text": "Username − admin (depending on the configuration in tomcat-users.xml file)"
},
{
"code": null,
"e": 49316,
"s": 49241,
"text": "Username − admin (depending on the configuration in tomcat-users.xml file)"
},
{
"code": null,
"e": 49394,
"s": 49316,
"text": "Password − admin (depending on the configuration in the tomcatusers.xml file)"
},
{
"code": null,
"e": 49472,
"s": 49394,
"text": "Password − admin (depending on the configuration in the tomcatusers.xml file)"
},
{
"code": null,
"e": 49505,
"s": 49472,
"text": "The other fields are left empty."
},
{
"code": null,
"e": 49538,
"s": 49505,
"text": "The other fields are left empty."
},
{
"code": null,
"e": 49664,
"s": 49538,
"text": "Now that we have defined our users, it is time to define the tasks that they will be performing. We add HTTP Request element."
},
{
"code": null,
"e": 49714,
"s": 49664,
"text": "Right click the mouse button to get the Add menu."
},
{
"code": null,
"e": 49764,
"s": 49714,
"text": "Right click the mouse button to get the Add menu."
},
{
"code": null,
"e": 49801,
"s": 49764,
"text": "Select Add → Sampler → HTTP Request."
},
{
"code": null,
"e": 49838,
"s": 49801,
"text": "Select Add → Sampler → HTTP Request."
},
{
"code": null,
"e": 49889,
"s": 49838,
"text": "Then, select the HTTP Request element in the tree."
},
{
"code": null,
"e": 49940,
"s": 49889,
"text": "Then, select the HTTP Request element in the tree."
},
{
"code": null,
"e": 49994,
"s": 49940,
"text": "Edit the following properties as in the image below −"
},
{
"code": null,
"e": 50048,
"s": 49994,
"text": "Edit the following properties as in the image below −"
},
{
"code": null,
"e": 50362,
"s": 50048,
"text": "The following details are entered in this element −\n\nName − Server Status\nServer Name or IP − localhost\nPort − 8080\nPath − /manager/status\nParameters − Add a request parameter named \"XML\" in uppercase. Give it a value of \"true\" in lowercase.\nOptional Tasks − Check \"Use as Monitor\" at the bottom of the sampler.\n\n"
},
{
"code": null,
"e": 50414,
"s": 50362,
"text": "The following details are entered in this element −"
},
{
"code": null,
"e": 50435,
"s": 50414,
"text": "Name − Server Status"
},
{
"code": null,
"e": 50456,
"s": 50435,
"text": "Name − Server Status"
},
{
"code": null,
"e": 50486,
"s": 50456,
"text": "Server Name or IP − localhost"
},
{
"code": null,
"e": 50516,
"s": 50486,
"text": "Server Name or IP − localhost"
},
{
"code": null,
"e": 50528,
"s": 50516,
"text": "Port − 8080"
},
{
"code": null,
"e": 50540,
"s": 50528,
"text": "Port − 8080"
},
{
"code": null,
"e": 50563,
"s": 50540,
"text": "Path − /manager/status"
},
{
"code": null,
"e": 50586,
"s": 50563,
"text": "Path − /manager/status"
},
{
"code": null,
"e": 50689,
"s": 50586,
"text": "Parameters − Add a request parameter named \"XML\" in uppercase. Give it a value of \"true\" in lowercase."
},
{
"code": null,
"e": 50792,
"s": 50689,
"text": "Parameters − Add a request parameter named \"XML\" in uppercase. Give it a value of \"true\" in lowercase."
},
{
"code": null,
"e": 50862,
"s": 50792,
"text": "Optional Tasks − Check \"Use as Monitor\" at the bottom of the sampler."
},
{
"code": null,
"e": 50932,
"s": 50862,
"text": "Optional Tasks − Check \"Use as Monitor\" at the bottom of the sampler."
},
{
"code": null,
"e": 51134,
"s": 50932,
"text": "To request the status of the server periodically, add a Constant Timer which will allow a time interval between each request. Add a timer to this thread group by selecting Add → Timer → Constant Timer."
},
{
"code": null,
"e": 51367,
"s": 51134,
"text": "Enter 5000 milliseconds in the Thread Delay box. In general, using intervals shorter than 5 seconds may add stress to your server. Find out what is an acceptable interval before you deploy the monitor in your production environment."
},
{
"code": null,
"e": 51556,
"s": 51367,
"text": "The final element you need to add to your Test Plan is a Listener. We add two types of listeners. One that stores results in a file and second that shows the graphical view of the results."
},
{
"code": null,
"e": 51589,
"s": 51556,
"text": "Select the thread group element."
},
{
"code": null,
"e": 51622,
"s": 51589,
"text": "Select the thread group element."
},
{
"code": null,
"e": 51693,
"s": 51622,
"text": "Add a Simple Data Writer listener Add → Listener → Simple Data Writer."
},
{
"code": null,
"e": 51764,
"s": 51693,
"text": "Add a Simple Data Writer listener Add → Listener → Simple Data Writer."
},
{
"code": null,
"e": 51867,
"s": 51764,
"text": "Specify a directory and filename of the output file (in our case, it is /home/manisha/work/sample.csv)"
},
{
"code": null,
"e": 51970,
"s": 51867,
"text": "Specify a directory and filename of the output file (in our case, it is /home/manisha/work/sample.csv)"
},
{
"code": null,
"e": 52067,
"s": 51970,
"text": "Let us add another listener by selecting the test plan element Add → Listener → Monitor Results."
},
{
"code": null,
"e": 52164,
"s": 52067,
"text": "Let us add another listener by selecting the test plan element Add → Listener → Monitor Results."
},
{
"code": null,
"e": 52263,
"s": 52164,
"text": "Now save the above test plan as monitor_test.jmx. Execute this test plan using Run → Start option."
},
{
"code": null,
"e": 52414,
"s": 52263,
"text": "Results will be saved in /home/manisha/work/sample.csv file. You can also see a graphical result in the Monitor result listener as in the image below."
},
{
"code": null,
"e": 52859,
"s": 52414,
"text": "Note the graph has captions on both sides of the graph. On the left is percent and the right is dead/healthy. If the memory line spikes up and down rapidly, it could indicate memory thrashing. In those situations, it is a good idea to profile the application with Borland OptimizeIt or JProbe. What you want to see is a regular pattern for load, memory and threads. Any erratic behavior usually indicates poor performance or a bug of some sort."
},
{
"code": null,
"e": 53037,
"s": 52859,
"text": "Listeners provide access to the information JMeter gathers about the test cases while JMeter runs. The results or information gathered by listeners can be shown in the form of −"
},
{
"code": null,
"e": 53042,
"s": 53037,
"text": "tree"
},
{
"code": null,
"e": 53049,
"s": 53042,
"text": "tables"
},
{
"code": null,
"e": 53056,
"s": 53049,
"text": "graphs"
},
{
"code": null,
"e": 53065,
"s": 53056,
"text": "log file"
},
{
"code": null,
"e": 53145,
"s": 53065,
"text": "All listeners write the same raw data to the output file when one is specified."
},
{
"code": null,
"e": 53225,
"s": 53145,
"text": "The default items to be saved can be defined in one of the following two ways −"
},
{
"code": null,
"e": 53404,
"s": 53225,
"text": "In the jmeter.properties (or user.properties) file. This file is present in the /bin folder of JMeter.To change the default format, find the following line in jmeter.properties −"
},
{
"code": null,
"e": 53583,
"s": 53404,
"text": "In the jmeter.properties (or user.properties) file. This file is present in the /bin folder of JMeter.To change the default format, find the following line in jmeter.properties −"
},
{
"code": null,
"e": 53623,
"s": 53583,
"text": "jmeter.save.saveservice.output_format=\n"
},
{
"code": null,
"e": 53688,
"s": 53623,
"text": "By using the Config popup as shown in the following screenshot −"
},
{
"code": null,
"e": 53753,
"s": 53688,
"text": "By using the Config popup as shown in the following screenshot −"
},
{
"code": null,
"e": 53919,
"s": 53753,
"text": "JMeter creates results of a test run as JMeter Text Logs(JTL). These are normally called JTL files, as that is the default extension − but any extension can be used."
},
{
"code": null,
"e": 54045,
"s": 53919,
"text": "If multiple tests are run using the same output file name, then JMeter automatically appends new data at the end of the file."
},
{
"code": null,
"e": 54195,
"s": 54045,
"text": "The listener can record results to a file but not to the UI. It is meant to provide an efficient means of recording data by eliminating GUI overhead."
},
{
"code": null,
"e": 54213,
"s": 54195,
"text": "When running in −"
},
{
"code": null,
"e": 54260,
"s": 54213,
"text": "GUI mode − use the listener Simple Data Writer"
},
{
"code": null,
"e": 54307,
"s": 54260,
"text": "GUI mode − use the listener Simple Data Writer"
},
{
"code": null,
"e": 54369,
"s": 54307,
"text": "non-GUI mode − the -l flag can be used to create a data file."
},
{
"code": null,
"e": 54431,
"s": 54369,
"text": "non-GUI mode − the -l flag can be used to create a data file."
},
{
"code": null,
"e": 54580,
"s": 54431,
"text": "Listeners can use a lot of memory if there are a lot of samples. To minimize the amount of memory needed, use the Simple Data Write with CSV format."
},
{
"code": null,
"e": 54783,
"s": 54580,
"text": "The CSV log format depends on which data items are selected in the configuration. Only the specified data items are recorded in the file. The order of appearance of columns is fixed, and is as follows −"
},
{
"code": null,
"e": 55206,
"s": 54783,
"text": "The response data can be saved in the XML log file if required. However it does not allow to save large files and images. In such cases, use the Post-Processor Save_Responses_to_a_file. This generates a new file for each sample, and saves the file name with the sample. The file name can then be included in the sample log output. The data will be retrieved from the file if necessary when the sample log file is reloaded."
},
{
"code": null,
"e": 55378,
"s": 55206,
"text": "To view an existing results file, you can use the file \"Browse...\" button to select a file. If necessary, just create a dummy testplan with the appropriate Listener in it."
},
{
"code": null,
"e": 55444,
"s": 55378,
"text": "JMeter is capable of saving any listener as a PNG file. To do so,"
},
{
"code": null,
"e": 55540,
"s": 55444,
"text": "Select the listener in the left panel by selecting Edit → Save As Image. A file dialog appears."
},
{
"code": null,
"e": 55636,
"s": 55540,
"text": "Select the listener in the left panel by selecting Edit → Save As Image. A file dialog appears."
},
{
"code": null,
"e": 55660,
"s": 55636,
"text": "Enter the desired name."
},
{
"code": null,
"e": 55684,
"s": 55660,
"text": "Enter the desired name."
},
{
"code": null,
"e": 55703,
"s": 55684,
"text": "Save the listener."
},
{
"code": null,
"e": 55722,
"s": 55703,
"text": "Save the listener."
},
{
"code": null,
"e": 55831,
"s": 55722,
"text": "JMeter functions are special values that can populate fields of any Sampler or other element in a test tree."
},
{
"code": null,
"e": 55865,
"s": 55831,
"text": "A function call looks like this −"
},
{
"code": null,
"e": 55899,
"s": 55865,
"text": "A function call looks like this −"
},
{
"code": null,
"e": 55934,
"s": 55899,
"text": "${__functionName(var1,var2,var3)}\n"
},
{
"code": null,
"e": 56008,
"s": 55934,
"text": "_functionName matches the name of a function. For example ${__threadNum}."
},
{
"code": null,
"e": 56082,
"s": 56008,
"text": "_functionName matches the name of a function. For example ${__threadNum}."
},
{
"code": null,
"e": 56181,
"s": 56082,
"text": "If a function parameter contains a comma, then make sure you escape this with \"\\\" as shown below −"
},
{
"code": null,
"e": 56280,
"s": 56181,
"text": "If a function parameter contains a comma, then make sure you escape this with \"\\\" as shown below −"
},
{
"code": null,
"e": 56309,
"s": 56280,
"text": "${__time(EEE\\, d MMM yyyy)}\n"
},
{
"code": null,
"e": 56339,
"s": 56309,
"text": "Variables are referenced as −"
},
{
"code": null,
"e": 56369,
"s": 56339,
"text": "Variables are referenced as −"
},
{
"code": null,
"e": 56382,
"s": 56369,
"text": "${VARIABLE}\n"
},
{
"code": null,
"e": 56454,
"s": 56382,
"text": "Following table lists a group of functions loosely grouped into types −"
},
{
"code": null,
"e": 56553,
"s": 56454,
"text": "There are two kinds of functions −\n\nUser-defined static values (or variables)\nBuilt-in functions\n\n"
},
{
"code": null,
"e": 56588,
"s": 56553,
"text": "There are two kinds of functions −"
},
{
"code": null,
"e": 56630,
"s": 56588,
"text": "User-defined static values (or variables)"
},
{
"code": null,
"e": 56672,
"s": 56630,
"text": "User-defined static values (or variables)"
},
{
"code": null,
"e": 56691,
"s": 56672,
"text": "Built-in functions"
},
{
"code": null,
"e": 56710,
"s": 56691,
"text": "Built-in functions"
},
{
"code": null,
"e": 56865,
"s": 56710,
"text": "User-defined static values allow the user to define variables to be replaced with their static value when a test tree is compiled and submitted to be run."
},
{
"code": null,
"e": 57020,
"s": 56865,
"text": "User-defined static values allow the user to define variables to be replaced with their static value when a test tree is compiled and submitted to be run."
},
{
"code": null,
"e": 57082,
"s": 57020,
"text": "The variables cannot be nested; i.e ${Var${N}} does not work."
},
{
"code": null,
"e": 57144,
"s": 57082,
"text": "The variables cannot be nested; i.e ${Var${N}} does not work."
},
{
"code": null,
"e": 57236,
"s": 57144,
"text": "The __V (variable) function (versions after 2.2) can be used to do this − ${__V(Var${N})}. "
},
{
"code": null,
"e": 57328,
"s": 57236,
"text": "The __V (variable) function (versions after 2.2) can be used to do this − ${__V(Var${N})}. "
},
{
"code": null,
"e": 57430,
"s": 57328,
"text": "This type of replacement is possible without functions, but it is less convenient and less intuitive."
},
{
"code": null,
"e": 57532,
"s": 57430,
"text": "This type of replacement is possible without functions, but it is less convenient and less intuitive."
},
{
"code": null,
"e": 57609,
"s": 57532,
"text": "Functions and variables can be written into any field of any test component."
},
{
"code": null,
"e": 57667,
"s": 57609,
"text": "The following functions should work well in a test plan −"
},
{
"code": null,
"e": 57674,
"s": 57667,
"text": "intSum"
},
{
"code": null,
"e": 57682,
"s": 57674,
"text": "longSum"
},
{
"code": null,
"e": 57694,
"s": 57682,
"text": "machineName"
},
{
"code": null,
"e": 57704,
"s": 57694,
"text": "BeanShell"
},
{
"code": null,
"e": 57715,
"s": 57704,
"text": "javaScript"
},
{
"code": null,
"e": 57720,
"s": 57715,
"text": "jexl"
},
{
"code": null,
"e": 57727,
"s": 57720,
"text": "random"
},
{
"code": null,
"e": 57732,
"s": 57727,
"text": "time"
},
{
"code": null,
"e": 57751,
"s": 57732,
"text": "property functions"
},
{
"code": null,
"e": 57765,
"s": 57751,
"text": "log functions"
},
{
"code": null,
"e": 58184,
"s": 57765,
"text": "Functions which are used on the Test Plan have some restrictions. JMeter thread variables will have not been fully set up when the functions are processed, so variable names passed as parameters will not be set up and variable references will not work. Hence, split() and regex() and the variable evaluation functions will not work. The threadNum() function will not work and it does not make sense at test plan level."
},
{
"code": null,
"e": 58284,
"s": 58184,
"text": "Referencing a variable in a test element is done by bracketing the variable name with '${' and '}'."
},
{
"code": null,
"e": 58384,
"s": 58284,
"text": "Referencing a variable in a test element is done by bracketing the variable name with '${' and '}'."
},
{
"code": null,
"e": 58528,
"s": 58384,
"text": "Functions are referenced in the same manner, but by convention, the names of functions begin with \"__\" to avoid conflict with user value names."
},
{
"code": null,
"e": 58672,
"s": 58528,
"text": "Functions are referenced in the same manner, but by convention, the names of functions begin with \"__\" to avoid conflict with user value names."
},
{
"code": null,
"e": 58849,
"s": 58672,
"text": "Some functions take arguments to configure them, and these go in parentheses, comma-delimited. If the function takes no arguments, the parentheses can be omitted. For example −"
},
{
"code": null,
"e": 59026,
"s": 58849,
"text": "Some functions take arguments to configure them, and these go in parentheses, comma-delimited. If the function takes no arguments, the parentheses can be omitted. For example −"
},
{
"code": null,
"e": 59069,
"s": 59026,
"text": "${__BeanShell(vars.put(\"name\"\\,\"value\"))}\n"
},
{
"code": null,
"e": 59150,
"s": 59069,
"text": "Alternatively, you can define your script as a variable, e.g. on the Test Plan −"
},
{
"code": null,
"e": 59231,
"s": 59150,
"text": "Alternatively, you can define your script as a variable, e.g. on the Test Plan −"
},
{
"code": null,
"e": 59268,
"s": 59231,
"text": "SCRIPT vars.put(\"name\",\"value\")\n"
},
{
"code": null,
"e": 59315,
"s": 59268,
"text": "The script can then be referenced as follows −"
},
{
"code": null,
"e": 59362,
"s": 59315,
"text": "The script can then be referenced as follows −"
},
{
"code": null,
"e": 59389,
"s": 59362,
"text": "${__BeanShell(${SCRIPT})}\n"
},
{
"code": null,
"e": 59456,
"s": 59389,
"text": "The Function Helper Dialog is available from JMeter's Options tab."
},
{
"code": null,
"e": 59756,
"s": 59456,
"text": "Using the Function Helper, you can select a function from the pull down, and assign values for its arguments. The left column in the table provides a brief description of the argument, and the right column is where you write the value for that argument. Different functions take different arguments."
},
{
"code": null,
"e": 60056,
"s": 59756,
"text": "Using the Function Helper, you can select a function from the pull down, and assign values for its arguments. The left column in the table provides a brief description of the argument, and the right column is where you write the value for that argument. Different functions take different arguments."
},
{
"code": null,
"e": 60217,
"s": 60056,
"text": "Once you have done this, click the “Generate\" button, and the appropriate string is generated, which you can copy-paste into the test plan wherever you need to."
},
{
"code": null,
"e": 60378,
"s": 60217,
"text": "Once you have done this, click the “Generate\" button, and the appropriate string is generated, which you can copy-paste into the test plan wherever you need to."
},
{
"code": null,
"e": 60438,
"s": 60378,
"text": "Some variables are defined internally by JMeter. They are −"
},
{
"code": null,
"e": 60485,
"s": 60438,
"text": "COOKIE_cookiename − contains the cookie value."
},
{
"code": null,
"e": 60532,
"s": 60485,
"text": "COOKIE_cookiename − contains the cookie value."
},
{
"code": null,
"e": 60688,
"s": 60532,
"text": "JMeterThread.last_sample_ok − whether or not the last sample was OK − true/false. Note − this is updated after PostProcessors and Assertions have been run."
},
{
"code": null,
"e": 60844,
"s": 60688,
"text": "JMeterThread.last_sample_ok − whether or not the last sample was OK − true/false. Note − this is updated after PostProcessors and Assertions have been run."
},
{
"code": null,
"e": 60861,
"s": 60844,
"text": "START variables."
},
{
"code": null,
"e": 60878,
"s": 60861,
"text": "START variables."
},
{
"code": null,
"e": 61038,
"s": 60878,
"text": "Some built-in properties are defined by JMeter. These are listed below. For convenience, the START properties are also copied to variables with the same names."
},
{
"code": null,
"e": 61084,
"s": 61038,
"text": "START.MS − JMeter start time in milliseconds."
},
{
"code": null,
"e": 61130,
"s": 61084,
"text": "START.MS − JMeter start time in milliseconds."
},
{
"code": null,
"e": 61173,
"s": 61130,
"text": "START.YMD − JMeter start time as yyyyMMdd."
},
{
"code": null,
"e": 61216,
"s": 61173,
"text": "START.YMD − JMeter start time as yyyyMMdd."
},
{
"code": null,
"e": 61257,
"s": 61216,
"text": "START.HMS − JMeter start time as HHmmss."
},
{
"code": null,
"e": 61298,
"s": 61257,
"text": "START.HMS − JMeter start time as HHmmss."
},
{
"code": null,
"e": 61346,
"s": 61298,
"text": "TESTSTART.MS − test start time in milliseconds."
},
{
"code": null,
"e": 61394,
"s": 61346,
"text": "TESTSTART.MS − test start time in milliseconds."
},
{
"code": null,
"e": 61545,
"s": 61394,
"text": "Note that the START variables / properties represent JMeter startup time, not the test start time. They are mainly intended for use in file names etc."
},
{
"code": null,
"e": 61788,
"s": 61545,
"text": "Regular expressions are used to search and manipulate text, based on patterns. JMeter interprets forms of regular expressions or patterns being used throughout a JMeter test plan, by including the pattern matching software Apache Jakarta ORO."
},
{
"code": null,
"e": 62062,
"s": 61788,
"text": "With the use of regular expressions, we can certainly save a lot of time and achieve greater flexibility as we create or enhance a Test Plan. Regular expressions provide a simple method to get information from pages when it is impossible or very hard to predict an outcome."
},
{
"code": null,
"e": 62235,
"s": 62062,
"text": "To use regular expressions in your test plan, you need to use the Regular Expression Extractor of JMeter. You can place regular expressions in any component in a Test Plan."
},
{
"code": null,
"e": 62351,
"s": 62235,
"text": "It is worth stressing the difference between contains and matches, as used on the Response Assertion test element −"
},
{
"code": null,
"e": 62531,
"s": 62351,
"text": "contains means that the regular expression matched at least some part of the target, so 'alphabet' \"contains\" 'ph.b.' because the regular expression matches the substring 'phabe'."
},
{
"code": null,
"e": 62711,
"s": 62531,
"text": "contains means that the regular expression matched at least some part of the target, so 'alphabet' \"contains\" 'ph.b.' because the regular expression matches the substring 'phabe'."
},
{
"code": null,
"e": 62825,
"s": 62711,
"text": "matches means that the regular expression matched the whole target. Hence the 'alphabet' is \"matched\" by 'al.*t'."
},
{
"code": null,
"e": 62939,
"s": 62825,
"text": "matches means that the regular expression matched the whole target. Hence the 'alphabet' is \"matched\" by 'al.*t'."
},
{
"code": null,
"e": 63003,
"s": 62939,
"text": "Suppose you want to match the following portion of a web-page −"
},
{
"code": null,
"e": 63040,
"s": 63003,
"text": "name = \"file\" value = \"readme.txt\" \n"
},
{
"code": null,
"e": 63117,
"s": 63040,
"text": "And you want to extract readme.txt. A suitable regular expression would be −"
},
{
"code": null,
"e": 63149,
"s": 63117,
"text": "name = \"file\" value = \"(.+?)\">\n"
},
{
"code": null,
"e": 63184,
"s": 63149,
"text": "The special characters above are −"
},
{
"code": null,
"e": 63255,
"s": 63184,
"text": "( and ) − these enclose the portion of the match string to be returned"
},
{
"code": null,
"e": 63326,
"s": 63255,
"text": "( and ) − these enclose the portion of the match string to be returned"
},
{
"code": null,
"e": 63350,
"s": 63326,
"text": ". − match any character"
},
{
"code": null,
"e": 63374,
"s": 63350,
"text": ". − match any character"
},
{
"code": null,
"e": 63396,
"s": 63374,
"text": "+ − one or more times"
},
{
"code": null,
"e": 63418,
"s": 63396,
"text": "+ − one or more times"
},
{
"code": null,
"e": 63453,
"s": 63418,
"text": "? − stop when first match succeeds"
},
{
"code": null,
"e": 63488,
"s": 63453,
"text": "? − stop when first match succeeds"
},
{
"code": null,
"e": 63765,
"s": 63488,
"text": "Let us understand the use of Regular expressions in the Regular Expression Extractor—a Post-Processor Element by writing a test plan. This element extracts text from the current page using a Regular Expression to identify the text pattern that a desired element conforms with."
},
{
"code": null,
"e": 63923,
"s": 63765,
"text": "First we write an HTML page which a list of people and their email IDs. We deploy it to our tomcat server. The contents of html (index.html) are as follows −"
},
{
"code": null,
"e": 64768,
"s": 63923,
"text": "<html>\n <head>\n </head>\n\t\n <body>\n <table style = \"border: 1px solid #000000;\">\n\t\t\n <th style = \"border: 1px solid #000000;\">ID</th>\n <th style = \"border: 1px solid #000000;\">name</th>\n <th style = \"border: 1px solid #000000;\">Email</th>\n\t\t\t\n <tr>\n <td id = \"ID\" style = \"border: 1px solid #000000;\">3</td>\n <td id = \"Name\" style = \"border: 1px solid #000000;\">Manisha</td>\n <td id = \"Email\" style = \"border: 1px solid #000000;\">[email protected]</td>\n </tr>\n\t\t\t\n <tr>\n <td id = \"ID\" style = \"border: 1px solid #000000;\">4</td>\n <td id = \"Name\" style = \"border: 1px solid #000000;\">joe</td>\n <td id = \"Email\" style = \"border: 1px solid #000000;\">[email protected]</td>\n </tr>\n\t\t\t\n </table>\n </body>\n</html>"
},
{
"code": null,
"e": 64871,
"s": 64768,
"text": "On deploying it on the tomcat server, this page would look like as shown in the following screenshot −"
},
{
"code": null,
"e": 65107,
"s": 64871,
"text": "In our test plan, we will select the person in the first row of the person table seen in the person list page above. To capture the ID of this person, let us first determine the pattern where we will find the person in the second row. "
},
{
"code": null,
"e": 65495,
"s": 65107,
"text": "As can be seen in the following snapshot, the ID of the second person is surrounded by <td id = \"ID\"> and </td >, and it is the second row of data having this pattern. We can use this to match the exact pattern that we want to extract information from. As we want to extract two pieces of information from this page, the person ID and the person name, the fields are defined as follows −"
},
{
"code": null,
"e": 65575,
"s": 65495,
"text": "Start JMeter, add a Thread group Test Plan → Add→ Threads(Users)→ Thread Group."
},
{
"code": null,
"e": 65710,
"s": 65575,
"text": "Next add a sampler HTTP Request, select the test plan, right click Add → Sampler → HTTP Request and enter the details as shown below −"
},
{
"code": null,
"e": 65724,
"s": 65710,
"text": "Name − Manage"
},
{
"code": null,
"e": 65738,
"s": 65724,
"text": "Name − Manage"
},
{
"code": null,
"e": 65768,
"s": 65738,
"text": "Server Name or IP − localhost"
},
{
"code": null,
"e": 65798,
"s": 65768,
"text": "Server Name or IP − localhost"
},
{
"code": null,
"e": 65817,
"s": 65798,
"text": "Port Number − 8080"
},
{
"code": null,
"e": 65836,
"s": 65817,
"text": "Port Number − 8080"
},
{
"code": null,
"e": 65914,
"s": 65836,
"text": "Protocol − We will keep this blank, which means we want HTTP as the protocol."
},
{
"code": null,
"e": 65992,
"s": 65914,
"text": "Protocol − We will keep this blank, which means we want HTTP as the protocol."
},
{
"code": null,
"e": 66017,
"s": 65992,
"text": "Path − jmeter/index.html"
},
{
"code": null,
"e": 66042,
"s": 66017,
"text": "Path − jmeter/index.html"
},
{
"code": null,
"e": 66191,
"s": 66042,
"text": "Next, add a Regular Expression Extractor. Select the HTTP Request Sampler (Manage), right click Add → Post Processor → Regular Expression Extractor."
},
{
"code": null,
"e": 66279,
"s": 66191,
"text": "The following table provides a description of the fields used in the above screenshot −"
},
{
"code": null,
"e": 66294,
"s": 66279,
"text": "Reference Name"
},
{
"code": null,
"e": 66373,
"s": 66294,
"text": "The name of the variable in which the extracted test will be stored (refname)."
},
{
"code": null,
"e": 66392,
"s": 66373,
"text": "Regular Expression"
},
{
"code": null,
"e": 66721,
"s": 66392,
"text": "The pattern against which the text to be extracted will be matched. The text groups that will extracted are enclosed by the characters '(' and ')'. We use '.+?' to indicate a single instance of the text enclosed by the <td..>..</td> tags. In our example the expression is − <td id = \"ID\">(+?)</td>\\s*<td id = \"Name\">(+?)</td>\\s*"
},
{
"code": null,
"e": 66730,
"s": 66721,
"text": "Template"
},
{
"code": null,
"e": 67217,
"s": 66730,
"text": "Each group of extracted text placed as a member of the variable Person, following the order of each group of pattern enclosed by '(' and ')'. Each group is stored as refname_g#, where refname is the string you entered as the reference name, and # is the group number. $1$ to refers to group 1, $2$ to refers to group 2, etc. $0$ refers to whatever the entire expression matches. In this example, the ID we extract is maintained in Person_g1, while the Name value is stored in Person_g2."
},
{
"code": null,
"e": 67227,
"s": 67217,
"text": "Match No."
},
{
"code": null,
"e": 67450,
"s": 67227,
"text": "Since we plan to extract only the second occurrence of this pattern, matching the second volunteer, we use value 2. Value 0 would make a random matching, while a negative value needs to be used with the ForEach Controller."
},
{
"code": null,
"e": 67458,
"s": 67450,
"text": "Default"
},
{
"code": null,
"e": 67567,
"s": 67458,
"text": "If the item is not found, this will be the default value. This is an optional field. You may leave it blank."
},
{
"code": null,
"e": 67726,
"s": 67567,
"text": "Add a listener to capture the result of this Test Plan. Right-click the Thread Group and select Add → Listener → View Results Tree option to add the listener."
},
{
"code": null,
"e": 67856,
"s": 67726,
"text": "Save the test plan as reg_express_test.jmx and run the test. The output would be a success as shown in the following screenshot −"
},
{
"code": null,
"e": 68020,
"s": 67856,
"text": "JMeter has some limitations especially when it is run in a distributed environment. Following these guidelines will assist in creating a real and continuous load −"
},
{
"code": null,
"e": 68094,
"s": 68020,
"text": "Use multiple instances of JMeter in case, the number of threads are more."
},
{
"code": null,
"e": 68168,
"s": 68094,
"text": "Use multiple instances of JMeter in case, the number of threads are more."
},
{
"code": null,
"e": 68216,
"s": 68168,
"text": "Check the Scoping Rules and design accordingly."
},
{
"code": null,
"e": 68264,
"s": 68216,
"text": "Check the Scoping Rules and design accordingly."
},
{
"code": null,
"e": 68312,
"s": 68264,
"text": "Use naming conventions always for all elements."
},
{
"code": null,
"e": 68360,
"s": 68312,
"text": "Use naming conventions always for all elements."
},
{
"code": null,
"e": 68435,
"s": 68360,
"text": "Check the default browser Connectivity settings, before executing scripts."
},
{
"code": null,
"e": 68510,
"s": 68435,
"text": "Check the default browser Connectivity settings, before executing scripts."
},
{
"code": null,
"e": 68539,
"s": 68510,
"text": "Add Listeners appropriately."
},
{
"code": null,
"e": 68568,
"s": 68539,
"text": "Add Listeners appropriately."
},
{
"code": null,
"e": 68627,
"s": 68568,
"text": "Here are some suggestion to reduce resource requirements −"
},
{
"code": null,
"e": 68686,
"s": 68627,
"text": "Here are some suggestion to reduce resource requirements −"
},
{
"code": null,
"e": 68739,
"s": 68686,
"text": "Use non-GUI mode: jmeter -n -t test.jmx -l test.jtl."
},
{
"code": null,
"e": 68792,
"s": 68739,
"text": "Use non-GUI mode: jmeter -n -t test.jmx -l test.jtl."
},
{
"code": null,
"e": 68894,
"s": 68792,
"text": "Use as few Listeners as possible; if using the -l flag as above, they can all be deleted or disabled."
},
{
"code": null,
"e": 68996,
"s": 68894,
"text": "Use as few Listeners as possible; if using the -l flag as above, they can all be deleted or disabled."
},
{
"code": null,
"e": 69227,
"s": 68996,
"text": "Disable the “View Result Tree” listener as it consumes a lot of memory and can result in the console freezing or JMeter running out of memory. It is, however, safe to use the “View Result Tree” listener with only “Errors” checked."
},
{
"code": null,
"e": 69458,
"s": 69227,
"text": "Disable the “View Result Tree” listener as it consumes a lot of memory and can result in the console freezing or JMeter running out of memory. It is, however, safe to use the “View Result Tree” listener with only “Errors” checked."
},
{
"code": null,
"e": 69626,
"s": 69458,
"text": "Rather than using lots of similar samplers, use the same sampler in a loop, and use variables (CSV Data Set) to vary the sample. Or perhaps use the Access Log Sampler."
},
{
"code": null,
"e": 69794,
"s": 69626,
"text": "Rather than using lots of similar samplers, use the same sampler in a loop, and use variables (CSV Data Set) to vary the sample. Or perhaps use the Access Log Sampler."
},
{
"code": null,
"e": 69822,
"s": 69794,
"text": "Do not use functional mode."
},
{
"code": null,
"e": 69850,
"s": 69822,
"text": "Do not use functional mode."
},
{
"code": null,
"e": 69882,
"s": 69850,
"text": "Use CSV output rather than XML."
},
{
"code": null,
"e": 69914,
"s": 69882,
"text": "Use CSV output rather than XML."
},
{
"code": null,
"e": 69948,
"s": 69914,
"text": "Only save the data that you need."
},
{
"code": null,
"e": 69982,
"s": 69948,
"text": "Only save the data that you need."
},
{
"code": null,
"e": 70017,
"s": 69982,
"text": "Use as few Assertions as possible."
},
{
"code": null,
"e": 70052,
"s": 70017,
"text": "Use as few Assertions as possible."
},
{
"code": null,
"e": 70194,
"s": 70052,
"text": "Disable all JMeter graphs as they consume a lot of memory. You can view all of the real time graphs using the JTLs tab in your web interface."
},
{
"code": null,
"e": 70336,
"s": 70194,
"text": "Disable all JMeter graphs as they consume a lot of memory. You can view all of the real time graphs using the JTLs tab in your web interface."
},
{
"code": null,
"e": 70408,
"s": 70336,
"text": "Do not forget to erase the local path from CSV Data Set Config if used."
},
{
"code": null,
"e": 70480,
"s": 70408,
"text": "Do not forget to erase the local path from CSV Data Set Config if used."
},
{
"code": null,
"e": 70525,
"s": 70480,
"text": "Clean the Files tab prior to every test run."
},
{
"code": null,
"e": 70570,
"s": 70525,
"text": "Clean the Files tab prior to every test run."
},
{
"code": null,
"e": 70605,
"s": 70570,
"text": "\n 59 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 70619,
"s": 70605,
"text": " Rahul Shetty"
},
{
"code": null,
"e": 70655,
"s": 70619,
"text": "\n 54 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 70672,
"s": 70655,
"text": " Wallace Tauriac"
},
{
"code": null,
"e": 70707,
"s": 70672,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 70719,
"s": 70707,
"text": " Anuja Jain"
},
{
"code": null,
"e": 70752,
"s": 70719,
"text": "\n 12 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 70766,
"s": 70752,
"text": " Spotle Learn"
},
{
"code": null,
"e": 70773,
"s": 70766,
"text": " Print"
},
{
"code": null,
"e": 70784,
"s": 70773,
"text": " Add Notes"
}
]
|
Forecasting the Future Power Consumption using LSTM, Deep Neural Network and Exploratory Data Analysis | Towards Data Science | Human beings live on the time axis and design their daily life accordingly. Mostly they sleep at night and other activities are mostly done at certain times (e.g. breakfast — in the morning). When we consider language, it is known that what is spoken or written maintains and follows certain integrity of meaning. When we talk about machine learning, model training in such sequential datasets is made by using statistical methods such as ARIMA, SARIMAX, as well as using a neural network. The fundamental idea is that the data at time t is the result of several previous data points. This article explains the theoretical part of RNN — LSTM and includes a tutorial about quick exploratory data analysis of time series dataset and predicting the future power consumptions of Germany using LSTM and DNN.
Table of Contents1. Theory1.1. Recurrent Neural Networks1.1.1. Under the Hood1.1.2. Vanishing Gradient Descent1.2. Long-Short Term Memory2. Tutorial3. Conclusion4. References
In a dataset, which flows sequential, each data at time t occurs in relation to the historical data. For example, if we consider NLP, the continuation of a paragraph is shaped according to the keywords before it, that is, according to the integrity of the meaning. While reading a novel, an average of 3–4 words per second is seen and the book continues to be read fluently. Although thousands of words have been seen and read at the end of 1 hour of reading, it is difficult to repeat them by heart. However, the section read can be understood and explained easily. In machine learning, Recurrent Neural Networks can be used to extract the basic meaning & pattern from such sequential datasets. Let’s continue with different examples; movies consist of frames and these frames are in certain integrity according to the subject & content of the movie. We can easily predict the next moment or the next frame in the movie after we have understood the movie. Recurrent Neural Networks can be used to predict the future by detecting the flow pattern in sequential data. In another example, it provides time-series, that is, in time-changing graphics (stock market, spreading of coronavirus by time), to detect the flow and perform forecasting. So, how to explain mathematically what provides these possibilities using numbers?
The figure below shows how the Recurrent Neural Network process works in a sequential dataset with 4 data in 4 seconds. Its basic working principle is similar to Feedforward Neural Network. The whole system can be briefly summarized as follows:
The weight values assigned to the input turn into output after the layers and are compared with the real output to determine the Loss value, that is, the distance from where it should be. According to this loss value, the value of the weight is updated and the same process is repeated. The purpose of updating the weights is to minimize the loss value and determine the optimum weight value.
RNN, on the other hand, is designed sequentially, that is, in a backward connection to detect the connection of the data at time t with (t-1). Of course, beyond just t and (t-1), perhaps its value at time t is calculated according to the last 10 values, thanks to its backward-connected structure. Now let’s dive into Figure 1 in detail.
Let’s consider 4 data points (x1, x2, x3, and x4). Yellow structures represent layers. The equation of each output is depicted above. As it is seen, the output of each layer is sequentially presented as an additional input to the next layer. The final output results are based on the selected activation function. Then, the deviation of the obtained result is calculated, the weights are derived according to the loss output and updated with the backpropagation process. The RNN structure basically follows this pattern. If we take a look at the disadvantages of this RNN structure, the vanishing gradient problem meets us.
When it is hard to converge the global minimum point, this case is called Vanishing Gradient Descent.
In RNN, this process occurs when there are too many layers and the weights are updated with the Sigmoid Function. The value obtained with the Sigmoid Function should be between 0 and 1. However, in the backpropagation process, the effect of the first inputs (first a few words for NLP, first a few times for Time Series) on the system in the learning of the sequential series is minimized, since the weights update is at such a low level that when the first layers are reached. This causes these inputs and their weights to be ignored, concentrating sequential learning on the last inputs.
If another activation function is used instead of Sigmoid Function, such as ReLu, due to the structure of ReLu, a situation opposite to vanishing gradient descent, that is, too much change in weights so that cannot reach the global minimum point safely.
LSTM is designed to prevent ignoring the effect of first inputs in the sequential series during the updating of the weights. Figure 2 shows how the LSTM model avoids the problem of not considering prior data (weights of previous data) unimportant in weights adjustments.
Logistic (Sigmoid) activation function outputs the data between 0–1. In this way, the level of significance of the data is evaluated between 0–1. 0 becomes unimportant and is reflected as 0 in the multiplied operation. 1 means it is important.
Tanh activation function takes on the task of regulation by giving the value between (-1) and (+1) as output.
Previous cell output(h(t-1)) and current input(x(t)) are passed through the logistic(sigmoid) function. The long-term state (c(t-1)) is multiplied with the resulting value (f(t)). At this stage (forget gate), it is mathematically inferred which data is important and to what extent from the long-term states.The sigmoid value obtained in the first step is also obtained here (i(t)) with the same inputs (Previous cell output(h(t-1)) and current input(x(t)). In addition, these inputs are also passed through the tanh activation function and multiplied with the sigmoid output (g(t)). At this stage, (input gate) i(t) mathematically expresses how important the g(t) value is.Mathematical expressions (Forget Gate and Input Gate) obtained in the first two cases are added and form the new cell state (c(t)). In addition, this result is regularized by passing through tanh and multiplied by the logistic(sigmoid) function result (o(t)) of the two inputs in the first two stages (Previous cell output(h(t-1)) and current input(x(t)). Returns the short term state (h(t)). At this stage (output gate), the importance of long-term states is transferred to the system.
Previous cell output(h(t-1)) and current input(x(t)) are passed through the logistic(sigmoid) function. The long-term state (c(t-1)) is multiplied with the resulting value (f(t)). At this stage (forget gate), it is mathematically inferred which data is important and to what extent from the long-term states.
The sigmoid value obtained in the first step is also obtained here (i(t)) with the same inputs (Previous cell output(h(t-1)) and current input(x(t)). In addition, these inputs are also passed through the tanh activation function and multiplied with the sigmoid output (g(t)). At this stage, (input gate) i(t) mathematically expresses how important the g(t) value is.
Mathematical expressions (Forget Gate and Input Gate) obtained in the first two cases are added and form the new cell state (c(t)). In addition, this result is regularized by passing through tanh and multiplied by the logistic(sigmoid) function result (o(t)) of the two inputs in the first two stages (Previous cell output(h(t-1)) and current input(x(t)). Returns the short term state (h(t)). At this stage (output gate), the importance of long-term states is transferred to the system.
LSTM and configured versions of it are suitable methods for many time-based datasets, especially stock market price prediction.
In this tutorial, models are trained with LSTM and DNN using hourly power consumption of the Germany dataset between 01.01.2015 and 01.09.2020. The dataset can be downloaded from the link.
The license of the dataset: CC0: Public Domain
First, the necessary libraries are imported and since the data at time t is related to the previous data, from 01.01.2015 to 31.05.2019 is reserved as the training set and 31.05.2019–01.09.2020 as the test set. Dataset consists of power consumption values every 15 minutes. Dataset is converted to hourly based by summing the 4 values (0–15 min, 15 min-30 min, 30 min-45 min, 45 min-60 min). Then it is visualized as in Figure 3.
After adding years and months columns, box plots according to years and months are visualized as in Figure 4 and in Figure 5 respectively.
In this section, the dataset is rescaled and redesigned according to the neural network model using the following strategy:
24 data (1 day = 24 hours) sequentially with last_n = 24 is designed as input, 25. data is output. For example, on the basis of the index, 0–24 is input while 24. data output; 25. Data output when 1–25 is input; 26. data output when 2–26 is input, etc.
While the LSTM model is being designed, return sequence=True is set until the last LSTM layer and the model is trained. At the end of the training, the updated weights and the training and test dataset are predicted separately by the model.
The visualization result of a random part of the test dataset by rearranging the shifting caused by the selected number while creating the input-output is shown in Figure 6.
In this section, the model is built using the Dense layers to train the model with the Deep Neural Network. The same scaler method is used in the dataset and it is trained after making the shapes suitable for the model. The processes used in LSTM are configured and made suitable for the DNN model, and the prediction of a random part of the test dataset is visualized in Figure 7.
As the name suggests, Long Short Term Memory (LSTM) is based on training the model by updating the weights, taking into account the importance of long-term historical data. The DNN model, which is created using the dense layers as above, is the updating of the weights according to the activation function between the input and output on the basis of the neural network. When we roughly compare the results above (Figure 6 and Figure 7), it can be said that the two outcomes are close to reality. However, when looked in detail, it is seen that LSTM draws a more successful graph at the lower and upper peaks, especially at the lower peak points. While almost all lower peaks of the DNN results are lower than they should have been, LSTM draws a more successful and appropriate graph even though there are small upward and downward deviations.
Since LSTM is designed to take into account the importance of previous data, it performs the learning process more effectively. Therefore, while the model is being trained, DNN can make the error pattern a part of the learning process, while LSTM presents the model more flexibly at this point. As this dataset structure roughly follows a certain order (see Figure 3), the distinction between the two models can only be seen when investigated carefully. However, the difference of LSTM can be seen more clearly for datasets with higher randomness (hard to detect pattern) and time-varying datasets. | [
{
"code": null,
"e": 975,
"s": 172,
"text": "Human beings live on the time axis and design their daily life accordingly. Mostly they sleep at night and other activities are mostly done at certain times (e.g. breakfast — in the morning). When we consider language, it is known that what is spoken or written maintains and follows certain integrity of meaning. When we talk about machine learning, model training in such sequential datasets is made by using statistical methods such as ARIMA, SARIMAX, as well as using a neural network. The fundamental idea is that the data at time t is the result of several previous data points. This article explains the theoretical part of RNN — LSTM and includes a tutorial about quick exploratory data analysis of time series dataset and predicting the future power consumptions of Germany using LSTM and DNN."
},
{
"code": null,
"e": 1150,
"s": 975,
"text": "Table of Contents1. Theory1.1. Recurrent Neural Networks1.1.1. Under the Hood1.1.2. Vanishing Gradient Descent1.2. Long-Short Term Memory2. Tutorial3. Conclusion4. References"
},
{
"code": null,
"e": 2474,
"s": 1150,
"text": "In a dataset, which flows sequential, each data at time t occurs in relation to the historical data. For example, if we consider NLP, the continuation of a paragraph is shaped according to the keywords before it, that is, according to the integrity of the meaning. While reading a novel, an average of 3–4 words per second is seen and the book continues to be read fluently. Although thousands of words have been seen and read at the end of 1 hour of reading, it is difficult to repeat them by heart. However, the section read can be understood and explained easily. In machine learning, Recurrent Neural Networks can be used to extract the basic meaning & pattern from such sequential datasets. Let’s continue with different examples; movies consist of frames and these frames are in certain integrity according to the subject & content of the movie. We can easily predict the next moment or the next frame in the movie after we have understood the movie. Recurrent Neural Networks can be used to predict the future by detecting the flow pattern in sequential data. In another example, it provides time-series, that is, in time-changing graphics (stock market, spreading of coronavirus by time), to detect the flow and perform forecasting. So, how to explain mathematically what provides these possibilities using numbers?"
},
{
"code": null,
"e": 2719,
"s": 2474,
"text": "The figure below shows how the Recurrent Neural Network process works in a sequential dataset with 4 data in 4 seconds. Its basic working principle is similar to Feedforward Neural Network. The whole system can be briefly summarized as follows:"
},
{
"code": null,
"e": 3114,
"s": 2719,
"text": "The weight values assigned to the input turn into output after the layers and are compared with the real output to determine the Loss value, that is, the distance from where it should be. According to this loss value, the value of the weight is updated and the same process is repeated. The purpose of updating the weights is to minimize the loss value and determine the optimum weight value."
},
{
"code": null,
"e": 3452,
"s": 3114,
"text": "RNN, on the other hand, is designed sequentially, that is, in a backward connection to detect the connection of the data at time t with (t-1). Of course, beyond just t and (t-1), perhaps its value at time t is calculated according to the last 10 values, thanks to its backward-connected structure. Now let’s dive into Figure 1 in detail."
},
{
"code": null,
"e": 4076,
"s": 3452,
"text": "Let’s consider 4 data points (x1, x2, x3, and x4). Yellow structures represent layers. The equation of each output is depicted above. As it is seen, the output of each layer is sequentially presented as an additional input to the next layer. The final output results are based on the selected activation function. Then, the deviation of the obtained result is calculated, the weights are derived according to the loss output and updated with the backpropagation process. The RNN structure basically follows this pattern. If we take a look at the disadvantages of this RNN structure, the vanishing gradient problem meets us."
},
{
"code": null,
"e": 4178,
"s": 4076,
"text": "When it is hard to converge the global minimum point, this case is called Vanishing Gradient Descent."
},
{
"code": null,
"e": 4768,
"s": 4178,
"text": "In RNN, this process occurs when there are too many layers and the weights are updated with the Sigmoid Function. The value obtained with the Sigmoid Function should be between 0 and 1. However, in the backpropagation process, the effect of the first inputs (first a few words for NLP, first a few times for Time Series) on the system in the learning of the sequential series is minimized, since the weights update is at such a low level that when the first layers are reached. This causes these inputs and their weights to be ignored, concentrating sequential learning on the last inputs."
},
{
"code": null,
"e": 5022,
"s": 4768,
"text": "If another activation function is used instead of Sigmoid Function, such as ReLu, due to the structure of ReLu, a situation opposite to vanishing gradient descent, that is, too much change in weights so that cannot reach the global minimum point safely."
},
{
"code": null,
"e": 5293,
"s": 5022,
"text": "LSTM is designed to prevent ignoring the effect of first inputs in the sequential series during the updating of the weights. Figure 2 shows how the LSTM model avoids the problem of not considering prior data (weights of previous data) unimportant in weights adjustments."
},
{
"code": null,
"e": 5537,
"s": 5293,
"text": "Logistic (Sigmoid) activation function outputs the data between 0–1. In this way, the level of significance of the data is evaluated between 0–1. 0 becomes unimportant and is reflected as 0 in the multiplied operation. 1 means it is important."
},
{
"code": null,
"e": 5647,
"s": 5537,
"text": "Tanh activation function takes on the task of regulation by giving the value between (-1) and (+1) as output."
},
{
"code": null,
"e": 6808,
"s": 5647,
"text": "Previous cell output(h(t-1)) and current input(x(t)) are passed through the logistic(sigmoid) function. The long-term state (c(t-1)) is multiplied with the resulting value (f(t)). At this stage (forget gate), it is mathematically inferred which data is important and to what extent from the long-term states.The sigmoid value obtained in the first step is also obtained here (i(t)) with the same inputs (Previous cell output(h(t-1)) and current input(x(t)). In addition, these inputs are also passed through the tanh activation function and multiplied with the sigmoid output (g(t)). At this stage, (input gate) i(t) mathematically expresses how important the g(t) value is.Mathematical expressions (Forget Gate and Input Gate) obtained in the first two cases are added and form the new cell state (c(t)). In addition, this result is regularized by passing through tanh and multiplied by the logistic(sigmoid) function result (o(t)) of the two inputs in the first two stages (Previous cell output(h(t-1)) and current input(x(t)). Returns the short term state (h(t)). At this stage (output gate), the importance of long-term states is transferred to the system."
},
{
"code": null,
"e": 7117,
"s": 6808,
"text": "Previous cell output(h(t-1)) and current input(x(t)) are passed through the logistic(sigmoid) function. The long-term state (c(t-1)) is multiplied with the resulting value (f(t)). At this stage (forget gate), it is mathematically inferred which data is important and to what extent from the long-term states."
},
{
"code": null,
"e": 7484,
"s": 7117,
"text": "The sigmoid value obtained in the first step is also obtained here (i(t)) with the same inputs (Previous cell output(h(t-1)) and current input(x(t)). In addition, these inputs are also passed through the tanh activation function and multiplied with the sigmoid output (g(t)). At this stage, (input gate) i(t) mathematically expresses how important the g(t) value is."
},
{
"code": null,
"e": 7971,
"s": 7484,
"text": "Mathematical expressions (Forget Gate and Input Gate) obtained in the first two cases are added and form the new cell state (c(t)). In addition, this result is regularized by passing through tanh and multiplied by the logistic(sigmoid) function result (o(t)) of the two inputs in the first two stages (Previous cell output(h(t-1)) and current input(x(t)). Returns the short term state (h(t)). At this stage (output gate), the importance of long-term states is transferred to the system."
},
{
"code": null,
"e": 8099,
"s": 7971,
"text": "LSTM and configured versions of it are suitable methods for many time-based datasets, especially stock market price prediction."
},
{
"code": null,
"e": 8288,
"s": 8099,
"text": "In this tutorial, models are trained with LSTM and DNN using hourly power consumption of the Germany dataset between 01.01.2015 and 01.09.2020. The dataset can be downloaded from the link."
},
{
"code": null,
"e": 8335,
"s": 8288,
"text": "The license of the dataset: CC0: Public Domain"
},
{
"code": null,
"e": 8765,
"s": 8335,
"text": "First, the necessary libraries are imported and since the data at time t is related to the previous data, from 01.01.2015 to 31.05.2019 is reserved as the training set and 31.05.2019–01.09.2020 as the test set. Dataset consists of power consumption values every 15 minutes. Dataset is converted to hourly based by summing the 4 values (0–15 min, 15 min-30 min, 30 min-45 min, 45 min-60 min). Then it is visualized as in Figure 3."
},
{
"code": null,
"e": 8904,
"s": 8765,
"text": "After adding years and months columns, box plots according to years and months are visualized as in Figure 4 and in Figure 5 respectively."
},
{
"code": null,
"e": 9028,
"s": 8904,
"text": "In this section, the dataset is rescaled and redesigned according to the neural network model using the following strategy:"
},
{
"code": null,
"e": 9281,
"s": 9028,
"text": "24 data (1 day = 24 hours) sequentially with last_n = 24 is designed as input, 25. data is output. For example, on the basis of the index, 0–24 is input while 24. data output; 25. Data output when 1–25 is input; 26. data output when 2–26 is input, etc."
},
{
"code": null,
"e": 9522,
"s": 9281,
"text": "While the LSTM model is being designed, return sequence=True is set until the last LSTM layer and the model is trained. At the end of the training, the updated weights and the training and test dataset are predicted separately by the model."
},
{
"code": null,
"e": 9696,
"s": 9522,
"text": "The visualization result of a random part of the test dataset by rearranging the shifting caused by the selected number while creating the input-output is shown in Figure 6."
},
{
"code": null,
"e": 10078,
"s": 9696,
"text": "In this section, the model is built using the Dense layers to train the model with the Deep Neural Network. The same scaler method is used in the dataset and it is trained after making the shapes suitable for the model. The processes used in LSTM are configured and made suitable for the DNN model, and the prediction of a random part of the test dataset is visualized in Figure 7."
},
{
"code": null,
"e": 10922,
"s": 10078,
"text": "As the name suggests, Long Short Term Memory (LSTM) is based on training the model by updating the weights, taking into account the importance of long-term historical data. The DNN model, which is created using the dense layers as above, is the updating of the weights according to the activation function between the input and output on the basis of the neural network. When we roughly compare the results above (Figure 6 and Figure 7), it can be said that the two outcomes are close to reality. However, when looked in detail, it is seen that LSTM draws a more successful graph at the lower and upper peaks, especially at the lower peak points. While almost all lower peaks of the DNN results are lower than they should have been, LSTM draws a more successful and appropriate graph even though there are small upward and downward deviations."
}
]
|
A Step-By-Step Guide To Web Scraping With R | by Dario Radečić | Towards Data Science | A good dataset is difficult to find. That’s expected, but nothing to fear about. Techniques like web scraping enable us to fetch data from anywhere at any time — if you know how. Today we’ll explore just how easy it is to scrape web data with R and do so through R Shiny’s nice GUI interface.
So, what is web scraping? In a nutshell, it’s just a technique of gathering data from various websites. One might use it when:
There’s no dataset available for the needed analysis
There’s no public API available
Still, you should always check the site’s policy on web scraping, alongside with this article on Ethics in web scraping. After that, you should be able to use common sense to decide if scraping is worth it.
If it feels wrong, don’t do it.
Luckily, some websites are made entirely for practicing web scraping. One of them is books.toscrape.com, which, as the name suggests, lists made up books in various genres:
So, let’s scrape the bastard next, shall we?
Open up the webpage and click on any two categories (sidebar on the left), and inspect the URL. Here’s our pick:
http://books.toscrape.com/catalogue/category/books/travel_2/index.htmlhttp://books.toscrape.com/catalogue/category/books/mystery_3/index.html
What do these URLs have in common? Well, everything except for the bolded part. That’s the category itself. No idea what’s the deal with the numbering, but it is what it is. Every page contains a list of books, and a single book looks like this:
Our job is to grab the information for every book in a category. Doing this requires a bit of HTML knowledge, but it’s a simple markup language, so I don’t see a problem there.
We want to scrape:
Title — h3 > a > title property
Rating — p.star-rating > class attribute
Price — div.product_price > div.price_color > text
Availability — div.product_price > div.instock > text
Book URL — div.image_container > a > href property
Thumbnail URL — div.image_container > img > src property
You know everything now, so let’s start with the scraping next.
The rvest package is used in R to perform web scraping tasks. It’s very similar to dplyr, a well-known data analysis package, due to the pipe operator’s usage and the behavior in general. We know how to get to certain elements, but how to implement this logic in R?
Here’s an example of how to scrape book titles in the travel category:
library(rvest)url <- 'http://books.toscrape.com/catalogue/category/books/travel_2/index.html'titles <- read_html(url) %>% html_nodes('h3') %>% html_nodes('a') %>% html_text()
Wasn’t that easy? We can similarly scrape everything else. Here’s the script:
library(rvest)library(stringr)titles <- read_html(url) %>% html_nodes('h3') %>% html_nodes('a') %>% html_text()urls <- read_html(url) %>% html_nodes('.image_container') %>% html_nodes('a') %>% html_attr('href') %>% str_replace_all('../../../', '/')imgs <- read_html(url) %>% html_nodes('.image_container') %>% html_nodes('img') %>% html_attr('src') %>% str_replace_all('../../../../', '/')ratings <- read_html(url) %>% html_nodes('p.star-rating') %>% html_attr('class') %>% str_replace_all('star-rating ', '')prices <- read_html(url) %>% html_nodes('.product_price') %>% html_nodes('.price_color') %>% html_text()availability <- read_html(url) %>% html_nodes('.product_price') %>% html_nodes('.instock') %>% html_text() %>% str_trim()
Awesome! As a final step, let’s glue all of this together in a single Data frame:
scraped <- data.frame( Title = titles, URL = urls, SourceImage = imgs, Rating = ratings, Price = prices, Availability = availability)
You can end the article here and call it a day, but there’s something else we can build from this — a simple, easy to use web application. Let’s do that next.
R has a fantastic library for web/dashboard development — Shiny. It’s far easier to use than anything similar in Python, so we’ll stick with it. To start, create a new R file and paste the following code inside:
library(shiny)library(rvest)library(stringr)library(glue)ui <- fluidPage()server <- function(input, output) {}shinyApp(ui=ui, server=server)
It is a boilerplate every Shiny app requires. Next, let’s style the UI. We’ll need:
Title — just a big, bold text on top of everything (optional)
Sidebar — contains a dropdown menu to select a book genre
Central area — displays a table output once the data gets scraped
Here’s the code:
ui <- fluidPage( column(12, tags$h2('Real-time web scraper with R')), sidebarPanel( width=3, selectInput( inputId='genreSelect', label='Genre', choices=c('Business', 'Classics', 'Fiction', 'Horror', 'Music'), selected='Business', ) ), mainPanel( width=9, tableOutput('table') ))
Next, we need to configure the server function. It has to remap our nicely formatted inputs to an URL portion (e.g., ‘Business’ to ‘business_35’) and scrape data for the selected genre. We already know how to do so. Here’s the code for the server function:
server <- function(input, output) { output$table <- renderTable({ mappings <- c('Business' = 'business_35', 'Classics' = 'classics_6', 'Fiction' = 'fiction_10', 'Horror' = 'horror_31', 'Music' = 'music_14') url <- glue('http://books.toscrape.com/catalogue/category/books/', mappings[input$genreSelect], '/index.html') titles <- read_html(url) %>% html_nodes('h3') %>% html_nodes('a') %>% html_text() urls <- read_html(url) %>% html_nodes('.image_container') %>% html_nodes('a') %>% html_attr('href') %>% str_replace_all('../../../', '/') imgs <- read_html(url) %>% html_nodes('.image_container') %>% html_nodes('img') %>% html_attr('src') %>% str_replace_all('../../../../', '/') ratings <- read_html(url) %>% html_nodes('p.star-rating') %>% html_attr('class') %>% str_replace_all('star-rating ', '') prices <- read_html(url) %>% html_nodes('.product_price') %>% html_nodes('.price_color') %>% html_text() availability <- read_html(url) %>% html_nodes('.product_price') %>% html_nodes('.instock') %>% html_text() %>% str_trim() data.frame( Title = titles, URL = urls, SourceImage = imgs, Rating = ratings, Price = prices, Availability = availability ) })}
And that’s it — we can run the app now and inspect the behavior!
Just what we wanted — simple, but still entirely understandable. Let’s wrap things up in the next section.
In only a couple of minutes, we went from zero to a working web scraping application. Options to scale this are endless — add more categories, work on the visuals, include more data, format data more nicely, add filters, etc.
I hope you’ve managed to follow and that you’re able to see the power of web scraping. This was a dummy website and a dummy example, but the approach stays the same irrelevant to the data source.
Thanks for reading.
Join my private email list for more helpful insights.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Originally published at https://betterdatascience.com on October 19, 2020. | [
{
"code": null,
"e": 465,
"s": 172,
"text": "A good dataset is difficult to find. That’s expected, but nothing to fear about. Techniques like web scraping enable us to fetch data from anywhere at any time — if you know how. Today we’ll explore just how easy it is to scrape web data with R and do so through R Shiny’s nice GUI interface."
},
{
"code": null,
"e": 592,
"s": 465,
"text": "So, what is web scraping? In a nutshell, it’s just a technique of gathering data from various websites. One might use it when:"
},
{
"code": null,
"e": 645,
"s": 592,
"text": "There’s no dataset available for the needed analysis"
},
{
"code": null,
"e": 677,
"s": 645,
"text": "There’s no public API available"
},
{
"code": null,
"e": 884,
"s": 677,
"text": "Still, you should always check the site’s policy on web scraping, alongside with this article on Ethics in web scraping. After that, you should be able to use common sense to decide if scraping is worth it."
},
{
"code": null,
"e": 916,
"s": 884,
"text": "If it feels wrong, don’t do it."
},
{
"code": null,
"e": 1089,
"s": 916,
"text": "Luckily, some websites are made entirely for practicing web scraping. One of them is books.toscrape.com, which, as the name suggests, lists made up books in various genres:"
},
{
"code": null,
"e": 1134,
"s": 1089,
"text": "So, let’s scrape the bastard next, shall we?"
},
{
"code": null,
"e": 1247,
"s": 1134,
"text": "Open up the webpage and click on any two categories (sidebar on the left), and inspect the URL. Here’s our pick:"
},
{
"code": null,
"e": 1389,
"s": 1247,
"text": "http://books.toscrape.com/catalogue/category/books/travel_2/index.htmlhttp://books.toscrape.com/catalogue/category/books/mystery_3/index.html"
},
{
"code": null,
"e": 1635,
"s": 1389,
"text": "What do these URLs have in common? Well, everything except for the bolded part. That’s the category itself. No idea what’s the deal with the numbering, but it is what it is. Every page contains a list of books, and a single book looks like this:"
},
{
"code": null,
"e": 1812,
"s": 1635,
"text": "Our job is to grab the information for every book in a category. Doing this requires a bit of HTML knowledge, but it’s a simple markup language, so I don’t see a problem there."
},
{
"code": null,
"e": 1831,
"s": 1812,
"text": "We want to scrape:"
},
{
"code": null,
"e": 1863,
"s": 1831,
"text": "Title — h3 > a > title property"
},
{
"code": null,
"e": 1904,
"s": 1863,
"text": "Rating — p.star-rating > class attribute"
},
{
"code": null,
"e": 1955,
"s": 1904,
"text": "Price — div.product_price > div.price_color > text"
},
{
"code": null,
"e": 2009,
"s": 1955,
"text": "Availability — div.product_price > div.instock > text"
},
{
"code": null,
"e": 2060,
"s": 2009,
"text": "Book URL — div.image_container > a > href property"
},
{
"code": null,
"e": 2117,
"s": 2060,
"text": "Thumbnail URL — div.image_container > img > src property"
},
{
"code": null,
"e": 2181,
"s": 2117,
"text": "You know everything now, so let’s start with the scraping next."
},
{
"code": null,
"e": 2447,
"s": 2181,
"text": "The rvest package is used in R to perform web scraping tasks. It’s very similar to dplyr, a well-known data analysis package, due to the pipe operator’s usage and the behavior in general. We know how to get to certain elements, but how to implement this logic in R?"
},
{
"code": null,
"e": 2518,
"s": 2447,
"text": "Here’s an example of how to scrape book titles in the travel category:"
},
{
"code": null,
"e": 2698,
"s": 2518,
"text": "library(rvest)url <- 'http://books.toscrape.com/catalogue/category/books/travel_2/index.html'titles <- read_html(url) %>% html_nodes('h3') %>% html_nodes('a') %>% html_text()"
},
{
"code": null,
"e": 2776,
"s": 2698,
"text": "Wasn’t that easy? We can similarly scrape everything else. Here’s the script:"
},
{
"code": null,
"e": 3548,
"s": 2776,
"text": "library(rvest)library(stringr)titles <- read_html(url) %>% html_nodes('h3') %>% html_nodes('a') %>% html_text()urls <- read_html(url) %>% html_nodes('.image_container') %>% html_nodes('a') %>% html_attr('href') %>% str_replace_all('../../../', '/')imgs <- read_html(url) %>% html_nodes('.image_container') %>% html_nodes('img') %>% html_attr('src') %>% str_replace_all('../../../../', '/')ratings <- read_html(url) %>% html_nodes('p.star-rating') %>% html_attr('class') %>% str_replace_all('star-rating ', '')prices <- read_html(url) %>% html_nodes('.product_price') %>% html_nodes('.price_color') %>% html_text()availability <- read_html(url) %>% html_nodes('.product_price') %>% html_nodes('.instock') %>% html_text() %>% str_trim()"
},
{
"code": null,
"e": 3630,
"s": 3548,
"text": "Awesome! As a final step, let’s glue all of this together in a single Data frame:"
},
{
"code": null,
"e": 3775,
"s": 3630,
"text": "scraped <- data.frame( Title = titles, URL = urls, SourceImage = imgs, Rating = ratings, Price = prices, Availability = availability)"
},
{
"code": null,
"e": 3934,
"s": 3775,
"text": "You can end the article here and call it a day, but there’s something else we can build from this — a simple, easy to use web application. Let’s do that next."
},
{
"code": null,
"e": 4146,
"s": 3934,
"text": "R has a fantastic library for web/dashboard development — Shiny. It’s far easier to use than anything similar in Python, so we’ll stick with it. To start, create a new R file and paste the following code inside:"
},
{
"code": null,
"e": 4287,
"s": 4146,
"text": "library(shiny)library(rvest)library(stringr)library(glue)ui <- fluidPage()server <- function(input, output) {}shinyApp(ui=ui, server=server)"
},
{
"code": null,
"e": 4371,
"s": 4287,
"text": "It is a boilerplate every Shiny app requires. Next, let’s style the UI. We’ll need:"
},
{
"code": null,
"e": 4433,
"s": 4371,
"text": "Title — just a big, bold text on top of everything (optional)"
},
{
"code": null,
"e": 4491,
"s": 4433,
"text": "Sidebar — contains a dropdown menu to select a book genre"
},
{
"code": null,
"e": 4557,
"s": 4491,
"text": "Central area — displays a table output once the data gets scraped"
},
{
"code": null,
"e": 4574,
"s": 4557,
"text": "Here’s the code:"
},
{
"code": null,
"e": 4893,
"s": 4574,
"text": "ui <- fluidPage( column(12, tags$h2('Real-time web scraper with R')), sidebarPanel( width=3, selectInput( inputId='genreSelect', label='Genre', choices=c('Business', 'Classics', 'Fiction', 'Horror', 'Music'), selected='Business', ) ), mainPanel( width=9, tableOutput('table') ))"
},
{
"code": null,
"e": 5150,
"s": 4893,
"text": "Next, we need to configure the server function. It has to remap our nicely formatted inputs to an URL portion (e.g., ‘Business’ to ‘business_35’) and scrape data for the selected genre. We already know how to do so. Here’s the code for the server function:"
},
{
"code": null,
"e": 6544,
"s": 5150,
"text": "server <- function(input, output) { output$table <- renderTable({ mappings <- c('Business' = 'business_35', 'Classics' = 'classics_6', 'Fiction' = 'fiction_10', 'Horror' = 'horror_31', 'Music' = 'music_14') url <- glue('http://books.toscrape.com/catalogue/category/books/', mappings[input$genreSelect], '/index.html') titles <- read_html(url) %>% html_nodes('h3') %>% html_nodes('a') %>% html_text() urls <- read_html(url) %>% html_nodes('.image_container') %>% html_nodes('a') %>% html_attr('href') %>% str_replace_all('../../../', '/') imgs <- read_html(url) %>% html_nodes('.image_container') %>% html_nodes('img') %>% html_attr('src') %>% str_replace_all('../../../../', '/') ratings <- read_html(url) %>% html_nodes('p.star-rating') %>% html_attr('class') %>% str_replace_all('star-rating ', '') prices <- read_html(url) %>% html_nodes('.product_price') %>% html_nodes('.price_color') %>% html_text() availability <- read_html(url) %>% html_nodes('.product_price') %>% html_nodes('.instock') %>% html_text() %>% str_trim() data.frame( Title = titles, URL = urls, SourceImage = imgs, Rating = ratings, Price = prices, Availability = availability ) })}"
},
{
"code": null,
"e": 6609,
"s": 6544,
"text": "And that’s it — we can run the app now and inspect the behavior!"
},
{
"code": null,
"e": 6716,
"s": 6609,
"text": "Just what we wanted — simple, but still entirely understandable. Let’s wrap things up in the next section."
},
{
"code": null,
"e": 6942,
"s": 6716,
"text": "In only a couple of minutes, we went from zero to a working web scraping application. Options to scale this are endless — add more categories, work on the visuals, include more data, format data more nicely, add filters, etc."
},
{
"code": null,
"e": 7138,
"s": 6942,
"text": "I hope you’ve managed to follow and that you’re able to see the power of web scraping. This was a dummy website and a dummy example, but the approach stays the same irrelevant to the data source."
},
{
"code": null,
"e": 7158,
"s": 7138,
"text": "Thanks for reading."
},
{
"code": null,
"e": 7212,
"s": 7158,
"text": "Join my private email list for more helpful insights."
},
{
"code": null,
"e": 7395,
"s": 7212,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 7406,
"s": 7395,
"text": "medium.com"
}
]
|
\bigstar - Tex Command | \bigstar - Used to draw big star symbol.
{ \bigstar }
\bigstar command draws big star symbol.
\bigstar
★
\bigstar
★
\bigstar
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8027,
"s": 7986,
"text": "\\bigstar - Used to draw big star symbol."
},
{
"code": null,
"e": 8040,
"s": 8027,
"text": "{ \\bigstar }"
},
{
"code": null,
"e": 8080,
"s": 8040,
"text": "\\bigstar command draws big star symbol."
},
{
"code": null,
"e": 8097,
"s": 8080,
"text": "\n\\bigstar \n\n★\n\n\n"
},
{
"code": null,
"e": 8112,
"s": 8097,
"text": "\\bigstar \n\n★\n\n"
},
{
"code": null,
"e": 8122,
"s": 8112,
"text": "\\bigstar "
},
{
"code": null,
"e": 8154,
"s": 8122,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8167,
"s": 8154,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8200,
"s": 8167,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8213,
"s": 8200,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8245,
"s": 8213,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8281,
"s": 8245,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8316,
"s": 8281,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8333,
"s": 8316,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8366,
"s": 8333,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8380,
"s": 8366,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8412,
"s": 8380,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8427,
"s": 8412,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8434,
"s": 8427,
"text": " Print"
},
{
"code": null,
"e": 8445,
"s": 8434,
"text": " Add Notes"
}
]
|
Try, catch, throw and throws in Java | 09 Jun, 2022
What is an Exception?
An exception is an “unwanted or unexpected event”, which occurs during the execution of the program i.e, at run-time, that disrupts the normal flow of the program’s instructions. When an exception occurs, the execution of the program gets terminated.
Why does an Exception occur?
An exception can occur due to several reasons like a Network connection problem, Bad input provided by a user, Opening a non-existing file in your program, etc
Blocks & Keywords used for exception handling
1. try: The try block contains a set of statements where an exception can occur.
try
{
// statement(s) that might cause exception
}
2. catch: The catch block is used to handle the uncertain condition of a try block. A try block is always followed by a catch block, which handles the exception that occurs in the associated try block.
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
3. throw: The throw keyword is used to transfer control from the try block to the catch block.
4. throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.
5. finally: It is executed after the catch block. We use it to put some common code (to be executed irrespective of whether an exception has occurred or not ) when there are multiple catch blocks.
Example of an exception generated by the system is given below :
Exception in thread "main"
java.lang.ArithmeticException: divide
by zero at ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo: The class name
main:The method name
ExceptionDemo.java:The file name
java:5:line number
Java
// Java program to demonstrate working of try,// catch and finally class Division { public static void main(String[] args) { int a = 10, b = 5, c = 5, result; try { result = a / (b - c); System.out.println("result" + result); } catch (ArithmeticException e) { System.out.println("Exception caught:Division by zero"); } finally { System.out.println("I am in final block"); } }}
Exception caught:Division by zero
I am in final block
An example of throws keyword:
Java
// Java program to demonstrate working of throwsclass ThrowsExecp { // This method throws an exception // to be handled // by caller or caller // of caller and so on. static void fun() throws IllegalAccessException { System.out.println("Inside fun(). "); throw new IllegalAccessException("demo"); } // This is a caller function public static void main(String args[]) { try { fun(); } catch (IllegalAccessException e) { System.out.println("caught in main."); } }}
Inside fun().
caught in main.
lauramakare00
sumathi_123
Java-Exception Handling
Java-Exceptions
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 75,
"s": 52,
"text": "What is an Exception? "
},
{
"code": null,
"e": 327,
"s": 75,
"text": "An exception is an “unwanted or unexpected event”, which occurs during the execution of the program i.e, at run-time, that disrupts the normal flow of the program’s instructions. When an exception occurs, the execution of the program gets terminated. "
},
{
"code": null,
"e": 357,
"s": 327,
"text": "Why does an Exception occur? "
},
{
"code": null,
"e": 518,
"s": 357,
"text": "An exception can occur due to several reasons like a Network connection problem, Bad input provided by a user, Opening a non-existing file in your program, etc "
},
{
"code": null,
"e": 565,
"s": 518,
"text": "Blocks & Keywords used for exception handling "
},
{
"code": null,
"e": 646,
"s": 565,
"text": "1. try: The try block contains a set of statements where an exception can occur."
},
{
"code": null,
"e": 701,
"s": 646,
"text": "try\n{\n // statement(s) that might cause exception\n}"
},
{
"code": null,
"e": 903,
"s": 701,
"text": "2. catch: The catch block is used to handle the uncertain condition of a try block. A try block is always followed by a catch block, which handles the exception that occurs in the associated try block."
},
{
"code": null,
"e": 1078,
"s": 903,
"text": "catch\n{\n // statement(s) that handle an exception\n // examples, closing a connection, closing\n // file, exiting the process after writing\n // details to a log file.\n}"
},
{
"code": null,
"e": 1174,
"s": 1078,
"text": "3. throw: The throw keyword is used to transfer control from the try block to the catch block. "
},
{
"code": null,
"e": 1357,
"s": 1174,
"text": "4. throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself. "
},
{
"code": null,
"e": 1555,
"s": 1357,
"text": "5. finally: It is executed after the catch block. We use it to put some common code (to be executed irrespective of whether an exception has occurred or not ) when there are multiple catch blocks. "
},
{
"code": null,
"e": 1620,
"s": 1555,
"text": "Example of an exception generated by the system is given below :"
},
{
"code": null,
"e": 1843,
"s": 1620,
"text": "Exception in thread \"main\" \njava.lang.ArithmeticException: divide \nby zero at ExceptionDemo.main(ExceptionDemo.java:5)\nExceptionDemo: The class name\nmain:The method name \nExceptionDemo.java:The file name\njava:5:line number"
},
{
"code": null,
"e": 1848,
"s": 1843,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of try,// catch and finally class Division { public static void main(String[] args) { int a = 10, b = 5, c = 5, result; try { result = a / (b - c); System.out.println(\"result\" + result); } catch (ArithmeticException e) { System.out.println(\"Exception caught:Division by zero\"); } finally { System.out.println(\"I am in final block\"); } }}",
"e": 2329,
"s": 1848,
"text": null
},
{
"code": null,
"e": 2383,
"s": 2329,
"text": "Exception caught:Division by zero\nI am in final block"
},
{
"code": null,
"e": 2414,
"s": 2383,
"text": "An example of throws keyword: "
},
{
"code": null,
"e": 2419,
"s": 2414,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of throwsclass ThrowsExecp { // This method throws an exception // to be handled // by caller or caller // of caller and so on. static void fun() throws IllegalAccessException { System.out.println(\"Inside fun(). \"); throw new IllegalAccessException(\"demo\"); } // This is a caller function public static void main(String args[]) { try { fun(); } catch (IllegalAccessException e) { System.out.println(\"caught in main.\"); } }}",
"e": 2981,
"s": 2419,
"text": null
},
{
"code": null,
"e": 3012,
"s": 2981,
"text": "Inside fun(). \ncaught in main."
},
{
"code": null,
"e": 3026,
"s": 3012,
"text": "lauramakare00"
},
{
"code": null,
"e": 3038,
"s": 3026,
"text": "sumathi_123"
},
{
"code": null,
"e": 3062,
"s": 3038,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 3078,
"s": 3062,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 3083,
"s": 3078,
"text": "Java"
},
{
"code": null,
"e": 3102,
"s": 3083,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3107,
"s": 3102,
"text": "Java"
}
]
|
Python | Pandas Series.dt.to_pydatetime | 20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.to_pydatetime() function return the data as an array of native Python datetime objects. Timezone information is retained if present.
Syntax: Series.dt.to_pydatetime()
Parameter : None
Returns : numpy.ndarray
Example #1: Use Series.dt.to_pydatetime() function to return the given series object as an array of native python datetime object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)
Output :
Now we will use Series.dt.to_pydatetime() function to return the data as an array of native Python datetime objects.
# return the series data as a # native python datetime dataresult = sr.dt.to_pydatetime() # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.to_pydatetime() function has successfully returned the underlying data of the given series object as an array of native python datetime data.
Example #2 : Use Series.dt.to_pydatetime() function to return the given series object as an array of native python datetime object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 00:00', periods = 5, freq = 'D', tz = 'US / Central')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.dt.to_pydatetime() function to return the data as an array of native Python datetime objects.
# return the series data as a # native python datetime dataresult = sr.dt.to_pydatetime() # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.to_pydatetime() function has successfully returned the underlying data of the given series object as an array of native python datetime data.
Python pandas-series-datetime
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
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
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 282,
"s": 28,
"text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.to_pydatetime() function return the data as an array of native Python datetime objects. Timezone information is retained if present."
},
{
"code": null,
"e": 316,
"s": 282,
"text": "Syntax: Series.dt.to_pydatetime()"
},
{
"code": null,
"e": 333,
"s": 316,
"text": "Parameter : None"
},
{
"code": null,
"e": 357,
"s": 333,
"text": "Returns : numpy.ndarray"
},
{
"code": null,
"e": 488,
"s": 357,
"text": "Example #1: Use Series.dt.to_pydatetime() function to return the given series object as an array of native python datetime object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)",
"e": 874,
"s": 488,
"text": null
},
{
"code": null,
"e": 883,
"s": 874,
"text": "Output :"
},
{
"code": null,
"e": 1000,
"s": 883,
"text": "Now we will use Series.dt.to_pydatetime() function to return the data as an array of native Python datetime objects."
},
{
"code": "# return the series data as a # native python datetime dataresult = sr.dt.to_pydatetime() # print the resultprint(result)",
"e": 1124,
"s": 1000,
"text": null
},
{
"code": null,
"e": 1133,
"s": 1124,
"text": "Output :"
},
{
"code": null,
"e": 1318,
"s": 1133,
"text": "As we can see in the output, the Series.dt.to_pydatetime() function has successfully returned the underlying data of the given series object as an array of native python datetime data."
},
{
"code": null,
"e": 1450,
"s": 1318,
"text": "Example #2 : Use Series.dt.to_pydatetime() function to return the given series object as an array of native python datetime object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 00:00', periods = 5, freq = 'D', tz = 'US / Central')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 1772,
"s": 1450,
"text": null
},
{
"code": null,
"e": 1781,
"s": 1772,
"text": "Output :"
},
{
"code": null,
"e": 1898,
"s": 1781,
"text": "Now we will use Series.dt.to_pydatetime() function to return the data as an array of native Python datetime objects."
},
{
"code": "# return the series data as a # native python datetime dataresult = sr.dt.to_pydatetime() # print the resultprint(result)",
"e": 2022,
"s": 1898,
"text": null
},
{
"code": null,
"e": 2031,
"s": 2022,
"text": "Output :"
},
{
"code": null,
"e": 2216,
"s": 2031,
"text": "As we can see in the output, the Series.dt.to_pydatetime() function has successfully returned the underlying data of the given series object as an array of native python datetime data."
},
{
"code": null,
"e": 2246,
"s": 2216,
"text": "Python pandas-series-datetime"
},
{
"code": null,
"e": 2260,
"s": 2246,
"text": "Python-pandas"
},
{
"code": null,
"e": 2267,
"s": 2260,
"text": "Python"
},
{
"code": null,
"e": 2365,
"s": 2267,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2383,
"s": 2365,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2425,
"s": 2383,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2460,
"s": 2425,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2486,
"s": 2460,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2518,
"s": 2486,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2547,
"s": 2518,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2574,
"s": 2547,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2595,
"s": 2574,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2618,
"s": 2595,
"text": "Introduction To PYTHON"
}
]
|
Wavelet Trees | Introduction | 11 Jun, 2021
A wavelet tree is a data structure that recursively partitions a stream into two parts until we’re left with homogeneous data. The name derives from an analogy with the wavelet transform for signals, which recursively decomposes a signal into low-frequency and high-frequency components. Wavelet trees can be used to answer range queries efficiently.Consider the problem to find number of elements in a range [L, R] of a given array A which are less than x. One way to solve this problem efficiently is using Persistent Segment Tree data structure. But we can also solve this easily using Wavelet Trees. Let us see how!
Constructing Wavelet Trees
Every node in a wavelet tree is represented by an array which is the subsequence of original array and a range [L, R]. Here [L, R] is the range in which elements of array falls. That is, ‘R’ denotes maximum element in the array and ‘L’ denotes the smallest element. So, the root node will contain the original array in which elements are in range [L, R]. Now we will calculate the middle of the range [L, R] and stable partition the array in two halfs for the left and right childs. Therefore, the left child will contains elements that lies in range [L, mid] and right child will contain elements that lies in the range [mid+1, R]. Suppose we are given an array of integers. Now we compute the mid (Max + Min / 2) and form two children. Left Children: Integers less than/equal to Mid Right Children: Integers greater than Mid We recursively perform this operation until all node of similar elements are formed.Given array : 0 0 9 1 2 1 7 6 4 8 9 4 3 7 5 9 2 7 0 5 1 0
To construct a Wavelet Tree, let us see what will we need to store at each node. So at each node of the tree, we will store two arrays say S[] and freq[]. The array S[] will be a subsequence of the original array A[] and the array freq[] will store the count of the elements that will go to left and right childs of the node. That is, freq[i] will denote the count of elements from the first i elements of S[] that will go to left child. Therefore, count of elements that will go to right child can be easily calculated as (i – freq[i]).Below example shows how to maintain freq[] array:
Array : 1 5 2 6 4 4
Mid = (1 + 6) / 2 = 3
Left Child : 1 2
Right Child : 5 6 4 4
To maintain frequency array, we will check if the element is less than Mid or not. If yes, then we will add 1 to last element of frequency array, else 0 and push back again.For, above array : Freq array :{1, 1, 2, 2, 2, 2}It implies 1 element will go to left child of this node from index 1 and 2, and 2 elements will go to left child from indices 3 to 6. This can be easily depicted from the above given array. To compute the number of elements moving to right subtree, we subtract freq[i] from i.
From index 1, 0 elements go to right subtree.
From index 2, 1 element go to right subtree.
From index 3, 1 element go to right subtree.
From index 4, 2 elements go to right subtree.
From index 5, 3 elements go to right subtree.
From index 6, 4 elements go to right subtree.
We can use the stable_partition function and lambda expression in C++ STL to easily stable partition the array around a pivot without distorting the order of elements in original sequence. It is highly recommended to go through the stable_partition and lambda expression articles before moving onto implementation. Below is the implementation of construction of Wavelet Trees:
CPP
// CPP code to implement wavelet trees#include <bits/stdc++.h>using namespace std;#define N 100000 // Given arrayint arr[N]; // wavelet tree classclass wavelet_tree {public: // Range to elements int low, high; // Left and Right children wavelet_tree* l, *r; vector<int> freq; // Default constructor // Array is in range [x, y] // Indices are in range [from, to] wavelet_tree(int* from, int* to, int x, int y) { // Initialising low and high low = x, high = y; // Array is of 0 length if (from >= to) return; // Array is homogeneous // Example : 1 1 1 1 1 if (high == low) { // Assigning storage to freq array freq.reserve(to - from + 1); // Initialising the Freq array freq.push_back(0); // Assigning values for (auto it = from; it != to; it++) // freq will be increasing as there'll // be no further sub-tree freq.push_back(freq.back() + 1); return; } // Computing mid int mid = (low + high) / 2; // Lambda function to check if a number is // less than or equal to mid auto lessThanMid = [mid](int x) { return x <= mid; }; // Assigning storage to freq array freq.reserve(to - from + 1); // Initialising the freq array freq.push_back(0); // Assigning value to freq array for (auto it = from; it != to; it++) // If lessThanMid returns 1(true), we add // 1 to previous entry. Otherwise, we add // 0 (element goes to right sub-tree) freq.push_back(freq.back() + lessThanMid(*it)); // std::stable_partition partitions the array w.r.t Mid auto pivot = stable_partition(from, to, lessThanMid); // Left sub-tree's object l = new wavelet_tree(from, pivot, low, mid); // Right sub-tree's object r = new wavelet_tree(pivot, to, mid + 1, high); }}; // Driver codeint main(){ int size = 5, high = INT_MIN; int arr[] = {1 , 2, 3, 4, 5}; for (int i = 0; i < size; i++) high = max(high, arr[i]); // Object of class wavelet tree wavelet_tree obj(arr, arr + size, 1, high); return 0;}
Height of the tree: O(log(max(A)) , where max(A) is the maximum element in the array A[].
Querying in Wavelet Trees
We have already constructed our wavelet tree for the given array. Now we will move on to our problem to calculate number of elements less than or equal to x in range [ L,R ] in the given array. So, for each node we have a subsequence of original array, lowest and highest values present in the array and count of elements in left and right child.Now,
If high <= x,
we return R - L + 1.
i.e. all the elements in the current range is less than x.
Otherwise, We will use variable LtCount = freq[ L-1 ] (i.e. elements going to left sub-tree from L-1) , RtCount = freq[ R ] (i.e. elements going to right sub-tree from R) Now, we recursively call and add the return values of :
left sub-tree with range[ LtCount + 1, RtCount ] and,
right sub-tree with range[ L - Ltcount,R - RtCount ]
Below is the implementation in C++:
CPP
// CPP program for querying in// wavelet tree Data Structure#include <bits/stdc++.h>using namespace std;#define N 100000 // Given Arrayint arr[N]; // wavelet tree classclass wavelet_tree {public: // Range to elements int low, high; // Left and Right child wavelet_tree* l, *r; vector<int> freq; // Default constructor // Array is in range [x, y] // Indices are in range [from, to] wavelet_tree(int* from, int* to, int x, int y) { // Initialising low and high low = x, high = y; // Array is of 0 length if (from >= to) return; // Array is homogeneous // Example : 1 1 1 1 1 if (high == low) { // Assigning storage to freq array freq.reserve(to - from + 1); // Initialising the Freq array freq.push_back(0); // Assigning values for (auto it = from; it != to; it++) // freq will be increasing as there'll // be no further sub-tree freq.push_back(freq.back() + 1); return; } // Computing mid int mid = (low + high) / 2; // Lambda function to check if a number // is less than or equal to mid auto lessThanMid = [mid](int x) { return x <= mid; }; // Assigning storage to freq array freq.reserve(to - from + 1); // Initialising the freq array freq.push_back(0); // Assigning value to freq array for (auto it = from; it != to; it++) // If lessThanMid returns 1(true), we add // 1 to previous entry. Otherwise, we add 0 // (element goes to right sub-tree) freq.push_back(freq.back() + lessThanMid(*it)); // std::stable_partition partitions the array w.r.t Mid auto pivot = stable_partition(from, to, lessThanMid); // Left sub-tree's object l = new wavelet_tree(from, pivot, low, mid); // Right sub-tree's object r = new wavelet_tree(pivot, to, mid + 1, high); } // Count of numbers in range[L..R] less than // or equal to k int kOrLess(int l, int r, int k) { // No elements int range is less than k if (l > r or k < low) return 0; // All elements in the range are less than k if (high <= k) return r - l + 1; // Computing LtCount and RtCount int LtCount = freq[l - 1]; int RtCount = freq[r]; // Answer is (no. of element <= k) in // left + (those <= k) in right return (this->l->kOrLess(LtCount + 1, RtCount, k) + this->r->kOrLess(l - LtCount, r - RtCount, k)); } }; // Driver codeint main(){ int size = 5, high = INT_MIN; int arr[] = {1, 2, 3, 4, 5}; // Array : 1 2 3 4 5 for (int i = 0; i < size; i++) high = max(high, arr[i]); // Object of class wavelet tree wavelet_tree obj(arr, arr + size, 1, high); // count of elements less than 2 in range [1,3] cout << obj.kOrLess(0, 3, 2) << '\n'; return 0;}
Output :
2
Time Complexity: O(log(max(A)) , where max(A) is the maximum element in the array A[]. In this post we have discussed about a single problem on range queries without update. In further we will be discussing on range updates also.References :
https://users.dcc.uchile.cl/~jperez/papers/ioiconf16.pdf
https://en.wikipedia.org/wiki/Wavelet_Tree
https://www.youtube.com/watch?v=K7tju9j7UWU
This article is contributed by Rohit Thapliyal. 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.
ruhelaa48
Advanced Data Structure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 673,
"s": 52,
"text": "A wavelet tree is a data structure that recursively partitions a stream into two parts until we’re left with homogeneous data. The name derives from an analogy with the wavelet transform for signals, which recursively decomposes a signal into low-frequency and high-frequency components. Wavelet trees can be used to answer range queries efficiently.Consider the problem to find number of elements in a range [L, R] of a given array A which are less than x. One way to solve this problem efficiently is using Persistent Segment Tree data structure. But we can also solve this easily using Wavelet Trees. Let us see how! "
},
{
"code": null,
"e": 700,
"s": 673,
"text": "Constructing Wavelet Trees"
},
{
"code": null,
"e": 1671,
"s": 700,
"text": "Every node in a wavelet tree is represented by an array which is the subsequence of original array and a range [L, R]. Here [L, R] is the range in which elements of array falls. That is, ‘R’ denotes maximum element in the array and ‘L’ denotes the smallest element. So, the root node will contain the original array in which elements are in range [L, R]. Now we will calculate the middle of the range [L, R] and stable partition the array in two halfs for the left and right childs. Therefore, the left child will contains elements that lies in range [L, mid] and right child will contain elements that lies in the range [mid+1, R]. Suppose we are given an array of integers. Now we compute the mid (Max + Min / 2) and form two children. Left Children: Integers less than/equal to Mid Right Children: Integers greater than Mid We recursively perform this operation until all node of similar elements are formed.Given array : 0 0 9 1 2 1 7 6 4 8 9 4 3 7 5 9 2 7 0 5 1 0 "
},
{
"code": null,
"e": 2260,
"s": 1671,
"text": "To construct a Wavelet Tree, let us see what will we need to store at each node. So at each node of the tree, we will store two arrays say S[] and freq[]. The array S[] will be a subsequence of the original array A[] and the array freq[] will store the count of the elements that will go to left and right childs of the node. That is, freq[i] will denote the count of elements from the first i elements of S[] that will go to left child. Therefore, count of elements that will go to right child can be easily calculated as (i – freq[i]).Below example shows how to maintain freq[] array: "
},
{
"code": null,
"e": 2341,
"s": 2260,
"text": "Array : 1 5 2 6 4 4\nMid = (1 + 6) / 2 = 3\nLeft Child : 1 2\nRight Child : 5 6 4 4"
},
{
"code": null,
"e": 2842,
"s": 2341,
"text": "To maintain frequency array, we will check if the element is less than Mid or not. If yes, then we will add 1 to last element of frequency array, else 0 and push back again.For, above array : Freq array :{1, 1, 2, 2, 2, 2}It implies 1 element will go to left child of this node from index 1 and 2, and 2 elements will go to left child from indices 3 to 6. This can be easily depicted from the above given array. To compute the number of elements moving to right subtree, we subtract freq[i] from i. "
},
{
"code": null,
"e": 3116,
"s": 2842,
"text": "From index 1, 0 elements go to right subtree.\nFrom index 2, 1 element go to right subtree.\nFrom index 3, 1 element go to right subtree.\nFrom index 4, 2 elements go to right subtree.\nFrom index 5, 3 elements go to right subtree.\nFrom index 6, 4 elements go to right subtree."
},
{
"code": null,
"e": 3495,
"s": 3116,
"text": "We can use the stable_partition function and lambda expression in C++ STL to easily stable partition the array around a pivot without distorting the order of elements in original sequence. It is highly recommended to go through the stable_partition and lambda expression articles before moving onto implementation. Below is the implementation of construction of Wavelet Trees: "
},
{
"code": null,
"e": 3499,
"s": 3495,
"text": "CPP"
},
{
"code": "// CPP code to implement wavelet trees#include <bits/stdc++.h>using namespace std;#define N 100000 // Given arrayint arr[N]; // wavelet tree classclass wavelet_tree {public: // Range to elements int low, high; // Left and Right children wavelet_tree* l, *r; vector<int> freq; // Default constructor // Array is in range [x, y] // Indices are in range [from, to] wavelet_tree(int* from, int* to, int x, int y) { // Initialising low and high low = x, high = y; // Array is of 0 length if (from >= to) return; // Array is homogeneous // Example : 1 1 1 1 1 if (high == low) { // Assigning storage to freq array freq.reserve(to - from + 1); // Initialising the Freq array freq.push_back(0); // Assigning values for (auto it = from; it != to; it++) // freq will be increasing as there'll // be no further sub-tree freq.push_back(freq.back() + 1); return; } // Computing mid int mid = (low + high) / 2; // Lambda function to check if a number is // less than or equal to mid auto lessThanMid = [mid](int x) { return x <= mid; }; // Assigning storage to freq array freq.reserve(to - from + 1); // Initialising the freq array freq.push_back(0); // Assigning value to freq array for (auto it = from; it != to; it++) // If lessThanMid returns 1(true), we add // 1 to previous entry. Otherwise, we add // 0 (element goes to right sub-tree) freq.push_back(freq.back() + lessThanMid(*it)); // std::stable_partition partitions the array w.r.t Mid auto pivot = stable_partition(from, to, lessThanMid); // Left sub-tree's object l = new wavelet_tree(from, pivot, low, mid); // Right sub-tree's object r = new wavelet_tree(pivot, to, mid + 1, high); }}; // Driver codeint main(){ int size = 5, high = INT_MIN; int arr[] = {1 , 2, 3, 4, 5}; for (int i = 0; i < size; i++) high = max(high, arr[i]); // Object of class wavelet tree wavelet_tree obj(arr, arr + size, 1, high); return 0;}",
"e": 5834,
"s": 3499,
"text": null
},
{
"code": null,
"e": 5925,
"s": 5834,
"text": "Height of the tree: O(log(max(A)) , where max(A) is the maximum element in the array A[]. "
},
{
"code": null,
"e": 5951,
"s": 5925,
"text": "Querying in Wavelet Trees"
},
{
"code": null,
"e": 6304,
"s": 5951,
"text": "We have already constructed our wavelet tree for the given array. Now we will move on to our problem to calculate number of elements less than or equal to x in range [ L,R ] in the given array. So, for each node we have a subsequence of original array, lowest and highest values present in the array and count of elements in left and right child.Now, "
},
{
"code": null,
"e": 6403,
"s": 6304,
"text": "If high <= x, \n we return R - L + 1. \ni.e. all the elements in the current range is less than x."
},
{
"code": null,
"e": 6632,
"s": 6403,
"text": "Otherwise, We will use variable LtCount = freq[ L-1 ] (i.e. elements going to left sub-tree from L-1) , RtCount = freq[ R ] (i.e. elements going to right sub-tree from R) Now, we recursively call and add the return values of : "
},
{
"code": null,
"e": 6740,
"s": 6632,
"text": "left sub-tree with range[ LtCount + 1, RtCount ] and, \nright sub-tree with range[ L - Ltcount,R - RtCount ]"
},
{
"code": null,
"e": 6778,
"s": 6740,
"text": "Below is the implementation in C++: "
},
{
"code": null,
"e": 6782,
"s": 6778,
"text": "CPP"
},
{
"code": "// CPP program for querying in// wavelet tree Data Structure#include <bits/stdc++.h>using namespace std;#define N 100000 // Given Arrayint arr[N]; // wavelet tree classclass wavelet_tree {public: // Range to elements int low, high; // Left and Right child wavelet_tree* l, *r; vector<int> freq; // Default constructor // Array is in range [x, y] // Indices are in range [from, to] wavelet_tree(int* from, int* to, int x, int y) { // Initialising low and high low = x, high = y; // Array is of 0 length if (from >= to) return; // Array is homogeneous // Example : 1 1 1 1 1 if (high == low) { // Assigning storage to freq array freq.reserve(to - from + 1); // Initialising the Freq array freq.push_back(0); // Assigning values for (auto it = from; it != to; it++) // freq will be increasing as there'll // be no further sub-tree freq.push_back(freq.back() + 1); return; } // Computing mid int mid = (low + high) / 2; // Lambda function to check if a number // is less than or equal to mid auto lessThanMid = [mid](int x) { return x <= mid; }; // Assigning storage to freq array freq.reserve(to - from + 1); // Initialising the freq array freq.push_back(0); // Assigning value to freq array for (auto it = from; it != to; it++) // If lessThanMid returns 1(true), we add // 1 to previous entry. Otherwise, we add 0 // (element goes to right sub-tree) freq.push_back(freq.back() + lessThanMid(*it)); // std::stable_partition partitions the array w.r.t Mid auto pivot = stable_partition(from, to, lessThanMid); // Left sub-tree's object l = new wavelet_tree(from, pivot, low, mid); // Right sub-tree's object r = new wavelet_tree(pivot, to, mid + 1, high); } // Count of numbers in range[L..R] less than // or equal to k int kOrLess(int l, int r, int k) { // No elements int range is less than k if (l > r or k < low) return 0; // All elements in the range are less than k if (high <= k) return r - l + 1; // Computing LtCount and RtCount int LtCount = freq[l - 1]; int RtCount = freq[r]; // Answer is (no. of element <= k) in // left + (those <= k) in right return (this->l->kOrLess(LtCount + 1, RtCount, k) + this->r->kOrLess(l - LtCount, r - RtCount, k)); } }; // Driver codeint main(){ int size = 5, high = INT_MIN; int arr[] = {1, 2, 3, 4, 5}; // Array : 1 2 3 4 5 for (int i = 0; i < size; i++) high = max(high, arr[i]); // Object of class wavelet tree wavelet_tree obj(arr, arr + size, 1, high); // count of elements less than 2 in range [1,3] cout << obj.kOrLess(0, 3, 2) << '\\n'; return 0;}",
"e": 9908,
"s": 6782,
"text": null
},
{
"code": null,
"e": 9919,
"s": 9908,
"text": "Output : "
},
{
"code": null,
"e": 9921,
"s": 9919,
"text": "2"
},
{
"code": null,
"e": 10165,
"s": 9921,
"text": "Time Complexity: O(log(max(A)) , where max(A) is the maximum element in the array A[]. In this post we have discussed about a single problem on range queries without update. In further we will be discussing on range updates also.References : "
},
{
"code": null,
"e": 10222,
"s": 10165,
"text": "https://users.dcc.uchile.cl/~jperez/papers/ioiconf16.pdf"
},
{
"code": null,
"e": 10265,
"s": 10222,
"text": "https://en.wikipedia.org/wiki/Wavelet_Tree"
},
{
"code": null,
"e": 10309,
"s": 10265,
"text": "https://www.youtube.com/watch?v=K7tju9j7UWU"
},
{
"code": null,
"e": 10733,
"s": 10309,
"text": "This article is contributed by Rohit Thapliyal. 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": 10743,
"s": 10733,
"text": "ruhelaa48"
},
{
"code": null,
"e": 10767,
"s": 10743,
"text": "Advanced Data Structure"
}
]
|
How to scrape all the text from body tag using Beautifulsoup in Python? | 29 Jun, 2021
strings generator is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. One drawback of the string attribute is that it only works for tags with string inside it and returns nothing for tags with further tags inside it. Thus to resolve this issue, a strings generator is used to get all the strings inside a tag, recursively.
Syntax:
tag.strings
Below given examples explain the concept of strings in Beautiful Soup. Example 1: In this example, we are going to get the strings.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup # Create the documentdoc = "<body><b> Hello world </b><h1> New heading </h1><body>" # Initialize the object with the documentsoup = BeautifulSoup(doc, "html.parser") # Get the whole body tagtag = soup.body # Print each string recursivelyfor string in tag.strings: print(string)
Output:
Hello world
New heading
Example 2:
Python3
import requestsfrom bs4 import BeautifulSoup # url of the websitedoc = "https://www.geeksforgeeks.org" # getting response objectres = requests.get(doc) # Initialize the object with the documentsoup = BeautifulSoup(res.content, "html.parser") # Get the whole body tagtag = soup.body # Print each string recursivelyfor string in tag.strings: print(string)
Output:
simmytarika5
Python BeautifulSoup
Python web-scraping-exercises
Web-scraping
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 516,
"s": 54,
"text": "strings generator is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. One drawback of the string attribute is that it only works for tags with string inside it and returns nothing for tags with further tags inside it. Thus to resolve this issue, a strings generator is used to get all the strings inside a tag, recursively."
},
{
"code": null,
"e": 526,
"s": 516,
"text": "Syntax: "
},
{
"code": null,
"e": 539,
"s": 526,
"text": "tag.strings "
},
{
"code": null,
"e": 671,
"s": 539,
"text": "Below given examples explain the concept of strings in Beautiful Soup. Example 1: In this example, we are going to get the strings."
},
{
"code": null,
"e": 679,
"s": 671,
"text": "Python3"
},
{
"code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Create the documentdoc = \"<body><b> Hello world </b><h1> New heading </h1><body>\" # Initialize the object with the documentsoup = BeautifulSoup(doc, \"html.parser\") # Get the whole body tagtag = soup.body # Print each string recursivelyfor string in tag.strings: print(string)",
"e": 1013,
"s": 679,
"text": null
},
{
"code": null,
"e": 1022,
"s": 1013,
"text": "Output: "
},
{
"code": null,
"e": 1050,
"s": 1022,
"text": " Hello world \n New heading "
},
{
"code": null,
"e": 1061,
"s": 1050,
"text": "Example 2:"
},
{
"code": null,
"e": 1069,
"s": 1061,
"text": "Python3"
},
{
"code": "import requestsfrom bs4 import BeautifulSoup # url of the websitedoc = \"https://www.geeksforgeeks.org\" # getting response objectres = requests.get(doc) # Initialize the object with the documentsoup = BeautifulSoup(res.content, \"html.parser\") # Get the whole body tagtag = soup.body # Print each string recursivelyfor string in tag.strings: print(string)",
"e": 1426,
"s": 1069,
"text": null
},
{
"code": null,
"e": 1440,
"s": 1430,
"text": "Output: "
},
{
"code": null,
"e": 1457,
"s": 1444,
"text": "simmytarika5"
},
{
"code": null,
"e": 1478,
"s": 1457,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 1508,
"s": 1478,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 1521,
"s": 1508,
"text": "Web-scraping"
},
{
"code": null,
"e": 1528,
"s": 1521,
"text": "Python"
},
{
"code": null,
"e": 1626,
"s": 1528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1658,
"s": 1626,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1685,
"s": 1658,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1716,
"s": 1685,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1737,
"s": 1716,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1793,
"s": 1737,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1816,
"s": 1793,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1858,
"s": 1816,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1900,
"s": 1858,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1939,
"s": 1900,
"text": "Python | datetime.timedelta() function"
}
]
|
How to Print Prime Numbers in MS SQL Server? | 16 Nov, 2021
In this article, we are going to print Prime numbers using MS SQL. Here we will be using 2 while loops statement for printing prime numbers.
Steps 1: First we will DECLARE a variable I with initial value 2.
Query:
DECLARE @I INT=2
Step 2: Then we will DECLARE a variable PRIME with an initial value of 0 (this will set the value of PRIME).
Query:
DECLARE @PRIME INT=0
Step 3: Table Definition
We will create a temporary table variable that will hold prime numbers (using DECLARE and TABLE keywords).
Query:
DECLARE @OUTPUT TABLE (NUM INT)
Step 4: Now we will use nested while loop, same as we write a program for prime numbers.
Query:
DECLARE @I INT=2
DECLARE @PRIME INT=0
DECLARE @OUTPUT TABLE (NUM INT)
WHILE @I<=100
BEGIN
DECLARE @J INT = @I-1
SET @PRIME=1
WHILE @J>1
BEGIN
IF @I % @J=0
BEGIN
SET @PRIME=0
END
SET @J=@J-1
END
IF @PRIME =1
BEGIN
INSERT @OUTPUT VALUES (@I)
END
SET @I=@I+1
END
SELECT * FROM @OUTPUT
Explanation:
In the First while loop, we will DECLARE the initial value of I as 100, which means this loop will provide us the prime numbers between 2 and 100.
Now, we will declare J with the initial value as I-1. As shown in the above code.
Then, a second while loop will be inserted which will run until J is greater than 1.
if the statement is there with condition @I % @J = 0, which means when the remainder of I/J is 0 then PRIME will be set to 0, and the value of J is decremented by 1.
If at the end of loop PRIME is set to 1, then that number will be inserted in our OUTPUT TABLE using the below code.
Query:
INSERT @OUTPUT VALUES (@I)
And then another loop will start for the next number.
Step 5: Suppose that I have an initial value of 4, i.e I = 4.
Now in the second loop J will have an initial value of I-1 which is 3.
By 4%3 we will get 1 so Prime will be set to 1 as before and J is decremented by 1.
Now for 4%2, we will get 0, Now as per our condition, PRIME will be set to 0. Since 4 has more factors than 1 and itself, the loop will be started again with an incremented value of I, that is 5(I+1).
Output: Below output for I<=100 which means it will print prime numbers from 2 to 100.
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 193,
"s": 52,
"text": "In this article, we are going to print Prime numbers using MS SQL. Here we will be using 2 while loops statement for printing prime numbers."
},
{
"code": null,
"e": 260,
"s": 193,
"text": " Steps 1: First we will DECLARE a variable I with initial value 2."
},
{
"code": null,
"e": 267,
"s": 260,
"text": "Query:"
},
{
"code": null,
"e": 284,
"s": 267,
"text": "DECLARE @I INT=2"
},
{
"code": null,
"e": 393,
"s": 284,
"text": "Step 2: Then we will DECLARE a variable PRIME with an initial value of 0 (this will set the value of PRIME)."
},
{
"code": null,
"e": 400,
"s": 393,
"text": "Query:"
},
{
"code": null,
"e": 421,
"s": 400,
"text": "DECLARE @PRIME INT=0"
},
{
"code": null,
"e": 447,
"s": 421,
"text": "Step 3: Table Definition "
},
{
"code": null,
"e": 554,
"s": 447,
"text": "We will create a temporary table variable that will hold prime numbers (using DECLARE and TABLE keywords)."
},
{
"code": null,
"e": 561,
"s": 554,
"text": "Query:"
},
{
"code": null,
"e": 593,
"s": 561,
"text": "DECLARE @OUTPUT TABLE (NUM INT)"
},
{
"code": null,
"e": 682,
"s": 593,
"text": "Step 4: Now we will use nested while loop, same as we write a program for prime numbers."
},
{
"code": null,
"e": 689,
"s": 682,
"text": "Query:"
},
{
"code": null,
"e": 1059,
"s": 689,
"text": "DECLARE @I INT=2\nDECLARE @PRIME INT=0\nDECLARE @OUTPUT TABLE (NUM INT)\nWHILE @I<=100\nBEGIN\n DECLARE @J INT = @I-1\n SET @PRIME=1\n WHILE @J>1\n BEGIN\n IF @I % @J=0\n BEGIN\n SET @PRIME=0\n END\n SET @J=@J-1\n END\n IF @PRIME =1\n BEGIN\n INSERT @OUTPUT VALUES (@I)\n END\n SET @I=@I+1\nEND\nSELECT * FROM @OUTPUT"
},
{
"code": null,
"e": 1072,
"s": 1059,
"text": "Explanation:"
},
{
"code": null,
"e": 1219,
"s": 1072,
"text": "In the First while loop, we will DECLARE the initial value of I as 100, which means this loop will provide us the prime numbers between 2 and 100."
},
{
"code": null,
"e": 1301,
"s": 1219,
"text": "Now, we will declare J with the initial value as I-1. As shown in the above code."
},
{
"code": null,
"e": 1386,
"s": 1301,
"text": "Then, a second while loop will be inserted which will run until J is greater than 1."
},
{
"code": null,
"e": 1552,
"s": 1386,
"text": "if the statement is there with condition @I % @J = 0, which means when the remainder of I/J is 0 then PRIME will be set to 0, and the value of J is decremented by 1."
},
{
"code": null,
"e": 1669,
"s": 1552,
"text": "If at the end of loop PRIME is set to 1, then that number will be inserted in our OUTPUT TABLE using the below code."
},
{
"code": null,
"e": 1676,
"s": 1669,
"text": "Query:"
},
{
"code": null,
"e": 1703,
"s": 1676,
"text": "INSERT @OUTPUT VALUES (@I)"
},
{
"code": null,
"e": 1757,
"s": 1703,
"text": "And then another loop will start for the next number."
},
{
"code": null,
"e": 1821,
"s": 1757,
"text": "Step 5: Suppose that I have an initial value of 4, i.e I = 4."
},
{
"code": null,
"e": 1892,
"s": 1821,
"text": "Now in the second loop J will have an initial value of I-1 which is 3."
},
{
"code": null,
"e": 1976,
"s": 1892,
"text": "By 4%3 we will get 1 so Prime will be set to 1 as before and J is decremented by 1."
},
{
"code": null,
"e": 2177,
"s": 1976,
"text": "Now for 4%2, we will get 0, Now as per our condition, PRIME will be set to 0. Since 4 has more factors than 1 and itself, the loop will be started again with an incremented value of I, that is 5(I+1)."
},
{
"code": null,
"e": 2264,
"s": 2177,
"text": "Output: Below output for I<=100 which means it will print prime numbers from 2 to 100."
},
{
"code": null,
"e": 2271,
"s": 2264,
"text": "Picked"
},
{
"code": null,
"e": 2282,
"s": 2271,
"text": "SQL-Server"
},
{
"code": null,
"e": 2286,
"s": 2282,
"text": "SQL"
},
{
"code": null,
"e": 2290,
"s": 2286,
"text": "SQL"
},
{
"code": null,
"e": 2388,
"s": 2290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2454,
"s": 2388,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2478,
"s": 2454,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2511,
"s": 2478,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2543,
"s": 2511,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2560,
"s": 2543,
"text": "SQL using Python"
},
{
"code": null,
"e": 2638,
"s": 2560,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2674,
"s": 2638,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2704,
"s": 2674,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2735,
"s": 2704,
"text": "SQL Query to Compare Two Dates"
}
]
|
turtle.undo() function in Python | 26 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to undo (repeatedly) the last turtle action. The number of available undo actions is determined by the size of the undobuffer. It doesn’t require any argument.
Syntax :
turtle.undo()
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # set speedturtle.speed(1) # motionturtle.forward(100) # undo previous motionturtle.undo()
Output :
Example 2 :
Python3
# import packageimport turtle # set turtleturtle.speed(1)turtle.up()turtle.setpos(-50,50)turtle.down() # motionfor i in range(4): turtle.forward(100) turtle.right(90) # undofor i in range(8): turtle.undo()
Output :
Example 3 :
Python3
# import packageimport turtle # set speedturtle.speed(1) # loop for motionfor i in range(4): # motion turtle.forward(100) # undo previous work turtle.undo() # turn turtle.left(90)
Output :
Python-turtle
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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": "\n26 Jul, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 427,
"s": 245,
"text": "This function is used to undo (repeatedly) the last turtle action. The number of available undo actions is determined by the size of the undobuffer. It doesn’t require any argument."
},
{
"code": null,
"e": 436,
"s": 427,
"text": "Syntax :"
},
{
"code": null,
"e": 451,
"s": 436,
"text": "turtle.undo()\n"
},
{
"code": null,
"e": 520,
"s": 451,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 532,
"s": 520,
"text": "Example 1 :"
},
{
"code": null,
"e": 540,
"s": 532,
"text": "Python3"
},
{
"code": "# import packageimport turtle # set speedturtle.speed(1) # motionturtle.forward(100) # undo previous motionturtle.undo()",
"e": 664,
"s": 540,
"text": null
},
{
"code": null,
"e": 673,
"s": 664,
"text": "Output :"
},
{
"code": null,
"e": 685,
"s": 673,
"text": "Example 2 :"
},
{
"code": null,
"e": 693,
"s": 685,
"text": "Python3"
},
{
"code": "# import packageimport turtle # set turtleturtle.speed(1)turtle.up()turtle.setpos(-50,50)turtle.down() # motionfor i in range(4): turtle.forward(100) turtle.right(90) # undofor i in range(8): turtle.undo()",
"e": 915,
"s": 693,
"text": null
},
{
"code": null,
"e": 924,
"s": 915,
"text": "Output :"
},
{
"code": null,
"e": 936,
"s": 924,
"text": "Example 3 :"
},
{
"code": null,
"e": 944,
"s": 936,
"text": "Python3"
},
{
"code": "# import packageimport turtle # set speedturtle.speed(1) # loop for motionfor i in range(4): # motion turtle.forward(100) # undo previous work turtle.undo() # turn turtle.left(90)",
"e": 1160,
"s": 944,
"text": null
},
{
"code": null,
"e": 1169,
"s": 1160,
"text": "Output :"
},
{
"code": null,
"e": 1183,
"s": 1169,
"text": "Python-turtle"
},
{
"code": null,
"e": 1190,
"s": 1183,
"text": "Python"
},
{
"code": null,
"e": 1288,
"s": 1190,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1320,
"s": 1288,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1347,
"s": 1320,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1378,
"s": 1347,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1401,
"s": 1378,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1422,
"s": 1401,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1478,
"s": 1422,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1520,
"s": 1478,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1562,
"s": 1520,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1601,
"s": 1562,
"text": "Python | Get unique values from a list"
}
]
|
Perl | Getting the Number of Elements of an Array | 18 Feb, 2019
An array in Perl is a variable used to store an ordered list of scalar values. An array variable is preceded by an “at” (@) sign. The size of an array can be determined using the scalar context on the array which returns the number of elements in the array
Example 1:
#!/usr/bin/perl # Initializing the array@a = (1, 2, 3); # Assigning the array to a scalar# variable which stores size of# the array$s = @a; # Printing the sizeprint "Size of the Array is $s";
Size of the Array is 3
Above code returns the physical size of the array, not the number of valid elements. In order to obtain the maximum index of an array, ‘$#’ is used as shown in the example below:
Example 2:
#!/usr/bin/perl # Initializing the array@a = (1, 2, 3); # Store the value at any index# Let's take index 15 here,$a[15] = 20; # Printing the Arrayprint "Array is @a"; # Getting the maximum index # of the array$i = $#a; # Printing the Max. Indexprint "\nMaximum index is $i";
Array is 1 2 3 20
Maximum index is 15
Here is how the above code works:-Step1: Initializing an array with some valuesStep2: Assigning a value at any random index leaving the other indices blankStep3: Printing the array to show the blank spaces left in the arrayStep4: To get the maximum index ‘$#’ is usedStep5: Further, print the maximum index
Perl-Arrays
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "An array in Perl is a variable used to store an ordered list of scalar values. An array variable is preceded by an “at” (@) sign. The size of an array can be determined using the scalar context on the array which returns the number of elements in the array"
},
{
"code": null,
"e": 296,
"s": 285,
"text": "Example 1:"
},
{
"code": "#!/usr/bin/perl # Initializing the array@a = (1, 2, 3); # Assigning the array to a scalar# variable which stores size of# the array$s = @a; # Printing the sizeprint \"Size of the Array is $s\";",
"e": 491,
"s": 296,
"text": null
},
{
"code": null,
"e": 515,
"s": 491,
"text": "Size of the Array is 3\n"
},
{
"code": null,
"e": 694,
"s": 515,
"text": "Above code returns the physical size of the array, not the number of valid elements. In order to obtain the maximum index of an array, ‘$#’ is used as shown in the example below:"
},
{
"code": null,
"e": 705,
"s": 694,
"text": "Example 2:"
},
{
"code": "#!/usr/bin/perl # Initializing the array@a = (1, 2, 3); # Store the value at any index# Let's take index 15 here,$a[15] = 20; # Printing the Arrayprint \"Array is @a\"; # Getting the maximum index # of the array$i = $#a; # Printing the Max. Indexprint \"\\nMaximum index is $i\";",
"e": 985,
"s": 705,
"text": null
},
{
"code": null,
"e": 1036,
"s": 985,
"text": "Array is 1 2 3 20\nMaximum index is 15\n"
},
{
"code": null,
"e": 1343,
"s": 1036,
"text": "Here is how the above code works:-Step1: Initializing an array with some valuesStep2: Assigning a value at any random index leaving the other indices blankStep3: Printing the array to show the blank spaces left in the arrayStep4: To get the maximum index ‘$#’ is usedStep5: Further, print the maximum index"
},
{
"code": null,
"e": 1355,
"s": 1343,
"text": "Perl-Arrays"
},
{
"code": null,
"e": 1362,
"s": 1355,
"text": "Picked"
},
{
"code": null,
"e": 1367,
"s": 1362,
"text": "Perl"
},
{
"code": null,
"e": 1372,
"s": 1367,
"text": "Perl"
}
]
|
Filtering a row in PySpark DataFrame based on matching values from a list | 28 Jul, 2021
In this article, we are going to filter the rows in the dataframe based on matching values in the list by using isin in Pyspark dataframe
isin(): This is used to find the elements contains in a given dataframe, it will take the elements and get the elements to match to the data
Syntax: isin([element1,element2,.,element n])
Create Dataframe for demonstration:
Python3
# importing moduleimport pyspark # importing sparksessionfrom pyspark.sql import SparkSession # creating sparksession# and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data with null values# we can define null values with nonedata = [[1, "sravan", "vignan"], [2, "ramya", "vvit"], [3, "rohith", "klu"], [4, "sridevi", "vignan"], [5, "gnanesh", "iit"]] # specify column namescolumns = ['ID', 'NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show()
Output:
It is used to check the condition and give the results, Both are similar
Syntax: dataframe.filter(condition)
Where, condition is the dataframe condition.
Here we will use all the discussed methods.
Syntax: dataframe.filter((dataframe.column_name).isin([list_of_elements])).show()
where,
column_name is the column
elements are the values that are present in the column
show() is used to show the resultant dataframe
Example 1: Get the particular ID’s with filter() clause.
Python3
# get the ID : 1,2,3 from dataframedataframe.filter((dataframe.ID).isin([1,2,3])).show()
Output:
Example 2: Get ID’s not present in 1 and 3
Python3
# get the ID : not in 1 and 3 from dataframedataframe.filter(~(dataframe.ID).isin([1, 3])).show()
Output:
Example 3: Get names from dataframe.
Python3
# get name as sravandataframe.filter(( dataframe.NAME).isin(['sravan'])).show()
Output:
where() is used to check the condition and give the results
Syntax: dataframe.where(condition)
where, condition is the dataframe condition
Overall Syntax with where clause:
dataframe.where((dataframe.column_name).isin([elements])).show()
where,
column_name is the column
elements are the values that are present in the column
show() is used to show the resultant dataframe
Example: Get the particular colleges with where() clause
Python3
# get college as vignandataframe.where(( dataframe.college).isin(['vignan'])).show()
Output:
Picked
Python-Pyspark
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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": "\n28 Jul, 2021"
},
{
"code": null,
"e": 166,
"s": 28,
"text": "In this article, we are going to filter the rows in the dataframe based on matching values in the list by using isin in Pyspark dataframe"
},
{
"code": null,
"e": 307,
"s": 166,
"text": "isin(): This is used to find the elements contains in a given dataframe, it will take the elements and get the elements to match to the data"
},
{
"code": null,
"e": 353,
"s": 307,
"text": "Syntax: isin([element1,element2,.,element n])"
},
{
"code": null,
"e": 389,
"s": 353,
"text": "Create Dataframe for demonstration:"
},
{
"code": null,
"e": 397,
"s": 389,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksessionfrom pyspark.sql import SparkSession # creating sparksession# and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data with null values# we can define null values with nonedata = [[1, \"sravan\", \"vignan\"], [2, \"ramya\", \"vvit\"], [3, \"rohith\", \"klu\"], [4, \"sridevi\", \"vignan\"], [5, \"gnanesh\", \"iit\"]] # specify column namescolumns = ['ID', 'NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show()",
"e": 1009,
"s": 397,
"text": null
},
{
"code": null,
"e": 1017,
"s": 1009,
"text": "Output:"
},
{
"code": null,
"e": 1090,
"s": 1017,
"text": "It is used to check the condition and give the results, Both are similar"
},
{
"code": null,
"e": 1126,
"s": 1090,
"text": "Syntax: dataframe.filter(condition)"
},
{
"code": null,
"e": 1171,
"s": 1126,
"text": "Where, condition is the dataframe condition."
},
{
"code": null,
"e": 1215,
"s": 1171,
"text": "Here we will use all the discussed methods."
},
{
"code": null,
"e": 1297,
"s": 1215,
"text": "Syntax: dataframe.filter((dataframe.column_name).isin([list_of_elements])).show()"
},
{
"code": null,
"e": 1304,
"s": 1297,
"text": "where,"
},
{
"code": null,
"e": 1330,
"s": 1304,
"text": "column_name is the column"
},
{
"code": null,
"e": 1385,
"s": 1330,
"text": "elements are the values that are present in the column"
},
{
"code": null,
"e": 1432,
"s": 1385,
"text": "show() is used to show the resultant dataframe"
},
{
"code": null,
"e": 1489,
"s": 1432,
"text": "Example 1: Get the particular ID’s with filter() clause."
},
{
"code": null,
"e": 1497,
"s": 1489,
"text": "Python3"
},
{
"code": "# get the ID : 1,2,3 from dataframedataframe.filter((dataframe.ID).isin([1,2,3])).show()",
"e": 1586,
"s": 1497,
"text": null
},
{
"code": null,
"e": 1594,
"s": 1586,
"text": "Output:"
},
{
"code": null,
"e": 1637,
"s": 1594,
"text": "Example 2: Get ID’s not present in 1 and 3"
},
{
"code": null,
"e": 1645,
"s": 1637,
"text": "Python3"
},
{
"code": "# get the ID : not in 1 and 3 from dataframedataframe.filter(~(dataframe.ID).isin([1, 3])).show()",
"e": 1743,
"s": 1645,
"text": null
},
{
"code": null,
"e": 1751,
"s": 1743,
"text": "Output:"
},
{
"code": null,
"e": 1788,
"s": 1751,
"text": "Example 3: Get names from dataframe."
},
{
"code": null,
"e": 1796,
"s": 1788,
"text": "Python3"
},
{
"code": "# get name as sravandataframe.filter(( dataframe.NAME).isin(['sravan'])).show()",
"e": 1877,
"s": 1796,
"text": null
},
{
"code": null,
"e": 1885,
"s": 1877,
"text": "Output:"
},
{
"code": null,
"e": 1945,
"s": 1885,
"text": "where() is used to check the condition and give the results"
},
{
"code": null,
"e": 1980,
"s": 1945,
"text": "Syntax: dataframe.where(condition)"
},
{
"code": null,
"e": 2024,
"s": 1980,
"text": "where, condition is the dataframe condition"
},
{
"code": null,
"e": 2058,
"s": 2024,
"text": "Overall Syntax with where clause:"
},
{
"code": null,
"e": 2123,
"s": 2058,
"text": "dataframe.where((dataframe.column_name).isin([elements])).show()"
},
{
"code": null,
"e": 2130,
"s": 2123,
"text": "where,"
},
{
"code": null,
"e": 2156,
"s": 2130,
"text": "column_name is the column"
},
{
"code": null,
"e": 2211,
"s": 2156,
"text": "elements are the values that are present in the column"
},
{
"code": null,
"e": 2258,
"s": 2211,
"text": "show() is used to show the resultant dataframe"
},
{
"code": null,
"e": 2315,
"s": 2258,
"text": "Example: Get the particular colleges with where() clause"
},
{
"code": null,
"e": 2323,
"s": 2315,
"text": "Python3"
},
{
"code": "# get college as vignandataframe.where(( dataframe.college).isin(['vignan'])).show()",
"e": 2409,
"s": 2323,
"text": null
},
{
"code": null,
"e": 2417,
"s": 2409,
"text": "Output:"
},
{
"code": null,
"e": 2424,
"s": 2417,
"text": "Picked"
},
{
"code": null,
"e": 2439,
"s": 2424,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 2446,
"s": 2439,
"text": "Python"
},
{
"code": null,
"e": 2544,
"s": 2446,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2576,
"s": 2544,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2603,
"s": 2576,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2634,
"s": 2603,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2657,
"s": 2634,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2678,
"s": 2657,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2734,
"s": 2678,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2776,
"s": 2734,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2818,
"s": 2776,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2857,
"s": 2818,
"text": "Python | Get unique values from a list"
}
]
|
JavaScript Code Execution | 16 Nov, 2021
JavaScript is a synchronous (Moves to the next line only when the execution of the current line is completed) and single-threaded (Executes one command at a time in a specific order one after another serially) language. To know behind the scene of how JavaScript code gets executed internally, we have to know something called Execution Context and its role in the execution of JavaScript code.
Execution Context: Everything in JavaScript is wrapped inside Execution Context, which is an abstract concept (can be treated as a container) that holds the whole information about the environment within which the current JavaScript code is being executed.
Now, an Execution Context has two components and JavaScript code gets executed in two phases.
Memory Allocation Phase: In this phase, all the functions and variables of the JavaScript code get stored as a key-value pair inside the memory component of the execution context. In the case of a function, JavaScript copied the whole function into the memory block but in the case of variables, it assigns undefined as a placeholder.
Code Execution Phase: In this phase, the JavaScript code is executed one line at a time inside the Code Component (also known as the Thread of execution) of Execution Context.
Let’s see the whole process through an example.
Javascript
var number = 2;function Square (n) { var res = n * n; return res;}var newNumber = Square(3);
In the above JavaScript code, there are two variables named number and newNumber and one function named Square which is returning the square of the number. So when we run this program, Global Execution Context is created.
So, in the Memory Allocation phase, the memory will be allocated for these variables and functions like this.
Global Execution Context
In the Code Execution Phase, JavaScript being a single thread language again runs through the code line by line and updates the values of function and variables which are stored in the Memory Allocation Phase in the Memory Component.
So in the code execution phase, whenever a new function is called, a new Execution Context is created. So, every time a function is invoked in the Code Component, a new Execution Context is created inside the previous global execution context.
Global Execution Context
So again, before the memory allocation is completed in the Memory Component of the new Execution Context. Then, in the Code Execution Phase of the newly created Execution Context, the global Execution Context will look like the following.
Global Execution Context
As we can see, the values are assigned in the memory component after executing the code line by line, i.e. number: 2, res: 4, newNumber: 4.
After the return statement of the invoked function, the returned value is assigned in place of undefined in the memory allocation of the previous execution context. After returning the value, the new execution context (temporary) gets completely deleted. Whenever the execution encounters the return statement, It gives the control back to the execution context where the function was invoked.
Global Execution Context
After executing the first function call when we call the function again, JavaScript creates again another temporary context where the same procedure repeats accordingly (memory execution and code execution). In the end, the global execution context gets deleted just like child execution contexts. The whole execution context for the instance of that function will be deleted
Call Stack: When a program starts execution JavaScript pushes the whole program as global context into a stack which is known as Call Stack and continues execution. Whenever JavaScript executes a new context and just follows the same process and pushes to the stack. When the context finishes, JavaScript just pops the top of the stack accordingly.
Call Stack
When JavaScript completes the execution of the entire code, the Global Execution Context gets deleted and popped out from the Call Stack making the Call stack empty.
Palak Jain 5
javascript-basics
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 423,
"s": 28,
"text": "JavaScript is a synchronous (Moves to the next line only when the execution of the current line is completed) and single-threaded (Executes one command at a time in a specific order one after another serially) language. To know behind the scene of how JavaScript code gets executed internally, we have to know something called Execution Context and its role in the execution of JavaScript code."
},
{
"code": null,
"e": 680,
"s": 423,
"text": "Execution Context: Everything in JavaScript is wrapped inside Execution Context, which is an abstract concept (can be treated as a container) that holds the whole information about the environment within which the current JavaScript code is being executed."
},
{
"code": null,
"e": 774,
"s": 680,
"text": "Now, an Execution Context has two components and JavaScript code gets executed in two phases."
},
{
"code": null,
"e": 1109,
"s": 774,
"text": "Memory Allocation Phase: In this phase, all the functions and variables of the JavaScript code get stored as a key-value pair inside the memory component of the execution context. In the case of a function, JavaScript copied the whole function into the memory block but in the case of variables, it assigns undefined as a placeholder."
},
{
"code": null,
"e": 1286,
"s": 1109,
"text": "Code Execution Phase: In this phase, the JavaScript code is executed one line at a time inside the Code Component (also known as the Thread of execution) of Execution Context. "
},
{
"code": null,
"e": 1334,
"s": 1286,
"text": "Let’s see the whole process through an example."
},
{
"code": null,
"e": 1345,
"s": 1334,
"text": "Javascript"
},
{
"code": "var number = 2;function Square (n) { var res = n * n; return res;}var newNumber = Square(3);",
"e": 1444,
"s": 1345,
"text": null
},
{
"code": null,
"e": 1666,
"s": 1444,
"text": "In the above JavaScript code, there are two variables named number and newNumber and one function named Square which is returning the square of the number. So when we run this program, Global Execution Context is created."
},
{
"code": null,
"e": 1776,
"s": 1666,
"text": "So, in the Memory Allocation phase, the memory will be allocated for these variables and functions like this."
},
{
"code": null,
"e": 1801,
"s": 1776,
"text": "Global Execution Context"
},
{
"code": null,
"e": 2035,
"s": 1801,
"text": "In the Code Execution Phase, JavaScript being a single thread language again runs through the code line by line and updates the values of function and variables which are stored in the Memory Allocation Phase in the Memory Component."
},
{
"code": null,
"e": 2280,
"s": 2035,
"text": "So in the code execution phase, whenever a new function is called, a new Execution Context is created. So, every time a function is invoked in the Code Component, a new Execution Context is created inside the previous global execution context. "
},
{
"code": null,
"e": 2305,
"s": 2280,
"text": "Global Execution Context"
},
{
"code": null,
"e": 2544,
"s": 2305,
"text": "So again, before the memory allocation is completed in the Memory Component of the new Execution Context. Then, in the Code Execution Phase of the newly created Execution Context, the global Execution Context will look like the following."
},
{
"code": null,
"e": 2569,
"s": 2544,
"text": "Global Execution Context"
},
{
"code": null,
"e": 2709,
"s": 2569,
"text": "As we can see, the values are assigned in the memory component after executing the code line by line, i.e. number: 2, res: 4, newNumber: 4."
},
{
"code": null,
"e": 3103,
"s": 2709,
"text": "After the return statement of the invoked function, the returned value is assigned in place of undefined in the memory allocation of the previous execution context. After returning the value, the new execution context (temporary) gets completely deleted. Whenever the execution encounters the return statement, It gives the control back to the execution context where the function was invoked."
},
{
"code": null,
"e": 3128,
"s": 3103,
"text": "Global Execution Context"
},
{
"code": null,
"e": 3504,
"s": 3128,
"text": "After executing the first function call when we call the function again, JavaScript creates again another temporary context where the same procedure repeats accordingly (memory execution and code execution). In the end, the global execution context gets deleted just like child execution contexts. The whole execution context for the instance of that function will be deleted"
},
{
"code": null,
"e": 3853,
"s": 3504,
"text": "Call Stack: When a program starts execution JavaScript pushes the whole program as global context into a stack which is known as Call Stack and continues execution. Whenever JavaScript executes a new context and just follows the same process and pushes to the stack. When the context finishes, JavaScript just pops the top of the stack accordingly."
},
{
"code": null,
"e": 3864,
"s": 3853,
"text": "Call Stack"
},
{
"code": null,
"e": 4030,
"s": 3864,
"text": "When JavaScript completes the execution of the entire code, the Global Execution Context gets deleted and popped out from the Call Stack making the Call stack empty."
},
{
"code": null,
"e": 4043,
"s": 4030,
"text": "Palak Jain 5"
},
{
"code": null,
"e": 4061,
"s": 4043,
"text": "javascript-basics"
},
{
"code": null,
"e": 4072,
"s": 4061,
"text": "JavaScript"
},
{
"code": null,
"e": 4089,
"s": 4072,
"text": "Web Technologies"
},
{
"code": null,
"e": 4187,
"s": 4089,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4248,
"s": 4187,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4288,
"s": 4248,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4329,
"s": 4288,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4371,
"s": 4329,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4393,
"s": 4371,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 4426,
"s": 4393,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4488,
"s": 4426,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4549,
"s": 4488,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4599,
"s": 4549,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Tryit Editor v3.7 | Tryit: HTML semantics | []
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.