title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Unsupervised Learning: Image Compression In 10 Lines of R Code | by Leihua Ye, PhD | Towards Data Science | Principal Component Analysis (PCA) is a powerful Machine Learning tool. As an unsupervised learning technique, it excels in dimension reduction and feature extraction.
However, do you know we can use PCA to compress images?
In this post, I’ll walk through the process and explain how PCA can compress images in 10 lines of R code with simple maths described in the end.
# Install packages and load libraries
#install.packages(“tidyverse”)#install.packages(“gbm”)#install.packages(“e1071”)#install.packages(“imager”)library(tidyverse)library(tree) library(randomForest) library(gbm) library(ROCR) library(e1071) library(imager)# load the dataset. This is a 100*100*1000 array of data. An array is a generalization of a matrix to more than 2 dimensions. The first two dimensions index the pixels in a 100*100 black and white image of a face; the last dimension is the index for one of 1000 face images. The dataset can be accessed at: https://cyberextruder.com/face-matching-data-set-download/.load(“faces_array.RData”)#PAC requires a single matrix. so, we need to transform the 100*100 matrix into a single vector (10,000). face_mat <- sapply(1:1000, function(i) as.numeric(faces_array[, , i])) %>% t# To visualize the image, we need a matrix. so, let's convert 10000 dimensional vector to a matrixplot_face <- function(image_vector) { plot(as.cimg(t(matrix(image_vector, ncol=100))), axes=FALSE, asp=1) }plot_face(face_mat[, sample(1000, 1)])
Here, we are trying to obtain the basic information of the dataset and constructing a new function for analysis.
#check the average face
face_average = colMeans(face_mat)plot_face(face_average)
To a large extent, we can understand “average face” as the baseline for other images. By adding or subtracting values from the average face, we can obtain other faces.
#The above code doesn’t count to the 10 lines limit.#
# And, here it goes our 10 lines of code #
# generate PCA results;# scale=TRUE and center=TRUE --> mean 0 and variance 1pr.out = prcomp(face_mat,center=TRUE, scale=FALSE)# pr.out$sdev: the standard deviations of the principal components; # (pr.out$sdev)2: variance of the principal componentspr.var=(pr.out$sdev)2 # pve: variance explained by the principal componentpve = pr.var/sum(pr.var) # cumulative explained variancecumulative_pve <-cumsum(pve)#see the math explanation attached in the endU = pr.out$rotationZ = t(pr.out$x)# Let's compress the 232nd face of the dataset and add the average face back and create four other images adopting the first 10,50,100, and 300 columns.par(mfrow=c(1,5))plot_face(face_mat[232,])for (i in c(10,50,100,300)) { plot_face((U[,1:i]%*%Z[1:i,])[,232]+face_average) }
We did it! The results are not too bad. We have the original image on the far left, followed by the four compressed images.
Simple Math Explanations.
PCA is closely related to the singular value decomposition (SVD) of a matrix. So, x = UD(V^T) = z*(V^T),
where x is the 1000*10000 matrix,
V: the matrix of eigenvectors (rotation returned by prcomp)
D: standard deviation of the principal components (sdev returned by prcomp)
So, z = UD (the coordinates of the principal components in the rotated space (prcomp$x).
In other words, we can compress the images using the first k columns of V and the first k columns of z:
End of math.
Please find me at LinkedIn and Twitter.
Check out my other posts on Artificial Intelligence and Machine Learning. | [
{
"code": null,
"e": 340,
"s": 172,
"text": "Principal Component Analysis (PCA) is a powerful Machine Learning tool. As an unsupervised learning technique, it excels in dimension reduction and feature extraction."
},
{
"code": null,
"e": 396,
"s": 340,
"text": "However, do you know we can use PCA to compress images?"
},
{
"code": null,
"e": 542,
"s": 396,
"text": "In this post, I’ll walk through the process and explain how PCA can compress images in 10 lines of R code with simple maths described in the end."
},
{
"code": null,
"e": 580,
"s": 542,
"text": "# Install packages and load libraries"
},
{
"code": null,
"e": 1616,
"s": 580,
"text": "#install.packages(“tidyverse”)#install.packages(“gbm”)#install.packages(“e1071”)#install.packages(“imager”)library(tidyverse)library(tree) library(randomForest) library(gbm) library(ROCR) library(e1071) library(imager)# load the dataset. This is a 100*100*1000 array of data. An array is a generalization of a matrix to more than 2 dimensions. The first two dimensions index the pixels in a 100*100 black and white image of a face; the last dimension is the index for one of 1000 face images. The dataset can be accessed at: https://cyberextruder.com/face-matching-data-set-download/.load(“faces_array.RData”)#PAC requires a single matrix. so, we need to transform the 100*100 matrix into a single vector (10,000). face_mat <- sapply(1:1000, function(i) as.numeric(faces_array[, , i])) %>% t# To visualize the image, we need a matrix. so, let's convert 10000 dimensional vector to a matrixplot_face <- function(image_vector) { plot(as.cimg(t(matrix(image_vector, ncol=100))), axes=FALSE, asp=1) }plot_face(face_mat[, sample(1000, 1)])"
},
{
"code": null,
"e": 1729,
"s": 1616,
"text": "Here, we are trying to obtain the basic information of the dataset and constructing a new function for analysis."
},
{
"code": null,
"e": 1753,
"s": 1729,
"text": "#check the average face"
},
{
"code": null,
"e": 1810,
"s": 1753,
"text": "face_average = colMeans(face_mat)plot_face(face_average)"
},
{
"code": null,
"e": 1978,
"s": 1810,
"text": "To a large extent, we can understand “average face” as the baseline for other images. By adding or subtracting values from the average face, we can obtain other faces."
},
{
"code": null,
"e": 2032,
"s": 1978,
"text": "#The above code doesn’t count to the 10 lines limit.#"
},
{
"code": null,
"e": 2075,
"s": 2032,
"text": "# And, here it goes our 10 lines of code #"
},
{
"code": null,
"e": 2838,
"s": 2075,
"text": "# generate PCA results;# scale=TRUE and center=TRUE --> mean 0 and variance 1pr.out = prcomp(face_mat,center=TRUE, scale=FALSE)# pr.out$sdev: the standard deviations of the principal components; # (pr.out$sdev)2: variance of the principal componentspr.var=(pr.out$sdev)2 # pve: variance explained by the principal componentpve = pr.var/sum(pr.var) # cumulative explained variancecumulative_pve <-cumsum(pve)#see the math explanation attached in the endU = pr.out$rotationZ = t(pr.out$x)# Let's compress the 232nd face of the dataset and add the average face back and create four other images adopting the first 10,50,100, and 300 columns.par(mfrow=c(1,5))plot_face(face_mat[232,])for (i in c(10,50,100,300)) { plot_face((U[,1:i]%*%Z[1:i,])[,232]+face_average) }"
},
{
"code": null,
"e": 2962,
"s": 2838,
"text": "We did it! The results are not too bad. We have the original image on the far left, followed by the four compressed images."
},
{
"code": null,
"e": 2988,
"s": 2962,
"text": "Simple Math Explanations."
},
{
"code": null,
"e": 3093,
"s": 2988,
"text": "PCA is closely related to the singular value decomposition (SVD) of a matrix. So, x = UD(V^T) = z*(V^T),"
},
{
"code": null,
"e": 3127,
"s": 3093,
"text": "where x is the 1000*10000 matrix,"
},
{
"code": null,
"e": 3187,
"s": 3127,
"text": "V: the matrix of eigenvectors (rotation returned by prcomp)"
},
{
"code": null,
"e": 3263,
"s": 3187,
"text": "D: standard deviation of the principal components (sdev returned by prcomp)"
},
{
"code": null,
"e": 3352,
"s": 3263,
"text": "So, z = UD (the coordinates of the principal components in the rotated space (prcomp$x)."
},
{
"code": null,
"e": 3456,
"s": 3352,
"text": "In other words, we can compress the images using the first k columns of V and the first k columns of z:"
},
{
"code": null,
"e": 3469,
"s": 3456,
"text": "End of math."
},
{
"code": null,
"e": 3509,
"s": 3469,
"text": "Please find me at LinkedIn and Twitter."
}
] |
Angular 6 - Forms | In this chapter, we will see how forms are used in Angular 6. We will discuss two ways of working with forms - template driven form and model driven forms.
With a template driven form, most of the work is done in the template; and with the model driven form, most of the work is done in the component class.
Let us now consider working on the Template driven form. We will create a simple login form and add the email id, password and submit the button in the form. To start with, we need to import to FormsModule from @angular/core which is done in app.module.ts as follows −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { MyserviceService } from './myservice.service';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
{path: 'new-cmp',component: NewCmpComponent}
])
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
So in app.module.ts, we have imported the FormsModule and the same is added in the imports array as shown in the highlighted code.
Let us now create our form in the app.component.html file.
<form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)" >
<input type = "text" name = "emailid" placeholder = "emailid" ngModel>
<br/>
<input type = "password" name = "passwd" placeholder = "passwd" ngModel>
<br/>
<input type = "submit" value = "submit">
</form>
We have created a simple form with input tags having email id, password and the submit button. We have assigned type, name, and placeholder to it.
In template driven forms, we need to create the model form controls by adding the ngModel directive and the name attribute. Thus, wherever we want Angular to access our data from forms, add ngModel to that tag as shown above. Now, if we have to read the emailid and passwd, we need to add the ngModel across it.
If you see, we have also added the ngForm to the #userlogin. The ngForm directive needs to be added to the form template that we have created. We have also added function onClickSubmit and assigned userlogin.value to it.
Let us now create the function in the app.component.ts and fetch the values entered in the form.
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 6 Project!';
todaydate;
componentproperty;
constructor(private myservice: MyserviceService) { }
ngOnInit() {
this.todaydate = this.myservice.showTodayDate();
}
onClickSubmit(data) {
alert("Entered Email id : " + data.emailid);
}
}
In the above app.component.ts file, we have defined the function onClickSubmit. When you click on the form submit button, the control will come to the above function.
This is how the browser is displayed −
The form looks like as shown below. Let us enter the data in it and in the submit function, the email id is already entered.
The email id is displayed at the bottom as shown in the above screenshot.
In the model driven form, we need to import the ReactiveFormsModule from @angular/forms and use the same in the imports array.
There is a change which goes in app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
import { HttpModule } from '@angular/http';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { MyserviceService } from './myservice.service';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule,
HttpModule,
ReactiveFormsModule,
RouterModule.forRoot([
{
path: 'new-cmp',
component: NewCmpComponent
}
])
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
In app.component.ts, we need to import a few modules for the model driven form. For example, import { FormGroup, FormControl } from '@angular/forms'.
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 6 Project!';
todaydate;
componentproperty;
emailid;
formdata;
constructor(private myservice: MyserviceService) { }
ngOnInit() {
this.todaydate = this.myservice.showTodayDate();
this.formdata = new FormGroup({
emailid: new FormControl("[email protected]"),
passwd: new FormControl("abcd1234")
});
}
onClickSubmit(data) {this.emailid = data.emailid;}
}
The variable formdata is initialized at the start of the class and the same is initialized with FormGroup as shown above. The variables emailid and passwd are initialized with default values to be displayed in the form. You can keep it blank in case you want to.
This is how the values will be seen in the form UI.
We have used formdata to initialize the form values; we need to use the same in the form UI app.component.html.
<div>
<form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
<input type = "text" class = "fortextbox" name = "emailid" placeholder = "emailid"
formControlName="emailid">
<br/>
<input type = "password" class = "fortextbox" name="passwd"
placeholder = "passwd" formControlName = "passwd">
<br/>
<input type = "submit" class = "forsubmit" value = "Log In">
</form>
</div>
<p>
Email entered is : {{emailid}}
</p>
In the .html file, we have used formGroup in square bracket for the form; for example, [formGroup]="formdata". On submit, the function is called onClickSubmit for which formdata.value is passed.
The input tag formControlName is used. It is given a value that we have used in the app.component.ts file.
On clicking submit, the control will pass to the function onClickSubmit, which is defined in the app.component.ts file.
On clicking Login, the value will be displayed as shown in the above screenshot.
Let us now discuss form validation using model driven form. You can use the built-in form validation or also use the custom validation approach. We will use both the approaches in the form. We will continue with the same example that we created in one of our previous sections. With Angular 4, we need to import Validators from @angular/forms as shown below −
import { FormGroup, FormControl, Validators} from '@angular/forms'
Angular has built-in validators such as mandatory field, minlength, maxlength, and pattern. These are to be accessed using the Validators module.
You can just add validators or an array of validators required to tell Angular if a particular field is mandatory.
Let us now try the same on one of the input textboxes, i.e., email id. For the email id, we have added the following validation parameters −
Required
Pattern matching
This is how a code undergoes validation in app.component.ts.
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 6 Project!';
todaydate;
componentproperty;
emailid;
formdata;
ngOnInit() {
this.formdata = new FormGroup({
emailid: new FormControl("", Validators.compose([
Validators.required,
Validators.pattern("[^ @]*@[^ @]*")
])),
passwd: new FormControl("")
});
}
onClickSubmit(data) {this.emailid = data.emailid;}
}
In Validators.compose, you can add the list of things you want to validate on the input field. Right now, we have added the required and the pattern matching parameters to take only valid email.
In the app.component.html, the submit button is disabled if any of the form inputs are not valid. This is done as follows −
<div>
<form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
<input type = "text" class = "fortextbox" name = "emailid" placeholder = "emailid"
formControlName = "emailid">
<br/>
<input type = "password" class = "fortextbox" name = "passwd"
placeholder = "passwd" formControlName = "passwd">
<br/>
<input type = "submit" [disabled] = "!formdata.valid" class = "forsubmit"
value = "Log In">
</form>
</div>
<p>
Email entered is : {{emailid}}
</p>
For the submit button, we have added disabled in the square bracket, which is given value - !formdata.valid. Thus, if the formdata.valid is not valid, the button will remain disabled and the user will not be able to submit it.
Let us see the how this works in the browser −
In the above case, the email id entered is invalid, hence the login button is disabled. Let us now try entering the valid email id and see the difference.
Now, the email id entered is valid. Thus, we can see the login button is enabled and the user will be able to submit it. With this, the email id entered is displayed at the bottom.
Let us now try custom validation with the same form. For custom validation, we can define our own custom function and add the required details in it. We will now see an example for the same.
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 6 Project!';
todaydate;
componentproperty;
emailid;
formdata;
ngOnInit() {
this.formdata = new FormGroup({
emailid: new FormControl("", Validators.compose([
Validators.required,
Validators.pattern("[^ @]*@[^ @]*")
])),
passwd: new FormControl("", this.passwordvalidation)
});
}
passwordvalidation(formcontrol) {
if (formcontrol.value.length < 5) {
return {"passwd" : true};
}
}
onClickSubmit(data) {this.emailid = data.emailid;}
}
In the above example, we have created a function password validation and the same is used in a previous section in the formcontrol − passwd: new FormControl("", this.passwordvalidation).
In the function that we have created, we will check if the length of the characters entered is appropriate. If the characters are less than five, it will return with the passwd true as shown above - return {"passwd" : true};. If the characters are more than five, it will consider it as valid and the login will be enabled.
Let us now see how this is displayed in the browser −
We have entered only three characters in the password and the login is disabled. To enable login, we need more than five characters. Let us now enter a valid length of characters and check.
The login is enabled as both the email id and the password are valid. The email is displayed at the bottom as we log in.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2151,
"s": 1995,
"text": "In this chapter, we will see how forms are used in Angular 6. We will discuss two ways of working with forms - template driven form and model driven forms."
},
{
"code": null,
"e": 2303,
"s": 2151,
"text": "With a template driven form, most of the work is done in the template; and with the model driven form, most of the work is done in the component class."
},
{
"code": null,
"e": 2572,
"s": 2303,
"text": "Let us now consider working on the Template driven form. We will create a simple login form and add the email id, password and submit the button in the form. To start with, we need to import to FormsModule from @angular/core which is done in app.module.ts as follows −"
},
{
"code": null,
"e": 3464,
"s": 2572,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { RouterModule} from '@angular/router';\nimport { HttpModule } from '@angular/http';\nimport { FormsModule } from '@angular/forms';\nimport { AppComponent } from './app.component';\nimport { MyserviceService } from './myservice.service';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n imports: [\n BrowserModule,\n HttpModule,\n FormsModule,\n RouterModule.forRoot([\n {path: 'new-cmp',component: NewCmpComponent}\n ])\n ],\n providers: [MyserviceService],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3595,
"s": 3464,
"text": "So in app.module.ts, we have imported the FormsModule and the same is added in the imports array as shown in the highlighted code."
},
{
"code": null,
"e": 3654,
"s": 3595,
"text": "Let us now create our form in the app.component.html file."
},
{
"code": null,
"e": 3950,
"s": 3654,
"text": "<form #userlogin = \"ngForm\" (ngSubmit) = \"onClickSubmit(userlogin.value)\" >\n <input type = \"text\" name = \"emailid\" placeholder = \"emailid\" ngModel>\n <br/>\n <input type = \"password\" name = \"passwd\" placeholder = \"passwd\" ngModel>\n <br/>\n <input type = \"submit\" value = \"submit\">\n</form>"
},
{
"code": null,
"e": 4097,
"s": 3950,
"text": "We have created a simple form with input tags having email id, password and the submit button. We have assigned type, name, and placeholder to it."
},
{
"code": null,
"e": 4409,
"s": 4097,
"text": "In template driven forms, we need to create the model form controls by adding the ngModel directive and the name attribute. Thus, wherever we want Angular to access our data from forms, add ngModel to that tag as shown above. Now, if we have to read the emailid and passwd, we need to add the ngModel across it."
},
{
"code": null,
"e": 4630,
"s": 4409,
"text": "If you see, we have also added the ngForm to the #userlogin. The ngForm directive needs to be added to the form template that we have created. We have also added function onClickSubmit and assigned userlogin.value to it."
},
{
"code": null,
"e": 4727,
"s": 4630,
"text": "Let us now create the function in the app.component.ts and fetch the values entered in the form."
},
{
"code": null,
"e": 5257,
"s": 4727,
"text": "import { Component } from '@angular/core';\nimport { MyserviceService } from './myservice.service';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 6 Project!';\n todaydate;\n componentproperty;\n constructor(private myservice: MyserviceService) { }\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n }\n onClickSubmit(data) {\n alert(\"Entered Email id : \" + data.emailid);\n }\n}"
},
{
"code": null,
"e": 5424,
"s": 5257,
"text": "In the above app.component.ts file, we have defined the function onClickSubmit. When you click on the form submit button, the control will come to the above function."
},
{
"code": null,
"e": 5463,
"s": 5424,
"text": "This is how the browser is displayed −"
},
{
"code": null,
"e": 5588,
"s": 5463,
"text": "The form looks like as shown below. Let us enter the data in it and in the submit function, the email id is already entered."
},
{
"code": null,
"e": 5662,
"s": 5588,
"text": "The email id is displayed at the bottom as shown in the above screenshot."
},
{
"code": null,
"e": 5789,
"s": 5662,
"text": "In the model driven form, we need to import the ReactiveFormsModule from @angular/forms and use the same in the imports array."
},
{
"code": null,
"e": 5836,
"s": 5789,
"text": "There is a change which goes in app.module.ts."
},
{
"code": null,
"e": 6780,
"s": 5836,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { RouterModule} from '@angular/router';\nimport { HttpModule } from '@angular/http';\nimport { ReactiveFormsModule } from '@angular/forms';\nimport { AppComponent } from './app.component';\nimport { MyserviceService } from './myservice.service';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n imports: [\n BrowserModule,\n HttpModule,\n ReactiveFormsModule,\n RouterModule.forRoot([\n {\n path: 'new-cmp',\n component: NewCmpComponent\n }\n ])\n ],\n providers: [MyserviceService],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 6930,
"s": 6780,
"text": "In app.component.ts, we need to import a few modules for the model driven form. For example, import { FormGroup, FormControl } from '@angular/forms'."
},
{
"code": null,
"e": 7664,
"s": 6930,
"text": "import { Component } from '@angular/core';\nimport { MyserviceService } from './myservice.service';\nimport { FormGroup, FormControl } from '@angular/forms';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 6 Project!';\n todaydate;\n componentproperty;\n emailid;\n formdata;\n constructor(private myservice: MyserviceService) { }\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n this.formdata = new FormGroup({\n emailid: new FormControl(\"[email protected]\"),\n passwd: new FormControl(\"abcd1234\")\n });\n }\n onClickSubmit(data) {this.emailid = data.emailid;}\n}"
},
{
"code": null,
"e": 7927,
"s": 7664,
"text": "The variable formdata is initialized at the start of the class and the same is initialized with FormGroup as shown above. The variables emailid and passwd are initialized with default values to be displayed in the form. You can keep it blank in case you want to."
},
{
"code": null,
"e": 7979,
"s": 7927,
"text": "This is how the values will be seen in the form UI."
},
{
"code": null,
"e": 8091,
"s": 7979,
"text": "We have used formdata to initialize the form values; we need to use the same in the form UI app.component.html."
},
{
"code": null,
"e": 8597,
"s": 8091,
"text": "<div>\n <form [formGroup] = \"formdata\" (ngSubmit) = \"onClickSubmit(formdata.value)\" >\n <input type = \"text\" class = \"fortextbox\" name = \"emailid\" placeholder = \"emailid\" \n formControlName=\"emailid\">\n <br/>\n \n <input type = \"password\" class = \"fortextbox\" name=\"passwd\" \n placeholder = \"passwd\" formControlName = \"passwd\">\n <br/>\n \n <input type = \"submit\" class = \"forsubmit\" value = \"Log In\">\n </form>\n</div>\n<p>\n Email entered is : {{emailid}}\n</p>"
},
{
"code": null,
"e": 8792,
"s": 8597,
"text": "In the .html file, we have used formGroup in square bracket for the form; for example, [formGroup]=\"formdata\". On submit, the function is called onClickSubmit for which formdata.value is passed."
},
{
"code": null,
"e": 8899,
"s": 8792,
"text": "The input tag formControlName is used. It is given a value that we have used in the app.component.ts file."
},
{
"code": null,
"e": 9019,
"s": 8899,
"text": "On clicking submit, the control will pass to the function onClickSubmit, which is defined in the app.component.ts file."
},
{
"code": null,
"e": 9100,
"s": 9019,
"text": "On clicking Login, the value will be displayed as shown in the above screenshot."
},
{
"code": null,
"e": 9460,
"s": 9100,
"text": "Let us now discuss form validation using model driven form. You can use the built-in form validation or also use the custom validation approach. We will use both the approaches in the form. We will continue with the same example that we created in one of our previous sections. With Angular 4, we need to import Validators from @angular/forms as shown below −"
},
{
"code": null,
"e": 9528,
"s": 9460,
"text": "import { FormGroup, FormControl, Validators} from '@angular/forms'\n"
},
{
"code": null,
"e": 9674,
"s": 9528,
"text": "Angular has built-in validators such as mandatory field, minlength, maxlength, and pattern. These are to be accessed using the Validators module."
},
{
"code": null,
"e": 9789,
"s": 9674,
"text": "You can just add validators or an array of validators required to tell Angular if a particular field is mandatory."
},
{
"code": null,
"e": 9930,
"s": 9789,
"text": "Let us now try the same on one of the input textboxes, i.e., email id. For the email id, we have added the following validation parameters −"
},
{
"code": null,
"e": 9939,
"s": 9930,
"text": "Required"
},
{
"code": null,
"e": 9956,
"s": 9939,
"text": "Pattern matching"
},
{
"code": null,
"e": 10017,
"s": 9956,
"text": "This is how a code undergoes validation in app.component.ts."
},
{
"code": null,
"e": 10685,
"s": 10017,
"text": "import { Component } from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 6 Project!';\n todaydate;\n componentproperty;\n emailid;\n formdata;\n ngOnInit() {\n this.formdata = new FormGroup({\n emailid: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.pattern(\"[^ @]*@[^ @]*\")\n ])),\n passwd: new FormControl(\"\")\n });\n }\n onClickSubmit(data) {this.emailid = data.emailid;}\n}"
},
{
"code": null,
"e": 10880,
"s": 10685,
"text": "In Validators.compose, you can add the list of things you want to validate on the input field. Right now, we have added the required and the pattern matching parameters to take only valid email."
},
{
"code": null,
"e": 11004,
"s": 10880,
"text": "In the app.component.html, the submit button is disabled if any of the form inputs are not valid. This is done as follows −"
},
{
"code": null,
"e": 11541,
"s": 11004,
"text": "<div>\n <form [formGroup] = \"formdata\" (ngSubmit) = \"onClickSubmit(formdata.value)\" >\n <input type = \"text\" class = \"fortextbox\" name = \"emailid\" placeholder = \"emailid\" \n formControlName = \"emailid\">\n <br/>\n <input type = \"password\" class = \"fortextbox\" name = \"passwd\" \n placeholder = \"passwd\" formControlName = \"passwd\">\n <br/>\n <input type = \"submit\" [disabled] = \"!formdata.valid\" class = \"forsubmit\" \n value = \"Log In\">\n </form>\n</div>\n<p>\n Email entered is : {{emailid}}\n</p>"
},
{
"code": null,
"e": 11768,
"s": 11541,
"text": "For the submit button, we have added disabled in the square bracket, which is given value - !formdata.valid. Thus, if the formdata.valid is not valid, the button will remain disabled and the user will not be able to submit it."
},
{
"code": null,
"e": 11815,
"s": 11768,
"text": "Let us see the how this works in the browser −"
},
{
"code": null,
"e": 11970,
"s": 11815,
"text": "In the above case, the email id entered is invalid, hence the login button is disabled. Let us now try entering the valid email id and see the difference."
},
{
"code": null,
"e": 12151,
"s": 11970,
"text": "Now, the email id entered is valid. Thus, we can see the login button is enabled and the user will be able to submit it. With this, the email id entered is displayed at the bottom."
},
{
"code": null,
"e": 12342,
"s": 12151,
"text": "Let us now try custom validation with the same form. For custom validation, we can define our own custom function and add the required details in it. We will now see an example for the same."
},
{
"code": null,
"e": 13162,
"s": 12342,
"text": "import { Component } from '@angular/core';\nimport { FormGroup, FormControl, Validators} from '@angular/forms';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 6 Project!';\n todaydate;\n componentproperty;\n emailid;\n formdata;\n ngOnInit() {\n this.formdata = new FormGroup({\n emailid: new FormControl(\"\", Validators.compose([\n Validators.required,\n Validators.pattern(\"[^ @]*@[^ @]*\")\n ])),\n passwd: new FormControl(\"\", this.passwordvalidation)\n });\n }\n passwordvalidation(formcontrol) {\n if (formcontrol.value.length < 5) {\n return {\"passwd\" : true};\n }\n }\n onClickSubmit(data) {this.emailid = data.emailid;}\n}"
},
{
"code": null,
"e": 13349,
"s": 13162,
"text": "In the above example, we have created a function password validation and the same is used in a previous section in the formcontrol − passwd: new FormControl(\"\", this.passwordvalidation)."
},
{
"code": null,
"e": 13673,
"s": 13349,
"text": "In the function that we have created, we will check if the length of the characters entered is appropriate. If the characters are less than five, it will return with the passwd true as shown above - return {\"passwd\" : true};. If the characters are more than five, it will consider it as valid and the login will be enabled."
},
{
"code": null,
"e": 13727,
"s": 13673,
"text": "Let us now see how this is displayed in the browser −"
},
{
"code": null,
"e": 13917,
"s": 13727,
"text": "We have entered only three characters in the password and the login is disabled. To enable login, we need more than five characters. Let us now enter a valid length of characters and check."
},
{
"code": null,
"e": 14038,
"s": 13917,
"text": "The login is enabled as both the email id and the password are valid. The email is displayed at the bottom as we log in."
},
{
"code": null,
"e": 14073,
"s": 14038,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 14087,
"s": 14073,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 14122,
"s": 14087,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 14136,
"s": 14122,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 14171,
"s": 14136,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 14191,
"s": 14171,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 14226,
"s": 14191,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 14243,
"s": 14226,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 14276,
"s": 14243,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 14288,
"s": 14276,
"text": " Senol Atac"
},
{
"code": null,
"e": 14323,
"s": 14288,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 14335,
"s": 14323,
"text": " Senol Atac"
},
{
"code": null,
"e": 14342,
"s": 14335,
"text": " Print"
},
{
"code": null,
"e": 14353,
"s": 14342,
"text": " Add Notes"
}
] |
Create a grid of cards using Bootstrap 4 .card-deck class | Use the card-deck class in Bootstrap to form a grid of cards with equal width and height.
Set the cards inside the following div −
<div class="card-deck">
<! - - deck- - >
</div>
Let us set the grid of cards now in the card-deck class −
<div class="card-deck">
<div class="card bg-primary">
<div class="card-body text-center">
<p class="card-text">Nothing new!</p>
</div>
</div>
You can try to run the following code to implement the card-deck class
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h3>Demo Messages</h3>
<p>Note: Resize the browser to check the effect.</p>
<div class="card-deck">
<div class="card bg-primary">
<div class="card-body text-center">
<p class="card-text">Nothing new!</p>
</div>
</div>
<div class="card bg-warning">
<div class="card-body text-center">
<p class="card-text">Warning! Compile-time error!</p>
<p class="card-text">Check again!</p>
</div>
</div>
<div class="card bg-success">
<div class="card-body text-center">
<p class="card-text">We won!</p>
</div>
</div>
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "Use the card-deck class in Bootstrap to form a grid of cards with equal width and height."
},
{
"code": null,
"e": 1193,
"s": 1152,
"text": "Set the cards inside the following div −"
},
{
"code": null,
"e": 1243,
"s": 1193,
"text": "<div class=\"card-deck\">\n <! - - deck- - >\n</div>"
},
{
"code": null,
"e": 1301,
"s": 1243,
"text": "Let us set the grid of cards now in the card-deck class −"
},
{
"code": null,
"e": 1455,
"s": 1301,
"text": "<div class=\"card-deck\">\n <div class=\"card bg-primary\">\n <div class=\"card-body text-center\">\n <p class=\"card-text\">Nothing new!</p>\n </div>\n</div>"
},
{
"code": null,
"e": 1526,
"s": 1455,
"text": "You can try to run the following code to implement the card-deck class"
},
{
"code": null,
"e": 1536,
"s": 1526,
"text": "Live Demo"
},
{
"code": null,
"e": 2712,
"s": 1536,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n\n <div class=\"container\"> \n <h3>Demo Messages</h3>\n <p>Note: Resize the browser to check the effect.</p>\n <div class=\"card-deck\">\n <div class=\"card bg-primary\">\n <div class=\"card-body text-center\">\n <p class=\"card-text\">Nothing new!</p>\n </div>\n </div>\n <div class=\"card bg-warning\">\n <div class=\"card-body text-center\">\n <p class=\"card-text\">Warning! Compile-time error!</p>\n <p class=\"card-text\">Check again!</p>\n </div>\n </div>\n <div class=\"card bg-success\">\n <div class=\"card-body text-center\">\n <p class=\"card-text\">We won!</p>\n </div>\n </div>\n </div>\n</div>\n\n</body>\n</html>"
}
] |
How to convert date to timestamp in MongoDB | To convert date to timestamp in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo93.insertOne({"UserName":"Chris","ArrivalDate":new ISODate("2020-10-01")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2d4b6479799acab037af68")
}
> db.demo93.insertOne({"UserName":"David","ArrivalDate":new ISODate("2019-12-31")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2d4b7379799acab037af69")
}
Display all documents from a collection with the help of find() method −
> db.demo93.find();
This will produce the following output −
{ "_id" : ObjectId("5e2d4b6479799acab037af68"), "UserName" : "Chris", "ArrivalDate" : ISODate("2020-10-01T00:00:00Z") }
{ "_id" : ObjectId("5e2d4b7379799acab037af69"), "UserName" : "David", "ArrivalDate" : ISODate("2019-12-31T00:00:00Z") }
Following is the query to convert date to timestamp in MongoDB −
> db.demo93.aggregate([
... { "$match": { "UserName": "Chris" }},
... { "$addFields": {
... "timestamp": { "$toLong": "$ArrivalDate" }
... }}
... ]);
This will produce the following output −
{ "_id" : ObjectId("5e2d4b6479799acab037af68"), "UserName" : "Chris", "ArrivalDate" : ISODate("2020-10-01T00:00:00Z"), "timestamp" : NumberLong("1601510400000") } | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "To convert date to timestamp in MongoDB, use aggregate(). Let us create a collection with documents −"
},
{
"code": null,
"e": 1504,
"s": 1164,
"text": "> db.demo93.insertOne({\"UserName\":\"Chris\",\"ArrivalDate\":new ISODate(\"2020-10-01\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2d4b6479799acab037af68\")\n}\n> db.demo93.insertOne({\"UserName\":\"David\",\"ArrivalDate\":new ISODate(\"2019-12-31\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2d4b7379799acab037af69\")\n}"
},
{
"code": null,
"e": 1577,
"s": 1504,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1597,
"s": 1577,
"text": "> db.demo93.find();"
},
{
"code": null,
"e": 1638,
"s": 1597,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1878,
"s": 1638,
"text": "{ \"_id\" : ObjectId(\"5e2d4b6479799acab037af68\"), \"UserName\" : \"Chris\", \"ArrivalDate\" : ISODate(\"2020-10-01T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5e2d4b7379799acab037af69\"), \"UserName\" : \"David\", \"ArrivalDate\" : ISODate(\"2019-12-31T00:00:00Z\") }"
},
{
"code": null,
"e": 1943,
"s": 1878,
"text": "Following is the query to convert date to timestamp in MongoDB −"
},
{
"code": null,
"e": 2108,
"s": 1943,
"text": "> db.demo93.aggregate([\n... { \"$match\": { \"UserName\": \"Chris\" }},\n... { \"$addFields\": {\n... \"timestamp\": { \"$toLong\": \"$ArrivalDate\" }\n... }}\n... ]);"
},
{
"code": null,
"e": 2149,
"s": 2108,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2312,
"s": 2149,
"text": "{ \"_id\" : ObjectId(\"5e2d4b6479799acab037af68\"), \"UserName\" : \"Chris\", \"ArrivalDate\" : ISODate(\"2020-10-01T00:00:00Z\"), \"timestamp\" : NumberLong(\"1601510400000\") }"
}
] |
Python - Tkinter Relief styles | The relief style of a widget refers to certain simulated 3-D effects around the outside of the widget. Here is a screenshot of a row of buttons exhibiting all the possible relief styles −
Here is list of possible constants which can be used for relief attribute.
FLAT
RAISED
SUNKEN
GROOVE
RIDGE
from Tkinter import *
import Tkinter
top = Tkinter.Tk()
B1 = Tkinter.Button(top, text ="FLAT", relief=FLAT )
B2 = Tkinter.Button(top, text ="RAISED", relief=RAISED )
B3 = Tkinter.Button(top, text ="SUNKEN", relief=SUNKEN )
B4 = Tkinter.Button(top, text ="GROOVE", relief=GROOVE )
B5 = Tkinter.Button(top, text ="RIDGE", relief=RIDGE )
B1.pack()
B2.pack()
B3.pack()
B4.pack()
B5.pack()
top.mainloop()
When the above code is executed, it produces the following result −
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2432,
"s": 2244,
"text": "The relief style of a widget refers to certain simulated 3-D effects around the outside of the widget. Here is a screenshot of a row of buttons exhibiting all the possible relief styles −"
},
{
"code": null,
"e": 2507,
"s": 2432,
"text": "Here is list of possible constants which can be used for relief attribute."
},
{
"code": null,
"e": 2512,
"s": 2507,
"text": "FLAT"
},
{
"code": null,
"e": 2519,
"s": 2512,
"text": "RAISED"
},
{
"code": null,
"e": 2526,
"s": 2519,
"text": "SUNKEN"
},
{
"code": null,
"e": 2533,
"s": 2526,
"text": "GROOVE"
},
{
"code": null,
"e": 2539,
"s": 2533,
"text": "RIDGE"
},
{
"code": null,
"e": 2942,
"s": 2539,
"text": "from Tkinter import *\nimport Tkinter\n\ntop = Tkinter.Tk()\n\nB1 = Tkinter.Button(top, text =\"FLAT\", relief=FLAT )\nB2 = Tkinter.Button(top, text =\"RAISED\", relief=RAISED )\nB3 = Tkinter.Button(top, text =\"SUNKEN\", relief=SUNKEN )\nB4 = Tkinter.Button(top, text =\"GROOVE\", relief=GROOVE )\nB5 = Tkinter.Button(top, text =\"RIDGE\", relief=RIDGE )\n\nB1.pack()\nB2.pack()\nB3.pack()\nB4.pack()\nB5.pack()\ntop.mainloop()"
},
{
"code": null,
"e": 3011,
"s": 2942,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3048,
"s": 3011,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3064,
"s": 3048,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3097,
"s": 3064,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3116,
"s": 3097,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3151,
"s": 3116,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3173,
"s": 3151,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3207,
"s": 3173,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3235,
"s": 3207,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3270,
"s": 3235,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3284,
"s": 3270,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3317,
"s": 3284,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3334,
"s": 3317,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3341,
"s": 3334,
"text": " Print"
},
{
"code": null,
"e": 3352,
"s": 3341,
"text": " Add Notes"
}
] |
Python - Tkinter Listbox | The Listbox widget is used to display a list of items from which a user can select a number of items.
Here is the simple syntax to create this widget −
w = Listbox ( master, option, ... )
master − This represents the parent window.
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
bg
The normal background color displayed behind the label and indicator.
bd
The size of the border around the indicator. Default is 2 pixels.
cursor
The cursor that appears when the mouse is over the listbox.
font
The font used for the text in the listbox.
fg
The color used for the text in the listbox.
height
Number of lines (not pixels!) shown in the listbox. Default is 10.
highlightcolor
Color shown in the focus highlight when the widget has the focus.
highlightthickness
Thickness of the focus highlight.
relief
Selects three-dimensional border shading effects. The default is SUNKEN.
selectbackground
The background color to use displaying selected text.
selectmode
Determines how many items can be selected, and how mouse drags affect the selection −
BROWSE − Normally, you can only select one line out of a listbox. If you click on an item and then drag to a different line, the selection will follow the mouse. This is the default.
SINGLE − You can only select one line, and you can't drag the mouse.wherever you click button 1, that line is selected.
MULTIPLE − You can select any number of lines at once. Clicking on any line toggles whether or not it is selected.
EXTENDED − You can select any adjacent group of lines at once by clicking on the first line and dragging to the last line.
width
The width of the widget in characters. The default is 20.
xscrollcommand
If you want to allow the user to scroll the listbox horizontally, you can link your listbox widget to a horizontal scrollbar.
yscrollcommand
If you want to allow the user to scroll the listbox vertically, you can link your listbox widget to a vertical scrollbar.
Methods on listbox objects include −
activate ( index )
Selects the line specifies by the given index.
curselection()
Returns a tuple containing the line numbers of the selected element or elements, counting from 0. If nothing is selected, returns an empty tuple.
delete ( first, last=None )
Deletes the lines whose indices are in the range [first, last]. If the second argument is omitted, the single line with index first is deleted.
get ( first, last=None )
Returns a tuple containing the text of the lines with indices from first to last, inclusive. If the second argument is omitted, returns the text of the line closest to first.
index ( i )
If possible, positions the visible part of the listbox so that the line containing index i is at the top of the widget.
insert ( index, *elements )
Insert one or more new lines into the listbox before the line specified by index. Use END as the first argument if you want to add new lines to the end of the listbox.
nearest ( y )
Return the index of the visible line closest to the y-coordinate y relative to the listbox widget.
see ( index )
Adjust the position of the listbox so that the line referred to by index is visible.
size()
Returns the number of lines in the listbox.
xview()
To make the listbox horizontally scrollable, set the command option of the associated horizontal scrollbar to this method.
xview_moveto ( fraction )
Scroll the listbox so that the leftmost fraction of the width of its longest line is outside the left side of the listbox. Fraction is in the range [0,1].
xview_scroll ( number, what )
Scrolls the listbox horizontally. For the what argument, use either UNITS to scroll by characters, or PAGES to scroll by pages, that is, by the width of the listbox. The number argument tells how many to scroll.
yview()
To make the listbox vertically scrollable, set the command option of the associated vertical scrollbar to this method.
yview_moveto ( fraction )
Scroll the listbox so that the top fraction of the width of its longest line is outside the left side of the listbox. Fraction is in the range [0,1].
yview_scroll ( number, what )
Scrolls the listbox vertically. For the what argument, use either UNITS to scroll by lines, or PAGES to scroll by pages, that is, by the height of the listbox. The number argument tells how many to scroll.
Try the following example yourself −
from Tkinter import *
import tkMessageBox
import Tkinter
top = Tk()
Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")
Lb1.pack()
top.mainloop()
When the above code is executed, it produces the following result −
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2346,
"s": 2244,
"text": "The Listbox widget is used to display a list of items from which a user can select a number of items."
},
{
"code": null,
"e": 2396,
"s": 2346,
"text": "Here is the simple syntax to create this widget −"
},
{
"code": null,
"e": 2433,
"s": 2396,
"text": "w = Listbox ( master, option, ... )\n"
},
{
"code": null,
"e": 2477,
"s": 2433,
"text": "master − This represents the parent window."
},
{
"code": null,
"e": 2521,
"s": 2477,
"text": "master − This represents the parent window."
},
{
"code": null,
"e": 2661,
"s": 2521,
"text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 2801,
"s": 2661,
"text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 2804,
"s": 2801,
"text": "bg"
},
{
"code": null,
"e": 2874,
"s": 2804,
"text": "The normal background color displayed behind the label and indicator."
},
{
"code": null,
"e": 2878,
"s": 2874,
"text": "bd "
},
{
"code": null,
"e": 2944,
"s": 2878,
"text": "The size of the border around the indicator. Default is 2 pixels."
},
{
"code": null,
"e": 2951,
"s": 2944,
"text": "cursor"
},
{
"code": null,
"e": 3011,
"s": 2951,
"text": "The cursor that appears when the mouse is over the listbox."
},
{
"code": null,
"e": 3016,
"s": 3011,
"text": "font"
},
{
"code": null,
"e": 3059,
"s": 3016,
"text": "The font used for the text in the listbox."
},
{
"code": null,
"e": 3063,
"s": 3059,
"text": "fg "
},
{
"code": null,
"e": 3107,
"s": 3063,
"text": "The color used for the text in the listbox."
},
{
"code": null,
"e": 3114,
"s": 3107,
"text": "height"
},
{
"code": null,
"e": 3181,
"s": 3114,
"text": "Number of lines (not pixels!) shown in the listbox. Default is 10."
},
{
"code": null,
"e": 3196,
"s": 3181,
"text": "highlightcolor"
},
{
"code": null,
"e": 3262,
"s": 3196,
"text": "Color shown in the focus highlight when the widget has the focus."
},
{
"code": null,
"e": 3281,
"s": 3262,
"text": "highlightthickness"
},
{
"code": null,
"e": 3315,
"s": 3281,
"text": "Thickness of the focus highlight."
},
{
"code": null,
"e": 3322,
"s": 3315,
"text": "relief"
},
{
"code": null,
"e": 3395,
"s": 3322,
"text": "Selects three-dimensional border shading effects. The default is SUNKEN."
},
{
"code": null,
"e": 3412,
"s": 3395,
"text": "selectbackground"
},
{
"code": null,
"e": 3466,
"s": 3412,
"text": "The background color to use displaying selected text."
},
{
"code": null,
"e": 3477,
"s": 3466,
"text": "selectmode"
},
{
"code": null,
"e": 3563,
"s": 3477,
"text": "Determines how many items can be selected, and how mouse drags affect the selection −"
},
{
"code": null,
"e": 3746,
"s": 3563,
"text": "BROWSE − Normally, you can only select one line out of a listbox. If you click on an item and then drag to a different line, the selection will follow the mouse. This is the default."
},
{
"code": null,
"e": 3866,
"s": 3746,
"text": "SINGLE − You can only select one line, and you can't drag the mouse.wherever you click button 1, that line is selected."
},
{
"code": null,
"e": 3981,
"s": 3866,
"text": "MULTIPLE − You can select any number of lines at once. Clicking on any line toggles whether or not it is selected."
},
{
"code": null,
"e": 4104,
"s": 3981,
"text": "EXTENDED − You can select any adjacent group of lines at once by clicking on the first line and dragging to the last line."
},
{
"code": null,
"e": 4110,
"s": 4104,
"text": "width"
},
{
"code": null,
"e": 4168,
"s": 4110,
"text": "The width of the widget in characters. The default is 20."
},
{
"code": null,
"e": 4183,
"s": 4168,
"text": "xscrollcommand"
},
{
"code": null,
"e": 4309,
"s": 4183,
"text": "If you want to allow the user to scroll the listbox horizontally, you can link your listbox widget to a horizontal scrollbar."
},
{
"code": null,
"e": 4324,
"s": 4309,
"text": "yscrollcommand"
},
{
"code": null,
"e": 4446,
"s": 4324,
"text": "If you want to allow the user to scroll the listbox vertically, you can link your listbox widget to a vertical scrollbar."
},
{
"code": null,
"e": 4483,
"s": 4446,
"text": "Methods on listbox objects include −"
},
{
"code": null,
"e": 4502,
"s": 4483,
"text": "activate ( index )"
},
{
"code": null,
"e": 4549,
"s": 4502,
"text": "Selects the line specifies by the given index."
},
{
"code": null,
"e": 4564,
"s": 4549,
"text": "curselection()"
},
{
"code": null,
"e": 4710,
"s": 4564,
"text": "Returns a tuple containing the line numbers of the selected element or elements, counting from 0. If nothing is selected, returns an empty tuple."
},
{
"code": null,
"e": 4738,
"s": 4710,
"text": "delete ( first, last=None )"
},
{
"code": null,
"e": 4882,
"s": 4738,
"text": "Deletes the lines whose indices are in the range [first, last]. If the second argument is omitted, the single line with index first is deleted."
},
{
"code": null,
"e": 4907,
"s": 4882,
"text": "get ( first, last=None )"
},
{
"code": null,
"e": 5082,
"s": 4907,
"text": "Returns a tuple containing the text of the lines with indices from first to last, inclusive. If the second argument is omitted, returns the text of the line closest to first."
},
{
"code": null,
"e": 5094,
"s": 5082,
"text": "index ( i )"
},
{
"code": null,
"e": 5214,
"s": 5094,
"text": "If possible, positions the visible part of the listbox so that the line containing index i is at the top of the widget."
},
{
"code": null,
"e": 5242,
"s": 5214,
"text": "insert ( index, *elements )"
},
{
"code": null,
"e": 5410,
"s": 5242,
"text": "Insert one or more new lines into the listbox before the line specified by index. Use END as the first argument if you want to add new lines to the end of the listbox."
},
{
"code": null,
"e": 5424,
"s": 5410,
"text": "nearest ( y )"
},
{
"code": null,
"e": 5523,
"s": 5424,
"text": "Return the index of the visible line closest to the y-coordinate y relative to the listbox widget."
},
{
"code": null,
"e": 5537,
"s": 5523,
"text": "see ( index )"
},
{
"code": null,
"e": 5622,
"s": 5537,
"text": "Adjust the position of the listbox so that the line referred to by index is visible."
},
{
"code": null,
"e": 5629,
"s": 5622,
"text": "size()"
},
{
"code": null,
"e": 5673,
"s": 5629,
"text": "Returns the number of lines in the listbox."
},
{
"code": null,
"e": 5681,
"s": 5673,
"text": "xview()"
},
{
"code": null,
"e": 5805,
"s": 5681,
"text": "To make the listbox horizontally scrollable, set the command option of the associated horizontal scrollbar to this method. "
},
{
"code": null,
"e": 5831,
"s": 5805,
"text": "xview_moveto ( fraction )"
},
{
"code": null,
"e": 5986,
"s": 5831,
"text": "Scroll the listbox so that the leftmost fraction of the width of its longest line is outside the left side of the listbox. Fraction is in the range [0,1]."
},
{
"code": null,
"e": 6016,
"s": 5986,
"text": "xview_scroll ( number, what )"
},
{
"code": null,
"e": 6228,
"s": 6016,
"text": "Scrolls the listbox horizontally. For the what argument, use either UNITS to scroll by characters, or PAGES to scroll by pages, that is, by the width of the listbox. The number argument tells how many to scroll."
},
{
"code": null,
"e": 6236,
"s": 6228,
"text": "yview()"
},
{
"code": null,
"e": 6356,
"s": 6236,
"text": "To make the listbox vertically scrollable, set the command option of the associated vertical scrollbar to this method. "
},
{
"code": null,
"e": 6382,
"s": 6356,
"text": "yview_moveto ( fraction )"
},
{
"code": null,
"e": 6532,
"s": 6382,
"text": "Scroll the listbox so that the top fraction of the width of its longest line is outside the left side of the listbox. Fraction is in the range [0,1]."
},
{
"code": null,
"e": 6562,
"s": 6532,
"text": "yview_scroll ( number, what )"
},
{
"code": null,
"e": 6768,
"s": 6562,
"text": "Scrolls the listbox vertically. For the what argument, use either UNITS to scroll by lines, or PAGES to scroll by pages, that is, by the height of the listbox. The number argument tells how many to scroll."
},
{
"code": null,
"e": 6805,
"s": 6768,
"text": "Try the following example yourself −"
},
{
"code": null,
"e": 7050,
"s": 6805,
"text": "from Tkinter import *\nimport tkMessageBox\nimport Tkinter\n\ntop = Tk()\n\nLb1 = Listbox(top)\nLb1.insert(1, \"Python\")\nLb1.insert(2, \"Perl\")\nLb1.insert(3, \"C\")\nLb1.insert(4, \"PHP\")\nLb1.insert(5, \"JSP\")\nLb1.insert(6, \"Ruby\")\n\nLb1.pack()\ntop.mainloop()"
},
{
"code": null,
"e": 7119,
"s": 7050,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 7156,
"s": 7119,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7172,
"s": 7156,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7205,
"s": 7172,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7224,
"s": 7205,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7259,
"s": 7224,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 7281,
"s": 7259,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 7315,
"s": 7281,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 7343,
"s": 7315,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7378,
"s": 7343,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7392,
"s": 7378,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7425,
"s": 7392,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7442,
"s": 7425,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7449,
"s": 7442,
"text": " Print"
},
{
"code": null,
"e": 7460,
"s": 7449,
"text": " Add Notes"
}
] |
How to tune multiple ML models with GridSearchCV at once? | by Satyam Kumar | Towards Data Science | Model selection is an essential component for a data science model development pipeline. After performing feature engineering the data scientist needs to choose the model with the best set of hyperparameters that performs best for the training dataset. There are various Auto-ML libraries that automate the model selection component.
Grid Search is a cross-validation technique that can be used to tune the hyperparameters of a machine learning model. To choose the robust model from a list of ML models, one needs to perform cross-validation multiple times for each model. In this article, we will discuss a hack or technique to tune multiple models simultaneously using Grid Search and Randomized Searchcross-validation.
GridSearchCV or RandomizedSearchCV are cross-validation techniques to perform hyperparameter tuning to determine the optimal values for a machine learning model. GridSearchCV ideally tries all the possible values of the parameters while RandomizedSearchCV randomly picks the parameters and speeds up the cross-validation workflow.
The above-mentioned code snippet can be used to select the best set of hyperparameters for the random forest classifier model.
Ideally, GridSearchCV or RandomizedSearchCV need to run multiple pipelines for multiple machine learning models, to pick the best model with the best set of hyperparameter values. A data scientist might take a lot of time to develop the code and work through it.
You can tune multiple machine learning models simultaneously with GridSearchCV or RandomizedSearchCV by creating multiple parameters dictionaries and specifying models for each dictionary. The step by step approaches to tune multiple models at once are:
Initialize multiple classifier estimatorsPrepare a pipeline of the 1st classifier.Prepare hyperparameter dictionary of each estimator each having a key as ‘classifier’ and value as estimator object. The hyperparameter keys should start with the word of the classifier separated by ‘__’ (double underscore).List the hyperparameter dictionary.Train a GridSearchCV model with the pipeline and parameter dictionary list.
Initialize multiple classifier estimators
Prepare a pipeline of the 1st classifier.
Prepare hyperparameter dictionary of each estimator each having a key as ‘classifier’ and value as estimator object. The hyperparameter keys should start with the word of the classifier separated by ‘__’ (double underscore).
List the hyperparameter dictionary.
Train a GridSearchCV model with the pipeline and parameter dictionary list.
# Import necessary packages
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import *
# Read the dataset
df = pd.read_csv("DATA/creditcard.csv")
df = df.drop('Time', axis=1)
print(df.shape)
df.head()
(284807, 30)
5 rows × 30 columns
# Dataset sampling for faster computation
pos_idx = list(df[df['Class']==1].index)
neg_idx = list(df[df['Class']==0].sample(5000).index)
df = df.loc[pos_idx+neg_idx]
print(df.shape)
df['Class'].value_counts()
(5492, 30)
0 5000
1 492
Name: Class, dtype: int64
# Train Test Split
y = df['Class']
X = df.drop('Class', axis=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
print(X_train.shape)
print(X_test.shape)
(4393, 29)
(1099, 29)
# Initialze the estimators
clf1 = RandomForestClassifier(random_state=42)
clf2 = SVC(probability=True, random_state=42)
clf3 = LogisticRegression(random_state=42)
clf4 = DecisionTreeClassifier(random_state=42)
clf5 = KNeighborsClassifier()
clf6 = MultinomialNB()
clf7 = GradientBoostingClassifier(random_state=42)
# Initiaze the hyperparameters for each dictionary
param1 = {}
param1['classifier__n_estimators'] = [10, 50, 100, 250]
param1['classifier__max_depth'] = [5, 10, 20]
param1['classifier__class_weight'] = [None, {0:1,1:5}, {0:1,1:10}, {0:1,1:25}]
param1['classifier'] = [clf1]
param2 = {}
param2['classifier__C'] = [10**-2, 10**-1, 10**0, 10**1, 10**2]
param2['classifier__class_weight'] = [None, {0:1,1:5}, {0:1,1:10}, {0:1,1:25}]
param2['classifier'] = [clf2]
param3 = {}
param3['classifier__C'] = [10**-2, 10**-1, 10**0, 10**1, 10**2]
param3['classifier__penalty'] = ['l1', 'l2']
param3['classifier__class_weight'] = [None, {0:1,1:5}, {0:1,1:10}, {0:1,1:25}]
param3['classifier'] = [clf3]
param4 = {}
param4['classifier__max_depth'] = [5,10,25,None]
param4['classifier__min_samples_split'] = [2,5,10]
param4['classifier__class_weight'] = [None, {0:1,1:5}, {0:1,1:10}, {0:1,1:25}]
param4['classifier'] = [clf4]
param5 = {}
param5['classifier__n_neighbors'] = [2,5,10,25,50]
param5['classifier'] = [clf5]
param6 = {}
param6['classifier__alpha'] = [10**0, 10**1, 10**2]
param6['classifier'] = [clf6]
param7 = {}
param7['classifier__n_estimators'] = [10, 50, 100, 250]
param7['classifier__max_depth'] = [5, 10, 20]
param7['classifier'] = [clf7]
pipeline = Pipeline([('classifier', clf1)])
params = [param1, param2, param3, param4, param5, param6, param7]
%%time
# Train the grid search model
gs = GridSearchCV(pipeline, params, cv=3, n_jobs=-1, scoring='roc_auc').fit(X_train, y_train)
# Best performing model and its corresponding hyperparameters
gs.best_params_
{'classifier': SVC(C=10, probability=True, random_state=42),
'classifier__C': 10,
'classifier__class_weight': None}
# ROC-AUC score for the best model
gs.best_score_
0.9838906204691353
# Test data performance
print("Test Precision:",precision_score(gs.predict(X_test), y_test))
print("Test Recall:",recall_score(gs.predict(X_test), y_test))
print("Test ROC AUC Score:",roc_auc_score(gs.predict(X_test), y_test))
Test Precision: 0.7142857142857143
Test Recall: 0.9859154929577465
Test ROC AUC Score: 0.9793390694360716
%%time
# Train the random search model
rs = RandomizedSearchCV(pipeline, params, cv=3, n_jobs=-1, scoring='roc_auc').fit(X_train, y_train)
# Best performing model and its corresponding hyperparameters
gs.best_params_
{'classifier': SVC(C=10, probability=True, random_state=42),
'classifier__C': 10,
'classifier__class_weight': None}
# ROC-AUC score for the best model
gs.best_score_
0.9838906204691353
# Test data performance
print("Precision:",precision_score(rs.predict(X_test), y_test))
print("Recall:",recall_score(rs.predict(X_test), y_test))
print("ROC AUC Score:",roc_auc_score(rs.predict(X_test), y_test))
Precision: 0.8571428571428571
Recall: 0.9882352941176471
ROC AUC Score: 0.9872142940016244
I have used a sample binary classification dataset having ~5000 instances and 29 independent features. To train a robust machine learning model, I have initialized 7 machine learning estimators including:
Random Forest
Support Vector Classifier
Logistic Regression
Decision Tree
k-Nearest Neighbours
Naive Bayes
Gradient Boosting
and further prepared their corresponding hyperparameters dictionary with the variable name param_i.
Scikit-learn package comes with the GridSearchCV implementation. I have passed the 1st estimator with the pipeline and the parameter dictionary list to the GridSearchCV model.
The GridSearchCV takes 120 secs to train 176 models for 7 estimators. The Support Vector Classifier with C=10, class_weight=None performs the best with a cross-validation ROC AUC score of 0.984 and test ROC AUC score of 0.979.
The RandomizedSearchCV model takes 9 secs to train the same set of models. The same Support Vector Classifier resulted to perform the best.
In this article, we have discussed how GridSearchCV and RandomizedSearchCV can be used to tune multiple machine learning models simultaneously. This is a very handy technique and speeds up the model selection workflow.
[1] Scikit-learn documentation: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you.
satyam-kumar.medium.com
Thank You for Reading | [
{
"code": null,
"e": 506,
"s": 172,
"text": "Model selection is an essential component for a data science model development pipeline. After performing feature engineering the data scientist needs to choose the model with the best set of hyperparameters that performs best for the training dataset. There are various Auto-ML libraries that automate the model selection component."
},
{
"code": null,
"e": 895,
"s": 506,
"text": "Grid Search is a cross-validation technique that can be used to tune the hyperparameters of a machine learning model. To choose the robust model from a list of ML models, one needs to perform cross-validation multiple times for each model. In this article, we will discuss a hack or technique to tune multiple models simultaneously using Grid Search and Randomized Searchcross-validation."
},
{
"code": null,
"e": 1226,
"s": 895,
"text": "GridSearchCV or RandomizedSearchCV are cross-validation techniques to perform hyperparameter tuning to determine the optimal values for a machine learning model. GridSearchCV ideally tries all the possible values of the parameters while RandomizedSearchCV randomly picks the parameters and speeds up the cross-validation workflow."
},
{
"code": null,
"e": 1353,
"s": 1226,
"text": "The above-mentioned code snippet can be used to select the best set of hyperparameters for the random forest classifier model."
},
{
"code": null,
"e": 1616,
"s": 1353,
"text": "Ideally, GridSearchCV or RandomizedSearchCV need to run multiple pipelines for multiple machine learning models, to pick the best model with the best set of hyperparameter values. A data scientist might take a lot of time to develop the code and work through it."
},
{
"code": null,
"e": 1870,
"s": 1616,
"text": "You can tune multiple machine learning models simultaneously with GridSearchCV or RandomizedSearchCV by creating multiple parameters dictionaries and specifying models for each dictionary. The step by step approaches to tune multiple models at once are:"
},
{
"code": null,
"e": 2287,
"s": 1870,
"text": "Initialize multiple classifier estimatorsPrepare a pipeline of the 1st classifier.Prepare hyperparameter dictionary of each estimator each having a key as ‘classifier’ and value as estimator object. The hyperparameter keys should start with the word of the classifier separated by ‘__’ (double underscore).List the hyperparameter dictionary.Train a GridSearchCV model with the pipeline and parameter dictionary list."
},
{
"code": null,
"e": 2329,
"s": 2287,
"text": "Initialize multiple classifier estimators"
},
{
"code": null,
"e": 2371,
"s": 2329,
"text": "Prepare a pipeline of the 1st classifier."
},
{
"code": null,
"e": 2596,
"s": 2371,
"text": "Prepare hyperparameter dictionary of each estimator each having a key as ‘classifier’ and value as estimator object. The hyperparameter keys should start with the word of the classifier separated by ‘__’ (double underscore)."
},
{
"code": null,
"e": 2632,
"s": 2596,
"text": "List the hyperparameter dictionary."
},
{
"code": null,
"e": 2708,
"s": 2632,
"text": "Train a GridSearchCV model with the pipeline and parameter dictionary list."
},
{
"code": null,
"e": 3280,
"s": 2708,
"text": "# Import necessary packages\nimport pandas as pd\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import *\n"
},
{
"code": null,
"e": 3395,
"s": 3280,
"text": "# Read the dataset\ndf = pd.read_csv(\"DATA/creditcard.csv\")\ndf = df.drop('Time', axis=1)\nprint(df.shape)\ndf.head()\n"
},
{
"code": null,
"e": 3409,
"s": 3395,
"text": "(284807, 30)\n"
},
{
"code": null,
"e": 3429,
"s": 3409,
"text": "5 rows × 30 columns"
},
{
"code": null,
"e": 3640,
"s": 3429,
"text": "# Dataset sampling for faster computation\npos_idx = list(df[df['Class']==1].index)\nneg_idx = list(df[df['Class']==0].sample(5000).index)\n\ndf = df.loc[pos_idx+neg_idx]\nprint(df.shape)\ndf['Class'].value_counts()\n"
},
{
"code": null,
"e": 3652,
"s": 3640,
"text": "(5492, 30)\n"
},
{
"code": null,
"e": 3698,
"s": 3652,
"text": "0 5000\n1 492\nName: Class, dtype: int64"
},
{
"code": null,
"e": 3907,
"s": 3698,
"text": "# Train Test Split\ny = df['Class']\nX = df.drop('Class', axis=1)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\nprint(X_train.shape)\nprint(X_test.shape)\n"
},
{
"code": null,
"e": 3930,
"s": 3907,
"text": "(4393, 29)\n(1099, 29)\n"
},
{
"code": null,
"e": 4245,
"s": 3930,
"text": "# Initialze the estimators\nclf1 = RandomForestClassifier(random_state=42)\nclf2 = SVC(probability=True, random_state=42)\nclf3 = LogisticRegression(random_state=42)\nclf4 = DecisionTreeClassifier(random_state=42)\nclf5 = KNeighborsClassifier()\nclf6 = MultinomialNB()\nclf7 = GradientBoostingClassifier(random_state=42)\n"
},
{
"code": null,
"e": 5493,
"s": 4245,
"text": "# Initiaze the hyperparameters for each dictionary\nparam1 = {}\nparam1['classifier__n_estimators'] = [10, 50, 100, 250]\nparam1['classifier__max_depth'] = [5, 10, 20]\nparam1['classifier__class_weight'] = [None, {0:1,1:5}, {0:1,1:10}, {0:1,1:25}]\nparam1['classifier'] = [clf1]\n\nparam2 = {}\nparam2['classifier__C'] = [10**-2, 10**-1, 10**0, 10**1, 10**2]\nparam2['classifier__class_weight'] = [None, {0:1,1:5}, {0:1,1:10}, {0:1,1:25}]\nparam2['classifier'] = [clf2]\n\nparam3 = {}\nparam3['classifier__C'] = [10**-2, 10**-1, 10**0, 10**1, 10**2]\nparam3['classifier__penalty'] = ['l1', 'l2']\nparam3['classifier__class_weight'] = [None, {0:1,1:5}, {0:1,1:10}, {0:1,1:25}]\nparam3['classifier'] = [clf3]\n\nparam4 = {}\nparam4['classifier__max_depth'] = [5,10,25,None]\nparam4['classifier__min_samples_split'] = [2,5,10]\nparam4['classifier__class_weight'] = [None, {0:1,1:5}, {0:1,1:10}, {0:1,1:25}]\nparam4['classifier'] = [clf4]\n\nparam5 = {}\nparam5['classifier__n_neighbors'] = [2,5,10,25,50]\nparam5['classifier'] = [clf5]\n\nparam6 = {}\nparam6['classifier__alpha'] = [10**0, 10**1, 10**2]\nparam6['classifier'] = [clf6]\n\nparam7 = {}\nparam7['classifier__n_estimators'] = [10, 50, 100, 250]\nparam7['classifier__max_depth'] = [5, 10, 20]\nparam7['classifier'] = [clf7]\n"
},
{
"code": null,
"e": 5604,
"s": 5493,
"text": "pipeline = Pipeline([('classifier', clf1)])\nparams = [param1, param2, param3, param4, param5, param6, param7]\n"
},
{
"code": null,
"e": 5736,
"s": 5604,
"text": "%%time\n# Train the grid search model\ngs = GridSearchCV(pipeline, params, cv=3, n_jobs=-1, scoring='roc_auc').fit(X_train, y_train)\n"
},
{
"code": null,
"e": 5815,
"s": 5736,
"text": "# Best performing model and its corresponding hyperparameters\ngs.best_params_\n"
},
{
"code": null,
"e": 5933,
"s": 5815,
"text": "{'classifier': SVC(C=10, probability=True, random_state=42),\n 'classifier__C': 10,\n 'classifier__class_weight': None}"
},
{
"code": null,
"e": 5984,
"s": 5933,
"text": "# ROC-AUC score for the best model\ngs.best_score_\n"
},
{
"code": null,
"e": 6003,
"s": 5984,
"text": "0.9838906204691353"
},
{
"code": null,
"e": 6231,
"s": 6003,
"text": "# Test data performance\nprint(\"Test Precision:\",precision_score(gs.predict(X_test), y_test))\nprint(\"Test Recall:\",recall_score(gs.predict(X_test), y_test))\nprint(\"Test ROC AUC Score:\",roc_auc_score(gs.predict(X_test), y_test))\n"
},
{
"code": null,
"e": 6338,
"s": 6231,
"text": "Test Precision: 0.7142857142857143\nTest Recall: 0.9859154929577465\nTest ROC AUC Score: 0.9793390694360716\n"
},
{
"code": null,
"e": 6478,
"s": 6338,
"text": "%%time\n# Train the random search model\nrs = RandomizedSearchCV(pipeline, params, cv=3, n_jobs=-1, scoring='roc_auc').fit(X_train, y_train)\n"
},
{
"code": null,
"e": 6557,
"s": 6478,
"text": "# Best performing model and its corresponding hyperparameters\ngs.best_params_\n"
},
{
"code": null,
"e": 6675,
"s": 6557,
"text": "{'classifier': SVC(C=10, probability=True, random_state=42),\n 'classifier__C': 10,\n 'classifier__class_weight': None}"
},
{
"code": null,
"e": 6726,
"s": 6675,
"text": "# ROC-AUC score for the best model\ngs.best_score_\n"
},
{
"code": null,
"e": 6745,
"s": 6726,
"text": "0.9838906204691353"
},
{
"code": null,
"e": 6958,
"s": 6745,
"text": "# Test data performance\nprint(\"Precision:\",precision_score(rs.predict(X_test), y_test))\nprint(\"Recall:\",recall_score(rs.predict(X_test), y_test))\nprint(\"ROC AUC Score:\",roc_auc_score(rs.predict(X_test), y_test))\n"
},
{
"code": null,
"e": 7050,
"s": 6958,
"text": "Precision: 0.8571428571428571\nRecall: 0.9882352941176471\nROC AUC Score: 0.9872142940016244\n"
},
{
"code": null,
"e": 7258,
"s": 7053,
"text": "I have used a sample binary classification dataset having ~5000 instances and 29 independent features. To train a robust machine learning model, I have initialized 7 machine learning estimators including:"
},
{
"code": null,
"e": 7272,
"s": 7258,
"text": "Random Forest"
},
{
"code": null,
"e": 7298,
"s": 7272,
"text": "Support Vector Classifier"
},
{
"code": null,
"e": 7318,
"s": 7298,
"text": "Logistic Regression"
},
{
"code": null,
"e": 7332,
"s": 7318,
"text": "Decision Tree"
},
{
"code": null,
"e": 7353,
"s": 7332,
"text": "k-Nearest Neighbours"
},
{
"code": null,
"e": 7365,
"s": 7353,
"text": "Naive Bayes"
},
{
"code": null,
"e": 7383,
"s": 7365,
"text": "Gradient Boosting"
},
{
"code": null,
"e": 7483,
"s": 7383,
"text": "and further prepared their corresponding hyperparameters dictionary with the variable name param_i."
},
{
"code": null,
"e": 7659,
"s": 7483,
"text": "Scikit-learn package comes with the GridSearchCV implementation. I have passed the 1st estimator with the pipeline and the parameter dictionary list to the GridSearchCV model."
},
{
"code": null,
"e": 7886,
"s": 7659,
"text": "The GridSearchCV takes 120 secs to train 176 models for 7 estimators. The Support Vector Classifier with C=10, class_weight=None performs the best with a cross-validation ROC AUC score of 0.984 and test ROC AUC score of 0.979."
},
{
"code": null,
"e": 8026,
"s": 7886,
"text": "The RandomizedSearchCV model takes 9 secs to train the same set of models. The same Support Vector Classifier resulted to perform the best."
},
{
"code": null,
"e": 8245,
"s": 8026,
"text": "In this article, we have discussed how GridSearchCV and RandomizedSearchCV can be used to tune multiple machine learning models simultaneously. This is a very handy technique and speeds up the model selection workflow."
},
{
"code": null,
"e": 8369,
"s": 8245,
"text": "[1] Scikit-learn documentation: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html"
},
{
"code": null,
"e": 8558,
"s": 8369,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 8582,
"s": 8558,
"text": "satyam-kumar.medium.com"
}
] |
Solidity - Loop Control | Solidity provides full control to handle loops and switch statements. There may be a situation when you need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your code block and start the next iteration of the loop.
To handle all such situations, Solidity provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively.
The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces.
The flow chart of a break statement would look as follows −
The following example illustrates the use of a break statement with a while loop.
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData;
constructor() public{
storedData = 10;
}
function getResult() public view returns(string memory){
uint a = 1;
uint b = 2;
uint result = a + b;
return integerToString(result);
}
function integerToString(uint _i) internal pure
returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (true) {
len++;
j /= 10;
if(j==0){
break; //using break statement
}
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
}
Run the above program using steps provided in Solidity First Application chapter.
0: string: 3
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.
This example illustrates the use of a continue statement with a while loop.
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData;
constructor() public{
storedData = 10;
}
function getResult() public view returns(string memory){
uint n = 1;
uint sum = 0;
while( n < 10){
n++;
if(n == 5){
continue; // skip n in sum when it is 5.
}
sum = sum + n;
}
return integerToString(sum);
}
function integerToString(uint _i) internal pure
returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (true) {
len++;
j /= 10;
if(j==0){
break; //using break statement
}
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
}
Run the above program using steps provided in Solidity First Application chapter.
0: string: 49
38 Lectures
4.5 hours
Abhilash Nelson
62 Lectures
8.5 hours
Frahaan Hussain
31 Lectures
3.5 hours
Swapnil Kole
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2835,
"s": 2555,
"text": "Solidity provides full control to handle loops and switch statements. There may be a situation when you need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your code block and start the next iteration of the loop."
},
{
"code": null,
"e": 3034,
"s": 2835,
"text": "To handle all such situations, Solidity provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively."
},
{
"code": null,
"e": 3185,
"s": 3034,
"text": "The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces."
},
{
"code": null,
"e": 3245,
"s": 3185,
"text": "The flow chart of a break statement would look as follows −"
},
{
"code": null,
"e": 3327,
"s": 3245,
"text": "The following example illustrates the use of a break statement with a while loop."
},
{
"code": null,
"e": 4148,
"s": 3327,
"text": "pragma solidity ^0.5.0;\n\ncontract SolidityTest {\n uint storedData; \n constructor() public{\n storedData = 10; \n }\n function getResult() public view returns(string memory){\n uint a = 1; \n uint b = 2;\n uint result = a + b;\n return integerToString(result); \n }\n function integerToString(uint _i) internal pure \n returns (string memory) {\n \n if (_i == 0) {\n return \"0\";\n }\n uint j = _i;\n uint len;\n \n while (true) {\n len++;\n j /= 10;\n if(j==0){\n break; //using break statement\n }\n }\n bytes memory bstr = new bytes(len);\n uint k = len - 1;\n \n while (_i != 0) {\n bstr[k--] = byte(uint8(48 + _i % 10));\n _i /= 10;\n }\n return string(bstr);\n }\n}"
},
{
"code": null,
"e": 4230,
"s": 4148,
"text": "Run the above program using steps provided in Solidity First Application chapter."
},
{
"code": null,
"e": 4244,
"s": 4230,
"text": "0: string: 3\n"
},
{
"code": null,
"e": 4597,
"s": 4244,
"text": "The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop."
},
{
"code": null,
"e": 4673,
"s": 4597,
"text": "This example illustrates the use of a continue statement with a while loop."
},
{
"code": null,
"e": 5625,
"s": 4673,
"text": "pragma solidity ^0.5.0;\n\ncontract SolidityTest {\n uint storedData; \n constructor() public{\n storedData = 10; \n }\n function getResult() public view returns(string memory){\n uint n = 1;\n uint sum = 0;\n \n while( n < 10){\n n++;\n if(n == 5){\n continue; // skip n in sum when it is 5.\n }\n sum = sum + n;\n }\n return integerToString(sum); \n }\n function integerToString(uint _i) internal pure \n returns (string memory) {\n \n if (_i == 0) {\n return \"0\";\n }\n uint j = _i;\n uint len;\n \n while (true) {\n len++;\n j /= 10;\n if(j==0){\n break; //using break statement\n }\n }\n bytes memory bstr = new bytes(len);\n uint k = len - 1;\n \n while (_i != 0) {\n bstr[k--] = byte(uint8(48 + _i % 10));\n _i /= 10;\n }\n return string(bstr);\n }\n}"
},
{
"code": null,
"e": 5707,
"s": 5625,
"text": "Run the above program using steps provided in Solidity First Application chapter."
},
{
"code": null,
"e": 5722,
"s": 5707,
"text": "0: string: 49\n"
},
{
"code": null,
"e": 5757,
"s": 5722,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5774,
"s": 5757,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5809,
"s": 5774,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5826,
"s": 5809,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5861,
"s": 5826,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5875,
"s": 5861,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 5882,
"s": 5875,
"text": " Print"
},
{
"code": null,
"e": 5893,
"s": 5882,
"text": " Add Notes"
}
] |
Difference between Increment and Decrement Operators - GeeksforGeeks | 07 Apr, 2020
Programming languages like C/C++/Java have increment and decrement operators. These are very useful and common operators.
Increment Operators: The increment operator is used to increment the value of a variable in an expression. In the Pre-Increment, value is first incremented and then used inside the expression. Whereas in the Post-Increment, value is first used inside the expression and then incremented.Syntax:// PREFIX
++m
// POSTFIX
m++
where m is a variable
Example:#include <stdio.h> int increment(int a, int b){ a = 5; // POSTFIX b = a++; printf("%d", b); // PREFIX int c = ++b; printf("\n%d", c);} // Driver codeint main(){ int x, y; increment(x, y); return 0;}Decrement Operators: The decrement operator is used to decrement the value of a variable in an expression. In the Pre-Decrement, value is first decremented and then used inside the expression. Whereas in the Post-Decrement, value is first used inside the expression and then decremented.Syntax:// PREFIX
--m
// POSTFIX
m--
where m is a variable
Example:#include <stdio.h> int decrement(int a, int b){ a = 5; // POSTFIX b = a--; printf("%d", b); // PREFIX int c = --b; printf("\n%d", c);} // Driver codeint main(){ int x, y; decrement(x, y); return 0;}Differences between Increment And Decrement Operators:Increment OperatorsDecrement OperatorsIncrement Operator adds 1 to the operand.Decrement Operator subtracts 1 from the operand.Postfix increment operator means the expression is evaluated first using the original value of the variable and then the variable is incremented(increased).Postfix decrement operator means the expression is evaluated first using the original value of the variable and then the variable is decremented(decreased).Prefix increment operator means the variable is incremented first and then the expression is evaluated using the new value of the variable.Prefix decrement operator means the variable is decremented first and then the expression is evaluated using the new value of the variable.Generally, we use this in decision making and looping.This is also used in decision making and looping.My Personal Notes
arrow_drop_upSave
Increment Operators: The increment operator is used to increment the value of a variable in an expression. In the Pre-Increment, value is first incremented and then used inside the expression. Whereas in the Post-Increment, value is first used inside the expression and then incremented.Syntax:// PREFIX
++m
// POSTFIX
m++
where m is a variable
Example:#include <stdio.h> int increment(int a, int b){ a = 5; // POSTFIX b = a++; printf("%d", b); // PREFIX int c = ++b; printf("\n%d", c);} // Driver codeint main(){ int x, y; increment(x, y); return 0;}
Syntax:
// PREFIX
++m
// POSTFIX
m++
where m is a variable
Example:
#include <stdio.h> int increment(int a, int b){ a = 5; // POSTFIX b = a++; printf("%d", b); // PREFIX int c = ++b; printf("\n%d", c);} // Driver codeint main(){ int x, y; increment(x, y); return 0;}
Decrement Operators: The decrement operator is used to decrement the value of a variable in an expression. In the Pre-Decrement, value is first decremented and then used inside the expression. Whereas in the Post-Decrement, value is first used inside the expression and then decremented.Syntax:// PREFIX
--m
// POSTFIX
m--
where m is a variable
Example:#include <stdio.h> int decrement(int a, int b){ a = 5; // POSTFIX b = a--; printf("%d", b); // PREFIX int c = --b; printf("\n%d", c);} // Driver codeint main(){ int x, y; decrement(x, y); return 0;}Differences between Increment And Decrement Operators:Increment OperatorsDecrement OperatorsIncrement Operator adds 1 to the operand.Decrement Operator subtracts 1 from the operand.Postfix increment operator means the expression is evaluated first using the original value of the variable and then the variable is incremented(increased).Postfix decrement operator means the expression is evaluated first using the original value of the variable and then the variable is decremented(decreased).Prefix increment operator means the variable is incremented first and then the expression is evaluated using the new value of the variable.Prefix decrement operator means the variable is decremented first and then the expression is evaluated using the new value of the variable.Generally, we use this in decision making and looping.This is also used in decision making and looping.My Personal Notes
arrow_drop_upSave
Syntax:
// PREFIX
--m
// POSTFIX
m--
where m is a variable
Example:
#include <stdio.h> int decrement(int a, int b){ a = 5; // POSTFIX b = a--; printf("%d", b); // PREFIX int c = --b; printf("\n%d", c);} // Driver codeint main(){ int x, y; decrement(x, y); return 0;}
Differences between Increment And Decrement Operators:
him_ansh_1608
Technical Scripter 2019
C Language
C++
Difference Between
Java
Programming Language
Technical Scripter
Java
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
Substring in C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects | [
{
"code": null,
"e": 25180,
"s": 25152,
"text": "\n07 Apr, 2020"
},
{
"code": null,
"e": 25302,
"s": 25180,
"text": "Programming languages like C/C++/Java have increment and decrement operators. These are very useful and common operators."
},
{
"code": null,
"e": 27394,
"s": 25302,
"text": "Increment Operators: The increment operator is used to increment the value of a variable in an expression. In the Pre-Increment, value is first incremented and then used inside the expression. Whereas in the Post-Increment, value is first used inside the expression and then incremented.Syntax:// PREFIX\n++m\n\n// POSTFIX\nm++\n\nwhere m is a variable\nExample:#include <stdio.h> int increment(int a, int b){ a = 5; // POSTFIX b = a++; printf(\"%d\", b); // PREFIX int c = ++b; printf(\"\\n%d\", c);} // Driver codeint main(){ int x, y; increment(x, y); return 0;}Decrement Operators: The decrement operator is used to decrement the value of a variable in an expression. In the Pre-Decrement, value is first decremented and then used inside the expression. Whereas in the Post-Decrement, value is first used inside the expression and then decremented.Syntax:// PREFIX\n--m\n\n// POSTFIX\nm--\n\nwhere m is a variable\nExample:#include <stdio.h> int decrement(int a, int b){ a = 5; // POSTFIX b = a--; printf(\"%d\", b); // PREFIX int c = --b; printf(\"\\n%d\", c);} // Driver codeint main(){ int x, y; decrement(x, y); return 0;}Differences between Increment And Decrement Operators:Increment OperatorsDecrement OperatorsIncrement Operator adds 1 to the operand.Decrement Operator subtracts 1 from the operand.Postfix increment operator means the expression is evaluated first using the original value of the variable and then the variable is incremented(increased).Postfix decrement operator means the expression is evaluated first using the original value of the variable and then the variable is decremented(decreased).Prefix increment operator means the variable is incremented first and then the expression is evaluated using the new value of the variable.Prefix decrement operator means the variable is decremented first and then the expression is evaluated using the new value of the variable.Generally, we use this in decision making and looping.This is also used in decision making and looping.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 27986,
"s": 27394,
"text": "Increment Operators: The increment operator is used to increment the value of a variable in an expression. In the Pre-Increment, value is first incremented and then used inside the expression. Whereas in the Post-Increment, value is first used inside the expression and then incremented.Syntax:// PREFIX\n++m\n\n// POSTFIX\nm++\n\nwhere m is a variable\nExample:#include <stdio.h> int increment(int a, int b){ a = 5; // POSTFIX b = a++; printf(\"%d\", b); // PREFIX int c = ++b; printf(\"\\n%d\", c);} // Driver codeint main(){ int x, y; increment(x, y); return 0;}"
},
{
"code": null,
"e": 27994,
"s": 27986,
"text": "Syntax:"
},
{
"code": null,
"e": 28048,
"s": 27994,
"text": "// PREFIX\n++m\n\n// POSTFIX\nm++\n\nwhere m is a variable\n"
},
{
"code": null,
"e": 28057,
"s": 28048,
"text": "Example:"
},
{
"code": "#include <stdio.h> int increment(int a, int b){ a = 5; // POSTFIX b = a++; printf(\"%d\", b); // PREFIX int c = ++b; printf(\"\\n%d\", c);} // Driver codeint main(){ int x, y; increment(x, y); return 0;}",
"e": 28294,
"s": 28057,
"text": null
},
{
"code": null,
"e": 29795,
"s": 28294,
"text": "Decrement Operators: The decrement operator is used to decrement the value of a variable in an expression. In the Pre-Decrement, value is first decremented and then used inside the expression. Whereas in the Post-Decrement, value is first used inside the expression and then decremented.Syntax:// PREFIX\n--m\n\n// POSTFIX\nm--\n\nwhere m is a variable\nExample:#include <stdio.h> int decrement(int a, int b){ a = 5; // POSTFIX b = a--; printf(\"%d\", b); // PREFIX int c = --b; printf(\"\\n%d\", c);} // Driver codeint main(){ int x, y; decrement(x, y); return 0;}Differences between Increment And Decrement Operators:Increment OperatorsDecrement OperatorsIncrement Operator adds 1 to the operand.Decrement Operator subtracts 1 from the operand.Postfix increment operator means the expression is evaluated first using the original value of the variable and then the variable is incremented(increased).Postfix decrement operator means the expression is evaluated first using the original value of the variable and then the variable is decremented(decreased).Prefix increment operator means the variable is incremented first and then the expression is evaluated using the new value of the variable.Prefix decrement operator means the variable is decremented first and then the expression is evaluated using the new value of the variable.Generally, we use this in decision making and looping.This is also used in decision making and looping.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 29803,
"s": 29795,
"text": "Syntax:"
},
{
"code": null,
"e": 29857,
"s": 29803,
"text": "// PREFIX\n--m\n\n// POSTFIX\nm--\n\nwhere m is a variable\n"
},
{
"code": null,
"e": 29866,
"s": 29857,
"text": "Example:"
},
{
"code": "#include <stdio.h> int decrement(int a, int b){ a = 5; // POSTFIX b = a--; printf(\"%d\", b); // PREFIX int c = --b; printf(\"\\n%d\", c);} // Driver codeint main(){ int x, y; decrement(x, y); return 0;}",
"e": 30103,
"s": 29866,
"text": null
},
{
"code": null,
"e": 30158,
"s": 30103,
"text": "Differences between Increment And Decrement Operators:"
},
{
"code": null,
"e": 30172,
"s": 30158,
"text": "him_ansh_1608"
},
{
"code": null,
"e": 30196,
"s": 30172,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 30207,
"s": 30196,
"text": "C Language"
},
{
"code": null,
"e": 30211,
"s": 30207,
"text": "C++"
},
{
"code": null,
"e": 30230,
"s": 30211,
"text": "Difference Between"
},
{
"code": null,
"e": 30235,
"s": 30230,
"text": "Java"
},
{
"code": null,
"e": 30256,
"s": 30235,
"text": "Programming Language"
},
{
"code": null,
"e": 30275,
"s": 30256,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30280,
"s": 30275,
"text": "Java"
},
{
"code": null,
"e": 30284,
"s": 30280,
"text": "CPP"
},
{
"code": null,
"e": 30382,
"s": 30284,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30417,
"s": 30382,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 30445,
"s": 30417,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 30485,
"s": 30445,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 30531,
"s": 30485,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 30548,
"s": 30531,
"text": "Substring in C++"
},
{
"code": null,
"e": 30566,
"s": 30548,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 30612,
"s": 30566,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 30631,
"s": 30612,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30674,
"s": 30631,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
How to Set the Location of the Label in C#? - GeeksforGeeks | 30 Jun, 2019
In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the location of the Label control using the Location Property in the windows form. This property contains the coordinates of the upper-left corner of the Label control relative to the upper-left corner of its form. You can set this property using two different methods:
1. Design-Time: It is the easiest method to set the Location property of the Label control using the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the Label control to set the Location property of the Label.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the location of the Label control in the windows forms programmatically with the help of given syntax:
public System.Drawing.Point Location { get; set; }
Here, the Point indicates the upper-left corner of the Label control relative to the upper-left corner of its form. Following steps are used to set the Location property of the Label:
Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class
Label mylab = new Label();
// Creating label using Label class
Label mylab = new Label();
Step 2: After creating Label, set the Location property of the Label provided by the Label class.// Set Location property of the label
mylab.Location = new Point(222, 90);
// Set Location property of the label
mylab.Location = new Point(222, 90);
Step 3: And last add this Label control to form using Add() method.// Add this label to the form
this.Controls.Add(mylab);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font("Calibri", 18); mylab.ForeColor = Color.Green; // Adding this control to the form this.Controls.Add(mylab); }}}Output:
// Add this label to the form
this.Controls.Add(mylab);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font("Calibri", 18); mylab.ForeColor = Color.Green; // Adding this control to the form this.Controls.Add(mylab); }}}
Output:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Introduction to .NET Framework
C# | Arrays | [
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n30 Jun, 2019"
},
{
"code": null,
"e": 25670,
"s": 25237,
"text": "In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the location of the Label control using the Location Property in the windows form. This property contains the coordinates of the upper-left corner of the Label control relative to the upper-left corner of its form. You can set this property using two different methods:"
},
{
"code": null,
"e": 25788,
"s": 25670,
"text": "1. Design-Time: It is the easiest method to set the Location property of the Label control using the following steps:"
},
{
"code": null,
"e": 25904,
"s": 25788,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 26079,
"s": 25904,
"text": "Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 26208,
"s": 26079,
"text": "Step 3: After drag and drop you will go to the properties of the Label control to set the Location property of the Label.Output:"
},
{
"code": null,
"e": 26216,
"s": 26208,
"text": "Output:"
},
{
"code": null,
"e": 26411,
"s": 26216,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the location of the Label control in the windows forms programmatically with the help of given syntax:"
},
{
"code": null,
"e": 26462,
"s": 26411,
"text": "public System.Drawing.Point Location { get; set; }"
},
{
"code": null,
"e": 26646,
"s": 26462,
"text": "Here, the Point indicates the upper-left corner of the Label control relative to the upper-left corner of its form. Following steps are used to set the Location property of the Label:"
},
{
"code": null,
"e": 26794,
"s": 26646,
"text": "Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class\nLabel mylab = new Label();\n"
},
{
"code": null,
"e": 26858,
"s": 26794,
"text": "// Creating label using Label class\nLabel mylab = new Label();\n"
},
{
"code": null,
"e": 27031,
"s": 26858,
"text": "Step 2: After creating Label, set the Location property of the Label provided by the Label class.// Set Location property of the label\nmylab.Location = new Point(222, 90);\n"
},
{
"code": null,
"e": 27107,
"s": 27031,
"text": "// Set Location property of the label\nmylab.Location = new Point(222, 90);\n"
},
{
"code": null,
"e": 27994,
"s": 27107,
"text": "Step 3: And last add this Label control to form using Add() method.// Add this label to the form\nthis.Controls.Add(mylab);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font(\"Calibri\", 18); mylab.ForeColor = Color.Green; // Adding this control to the form this.Controls.Add(mylab); }}}Output:"
},
{
"code": null,
"e": 28051,
"s": 27994,
"text": "// Add this label to the form\nthis.Controls.Add(mylab);\n"
},
{
"code": null,
"e": 28060,
"s": 28051,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font(\"Calibri\", 18); mylab.ForeColor = Color.Green; // Adding this control to the form this.Controls.Add(mylab); }}}",
"e": 28809,
"s": 28060,
"text": null
},
{
"code": null,
"e": 28817,
"s": 28809,
"text": "Output:"
},
{
"code": null,
"e": 28820,
"s": 28817,
"text": "C#"
},
{
"code": null,
"e": 28918,
"s": 28820,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28946,
"s": 28918,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28961,
"s": 28946,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28984,
"s": 28961,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 29006,
"s": 28984,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 29052,
"s": 29006,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 29075,
"s": 29052,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29115,
"s": 29075,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 29137,
"s": 29115,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 29168,
"s": 29137,
"text": "Introduction to .NET Framework"
}
] |
Python PIL | Image.save() method - GeeksforGeeks | 17 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.save() Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible.
Keyword options can be used to provide additional instructions to the writer. If a writer doesn’t recognise an option, it is silently ignored. The available options are described in the image format documentation for each writer.
You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the seek, tell, and write methods, and be opened in binary mode.
Syntax: Image.save(fp, format=None, **params)
Parameters:
fp – A filename (string), pathlib.Path object or file object.format – Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used.options – Extra parameters to the image writer.
Returns: None
Raises:
KeyError – If the output format could not be determined from the file name. Use the format option to solve this.IOError – If the file could not be written. The file may have been created, and may contain partial data.
Image Used:
# Importing Image module from PIL package from PIL import Image import PIL # creating a image object (main image) im1 = Image.open(r"C:\Users\System-Pc\Desktop\flower1.jpg") # save a image using extensionim1 = im1.save("geeks.jpg")
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python | [
{
"code": null,
"e": 25655,
"s": 25627,
"text": "\n17 Jul, 2019"
},
{
"code": null,
"e": 25982,
"s": 25655,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images."
},
{
"code": null,
"e": 26139,
"s": 25982,
"text": "Image.save() Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible."
},
{
"code": null,
"e": 26369,
"s": 26139,
"text": "Keyword options can be used to provide additional instructions to the writer. If a writer doesn’t recognise an option, it is silently ignored. The available options are described in the image format documentation for each writer."
},
{
"code": null,
"e": 26564,
"s": 26369,
"text": "You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the seek, tell, and write methods, and be opened in binary mode."
},
{
"code": null,
"e": 26610,
"s": 26564,
"text": "Syntax: Image.save(fp, format=None, **params)"
},
{
"code": null,
"e": 26622,
"s": 26610,
"text": "Parameters:"
},
{
"code": null,
"e": 26925,
"s": 26622,
"text": "fp – A filename (string), pathlib.Path object or file object.format – Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used.options – Extra parameters to the image writer."
},
{
"code": null,
"e": 26939,
"s": 26925,
"text": "Returns: None"
},
{
"code": null,
"e": 26947,
"s": 26939,
"text": "Raises:"
},
{
"code": null,
"e": 27165,
"s": 26947,
"text": "KeyError – If the output format could not be determined from the file name. Use the format option to solve this.IOError – If the file could not be written. The file may have been created, and may contain partial data."
},
{
"code": null,
"e": 27177,
"s": 27165,
"text": "Image Used:"
},
{
"code": " # Importing Image module from PIL package from PIL import Image import PIL # creating a image object (main image) im1 = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\flower1.jpg\") # save a image using extensionim1 = im1.save(\"geeks.jpg\")",
"e": 27418,
"s": 27177,
"text": null
},
{
"code": null,
"e": 27426,
"s": 27418,
"text": "Output:"
},
{
"code": null,
"e": 27437,
"s": 27426,
"text": "Python-pil"
},
{
"code": null,
"e": 27444,
"s": 27437,
"text": "Python"
},
{
"code": null,
"e": 27542,
"s": 27444,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27560,
"s": 27542,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27592,
"s": 27560,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27614,
"s": 27592,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27656,
"s": 27614,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27686,
"s": 27656,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27712,
"s": 27686,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27741,
"s": 27712,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27785,
"s": 27741,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27822,
"s": 27785,
"text": "Create a Pandas DataFrame from Lists"
}
] |
How to Iterate through Collection Objects in Java? - GeeksforGeeks | 07 Jan, 2021
Any group of individual objects which are represented as a single unit is known as the Collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface in it.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes.
How to iterate through Collection Objects?
Using enhanced For loopUsing Iterator methodUsing Simple For loopUsing forEach method
Using enhanced For loop
Using Iterator method
Using Simple For loop
Using forEach method
Method 1: Using enhanced For loop
Syntax used :
for (datatype variable : collection_used)
Example:
Java
// Java program to demonstrate the// working of enhanced for loop to iterate// collection objects import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Declaring the ArrayList Collection<String> gfg = new ArrayList<String>(); // Appending new elements at // the end of the list gfg.add("Abhishek Rout"); gfg.add("Vaibhav Kamble"); gfg.add("Anupam Kumar"); // for-each loop for iterating // unconditionally through collection for (String name : gfg) System.out.println("Name : " + name); }}
Name : Abhishek Rout
Name : Vaibhav Kamble
Name : Anupam Kumar
Method 2: Using Iterator method
Syntax used :
for (Iterator variable = collection.iterator(); variable.hasNext();)
Example:
Java
// Java program to demonstrate the// working of iterator method to iterate// collection objects import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Declaring the LinkedList LinkedList<String> gfg = new LinkedList<String>(); // Appending new elements at // the end of the list gfg.add("Abhishek Rout"); gfg.add("Vaibhav Kamble"); gfg.add("Anupam Kumar"); // for loop for iterating // conditionally through collection System.out.println("Using For loop"); for (Iterator<String> name = gfg.iterator(); name.hasNext();) System.out.println("Name : " + name.next()); // while loop for iterating // conditionally through collection System.out.println("\nUsing While Loop"); Iterator<String> name = gfg.iterator(); while (name.hasNext()) System.out.println("Name : " + name.next()); }}
Using For loop
Name : Abhishek Rout
Name : Vaibhav Kamble
Name : Anupam Kumar
Using While Loop
Name : Abhishek Rout
Name : Vaibhav Kamble
Name : Anupam Kumar
Method 3: Using Simple For loop
Syntax used :
for (int i = 0; i < collection_used.length; i++)
Example:
Java
// Java program to demonstrate the// working of for loop to iterate// collection objects import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Declaring the ArrayList Vector<String> gfg = new Vector<String>(); // Appending new elements at // the end of the list gfg.add("Abhishek Rout"); gfg.add("Vaibhav Kamble"); gfg.add("Anupam Kumar"); // for loop for iterating // through collection for (int i = 0; i < gfg.size(); i++) System.out.println("Name " + (i + 1) + ": " + gfg.get(i)); }}
Name 1: Abhishek Rout
Name 2: Vaibhav Kamble
Name 3: Anupam Kumar
Method 4: Using forEach method
forEach() method is available in Java 8 and each collection has this method that implements the iteration internally.
Syntax used :
With iterable variable
collection_used.forEach((data_type iterating_variable) -> { System.out.println(iterating_variable); });
Without iterable variable
collection_used.forEach(System.out::println);
Example:
Java
// Java program to demonstrate the// working of forEach method to iterate// collection objects import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Declaring the ArrayList ArrayList<String> gfg = new ArrayList<String>(); // Appending new elements at // the end of the list gfg.add("Abhishek Rout"); gfg.add("Vaibhav Kamble"); gfg.add("Anupam Kumar"); // forEach for iterating // through collection // with iterable variable System.out.println("With iterable"); gfg.forEach((String name) -> { System.out.println("Name : " + name); }); System.out.println("\nWithout iterable"); gfg.forEach(System.out::println); }}
With iterable
Name : Abhishek Rout
Name : Vaibhav Kamble
Name : Anupam Kumar
Without iterable
Abhishek Rout
Vaibhav Kamble
Anupam Kumar
Java-Collections
Picked
Technical Scripter 2020
Java Programs
Technical Scripter
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Replace a Element in Java ArrayList?
Java Program to Find Sum of Array Elements
Java Program to Read a File to String
Tic-Tac-Toe Game in Java
How to Write Data into Excel Sheet using Java?
Removing last element from ArrayList in Java
Java Program to Write an Array of Strings to the Output Console | [
{
"code": null,
"e": 26107,
"s": 26079,
"text": "\n07 Jan, 2021"
},
{
"code": null,
"e": 26372,
"s": 26107,
"text": "Any group of individual objects which are represented as a single unit is known as the Collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface in it."
},
{
"code": null,
"e": 26517,
"s": 26372,
"text": "The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes."
},
{
"code": null,
"e": 26560,
"s": 26517,
"text": "How to iterate through Collection Objects?"
},
{
"code": null,
"e": 26646,
"s": 26560,
"text": "Using enhanced For loopUsing Iterator methodUsing Simple For loopUsing forEach method"
},
{
"code": null,
"e": 26670,
"s": 26646,
"text": "Using enhanced For loop"
},
{
"code": null,
"e": 26692,
"s": 26670,
"text": "Using Iterator method"
},
{
"code": null,
"e": 26714,
"s": 26692,
"text": "Using Simple For loop"
},
{
"code": null,
"e": 26735,
"s": 26714,
"text": "Using forEach method"
},
{
"code": null,
"e": 26770,
"s": 26735,
"text": "Method 1: Using enhanced For loop "
},
{
"code": null,
"e": 26784,
"s": 26770,
"text": "Syntax used :"
},
{
"code": null,
"e": 26826,
"s": 26784,
"text": "for (datatype variable : collection_used)"
},
{
"code": null,
"e": 26835,
"s": 26826,
"text": "Example:"
},
{
"code": null,
"e": 26840,
"s": 26835,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of enhanced for loop to iterate// collection objects import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Declaring the ArrayList Collection<String> gfg = new ArrayList<String>(); // Appending new elements at // the end of the list gfg.add(\"Abhishek Rout\"); gfg.add(\"Vaibhav Kamble\"); gfg.add(\"Anupam Kumar\"); // for-each loop for iterating // unconditionally through collection for (String name : gfg) System.out.println(\"Name : \" + name); }}",
"e": 27468,
"s": 26840,
"text": null
},
{
"code": null,
"e": 27532,
"s": 27468,
"text": "Name : Abhishek Rout\nName : Vaibhav Kamble\nName : Anupam Kumar\n"
},
{
"code": null,
"e": 27565,
"s": 27532,
"text": "Method 2: Using Iterator method "
},
{
"code": null,
"e": 27579,
"s": 27565,
"text": "Syntax used :"
},
{
"code": null,
"e": 27648,
"s": 27579,
"text": "for (Iterator variable = collection.iterator(); variable.hasNext();)"
},
{
"code": null,
"e": 27657,
"s": 27648,
"text": "Example:"
},
{
"code": null,
"e": 27662,
"s": 27657,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of iterator method to iterate// collection objects import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Declaring the LinkedList LinkedList<String> gfg = new LinkedList<String>(); // Appending new elements at // the end of the list gfg.add(\"Abhishek Rout\"); gfg.add(\"Vaibhav Kamble\"); gfg.add(\"Anupam Kumar\"); // for loop for iterating // conditionally through collection System.out.println(\"Using For loop\"); for (Iterator<String> name = gfg.iterator(); name.hasNext();) System.out.println(\"Name : \" + name.next()); // while loop for iterating // conditionally through collection System.out.println(\"\\nUsing While Loop\"); Iterator<String> name = gfg.iterator(); while (name.hasNext()) System.out.println(\"Name : \" + name.next()); }}",
"e": 28679,
"s": 27662,
"text": null
},
{
"code": null,
"e": 28839,
"s": 28679,
"text": "Using For loop\nName : Abhishek Rout\nName : Vaibhav Kamble\nName : Anupam Kumar\n\nUsing While Loop\nName : Abhishek Rout\nName : Vaibhav Kamble\nName : Anupam Kumar\n"
},
{
"code": null,
"e": 28872,
"s": 28839,
"text": "Method 3: Using Simple For loop "
},
{
"code": null,
"e": 28886,
"s": 28872,
"text": "Syntax used :"
},
{
"code": null,
"e": 28935,
"s": 28886,
"text": "for (int i = 0; i < collection_used.length; i++)"
},
{
"code": null,
"e": 28944,
"s": 28935,
"text": "Example:"
},
{
"code": null,
"e": 28949,
"s": 28944,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of for loop to iterate// collection objects import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Declaring the ArrayList Vector<String> gfg = new Vector<String>(); // Appending new elements at // the end of the list gfg.add(\"Abhishek Rout\"); gfg.add(\"Vaibhav Kamble\"); gfg.add(\"Anupam Kumar\"); // for loop for iterating // through collection for (int i = 0; i < gfg.size(); i++) System.out.println(\"Name \" + (i + 1) + \": \" + gfg.get(i)); }}",
"e": 29604,
"s": 28949,
"text": null
},
{
"code": null,
"e": 29671,
"s": 29604,
"text": "Name 1: Abhishek Rout\nName 2: Vaibhav Kamble\nName 3: Anupam Kumar\n"
},
{
"code": null,
"e": 29703,
"s": 29671,
"text": "Method 4: Using forEach method "
},
{
"code": null,
"e": 29821,
"s": 29703,
"text": "forEach() method is available in Java 8 and each collection has this method that implements the iteration internally."
},
{
"code": null,
"e": 29835,
"s": 29821,
"text": "Syntax used :"
},
{
"code": null,
"e": 29858,
"s": 29835,
"text": "With iterable variable"
},
{
"code": null,
"e": 29962,
"s": 29858,
"text": "collection_used.forEach((data_type iterating_variable) -> { System.out.println(iterating_variable); });"
},
{
"code": null,
"e": 29988,
"s": 29962,
"text": "Without iterable variable"
},
{
"code": null,
"e": 30034,
"s": 29988,
"text": "collection_used.forEach(System.out::println);"
},
{
"code": null,
"e": 30043,
"s": 30034,
"text": "Example:"
},
{
"code": null,
"e": 30048,
"s": 30043,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of forEach method to iterate// collection objects import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Declaring the ArrayList ArrayList<String> gfg = new ArrayList<String>(); // Appending new elements at // the end of the list gfg.add(\"Abhishek Rout\"); gfg.add(\"Vaibhav Kamble\"); gfg.add(\"Anupam Kumar\"); // forEach for iterating // through collection // with iterable variable System.out.println(\"With iterable\"); gfg.forEach((String name) -> { System.out.println(\"Name : \" + name); }); System.out.println(\"\\nWithout iterable\"); gfg.forEach(System.out::println); }}",
"e": 30845,
"s": 30048,
"text": null
},
{
"code": null,
"e": 30983,
"s": 30845,
"text": "With iterable\nName : Abhishek Rout\nName : Vaibhav Kamble\nName : Anupam Kumar\n\nWithout iterable\nAbhishek Rout\nVaibhav Kamble\nAnupam Kumar\n"
},
{
"code": null,
"e": 31000,
"s": 30983,
"text": "Java-Collections"
},
{
"code": null,
"e": 31007,
"s": 31000,
"text": "Picked"
},
{
"code": null,
"e": 31031,
"s": 31007,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31045,
"s": 31031,
"text": "Java Programs"
},
{
"code": null,
"e": 31064,
"s": 31045,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31081,
"s": 31064,
"text": "Java-Collections"
},
{
"code": null,
"e": 31179,
"s": 31081,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31227,
"s": 31179,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 31278,
"s": 31227,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 31312,
"s": 31278,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 31356,
"s": 31312,
"text": "How to Replace a Element in Java ArrayList?"
},
{
"code": null,
"e": 31399,
"s": 31356,
"text": "Java Program to Find Sum of Array Elements"
},
{
"code": null,
"e": 31437,
"s": 31399,
"text": "Java Program to Read a File to String"
},
{
"code": null,
"e": 31462,
"s": 31437,
"text": "Tic-Tac-Toe Game in Java"
},
{
"code": null,
"e": 31509,
"s": 31462,
"text": "How to Write Data into Excel Sheet using Java?"
},
{
"code": null,
"e": 31554,
"s": 31509,
"text": "Removing last element from ArrayList in Java"
}
] |
DecimalFormat setRoundingMode() method in Java - GeeksforGeeks | 01 Apr, 2019
The setRoundingMode() method is a built-in method of the java.text.DecimalFomrat class in Java and is used to set the RoundingMode to be used with this DecimalFormat instance to round-off the decimal digits.
Syntax:
public void setRoundingMode(RoundingMode roundingMode)
Parameters: The function accepts a single parameter roundingMode which is the RoundingMode instance to be set for this DecimalFormat instance.
Return Value: The function does not returns any value.
Below is the implementation of the above function:
Program 1:
// Java program to illustrate the// setRoundingMode() method import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;import java.math.RoundingMode;import java.util.Currency;import java.util.Locale; public class Main { public static void main(String[] args) { // Create the DecimalFormat Instance DecimalFormat deciFormat = new DecimalFormat(); // Set the rounding mode as CEILING deciFormat.setRoundingMode(RoundingMode.CEILING); System.out.println(deciFormat.format(1234.5555)); }}
1, 234.556
Program 2:
// Java program to illustrate the// setRoundingMode() method import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;import java.math.RoundingMode;import java.util.Currency;import java.util.Locale; public class Main { public static void main(String[] args) { // Create the DecimalFormat Instance DecimalFormat deciFormat = new DecimalFormat(); // Set the rounding mode as HALF_DOWN deciFormat.setRoundingMode(RoundingMode.HALF_DOWN); System.out.println(deciFormat.format(1234.5555)); }}
1, 234.555
Reference: https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html#setRoundingMode(java.math.RoundingMode)
Java-DecimalFormat
Java-Functions
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java | [
{
"code": null,
"e": 25823,
"s": 25795,
"text": "\n01 Apr, 2019"
},
{
"code": null,
"e": 26031,
"s": 25823,
"text": "The setRoundingMode() method is a built-in method of the java.text.DecimalFomrat class in Java and is used to set the RoundingMode to be used with this DecimalFormat instance to round-off the decimal digits."
},
{
"code": null,
"e": 26039,
"s": 26031,
"text": "Syntax:"
},
{
"code": null,
"e": 26095,
"s": 26039,
"text": "public void setRoundingMode(RoundingMode roundingMode)\n"
},
{
"code": null,
"e": 26238,
"s": 26095,
"text": "Parameters: The function accepts a single parameter roundingMode which is the RoundingMode instance to be set for this DecimalFormat instance."
},
{
"code": null,
"e": 26293,
"s": 26238,
"text": "Return Value: The function does not returns any value."
},
{
"code": null,
"e": 26344,
"s": 26293,
"text": "Below is the implementation of the above function:"
},
{
"code": null,
"e": 26355,
"s": 26344,
"text": "Program 1:"
},
{
"code": "// Java program to illustrate the// setRoundingMode() method import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;import java.math.RoundingMode;import java.util.Currency;import java.util.Locale; public class Main { public static void main(String[] args) { // Create the DecimalFormat Instance DecimalFormat deciFormat = new DecimalFormat(); // Set the rounding mode as CEILING deciFormat.setRoundingMode(RoundingMode.CEILING); System.out.println(deciFormat.format(1234.5555)); }}",
"e": 26903,
"s": 26355,
"text": null
},
{
"code": null,
"e": 26915,
"s": 26903,
"text": "1, 234.556\n"
},
{
"code": null,
"e": 26926,
"s": 26915,
"text": "Program 2:"
},
{
"code": "// Java program to illustrate the// setRoundingMode() method import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;import java.math.RoundingMode;import java.util.Currency;import java.util.Locale; public class Main { public static void main(String[] args) { // Create the DecimalFormat Instance DecimalFormat deciFormat = new DecimalFormat(); // Set the rounding mode as HALF_DOWN deciFormat.setRoundingMode(RoundingMode.HALF_DOWN); System.out.println(deciFormat.format(1234.5555)); }}",
"e": 27478,
"s": 26926,
"text": null
},
{
"code": null,
"e": 27490,
"s": 27478,
"text": "1, 234.555\n"
},
{
"code": null,
"e": 27612,
"s": 27490,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html#setRoundingMode(java.math.RoundingMode)"
},
{
"code": null,
"e": 27631,
"s": 27612,
"text": "Java-DecimalFormat"
},
{
"code": null,
"e": 27646,
"s": 27631,
"text": "Java-Functions"
},
{
"code": null,
"e": 27664,
"s": 27646,
"text": "Java-text package"
},
{
"code": null,
"e": 27669,
"s": 27664,
"text": "Java"
},
{
"code": null,
"e": 27674,
"s": 27669,
"text": "Java"
},
{
"code": null,
"e": 27772,
"s": 27674,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27823,
"s": 27772,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27853,
"s": 27823,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27868,
"s": 27853,
"text": "Stream In Java"
},
{
"code": null,
"e": 27887,
"s": 27868,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27918,
"s": 27887,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27936,
"s": 27918,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27968,
"s": 27936,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27988,
"s": 27968,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28012,
"s": 27988,
"text": "Singleton Class in Java"
}
] |
How to Remove columns in Numpy array that contains non-numeric values? - GeeksforGeeks | 25 Oct, 2020
Many times we have non-numeric values in NumPy array. These values need to be removed, so that array will be free from all these unnecessary values and look more decent. It is possible to remove all columns containing Nan values using the Bitwise NOT operator and np.isnan() function.
Example 1:
Python3
# Importing Numpy moduleimport numpy as np # Creating 2X3 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, np.nan], [41, 52.5, np.nan]]) print("Given array:")print(n_arr) print("\nRemove all columns containing non-numeric elements ")print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])
Output:
In the above example, we remove columns containing non-numeric values from the 2X3 Numpy array.
Example 2:
Python3
# Importing Numpy moduleimport numpy as np # Creating 3X3 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, 10.5], [41, 52.5, 25], [100, np.nan, 41]]) print("Given array:")print(n_arr) print("\nRemove all columns containing non-numeric elements ")print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])
Output:
In the above example, we remove columns containing non-numeric values from the 3X3 Numpy array.
Example 3:
Python3
# Importing Numpy moduleimport numpy as np # Creating 5X3 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, 3.8], [23.45, 50, 78.7], [41, np.nan, np.nan], [20, 50.20, np.nan], [18.8, 50.60, 8.8]]) print("Given array:")print(n_arr) print("\nRemove all columns containing non-numeric elements ")print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])
Output:
In the above example, we remove columns containing non-numeric values from the 5X3 Numpy array.
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n25 Oct, 2020"
},
{
"code": null,
"e": 25822,
"s": 25537,
"text": "Many times we have non-numeric values in NumPy array. These values need to be removed, so that array will be free from all these unnecessary values and look more decent. It is possible to remove all columns containing Nan values using the Bitwise NOT operator and np.isnan() function."
},
{
"code": null,
"e": 25833,
"s": 25822,
"text": "Example 1:"
},
{
"code": null,
"e": 25841,
"s": 25833,
"text": "Python3"
},
{
"code": "# Importing Numpy moduleimport numpy as np # Creating 2X3 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, np.nan], [41, 52.5, np.nan]]) print(\"Given array:\")print(n_arr) print(\"\\nRemove all columns containing non-numeric elements \")print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])",
"e": 26137,
"s": 25841,
"text": null
},
{
"code": null,
"e": 26145,
"s": 26137,
"text": "Output:"
},
{
"code": null,
"e": 26241,
"s": 26145,
"text": "In the above example, we remove columns containing non-numeric values from the 2X3 Numpy array."
},
{
"code": null,
"e": 26252,
"s": 26241,
"text": "Example 2:"
},
{
"code": null,
"e": 26260,
"s": 26252,
"text": "Python3"
},
{
"code": "# Importing Numpy moduleimport numpy as np # Creating 3X3 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, 10.5], [41, 52.5, 25], [100, np.nan, 41]]) print(\"Given array:\")print(n_arr) print(\"\\nRemove all columns containing non-numeric elements \")print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])",
"e": 26586,
"s": 26260,
"text": null
},
{
"code": null,
"e": 26594,
"s": 26586,
"text": "Output:"
},
{
"code": null,
"e": 26690,
"s": 26594,
"text": "In the above example, we remove columns containing non-numeric values from the 3X3 Numpy array."
},
{
"code": null,
"e": 26701,
"s": 26690,
"text": "Example 3:"
},
{
"code": null,
"e": 26709,
"s": 26701,
"text": "Python3"
},
{
"code": "# Importing Numpy moduleimport numpy as np # Creating 5X3 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, 3.8], [23.45, 50, 78.7], [41, np.nan, np.nan], [20, 50.20, np.nan], [18.8, 50.60, 8.8]]) print(\"Given array:\")print(n_arr) print(\"\\nRemove all columns containing non-numeric elements \")print(n_arr[:, ~np.isnan(n_arr).any(axis=0)])",
"e": 27115,
"s": 26709,
"text": null
},
{
"code": null,
"e": 27123,
"s": 27115,
"text": "Output:"
},
{
"code": null,
"e": 27219,
"s": 27123,
"text": "In the above example, we remove columns containing non-numeric values from the 5X3 Numpy array."
},
{
"code": null,
"e": 27250,
"s": 27219,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 27263,
"s": 27250,
"text": "Python-numpy"
},
{
"code": null,
"e": 27270,
"s": 27263,
"text": "Python"
},
{
"code": null,
"e": 27368,
"s": 27270,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27400,
"s": 27368,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27442,
"s": 27400,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27484,
"s": 27442,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27540,
"s": 27484,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27567,
"s": 27540,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27606,
"s": 27567,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27637,
"s": 27606,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27659,
"s": 27637,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27688,
"s": 27659,
"text": "Create a directory in Python"
}
] |
numpy.tril_indices() function | Python - GeeksforGeeks | 22 Apr, 2020
numpy.tril_indices() function return the indices for the lower-triangle of an (n, m) array.
Syntax : numpy.tril_indices(n, k = 0, m = None)Parameters :n : [int] The row dimension of the arrays for which the returned indices will be valid.k : [int, optional] Diagonal offset.m : [int, optional] The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n.Return : [tuple of arrays] The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array.
Code #1 :
# Python program explaining# numpy.tril_indices() function # importing numpy as geek import numpy as geek gfg = geek.tril_indices(3) print (gfg)
Output :
(array([0, 1, 1, 2, 2, 2]), array([0, 0, 1, 0, 1, 2]))
Code #2 :
# Python program explaining# numpy.tril_indices() function # importing numpy as geek import numpy as geek gfg = geek.tril_indices(3, 2) print (gfg)
Output :
(array([0, 0, 0, 1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2, 0, 1, 2]))
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 25629,
"s": 25537,
"text": "numpy.tril_indices() function return the indices for the lower-triangle of an (n, m) array."
},
{
"code": null,
"e": 26097,
"s": 25629,
"text": "Syntax : numpy.tril_indices(n, k = 0, m = None)Parameters :n : [int] The row dimension of the arrays for which the returned indices will be valid.k : [int, optional] Diagonal offset.m : [int, optional] The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n.Return : [tuple of arrays] The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array."
},
{
"code": null,
"e": 26107,
"s": 26097,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.tril_indices() function # importing numpy as geek import numpy as geek gfg = geek.tril_indices(3) print (gfg)",
"e": 26255,
"s": 26107,
"text": null
},
{
"code": null,
"e": 26264,
"s": 26255,
"text": "Output :"
},
{
"code": null,
"e": 26320,
"s": 26264,
"text": "(array([0, 1, 1, 2, 2, 2]), array([0, 0, 1, 0, 1, 2]))\n"
},
{
"code": null,
"e": 26331,
"s": 26320,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# numpy.tril_indices() function # importing numpy as geek import numpy as geek gfg = geek.tril_indices(3, 2) print (gfg)",
"e": 26482,
"s": 26331,
"text": null
},
{
"code": null,
"e": 26491,
"s": 26482,
"text": "Output :"
},
{
"code": null,
"e": 26565,
"s": 26491,
"text": "(array([0, 0, 0, 1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2, 0, 1, 2]))\n"
},
{
"code": null,
"e": 26596,
"s": 26565,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 26609,
"s": 26596,
"text": "Python-numpy"
},
{
"code": null,
"e": 26616,
"s": 26609,
"text": "Python"
},
{
"code": null,
"e": 26714,
"s": 26616,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26746,
"s": 26714,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26788,
"s": 26746,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26830,
"s": 26788,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26857,
"s": 26830,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26913,
"s": 26857,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26952,
"s": 26913,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26974,
"s": 26952,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27005,
"s": 26974,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27034,
"s": 27005,
"text": "Create a directory in Python"
}
] |
How to select all even/odd rows in table using jQuery ? - GeeksforGeeks | 12 Aug, 2021
In this article, we will see how to make a table by selecting the alternate rows i.e. selecting the even or odd rows by clicking on the respective buttons. This feature can be useful at the time of selecting the specific data/elements of either of the rows or to highlight the table of data for display from the large data set. This enables us to quickly review the table at a glance. We can achieve the same by selecting the odd or even rows using tr: odd or tr: even selectors in the table. The row index starts from 0 in the HTML tables. We will use jQuery for selecting either of the rows by clicking the button.
In order to use jQuery in the HTML file, we will add the below syntax inside the <head> tag.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
letegrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous">
</script>
Syntax for selecting odd rows:
$("table tr:odd").css({"property":"value",
"property": "value"});
Syntax for selecting even rows:
$("table tr:even").css({"property":"value",
"property": "value"});
Approach:
Design a table that will contain the data. Use the required styling properties to highlight the different rows in order to differentiate the row data.
Use “tr: odd” to select the odd data & use “tr: even” to select the even data in the row.
Example: In this step, we will create a table having the table row & table column & will use the above all syntax for the selection of rows.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Geeks for Geeks</title> <!-- Including jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" letegrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script> <style> h1 { color: #006600; } button { color: white; background-color: #006600; width: auto; height: 30px; } body { text-align: center; } div { margin: 10px; height: auto; width: auto; position: relative; display: flex; justify-content: center; text-align: center; display: flex; } table, tr, thead, td { border: 5px solid #006600; border-collapse: collapse; padding: 10px; } thead { color: #006600; font-size: 20px; font-weight: bold; } </style> </head> <body> <h1>Geeks For Geeks</h1> <button id="odd">ODD ROWS</button> <button id="even">EVEN ROWS</button> <div> <table> <tbody> <thead> <td>Index</td> <td>Col-1</td> <td>Col-2</td> <td>Col-3</td> </thead> <tr> <td>1</td> <td>Column00</td> <td>Column01</td> <td>Column02</td> </tr> <tr> <td>2</td> <td>Column10</td> <td>Column11</td> <td>Column12</td> </tr> <tr> <td>3</td> <td>Column20</td> <td>Column21</td> <td>Column22</td> </tr> <tr> <td>4</td> <td>Column30</td> <td>Column31</td> <td>Column2</td> </tr> </tbody> </table> </div> <script> $(document).ready(function () { $("#odd").click(function () { $("table tr:odd").css({ "background-color": "#00e673", color: "white", }); }); $("#even").click(function () { $("table tr:even").css({ "background-color": "#b3b3cc", color: "white", }); }); }); </script> </body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Properties
jQuery-Methods
jQuery-Questions
jQuery-Selectors
Picked
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 26706,
"s": 26678,
"text": "\n12 Aug, 2021"
},
{
"code": null,
"e": 27324,
"s": 26706,
"text": "In this article, we will see how to make a table by selecting the alternate rows i.e. selecting the even or odd rows by clicking on the respective buttons. This feature can be useful at the time of selecting the specific data/elements of either of the rows or to highlight the table of data for display from the large data set. This enables us to quickly review the table at a glance. We can achieve the same by selecting the odd or even rows using tr: odd or tr: even selectors in the table. The row index starts from 0 in the HTML tables. We will use jQuery for selecting either of the rows by clicking the button. "
},
{
"code": null,
"e": 27417,
"s": 27324,
"text": "In order to use jQuery in the HTML file, we will add the below syntax inside the <head> tag."
},
{
"code": null,
"e": 27574,
"s": 27417,
"text": "<script src=\"https://code.jquery.com/jquery-3.6.0.min.js\"\nletegrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\"\ncrossorigin=\"anonymous\">\n</script>"
},
{
"code": null,
"e": 27605,
"s": 27574,
"text": "Syntax for selecting odd rows:"
},
{
"code": null,
"e": 27698,
"s": 27605,
"text": "$(\"table tr:odd\").css({\"property\":\"value\",\n \"property\": \"value\"});"
},
{
"code": null,
"e": 27730,
"s": 27698,
"text": "Syntax for selecting even rows:"
},
{
"code": null,
"e": 27824,
"s": 27730,
"text": "$(\"table tr:even\").css({\"property\":\"value\",\n \"property\": \"value\"});"
},
{
"code": null,
"e": 27836,
"s": 27826,
"text": "Approach:"
},
{
"code": null,
"e": 27987,
"s": 27836,
"text": "Design a table that will contain the data. Use the required styling properties to highlight the different rows in order to differentiate the row data."
},
{
"code": null,
"e": 28078,
"s": 27987,
"text": " Use “tr: odd” to select the odd data & use “tr: even” to select the even data in the row."
},
{
"code": null,
"e": 28220,
"s": 28078,
"text": "Example: In this step, we will create a table having the table row & table column & will use the above all syntax for the selection of rows. "
},
{
"code": null,
"e": 28225,
"s": 28220,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Geeks for Geeks</title> <!-- Including jQuery --> <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\" letegrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"> </script> <style> h1 { color: #006600; } button { color: white; background-color: #006600; width: auto; height: 30px; } body { text-align: center; } div { margin: 10px; height: auto; width: auto; position: relative; display: flex; justify-content: center; text-align: center; display: flex; } table, tr, thead, td { border: 5px solid #006600; border-collapse: collapse; padding: 10px; } thead { color: #006600; font-size: 20px; font-weight: bold; } </style> </head> <body> <h1>Geeks For Geeks</h1> <button id=\"odd\">ODD ROWS</button> <button id=\"even\">EVEN ROWS</button> <div> <table> <tbody> <thead> <td>Index</td> <td>Col-1</td> <td>Col-2</td> <td>Col-3</td> </thead> <tr> <td>1</td> <td>Column00</td> <td>Column01</td> <td>Column02</td> </tr> <tr> <td>2</td> <td>Column10</td> <td>Column11</td> <td>Column12</td> </tr> <tr> <td>3</td> <td>Column20</td> <td>Column21</td> <td>Column22</td> </tr> <tr> <td>4</td> <td>Column30</td> <td>Column31</td> <td>Column2</td> </tr> </tbody> </table> </div> <script> $(document).ready(function () { $(\"#odd\").click(function () { $(\"table tr:odd\").css({ \"background-color\": \"#00e673\", color: \"white\", }); }); $(\"#even\").click(function () { $(\"table tr:even\").css({ \"background-color\": \"#b3b3cc\", color: \"white\", }); }); }); </script> </body></html>",
"e": 30713,
"s": 28225,
"text": null
},
{
"code": null,
"e": 30721,
"s": 30713,
"text": "Output:"
},
{
"code": null,
"e": 30858,
"s": 30721,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 30873,
"s": 30858,
"text": "CSS-Properties"
},
{
"code": null,
"e": 30888,
"s": 30873,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 30905,
"s": 30888,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 30922,
"s": 30905,
"text": "jQuery-Selectors"
},
{
"code": null,
"e": 30929,
"s": 30922,
"text": "Picked"
},
{
"code": null,
"e": 30933,
"s": 30929,
"text": "CSS"
},
{
"code": null,
"e": 30938,
"s": 30933,
"text": "HTML"
},
{
"code": null,
"e": 30945,
"s": 30938,
"text": "JQuery"
},
{
"code": null,
"e": 30962,
"s": 30945,
"text": "Web Technologies"
},
{
"code": null,
"e": 30967,
"s": 30962,
"text": "HTML"
},
{
"code": null,
"e": 31065,
"s": 30967,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31104,
"s": 31065,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 31141,
"s": 31104,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 31170,
"s": 31141,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 31212,
"s": 31170,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 31247,
"s": 31212,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 31307,
"s": 31247,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31360,
"s": 31307,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 31421,
"s": 31360,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 31445,
"s": 31421,
"text": "REST API (Introduction)"
}
] |
Software Engineering | COCOMO Model - GeeksforGeeks | 15 Feb, 2022
Cocomo (Constructive Cost Model) is a regression model based on LOC, i.e number of Lines of Code. It is a procedural cost estimate model for software projects and is often used as a process of reliably predicting the various parameters associated with making a project such as size, effort, cost, time, and quality. It was proposed by Barry Boehm in 1981 and is based on the study of 63 projects, which makes it one of the best-documented models.
The key parameters which define the quality of any software products, which are also an outcome of the Cocomo are primarily Effort & Schedule:
Effort: Amount of labor that will be required to complete a task. It is measured in person-months units.
Schedule: Simply means the amount of time required for the completion of the job, which is, of course, proportional to the effort put in. It is measured in the units of time such as weeks, months.
Different models of Cocomo have been proposed to predict the cost estimation at different levels, based on the amount of accuracy and correctness required. All of these models can be applied to a variety of projects, whose characteristics determine the value of constant to be used in subsequent calculations. These characteristics pertaining to different system types are mentioned below.
Boehm’s definition of organic, semidetached, and embedded systems:
Organic – A software project is said to be an organic type if the team size required is adequately small, the problem is well understood and has been solved in the past and also the team members have a nominal experience regarding the problem.Semi-detached – A software project is said to be a Semi-detached type if the vital characteristics such as team size, experience, knowledge of the various programming environment lie in between that of organic and Embedded. The projects classified as Semi-Detached are comparatively less familiar and difficult to develop compared to the organic ones and require more experience and better guidance and creativity. Eg: Compilers or different Embedded Systems can be considered of Semi-Detached type.Embedded – A software project requiring the highest level of complexity, creativity, and experience requirement fall under this category. Such software requires a larger team size than the other two models and also the developers need to be sufficiently experienced and creative to develop such complex models.All the above system types utilize different values of the constants used in Effort Calculations.Types of Models: COCOMO consists of a hierarchy of three increasingly detailed and accurate forms. Any of the three forms can be adopted according to our requirements. These are types of COCOMO model:Basic COCOMO ModelIntermediate COCOMO ModelDetailed COCOMO ModelThe first level, Basic COCOMO can be used for quick and slightly rough calculations of Software Costs. Its accuracy is somewhat restricted due to the absence of sufficient factor considerations.Intermediate COCOMO takes these Cost Drivers into account and Detailed COCOMO additionally accounts for the influence of individual project phases, i.e in case of Detailed it accounts for both these cost drivers and also calculations are performed phase-wise henceforth producing a more accurate result. These two models are further discussed below.Estimation of Effort: Calculations –Basic Model –
The above formula is used for the cost estimation of for the basic COCOMO model, and also is used in the subsequent models. The constant values a,b,c and d for the Basic Model for the different categories of system:Software ProjectsabcdOrganic2.41.052.50.38Semi Detached3.01.122.50.35Embedded3.61.202.50.32The effort is measured in Person-Months and as evident from the formula is dependent on Kilo-Lines of code.The development time is measured in months.These formulas are used as such in the Basic Model calculations, as not much consideration of different factors such as reliability, expertise is taken into account, henceforth the estimate is rough.Below is the C++ program for Basic COCOMO// C++ program to implement basic COCOMO#include<bits/stdc++.h>using namespace std; // Function for rounding off float to intint fround(float x){ int a; x=x+0.5; a=x; return(a);} // Function to calculate parameters of Basic COCOMOvoid calculate(float table[][4], int n,char mode[][15], int size){ float effort,time,staff; int model; // Check the mode according to size if(size>=2 && size<=50) model=0; //organic else if(size>50 && size<=300) model=1; //semi-detached else if(size>300) model=2; //embedded cout<<"The mode is "<<mode[model]; // Calculate Effort effort = table[model][0]*pow(size,table[model][1]); // Calculate Time time = table[model][2]*pow(effort,table[model][3]); //Calculate Persons Required staff = effort/time; // Output the values calculated cout<<"\nEffort = "<<effort<<" Person-Month"; cout<<"\nDevelopment Time = "<<time<<" Months"; cout<<"\nAverage Staff Required = "<<fround(staff)<<" Persons"; } int main(){ float table[3][4]={2.4,1.05,2.5,0.38,3.0,1.12,2.5,0.35,3.6,1.20,2.5,0.32}; char mode[][15]={"Organic","Semi-Detached","Embedded"}; int size = 4; calculate(table,3,mode,size); return 0;}Output:The mode is Organic
Effort = 10.289 Person-Month
Development Time = 6.06237 Months
Average Staff Required = 2 Persons
Intermediate Model –The basic Cocomo model assumes that the effort is only a function of the number of lines of code and some constants evaluated according to the different software systems. However, in reality, no system’s effort and schedule can be solely calculated on the basis of Lines of Code. For that, various other factors such as reliability, experience, Capability. These factors are known as Cost Drivers and the Intermediate Model utilizes 15 such drivers for cost estimation.Classification of Cost Drivers and their attributes:(i) Product attributes –Required software reliability extentSize of the application databaseThe complexity of the product(ii) Hardware attributes –Run-time performance constraintsMemory constraintsThe volatility of the virtual machine environmentRequired turnabout time(iii) Personnel attributes –Analyst capabilitySoftware engineering capabilityApplications experienceVirtual machine experienceProgramming language experience(iv) Project attributes –Use of software toolsApplication of software engineering methodsRequired development scheduleCost DriversVery LowLowNominal;HighVery HighProduct AttributesRequired Software Reliability0.750.881.001.151.40Size of Application Database0.941.001.081.16Complexity of The Product0.700.851.001.151.30Hardware AttributesRuntime Performance Constraints1.001.111.30Memory Constraints1.001.061.21Volatility of the virtual machine environment0.871.001.151.30Required turnabout time0.941.001.071.15Personnel attributesAnalyst capability1.461.191.000.860.71Applications experience1.291.131.000.910.82Software engineer capability1.421.171.000.860.70Virtual machine experience1.211.101.000.90Programming language experience1.141.071.000.95Project AttributesApplication of software engineering methods1.241.101.000.910.82Use of software tools1.241.101.000.910.83Required development schedule1.231.081.001.041.10The project manager is to rate these 15 different parameters for a particular project on a scale of one to three. Then, depending on these ratings, appropriate cost driver values are taken from the above table. These 15 values are then multiplied to calculate the EAF (Effort Adjustment Factor). The Intermediate COCOMO formula now takes the form:
The values of a and b in case of the intermediate model are as follows:Software ProjectsabOrganic3.21.05Semi Detached3.01.12Embeddedc2.81.20Detailed Model –Detailed COCOMO incorporates all characteristics of the intermediate version with an assessment of the cost driver’s impact on each step of the software engineering process. The detailed model uses different effort multipliers for each cost driver attribute. In detailed cocomo, the whole software is divided into different modules and then we apply COCOMO in different modules to estimate effort and then sum the effort.The Six phases of detailed COCOMO are:Planning and requirementsSystem designDetailed designModule code and testIntegration and testCost Constructive modelThe effort is calculated as a function of program size and a set of cost drivers are given according to each phase of the software lifecycle.Also read: Classical Waterfall Model, Iterative Waterfall Model, Prototyping Model, Spiral ModelMy Personal Notes
arrow_drop_upSave
Organic – A software project is said to be an organic type if the team size required is adequately small, the problem is well understood and has been solved in the past and also the team members have a nominal experience regarding the problem.
Semi-detached – A software project is said to be a Semi-detached type if the vital characteristics such as team size, experience, knowledge of the various programming environment lie in between that of organic and Embedded. The projects classified as Semi-Detached are comparatively less familiar and difficult to develop compared to the organic ones and require more experience and better guidance and creativity. Eg: Compilers or different Embedded Systems can be considered of Semi-Detached type.
Embedded – A software project requiring the highest level of complexity, creativity, and experience requirement fall under this category. Such software requires a larger team size than the other two models and also the developers need to be sufficiently experienced and creative to develop such complex models.All the above system types utilize different values of the constants used in Effort Calculations.Types of Models: COCOMO consists of a hierarchy of three increasingly detailed and accurate forms. Any of the three forms can be adopted according to our requirements. These are types of COCOMO model:Basic COCOMO ModelIntermediate COCOMO ModelDetailed COCOMO ModelThe first level, Basic COCOMO can be used for quick and slightly rough calculations of Software Costs. Its accuracy is somewhat restricted due to the absence of sufficient factor considerations.Intermediate COCOMO takes these Cost Drivers into account and Detailed COCOMO additionally accounts for the influence of individual project phases, i.e in case of Detailed it accounts for both these cost drivers and also calculations are performed phase-wise henceforth producing a more accurate result. These two models are further discussed below.Estimation of Effort: Calculations –Basic Model –
The above formula is used for the cost estimation of for the basic COCOMO model, and also is used in the subsequent models. The constant values a,b,c and d for the Basic Model for the different categories of system:Software ProjectsabcdOrganic2.41.052.50.38Semi Detached3.01.122.50.35Embedded3.61.202.50.32The effort is measured in Person-Months and as evident from the formula is dependent on Kilo-Lines of code.The development time is measured in months.These formulas are used as such in the Basic Model calculations, as not much consideration of different factors such as reliability, expertise is taken into account, henceforth the estimate is rough.Below is the C++ program for Basic COCOMO// C++ program to implement basic COCOMO#include<bits/stdc++.h>using namespace std; // Function for rounding off float to intint fround(float x){ int a; x=x+0.5; a=x; return(a);} // Function to calculate parameters of Basic COCOMOvoid calculate(float table[][4], int n,char mode[][15], int size){ float effort,time,staff; int model; // Check the mode according to size if(size>=2 && size<=50) model=0; //organic else if(size>50 && size<=300) model=1; //semi-detached else if(size>300) model=2; //embedded cout<<"The mode is "<<mode[model]; // Calculate Effort effort = table[model][0]*pow(size,table[model][1]); // Calculate Time time = table[model][2]*pow(effort,table[model][3]); //Calculate Persons Required staff = effort/time; // Output the values calculated cout<<"\nEffort = "<<effort<<" Person-Month"; cout<<"\nDevelopment Time = "<<time<<" Months"; cout<<"\nAverage Staff Required = "<<fround(staff)<<" Persons"; } int main(){ float table[3][4]={2.4,1.05,2.5,0.38,3.0,1.12,2.5,0.35,3.6,1.20,2.5,0.32}; char mode[][15]={"Organic","Semi-Detached","Embedded"}; int size = 4; calculate(table,3,mode,size); return 0;}Output:The mode is Organic
Effort = 10.289 Person-Month
Development Time = 6.06237 Months
Average Staff Required = 2 Persons
Intermediate Model –The basic Cocomo model assumes that the effort is only a function of the number of lines of code and some constants evaluated according to the different software systems. However, in reality, no system’s effort and schedule can be solely calculated on the basis of Lines of Code. For that, various other factors such as reliability, experience, Capability. These factors are known as Cost Drivers and the Intermediate Model utilizes 15 such drivers for cost estimation.Classification of Cost Drivers and their attributes:(i) Product attributes –Required software reliability extentSize of the application databaseThe complexity of the product(ii) Hardware attributes –Run-time performance constraintsMemory constraintsThe volatility of the virtual machine environmentRequired turnabout time(iii) Personnel attributes –Analyst capabilitySoftware engineering capabilityApplications experienceVirtual machine experienceProgramming language experience(iv) Project attributes –Use of software toolsApplication of software engineering methodsRequired development scheduleCost DriversVery LowLowNominal;HighVery HighProduct AttributesRequired Software Reliability0.750.881.001.151.40Size of Application Database0.941.001.081.16Complexity of The Product0.700.851.001.151.30Hardware AttributesRuntime Performance Constraints1.001.111.30Memory Constraints1.001.061.21Volatility of the virtual machine environment0.871.001.151.30Required turnabout time0.941.001.071.15Personnel attributesAnalyst capability1.461.191.000.860.71Applications experience1.291.131.000.910.82Software engineer capability1.421.171.000.860.70Virtual machine experience1.211.101.000.90Programming language experience1.141.071.000.95Project AttributesApplication of software engineering methods1.241.101.000.910.82Use of software tools1.241.101.000.910.83Required development schedule1.231.081.001.041.10The project manager is to rate these 15 different parameters for a particular project on a scale of one to three. Then, depending on these ratings, appropriate cost driver values are taken from the above table. These 15 values are then multiplied to calculate the EAF (Effort Adjustment Factor). The Intermediate COCOMO formula now takes the form:
The values of a and b in case of the intermediate model are as follows:Software ProjectsabOrganic3.21.05Semi Detached3.01.12Embeddedc2.81.20Detailed Model –Detailed COCOMO incorporates all characteristics of the intermediate version with an assessment of the cost driver’s impact on each step of the software engineering process. The detailed model uses different effort multipliers for each cost driver attribute. In detailed cocomo, the whole software is divided into different modules and then we apply COCOMO in different modules to estimate effort and then sum the effort.The Six phases of detailed COCOMO are:Planning and requirementsSystem designDetailed designModule code and testIntegration and testCost Constructive modelThe effort is calculated as a function of program size and a set of cost drivers are given according to each phase of the software lifecycle.Also read: Classical Waterfall Model, Iterative Waterfall Model, Prototyping Model, Spiral ModelMy Personal Notes
arrow_drop_upSave
All the above system types utilize different values of the constants used in Effort Calculations.
Types of Models: COCOMO consists of a hierarchy of three increasingly detailed and accurate forms. Any of the three forms can be adopted according to our requirements. These are types of COCOMO model:
Basic COCOMO ModelIntermediate COCOMO ModelDetailed COCOMO Model
Basic COCOMO Model
Intermediate COCOMO Model
Detailed COCOMO Model
The first level, Basic COCOMO can be used for quick and slightly rough calculations of Software Costs. Its accuracy is somewhat restricted due to the absence of sufficient factor considerations.
Intermediate COCOMO takes these Cost Drivers into account and Detailed COCOMO additionally accounts for the influence of individual project phases, i.e in case of Detailed it accounts for both these cost drivers and also calculations are performed phase-wise henceforth producing a more accurate result. These two models are further discussed below.
Estimation of Effort: Calculations –
Basic Model –
The above formula is used for the cost estimation of for the basic COCOMO model, and also is used in the subsequent models. The constant values a,b,c and d for the Basic Model for the different categories of system:Software ProjectsabcdOrganic2.41.052.50.38Semi Detached3.01.122.50.35Embedded3.61.202.50.32The effort is measured in Person-Months and as evident from the formula is dependent on Kilo-Lines of code.The development time is measured in months.These formulas are used as such in the Basic Model calculations, as not much consideration of different factors such as reliability, expertise is taken into account, henceforth the estimate is rough.Below is the C++ program for Basic COCOMO// C++ program to implement basic COCOMO#include<bits/stdc++.h>using namespace std; // Function for rounding off float to intint fround(float x){ int a; x=x+0.5; a=x; return(a);} // Function to calculate parameters of Basic COCOMOvoid calculate(float table[][4], int n,char mode[][15], int size){ float effort,time,staff; int model; // Check the mode according to size if(size>=2 && size<=50) model=0; //organic else if(size>50 && size<=300) model=1; //semi-detached else if(size>300) model=2; //embedded cout<<"The mode is "<<mode[model]; // Calculate Effort effort = table[model][0]*pow(size,table[model][1]); // Calculate Time time = table[model][2]*pow(effort,table[model][3]); //Calculate Persons Required staff = effort/time; // Output the values calculated cout<<"\nEffort = "<<effort<<" Person-Month"; cout<<"\nDevelopment Time = "<<time<<" Months"; cout<<"\nAverage Staff Required = "<<fround(staff)<<" Persons"; } int main(){ float table[3][4]={2.4,1.05,2.5,0.38,3.0,1.12,2.5,0.35,3.6,1.20,2.5,0.32}; char mode[][15]={"Organic","Semi-Detached","Embedded"}; int size = 4; calculate(table,3,mode,size); return 0;}Output:The mode is Organic
Effort = 10.289 Person-Month
Development Time = 6.06237 Months
Average Staff Required = 2 Persons
Intermediate Model –The basic Cocomo model assumes that the effort is only a function of the number of lines of code and some constants evaluated according to the different software systems. However, in reality, no system’s effort and schedule can be solely calculated on the basis of Lines of Code. For that, various other factors such as reliability, experience, Capability. These factors are known as Cost Drivers and the Intermediate Model utilizes 15 such drivers for cost estimation.Classification of Cost Drivers and their attributes:(i) Product attributes –Required software reliability extentSize of the application databaseThe complexity of the product(ii) Hardware attributes –Run-time performance constraintsMemory constraintsThe volatility of the virtual machine environmentRequired turnabout time(iii) Personnel attributes –Analyst capabilitySoftware engineering capabilityApplications experienceVirtual machine experienceProgramming language experience(iv) Project attributes –Use of software toolsApplication of software engineering methodsRequired development scheduleCost DriversVery LowLowNominal;HighVery HighProduct AttributesRequired Software Reliability0.750.881.001.151.40Size of Application Database0.941.001.081.16Complexity of The Product0.700.851.001.151.30Hardware AttributesRuntime Performance Constraints1.001.111.30Memory Constraints1.001.061.21Volatility of the virtual machine environment0.871.001.151.30Required turnabout time0.941.001.071.15Personnel attributesAnalyst capability1.461.191.000.860.71Applications experience1.291.131.000.910.82Software engineer capability1.421.171.000.860.70Virtual machine experience1.211.101.000.90Programming language experience1.141.071.000.95Project AttributesApplication of software engineering methods1.241.101.000.910.82Use of software tools1.241.101.000.910.83Required development schedule1.231.081.001.041.10The project manager is to rate these 15 different parameters for a particular project on a scale of one to three. Then, depending on these ratings, appropriate cost driver values are taken from the above table. These 15 values are then multiplied to calculate the EAF (Effort Adjustment Factor). The Intermediate COCOMO formula now takes the form:
The values of a and b in case of the intermediate model are as follows:Software ProjectsabOrganic3.21.05Semi Detached3.01.12Embeddedc2.81.20Detailed Model –Detailed COCOMO incorporates all characteristics of the intermediate version with an assessment of the cost driver’s impact on each step of the software engineering process. The detailed model uses different effort multipliers for each cost driver attribute. In detailed cocomo, the whole software is divided into different modules and then we apply COCOMO in different modules to estimate effort and then sum the effort.The Six phases of detailed COCOMO are:Planning and requirementsSystem designDetailed designModule code and testIntegration and testCost Constructive modelThe effort is calculated as a function of program size and a set of cost drivers are given according to each phase of the software lifecycle.
Basic Model –
The above formula is used for the cost estimation of for the basic COCOMO model, and also is used in the subsequent models. The constant values a,b,c and d for the Basic Model for the different categories of system:Software ProjectsabcdOrganic2.41.052.50.38Semi Detached3.01.122.50.35Embedded3.61.202.50.32The effort is measured in Person-Months and as evident from the formula is dependent on Kilo-Lines of code.The development time is measured in months.These formulas are used as such in the Basic Model calculations, as not much consideration of different factors such as reliability, expertise is taken into account, henceforth the estimate is rough.Below is the C++ program for Basic COCOMO// C++ program to implement basic COCOMO#include<bits/stdc++.h>using namespace std; // Function for rounding off float to intint fround(float x){ int a; x=x+0.5; a=x; return(a);} // Function to calculate parameters of Basic COCOMOvoid calculate(float table[][4], int n,char mode[][15], int size){ float effort,time,staff; int model; // Check the mode according to size if(size>=2 && size<=50) model=0; //organic else if(size>50 && size<=300) model=1; //semi-detached else if(size>300) model=2; //embedded cout<<"The mode is "<<mode[model]; // Calculate Effort effort = table[model][0]*pow(size,table[model][1]); // Calculate Time time = table[model][2]*pow(effort,table[model][3]); //Calculate Persons Required staff = effort/time; // Output the values calculated cout<<"\nEffort = "<<effort<<" Person-Month"; cout<<"\nDevelopment Time = "<<time<<" Months"; cout<<"\nAverage Staff Required = "<<fround(staff)<<" Persons"; } int main(){ float table[3][4]={2.4,1.05,2.5,0.38,3.0,1.12,2.5,0.35,3.6,1.20,2.5,0.32}; char mode[][15]={"Organic","Semi-Detached","Embedded"}; int size = 4; calculate(table,3,mode,size); return 0;}Output:The mode is Organic
Effort = 10.289 Person-Month
Development Time = 6.06237 Months
Average Staff Required = 2 Persons
The above formula is used for the cost estimation of for the basic COCOMO model, and also is used in the subsequent models. The constant values a,b,c and d for the Basic Model for the different categories of system:
The effort is measured in Person-Months and as evident from the formula is dependent on Kilo-Lines of code.The development time is measured in months.
These formulas are used as such in the Basic Model calculations, as not much consideration of different factors such as reliability, expertise is taken into account, henceforth the estimate is rough.
Below is the C++ program for Basic COCOMO
// C++ program to implement basic COCOMO#include<bits/stdc++.h>using namespace std; // Function for rounding off float to intint fround(float x){ int a; x=x+0.5; a=x; return(a);} // Function to calculate parameters of Basic COCOMOvoid calculate(float table[][4], int n,char mode[][15], int size){ float effort,time,staff; int model; // Check the mode according to size if(size>=2 && size<=50) model=0; //organic else if(size>50 && size<=300) model=1; //semi-detached else if(size>300) model=2; //embedded cout<<"The mode is "<<mode[model]; // Calculate Effort effort = table[model][0]*pow(size,table[model][1]); // Calculate Time time = table[model][2]*pow(effort,table[model][3]); //Calculate Persons Required staff = effort/time; // Output the values calculated cout<<"\nEffort = "<<effort<<" Person-Month"; cout<<"\nDevelopment Time = "<<time<<" Months"; cout<<"\nAverage Staff Required = "<<fround(staff)<<" Persons"; } int main(){ float table[3][4]={2.4,1.05,2.5,0.38,3.0,1.12,2.5,0.35,3.6,1.20,2.5,0.32}; char mode[][15]={"Organic","Semi-Detached","Embedded"}; int size = 4; calculate(table,3,mode,size); return 0;}
The mode is Organic
Effort = 10.289 Person-Month
Development Time = 6.06237 Months
Average Staff Required = 2 Persons
Intermediate Model –The basic Cocomo model assumes that the effort is only a function of the number of lines of code and some constants evaluated according to the different software systems. However, in reality, no system’s effort and schedule can be solely calculated on the basis of Lines of Code. For that, various other factors such as reliability, experience, Capability. These factors are known as Cost Drivers and the Intermediate Model utilizes 15 such drivers for cost estimation.Classification of Cost Drivers and their attributes:(i) Product attributes –Required software reliability extentSize of the application databaseThe complexity of the product(ii) Hardware attributes –Run-time performance constraintsMemory constraintsThe volatility of the virtual machine environmentRequired turnabout time(iii) Personnel attributes –Analyst capabilitySoftware engineering capabilityApplications experienceVirtual machine experienceProgramming language experience(iv) Project attributes –Use of software toolsApplication of software engineering methodsRequired development scheduleCost DriversVery LowLowNominal;HighVery HighProduct AttributesRequired Software Reliability0.750.881.001.151.40Size of Application Database0.941.001.081.16Complexity of The Product0.700.851.001.151.30Hardware AttributesRuntime Performance Constraints1.001.111.30Memory Constraints1.001.061.21Volatility of the virtual machine environment0.871.001.151.30Required turnabout time0.941.001.071.15Personnel attributesAnalyst capability1.461.191.000.860.71Applications experience1.291.131.000.910.82Software engineer capability1.421.171.000.860.70Virtual machine experience1.211.101.000.90Programming language experience1.141.071.000.95Project AttributesApplication of software engineering methods1.241.101.000.910.82Use of software tools1.241.101.000.910.83Required development schedule1.231.081.001.041.10The project manager is to rate these 15 different parameters for a particular project on a scale of one to three. Then, depending on these ratings, appropriate cost driver values are taken from the above table. These 15 values are then multiplied to calculate the EAF (Effort Adjustment Factor). The Intermediate COCOMO formula now takes the form:
The values of a and b in case of the intermediate model are as follows:Software ProjectsabOrganic3.21.05Semi Detached3.01.12Embeddedc2.81.20
The basic Cocomo model assumes that the effort is only a function of the number of lines of code and some constants evaluated according to the different software systems. However, in reality, no system’s effort and schedule can be solely calculated on the basis of Lines of Code. For that, various other factors such as reliability, experience, Capability. These factors are known as Cost Drivers and the Intermediate Model utilizes 15 such drivers for cost estimation.
Classification of Cost Drivers and their attributes:
(i) Product attributes –
Required software reliability extent
Size of the application database
The complexity of the product
(ii) Hardware attributes –
Run-time performance constraints
Memory constraints
The volatility of the virtual machine environment
Required turnabout time
(iii) Personnel attributes –
Analyst capability
Software engineering capability
Applications experience
Virtual machine experience
Programming language experience
(iv) Project attributes –
Use of software tools
Application of software engineering methods
Required development schedule
;
The project manager is to rate these 15 different parameters for a particular project on a scale of one to three. Then, depending on these ratings, appropriate cost driver values are taken from the above table. These 15 values are then multiplied to calculate the EAF (Effort Adjustment Factor). The Intermediate COCOMO formula now takes the form:
The values of a and b in case of the intermediate model are as follows:
Detailed Model –Detailed COCOMO incorporates all characteristics of the intermediate version with an assessment of the cost driver’s impact on each step of the software engineering process. The detailed model uses different effort multipliers for each cost driver attribute. In detailed cocomo, the whole software is divided into different modules and then we apply COCOMO in different modules to estimate effort and then sum the effort.The Six phases of detailed COCOMO are:Planning and requirementsSystem designDetailed designModule code and testIntegration and testCost Constructive modelThe effort is calculated as a function of program size and a set of cost drivers are given according to each phase of the software lifecycle.
The Six phases of detailed COCOMO are:
Planning and requirementsSystem designDetailed designModule code and testIntegration and testCost Constructive model
Planning and requirements
System design
Detailed design
Module code and test
Integration and test
Cost Constructive model
The effort is calculated as a function of program size and a set of cost drivers are given according to each phase of the software lifecycle.
Also read: Classical Waterfall Model, Iterative Waterfall Model, Prototyping Model, Spiral Model
chitrasingla2001
yogirao
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Software Testing
Differences between Black Box Testing vs White Box Testing
Functional vs Non Functional Requirements
Differences between Verification and Validation
Software Testing | Basics
Software Requirement Specification (SRS) Format
Levels in Data Flow Diagrams (DFD)
Difference between Alpha and Beta Testing
Software Engineering | Architectural Design
Difference between Spring and Spring Boot | [
{
"code": null,
"e": 28627,
"s": 28599,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 29074,
"s": 28627,
"text": "Cocomo (Constructive Cost Model) is a regression model based on LOC, i.e number of Lines of Code. It is a procedural cost estimate model for software projects and is often used as a process of reliably predicting the various parameters associated with making a project such as size, effort, cost, time, and quality. It was proposed by Barry Boehm in 1981 and is based on the study of 63 projects, which makes it one of the best-documented models."
},
{
"code": null,
"e": 29217,
"s": 29074,
"text": "The key parameters which define the quality of any software products, which are also an outcome of the Cocomo are primarily Effort & Schedule:"
},
{
"code": null,
"e": 29322,
"s": 29217,
"text": "Effort: Amount of labor that will be required to complete a task. It is measured in person-months units."
},
{
"code": null,
"e": 29519,
"s": 29322,
"text": "Schedule: Simply means the amount of time required for the completion of the job, which is, of course, proportional to the effort put in. It is measured in the units of time such as weeks, months."
},
{
"code": null,
"e": 29909,
"s": 29519,
"text": "Different models of Cocomo have been proposed to predict the cost estimation at different levels, based on the amount of accuracy and correctness required. All of these models can be applied to a variety of projects, whose characteristics determine the value of constant to be used in subsequent calculations. These characteristics pertaining to different system types are mentioned below."
},
{
"code": null,
"e": 29976,
"s": 29909,
"text": "Boehm’s definition of organic, semidetached, and embedded systems:"
},
{
"code": null,
"e": 37346,
"s": 29976,
"text": "Organic – A software project is said to be an organic type if the team size required is adequately small, the problem is well understood and has been solved in the past and also the team members have a nominal experience regarding the problem.Semi-detached – A software project is said to be a Semi-detached type if the vital characteristics such as team size, experience, knowledge of the various programming environment lie in between that of organic and Embedded. The projects classified as Semi-Detached are comparatively less familiar and difficult to develop compared to the organic ones and require more experience and better guidance and creativity. Eg: Compilers or different Embedded Systems can be considered of Semi-Detached type.Embedded – A software project requiring the highest level of complexity, creativity, and experience requirement fall under this category. Such software requires a larger team size than the other two models and also the developers need to be sufficiently experienced and creative to develop such complex models.All the above system types utilize different values of the constants used in Effort Calculations.Types of Models: COCOMO consists of a hierarchy of three increasingly detailed and accurate forms. Any of the three forms can be adopted according to our requirements. These are types of COCOMO model:Basic COCOMO ModelIntermediate COCOMO ModelDetailed COCOMO ModelThe first level, Basic COCOMO can be used for quick and slightly rough calculations of Software Costs. Its accuracy is somewhat restricted due to the absence of sufficient factor considerations.Intermediate COCOMO takes these Cost Drivers into account and Detailed COCOMO additionally accounts for the influence of individual project phases, i.e in case of Detailed it accounts for both these cost drivers and also calculations are performed phase-wise henceforth producing a more accurate result. These two models are further discussed below.Estimation of Effort: Calculations –Basic Model –\n\n\nThe above formula is used for the cost estimation of for the basic COCOMO model, and also is used in the subsequent models. The constant values a,b,c and d for the Basic Model for the different categories of system:Software ProjectsabcdOrganic2.41.052.50.38Semi Detached3.01.122.50.35Embedded3.61.202.50.32The effort is measured in Person-Months and as evident from the formula is dependent on Kilo-Lines of code.The development time is measured in months.These formulas are used as such in the Basic Model calculations, as not much consideration of different factors such as reliability, expertise is taken into account, henceforth the estimate is rough.Below is the C++ program for Basic COCOMO// C++ program to implement basic COCOMO#include<bits/stdc++.h>using namespace std; // Function for rounding off float to intint fround(float x){ int a; x=x+0.5; a=x; return(a);} // Function to calculate parameters of Basic COCOMOvoid calculate(float table[][4], int n,char mode[][15], int size){ float effort,time,staff; int model; // Check the mode according to size if(size>=2 && size<=50) model=0; //organic else if(size>50 && size<=300) model=1; //semi-detached else if(size>300) model=2; //embedded cout<<\"The mode is \"<<mode[model]; // Calculate Effort effort = table[model][0]*pow(size,table[model][1]); // Calculate Time time = table[model][2]*pow(effort,table[model][3]); //Calculate Persons Required staff = effort/time; // Output the values calculated cout<<\"\\nEffort = \"<<effort<<\" Person-Month\"; cout<<\"\\nDevelopment Time = \"<<time<<\" Months\"; cout<<\"\\nAverage Staff Required = \"<<fround(staff)<<\" Persons\"; } int main(){ float table[3][4]={2.4,1.05,2.5,0.38,3.0,1.12,2.5,0.35,3.6,1.20,2.5,0.32}; char mode[][15]={\"Organic\",\"Semi-Detached\",\"Embedded\"}; int size = 4; calculate(table,3,mode,size); return 0;}Output:The mode is Organic\nEffort = 10.289 Person-Month\nDevelopment Time = 6.06237 Months\nAverage Staff Required = 2 Persons\nIntermediate Model –The basic Cocomo model assumes that the effort is only a function of the number of lines of code and some constants evaluated according to the different software systems. However, in reality, no system’s effort and schedule can be solely calculated on the basis of Lines of Code. For that, various other factors such as reliability, experience, Capability. These factors are known as Cost Drivers and the Intermediate Model utilizes 15 such drivers for cost estimation.Classification of Cost Drivers and their attributes:(i) Product attributes –Required software reliability extentSize of the application databaseThe complexity of the product(ii) Hardware attributes –Run-time performance constraintsMemory constraintsThe volatility of the virtual machine environmentRequired turnabout time(iii) Personnel attributes –Analyst capabilitySoftware engineering capabilityApplications experienceVirtual machine experienceProgramming language experience(iv) Project attributes –Use of software toolsApplication of software engineering methodsRequired development scheduleCost DriversVery LowLowNominal;HighVery HighProduct AttributesRequired Software Reliability0.750.881.001.151.40Size of Application Database0.941.001.081.16Complexity of The Product0.700.851.001.151.30Hardware AttributesRuntime Performance Constraints1.001.111.30Memory Constraints1.001.061.21Volatility of the virtual machine environment0.871.001.151.30Required turnabout time0.941.001.071.15Personnel attributesAnalyst capability1.461.191.000.860.71Applications experience1.291.131.000.910.82Software engineer capability1.421.171.000.860.70Virtual machine experience1.211.101.000.90Programming language experience1.141.071.000.95Project AttributesApplication of software engineering methods1.241.101.000.910.82Use of software tools1.241.101.000.910.83Required development schedule1.231.081.001.041.10The project manager is to rate these 15 different parameters for a particular project on a scale of one to three. Then, depending on these ratings, appropriate cost driver values are taken from the above table. These 15 values are then multiplied to calculate the EAF (Effort Adjustment Factor). The Intermediate COCOMO formula now takes the form:\nThe values of a and b in case of the intermediate model are as follows:Software ProjectsabOrganic3.21.05Semi Detached3.01.12Embeddedc2.81.20Detailed Model –Detailed COCOMO incorporates all characteristics of the intermediate version with an assessment of the cost driver’s impact on each step of the software engineering process. The detailed model uses different effort multipliers for each cost driver attribute. In detailed cocomo, the whole software is divided into different modules and then we apply COCOMO in different modules to estimate effort and then sum the effort.The Six phases of detailed COCOMO are:Planning and requirementsSystem designDetailed designModule code and testIntegration and testCost Constructive modelThe effort is calculated as a function of program size and a set of cost drivers are given according to each phase of the software lifecycle.Also read: Classical Waterfall Model, Iterative Waterfall Model, Prototyping Model, Spiral ModelMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 37590,
"s": 37346,
"text": "Organic – A software project is said to be an organic type if the team size required is adequately small, the problem is well understood and has been solved in the past and also the team members have a nominal experience regarding the problem."
},
{
"code": null,
"e": 38090,
"s": 37590,
"text": "Semi-detached – A software project is said to be a Semi-detached type if the vital characteristics such as team size, experience, knowledge of the various programming environment lie in between that of organic and Embedded. The projects classified as Semi-Detached are comparatively less familiar and difficult to develop compared to the organic ones and require more experience and better guidance and creativity. Eg: Compilers or different Embedded Systems can be considered of Semi-Detached type."
},
{
"code": null,
"e": 44718,
"s": 38090,
"text": "Embedded – A software project requiring the highest level of complexity, creativity, and experience requirement fall under this category. Such software requires a larger team size than the other two models and also the developers need to be sufficiently experienced and creative to develop such complex models.All the above system types utilize different values of the constants used in Effort Calculations.Types of Models: COCOMO consists of a hierarchy of three increasingly detailed and accurate forms. Any of the three forms can be adopted according to our requirements. These are types of COCOMO model:Basic COCOMO ModelIntermediate COCOMO ModelDetailed COCOMO ModelThe first level, Basic COCOMO can be used for quick and slightly rough calculations of Software Costs. Its accuracy is somewhat restricted due to the absence of sufficient factor considerations.Intermediate COCOMO takes these Cost Drivers into account and Detailed COCOMO additionally accounts for the influence of individual project phases, i.e in case of Detailed it accounts for both these cost drivers and also calculations are performed phase-wise henceforth producing a more accurate result. These two models are further discussed below.Estimation of Effort: Calculations –Basic Model –\n\n\nThe above formula is used for the cost estimation of for the basic COCOMO model, and also is used in the subsequent models. The constant values a,b,c and d for the Basic Model for the different categories of system:Software ProjectsabcdOrganic2.41.052.50.38Semi Detached3.01.122.50.35Embedded3.61.202.50.32The effort is measured in Person-Months and as evident from the formula is dependent on Kilo-Lines of code.The development time is measured in months.These formulas are used as such in the Basic Model calculations, as not much consideration of different factors such as reliability, expertise is taken into account, henceforth the estimate is rough.Below is the C++ program for Basic COCOMO// C++ program to implement basic COCOMO#include<bits/stdc++.h>using namespace std; // Function for rounding off float to intint fround(float x){ int a; x=x+0.5; a=x; return(a);} // Function to calculate parameters of Basic COCOMOvoid calculate(float table[][4], int n,char mode[][15], int size){ float effort,time,staff; int model; // Check the mode according to size if(size>=2 && size<=50) model=0; //organic else if(size>50 && size<=300) model=1; //semi-detached else if(size>300) model=2; //embedded cout<<\"The mode is \"<<mode[model]; // Calculate Effort effort = table[model][0]*pow(size,table[model][1]); // Calculate Time time = table[model][2]*pow(effort,table[model][3]); //Calculate Persons Required staff = effort/time; // Output the values calculated cout<<\"\\nEffort = \"<<effort<<\" Person-Month\"; cout<<\"\\nDevelopment Time = \"<<time<<\" Months\"; cout<<\"\\nAverage Staff Required = \"<<fround(staff)<<\" Persons\"; } int main(){ float table[3][4]={2.4,1.05,2.5,0.38,3.0,1.12,2.5,0.35,3.6,1.20,2.5,0.32}; char mode[][15]={\"Organic\",\"Semi-Detached\",\"Embedded\"}; int size = 4; calculate(table,3,mode,size); return 0;}Output:The mode is Organic\nEffort = 10.289 Person-Month\nDevelopment Time = 6.06237 Months\nAverage Staff Required = 2 Persons\nIntermediate Model –The basic Cocomo model assumes that the effort is only a function of the number of lines of code and some constants evaluated according to the different software systems. However, in reality, no system’s effort and schedule can be solely calculated on the basis of Lines of Code. For that, various other factors such as reliability, experience, Capability. These factors are known as Cost Drivers and the Intermediate Model utilizes 15 such drivers for cost estimation.Classification of Cost Drivers and their attributes:(i) Product attributes –Required software reliability extentSize of the application databaseThe complexity of the product(ii) Hardware attributes –Run-time performance constraintsMemory constraintsThe volatility of the virtual machine environmentRequired turnabout time(iii) Personnel attributes –Analyst capabilitySoftware engineering capabilityApplications experienceVirtual machine experienceProgramming language experience(iv) Project attributes –Use of software toolsApplication of software engineering methodsRequired development scheduleCost DriversVery LowLowNominal;HighVery HighProduct AttributesRequired Software Reliability0.750.881.001.151.40Size of Application Database0.941.001.081.16Complexity of The Product0.700.851.001.151.30Hardware AttributesRuntime Performance Constraints1.001.111.30Memory Constraints1.001.061.21Volatility of the virtual machine environment0.871.001.151.30Required turnabout time0.941.001.071.15Personnel attributesAnalyst capability1.461.191.000.860.71Applications experience1.291.131.000.910.82Software engineer capability1.421.171.000.860.70Virtual machine experience1.211.101.000.90Programming language experience1.141.071.000.95Project AttributesApplication of software engineering methods1.241.101.000.910.82Use of software tools1.241.101.000.910.83Required development schedule1.231.081.001.041.10The project manager is to rate these 15 different parameters for a particular project on a scale of one to three. Then, depending on these ratings, appropriate cost driver values are taken from the above table. These 15 values are then multiplied to calculate the EAF (Effort Adjustment Factor). The Intermediate COCOMO formula now takes the form:\nThe values of a and b in case of the intermediate model are as follows:Software ProjectsabOrganic3.21.05Semi Detached3.01.12Embeddedc2.81.20Detailed Model –Detailed COCOMO incorporates all characteristics of the intermediate version with an assessment of the cost driver’s impact on each step of the software engineering process. The detailed model uses different effort multipliers for each cost driver attribute. In detailed cocomo, the whole software is divided into different modules and then we apply COCOMO in different modules to estimate effort and then sum the effort.The Six phases of detailed COCOMO are:Planning and requirementsSystem designDetailed designModule code and testIntegration and testCost Constructive modelThe effort is calculated as a function of program size and a set of cost drivers are given according to each phase of the software lifecycle.Also read: Classical Waterfall Model, Iterative Waterfall Model, Prototyping Model, Spiral ModelMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 44816,
"s": 44718,
"text": "All the above system types utilize different values of the constants used in Effort Calculations."
},
{
"code": null,
"e": 45017,
"s": 44816,
"text": "Types of Models: COCOMO consists of a hierarchy of three increasingly detailed and accurate forms. Any of the three forms can be adopted according to our requirements. These are types of COCOMO model:"
},
{
"code": null,
"e": 45082,
"s": 45017,
"text": "Basic COCOMO ModelIntermediate COCOMO ModelDetailed COCOMO Model"
},
{
"code": null,
"e": 45101,
"s": 45082,
"text": "Basic COCOMO Model"
},
{
"code": null,
"e": 45127,
"s": 45101,
"text": "Intermediate COCOMO Model"
},
{
"code": null,
"e": 45149,
"s": 45127,
"text": "Detailed COCOMO Model"
},
{
"code": null,
"e": 45344,
"s": 45149,
"text": "The first level, Basic COCOMO can be used for quick and slightly rough calculations of Software Costs. Its accuracy is somewhat restricted due to the absence of sufficient factor considerations."
},
{
"code": null,
"e": 45694,
"s": 45344,
"text": "Intermediate COCOMO takes these Cost Drivers into account and Detailed COCOMO additionally accounts for the influence of individual project phases, i.e in case of Detailed it accounts for both these cost drivers and also calculations are performed phase-wise henceforth producing a more accurate result. These two models are further discussed below."
},
{
"code": null,
"e": 45731,
"s": 45694,
"text": "Estimation of Effort: Calculations –"
},
{
"code": null,
"e": 50978,
"s": 45731,
"text": "Basic Model –\n\n\nThe above formula is used for the cost estimation of for the basic COCOMO model, and also is used in the subsequent models. The constant values a,b,c and d for the Basic Model for the different categories of system:Software ProjectsabcdOrganic2.41.052.50.38Semi Detached3.01.122.50.35Embedded3.61.202.50.32The effort is measured in Person-Months and as evident from the formula is dependent on Kilo-Lines of code.The development time is measured in months.These formulas are used as such in the Basic Model calculations, as not much consideration of different factors such as reliability, expertise is taken into account, henceforth the estimate is rough.Below is the C++ program for Basic COCOMO// C++ program to implement basic COCOMO#include<bits/stdc++.h>using namespace std; // Function for rounding off float to intint fround(float x){ int a; x=x+0.5; a=x; return(a);} // Function to calculate parameters of Basic COCOMOvoid calculate(float table[][4], int n,char mode[][15], int size){ float effort,time,staff; int model; // Check the mode according to size if(size>=2 && size<=50) model=0; //organic else if(size>50 && size<=300) model=1; //semi-detached else if(size>300) model=2; //embedded cout<<\"The mode is \"<<mode[model]; // Calculate Effort effort = table[model][0]*pow(size,table[model][1]); // Calculate Time time = table[model][2]*pow(effort,table[model][3]); //Calculate Persons Required staff = effort/time; // Output the values calculated cout<<\"\\nEffort = \"<<effort<<\" Person-Month\"; cout<<\"\\nDevelopment Time = \"<<time<<\" Months\"; cout<<\"\\nAverage Staff Required = \"<<fround(staff)<<\" Persons\"; } int main(){ float table[3][4]={2.4,1.05,2.5,0.38,3.0,1.12,2.5,0.35,3.6,1.20,2.5,0.32}; char mode[][15]={\"Organic\",\"Semi-Detached\",\"Embedded\"}; int size = 4; calculate(table,3,mode,size); return 0;}Output:The mode is Organic\nEffort = 10.289 Person-Month\nDevelopment Time = 6.06237 Months\nAverage Staff Required = 2 Persons\nIntermediate Model –The basic Cocomo model assumes that the effort is only a function of the number of lines of code and some constants evaluated according to the different software systems. However, in reality, no system’s effort and schedule can be solely calculated on the basis of Lines of Code. For that, various other factors such as reliability, experience, Capability. These factors are known as Cost Drivers and the Intermediate Model utilizes 15 such drivers for cost estimation.Classification of Cost Drivers and their attributes:(i) Product attributes –Required software reliability extentSize of the application databaseThe complexity of the product(ii) Hardware attributes –Run-time performance constraintsMemory constraintsThe volatility of the virtual machine environmentRequired turnabout time(iii) Personnel attributes –Analyst capabilitySoftware engineering capabilityApplications experienceVirtual machine experienceProgramming language experience(iv) Project attributes –Use of software toolsApplication of software engineering methodsRequired development scheduleCost DriversVery LowLowNominal;HighVery HighProduct AttributesRequired Software Reliability0.750.881.001.151.40Size of Application Database0.941.001.081.16Complexity of The Product0.700.851.001.151.30Hardware AttributesRuntime Performance Constraints1.001.111.30Memory Constraints1.001.061.21Volatility of the virtual machine environment0.871.001.151.30Required turnabout time0.941.001.071.15Personnel attributesAnalyst capability1.461.191.000.860.71Applications experience1.291.131.000.910.82Software engineer capability1.421.171.000.860.70Virtual machine experience1.211.101.000.90Programming language experience1.141.071.000.95Project AttributesApplication of software engineering methods1.241.101.000.910.82Use of software tools1.241.101.000.910.83Required development schedule1.231.081.001.041.10The project manager is to rate these 15 different parameters for a particular project on a scale of one to three. Then, depending on these ratings, appropriate cost driver values are taken from the above table. These 15 values are then multiplied to calculate the EAF (Effort Adjustment Factor). The Intermediate COCOMO formula now takes the form:\nThe values of a and b in case of the intermediate model are as follows:Software ProjectsabOrganic3.21.05Semi Detached3.01.12Embeddedc2.81.20Detailed Model –Detailed COCOMO incorporates all characteristics of the intermediate version with an assessment of the cost driver’s impact on each step of the software engineering process. The detailed model uses different effort multipliers for each cost driver attribute. In detailed cocomo, the whole software is divided into different modules and then we apply COCOMO in different modules to estimate effort and then sum the effort.The Six phases of detailed COCOMO are:Planning and requirementsSystem designDetailed designModule code and testIntegration and testCost Constructive modelThe effort is calculated as a function of program size and a set of cost drivers are given according to each phase of the software lifecycle."
},
{
"code": null,
"e": 53119,
"s": 50978,
"text": "Basic Model –\n\n\nThe above formula is used for the cost estimation of for the basic COCOMO model, and also is used in the subsequent models. The constant values a,b,c and d for the Basic Model for the different categories of system:Software ProjectsabcdOrganic2.41.052.50.38Semi Detached3.01.122.50.35Embedded3.61.202.50.32The effort is measured in Person-Months and as evident from the formula is dependent on Kilo-Lines of code.The development time is measured in months.These formulas are used as such in the Basic Model calculations, as not much consideration of different factors such as reliability, expertise is taken into account, henceforth the estimate is rough.Below is the C++ program for Basic COCOMO// C++ program to implement basic COCOMO#include<bits/stdc++.h>using namespace std; // Function for rounding off float to intint fround(float x){ int a; x=x+0.5; a=x; return(a);} // Function to calculate parameters of Basic COCOMOvoid calculate(float table[][4], int n,char mode[][15], int size){ float effort,time,staff; int model; // Check the mode according to size if(size>=2 && size<=50) model=0; //organic else if(size>50 && size<=300) model=1; //semi-detached else if(size>300) model=2; //embedded cout<<\"The mode is \"<<mode[model]; // Calculate Effort effort = table[model][0]*pow(size,table[model][1]); // Calculate Time time = table[model][2]*pow(effort,table[model][3]); //Calculate Persons Required staff = effort/time; // Output the values calculated cout<<\"\\nEffort = \"<<effort<<\" Person-Month\"; cout<<\"\\nDevelopment Time = \"<<time<<\" Months\"; cout<<\"\\nAverage Staff Required = \"<<fround(staff)<<\" Persons\"; } int main(){ float table[3][4]={2.4,1.05,2.5,0.38,3.0,1.12,2.5,0.35,3.6,1.20,2.5,0.32}; char mode[][15]={\"Organic\",\"Semi-Detached\",\"Embedded\"}; int size = 4; calculate(table,3,mode,size); return 0;}Output:The mode is Organic\nEffort = 10.289 Person-Month\nDevelopment Time = 6.06237 Months\nAverage Staff Required = 2 Persons\n"
},
{
"code": null,
"e": 53341,
"s": 53125,
"text": "The above formula is used for the cost estimation of for the basic COCOMO model, and also is used in the subsequent models. The constant values a,b,c and d for the Basic Model for the different categories of system:"
},
{
"code": null,
"e": 53492,
"s": 53341,
"text": "The effort is measured in Person-Months and as evident from the formula is dependent on Kilo-Lines of code.The development time is measured in months."
},
{
"code": null,
"e": 53692,
"s": 53492,
"text": "These formulas are used as such in the Basic Model calculations, as not much consideration of different factors such as reliability, expertise is taken into account, henceforth the estimate is rough."
},
{
"code": null,
"e": 53734,
"s": 53692,
"text": "Below is the C++ program for Basic COCOMO"
},
{
"code": "// C++ program to implement basic COCOMO#include<bits/stdc++.h>using namespace std; // Function for rounding off float to intint fround(float x){ int a; x=x+0.5; a=x; return(a);} // Function to calculate parameters of Basic COCOMOvoid calculate(float table[][4], int n,char mode[][15], int size){ float effort,time,staff; int model; // Check the mode according to size if(size>=2 && size<=50) model=0; //organic else if(size>50 && size<=300) model=1; //semi-detached else if(size>300) model=2; //embedded cout<<\"The mode is \"<<mode[model]; // Calculate Effort effort = table[model][0]*pow(size,table[model][1]); // Calculate Time time = table[model][2]*pow(effort,table[model][3]); //Calculate Persons Required staff = effort/time; // Output the values calculated cout<<\"\\nEffort = \"<<effort<<\" Person-Month\"; cout<<\"\\nDevelopment Time = \"<<time<<\" Months\"; cout<<\"\\nAverage Staff Required = \"<<fround(staff)<<\" Persons\"; } int main(){ float table[3][4]={2.4,1.05,2.5,0.38,3.0,1.12,2.5,0.35,3.6,1.20,2.5,0.32}; char mode[][15]={\"Organic\",\"Semi-Detached\",\"Embedded\"}; int size = 4; calculate(table,3,mode,size); return 0;}",
"e": 55038,
"s": 53734,
"text": null
},
{
"code": null,
"e": 55157,
"s": 55038,
"text": "The mode is Organic\nEffort = 10.289 Person-Month\nDevelopment Time = 6.06237 Months\nAverage Staff Required = 2 Persons\n"
},
{
"code": null,
"e": 57532,
"s": 55157,
"text": "Intermediate Model –The basic Cocomo model assumes that the effort is only a function of the number of lines of code and some constants evaluated according to the different software systems. However, in reality, no system’s effort and schedule can be solely calculated on the basis of Lines of Code. For that, various other factors such as reliability, experience, Capability. These factors are known as Cost Drivers and the Intermediate Model utilizes 15 such drivers for cost estimation.Classification of Cost Drivers and their attributes:(i) Product attributes –Required software reliability extentSize of the application databaseThe complexity of the product(ii) Hardware attributes –Run-time performance constraintsMemory constraintsThe volatility of the virtual machine environmentRequired turnabout time(iii) Personnel attributes –Analyst capabilitySoftware engineering capabilityApplications experienceVirtual machine experienceProgramming language experience(iv) Project attributes –Use of software toolsApplication of software engineering methodsRequired development scheduleCost DriversVery LowLowNominal;HighVery HighProduct AttributesRequired Software Reliability0.750.881.001.151.40Size of Application Database0.941.001.081.16Complexity of The Product0.700.851.001.151.30Hardware AttributesRuntime Performance Constraints1.001.111.30Memory Constraints1.001.061.21Volatility of the virtual machine environment0.871.001.151.30Required turnabout time0.941.001.071.15Personnel attributesAnalyst capability1.461.191.000.860.71Applications experience1.291.131.000.910.82Software engineer capability1.421.171.000.860.70Virtual machine experience1.211.101.000.90Programming language experience1.141.071.000.95Project AttributesApplication of software engineering methods1.241.101.000.910.82Use of software tools1.241.101.000.910.83Required development schedule1.231.081.001.041.10The project manager is to rate these 15 different parameters for a particular project on a scale of one to three. Then, depending on these ratings, appropriate cost driver values are taken from the above table. These 15 values are then multiplied to calculate the EAF (Effort Adjustment Factor). The Intermediate COCOMO formula now takes the form:\nThe values of a and b in case of the intermediate model are as follows:Software ProjectsabOrganic3.21.05Semi Detached3.01.12Embeddedc2.81.20"
},
{
"code": null,
"e": 58002,
"s": 57532,
"text": "The basic Cocomo model assumes that the effort is only a function of the number of lines of code and some constants evaluated according to the different software systems. However, in reality, no system’s effort and schedule can be solely calculated on the basis of Lines of Code. For that, various other factors such as reliability, experience, Capability. These factors are known as Cost Drivers and the Intermediate Model utilizes 15 such drivers for cost estimation."
},
{
"code": null,
"e": 58055,
"s": 58002,
"text": "Classification of Cost Drivers and their attributes:"
},
{
"code": null,
"e": 58080,
"s": 58055,
"text": "(i) Product attributes –"
},
{
"code": null,
"e": 58117,
"s": 58080,
"text": "Required software reliability extent"
},
{
"code": null,
"e": 58150,
"s": 58117,
"text": "Size of the application database"
},
{
"code": null,
"e": 58180,
"s": 58150,
"text": "The complexity of the product"
},
{
"code": null,
"e": 58207,
"s": 58180,
"text": "(ii) Hardware attributes –"
},
{
"code": null,
"e": 58240,
"s": 58207,
"text": "Run-time performance constraints"
},
{
"code": null,
"e": 58259,
"s": 58240,
"text": "Memory constraints"
},
{
"code": null,
"e": 58309,
"s": 58259,
"text": "The volatility of the virtual machine environment"
},
{
"code": null,
"e": 58333,
"s": 58309,
"text": "Required turnabout time"
},
{
"code": null,
"e": 58362,
"s": 58333,
"text": "(iii) Personnel attributes –"
},
{
"code": null,
"e": 58381,
"s": 58362,
"text": "Analyst capability"
},
{
"code": null,
"e": 58413,
"s": 58381,
"text": "Software engineering capability"
},
{
"code": null,
"e": 58437,
"s": 58413,
"text": "Applications experience"
},
{
"code": null,
"e": 58464,
"s": 58437,
"text": "Virtual machine experience"
},
{
"code": null,
"e": 58496,
"s": 58464,
"text": "Programming language experience"
},
{
"code": null,
"e": 58522,
"s": 58496,
"text": "(iv) Project attributes –"
},
{
"code": null,
"e": 58544,
"s": 58522,
"text": "Use of software tools"
},
{
"code": null,
"e": 58588,
"s": 58544,
"text": "Application of software engineering methods"
},
{
"code": null,
"e": 58618,
"s": 58588,
"text": "Required development schedule"
},
{
"code": null,
"e": 58620,
"s": 58618,
"text": ";"
},
{
"code": null,
"e": 58968,
"s": 58620,
"text": "The project manager is to rate these 15 different parameters for a particular project on a scale of one to three. Then, depending on these ratings, appropriate cost driver values are taken from the above table. These 15 values are then multiplied to calculate the EAF (Effort Adjustment Factor). The Intermediate COCOMO formula now takes the form:"
},
{
"code": null,
"e": 59042,
"s": 58970,
"text": "The values of a and b in case of the intermediate model are as follows:"
},
{
"code": null,
"e": 59775,
"s": 59042,
"text": "Detailed Model –Detailed COCOMO incorporates all characteristics of the intermediate version with an assessment of the cost driver’s impact on each step of the software engineering process. The detailed model uses different effort multipliers for each cost driver attribute. In detailed cocomo, the whole software is divided into different modules and then we apply COCOMO in different modules to estimate effort and then sum the effort.The Six phases of detailed COCOMO are:Planning and requirementsSystem designDetailed designModule code and testIntegration and testCost Constructive modelThe effort is calculated as a function of program size and a set of cost drivers are given according to each phase of the software lifecycle."
},
{
"code": null,
"e": 59814,
"s": 59775,
"text": "The Six phases of detailed COCOMO are:"
},
{
"code": null,
"e": 59931,
"s": 59814,
"text": "Planning and requirementsSystem designDetailed designModule code and testIntegration and testCost Constructive model"
},
{
"code": null,
"e": 59957,
"s": 59931,
"text": "Planning and requirements"
},
{
"code": null,
"e": 59971,
"s": 59957,
"text": "System design"
},
{
"code": null,
"e": 59987,
"s": 59971,
"text": "Detailed design"
},
{
"code": null,
"e": 60008,
"s": 59987,
"text": "Module code and test"
},
{
"code": null,
"e": 60029,
"s": 60008,
"text": "Integration and test"
},
{
"code": null,
"e": 60053,
"s": 60029,
"text": "Cost Constructive model"
},
{
"code": null,
"e": 60195,
"s": 60053,
"text": "The effort is calculated as a function of program size and a set of cost drivers are given according to each phase of the software lifecycle."
},
{
"code": null,
"e": 60292,
"s": 60195,
"text": "Also read: Classical Waterfall Model, Iterative Waterfall Model, Prototyping Model, Spiral Model"
},
{
"code": null,
"e": 60309,
"s": 60292,
"text": "chitrasingla2001"
},
{
"code": null,
"e": 60317,
"s": 60309,
"text": "yogirao"
},
{
"code": null,
"e": 60338,
"s": 60317,
"text": "Software Engineering"
},
{
"code": null,
"e": 60436,
"s": 60338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 60462,
"s": 60436,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 60521,
"s": 60462,
"text": "Differences between Black Box Testing vs White Box Testing"
},
{
"code": null,
"e": 60563,
"s": 60521,
"text": "Functional vs Non Functional Requirements"
},
{
"code": null,
"e": 60611,
"s": 60563,
"text": "Differences between Verification and Validation"
},
{
"code": null,
"e": 60637,
"s": 60611,
"text": "Software Testing | Basics"
},
{
"code": null,
"e": 60685,
"s": 60637,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 60720,
"s": 60685,
"text": "Levels in Data Flow Diagrams (DFD)"
},
{
"code": null,
"e": 60762,
"s": 60720,
"text": "Difference between Alpha and Beta Testing"
},
{
"code": null,
"e": 60806,
"s": 60762,
"text": "Software Engineering | Architectural Design"
}
] |
JQuery hasData() method - GeeksforGeeks | 16 Jul, 2020
This hasData() method in JQuery is used to determine whether an element has any jQuery data associated with it. This data may be text, event associated with element. There are two examples discussed below:
Syntax:
jQuery.hasData(element)
Arguments:
element: This parameter is a DOM element which is to be checked for data.
Example: There is no data associated with <div> so the method returns false.<!DOCTYPE HTML> <html> <head> <title> JQuery | hasData() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <div> This is DIV </div> <br> <button onclick="Geeks()"> Click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var $div = jQuery( "div" ), div = $div[ 0 ]; el_up.innerHTML = "JQuery | hasData() method"; function Geeks() { el_down.innerHTML = jQuery.hasData(div); } </script> </body> </html>
Example: There is no data associated with <div> so the method returns false.
<!DOCTYPE HTML> <html> <head> <title> JQuery | hasData() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <div> This is DIV </div> <br> <button onclick="Geeks()"> Click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var $div = jQuery( "div" ), div = $div[ 0 ]; el_up.innerHTML = "JQuery | hasData() method"; function Geeks() { el_down.innerHTML = jQuery.hasData(div); } </script> </body> </html>
Output:
Example: There is a event associated with <div> so the method returns true.<!DOCTYPE HTML> <html> <head> <title> JQuery | hasData() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <div> This is DIV </div> <br> <button onclick="Geeks()"> Click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var $div = jQuery( "div" ), div = $div[ 0 ]; el_up.innerHTML = "JQuery | hasData() method"; $div.on( "click", function() {} ); function Geeks() { el_down.innerHTML = jQuery.hasData(div); } </script> </body> </html>
Example: There is a event associated with <div> so the method returns true.
<!DOCTYPE HTML> <html> <head> <title> JQuery | hasData() method </title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <div> This is DIV </div> <br> <button onclick="Geeks()"> Click here </button> <p id="GFG_DOWN"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var $div = jQuery( "div" ), div = $div[ 0 ]; el_up.innerHTML = "JQuery | hasData() method"; $div.on( "click", function() {} ); function Geeks() { el_down.innerHTML = jQuery.hasData(div); } </script> </body> </html>
Output:
jQuery-Methods
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
How to Show and Hide div elements using radio buttons?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26110,
"s": 26082,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 26316,
"s": 26110,
"text": "This hasData() method in JQuery is used to determine whether an element has any jQuery data associated with it. This data may be text, event associated with element. There are two examples discussed below:"
},
{
"code": null,
"e": 26324,
"s": 26316,
"text": "Syntax:"
},
{
"code": null,
"e": 26349,
"s": 26324,
"text": "jQuery.hasData(element)\n"
},
{
"code": null,
"e": 26360,
"s": 26349,
"text": "Arguments:"
},
{
"code": null,
"e": 26434,
"s": 26360,
"text": "element: This parameter is a DOM element which is to be checked for data."
},
{
"code": null,
"e": 27309,
"s": 26434,
"text": "Example: There is no data associated with <div> so the method returns false.<!DOCTYPE HTML> <html> <head> <title> JQuery | hasData() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <div> This is DIV </div> <br> <button onclick=\"Geeks()\"> Click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var $div = jQuery( \"div\" ), div = $div[ 0 ]; el_up.innerHTML = \"JQuery | hasData() method\"; function Geeks() { el_down.innerHTML = jQuery.hasData(div); } </script> </body> </html> "
},
{
"code": null,
"e": 27386,
"s": 27309,
"text": "Example: There is no data associated with <div> so the method returns false."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | hasData() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <div> This is DIV </div> <br> <button onclick=\"Geeks()\"> Click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var $div = jQuery( \"div\" ), div = $div[ 0 ]; el_up.innerHTML = \"JQuery | hasData() method\"; function Geeks() { el_down.innerHTML = jQuery.hasData(div); } </script> </body> </html> ",
"e": 28185,
"s": 27386,
"text": null
},
{
"code": null,
"e": 28193,
"s": 28185,
"text": "Output:"
},
{
"code": null,
"e": 29105,
"s": 28193,
"text": "Example: There is a event associated with <div> so the method returns true.<!DOCTYPE HTML> <html> <head> <title> JQuery | hasData() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"></script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <div> This is DIV </div> <br> <button onclick=\"Geeks()\"> Click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var $div = jQuery( \"div\" ), div = $div[ 0 ]; el_up.innerHTML = \"JQuery | hasData() method\"; $div.on( \"click\", function() {} ); function Geeks() { el_down.innerHTML = jQuery.hasData(div); } </script> </body> </html> "
},
{
"code": null,
"e": 29181,
"s": 29105,
"text": "Example: There is a event associated with <div> so the method returns true."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | hasData() method </title> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"></script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <div> This is DIV </div> <br> <button onclick=\"Geeks()\"> Click here </button> <p id=\"GFG_DOWN\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var $div = jQuery( \"div\" ), div = $div[ 0 ]; el_up.innerHTML = \"JQuery | hasData() method\"; $div.on( \"click\", function() {} ); function Geeks() { el_down.innerHTML = jQuery.hasData(div); } </script> </body> </html> ",
"e": 30018,
"s": 29181,
"text": null
},
{
"code": null,
"e": 30026,
"s": 30018,
"text": "Output:"
},
{
"code": null,
"e": 30041,
"s": 30026,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 30048,
"s": 30041,
"text": "JQuery"
},
{
"code": null,
"e": 30065,
"s": 30048,
"text": "Web Technologies"
},
{
"code": null,
"e": 30163,
"s": 30065,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30192,
"s": 30163,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30248,
"s": 30192,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 30302,
"s": 30248,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 30336,
"s": 30302,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 30391,
"s": 30336,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 30431,
"s": 30391,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30464,
"s": 30431,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30509,
"s": 30464,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30552,
"s": 30509,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Java Program to Delete a directory - GeeksforGeeks | 02 Nov, 2020
The class named java.io.File represents a file or directory (path names) in the system. This class provides methods to perform various operations on files/directories.
The delete() method of the File class deletes the files and empty directory represented by the current File object. If a directory is not empty or contain files then that cannot be deleted directly. First, empty the directory, then delete the folder.
Suppose there exists a directory with path C:\\GFG. The following image displays the files and directories present inside GFG folder. The subdirectory Ritik contains a file named Logistics.xlsx and subdirectory Rohan contains a file named Payments.xlsx.
GFG Directory
The following java programs illustrate how to delete a directory.
Method 1: using delete() to delete files and empty folders
Provide the path of a directory.
Call user-defined method deleteDirectory() to delete all the files and subfolders.
Java
// Java program to delete a directory import java.io.File; class DeleteDirectory { // function to delete subdirectories and files public static void deleteDirectory(File file) { // store all the paths of files and folders present // inside directory for (File subfile : file.listFiles()) { // if it is a subfolder,e.g Rohan and Ritik, // recursiley call function to empty subfolder if (subfile.isDirectory()) { deleteDirectory(subfile); } // delete files and empty subfolders subfile.delete(); } } public static void main(String[] args) { // store file path String filepath = "C:\\GFG"; File file = new File(filepath); // call deleteDirectory function to delete // subdirectory and files deleteDirectory(file); // delete main GFG folder file.delete(); }}
Output
Following is the image of C drive where no GFG folder is present.
GFG folder deleted successfully
Method 2: using deleteDirectory() method from commons-io
To use deleteDirectory() method you need to add a commons-io dependency to maven project.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
Java
// Java program to delete a directory import java.io.File;import org.apache.commons.io.FileUtils; class DelteDirectory { public static void main(String[] args) { // store file path String filepath = "C:\\GFG"; File file = new File(filepath); // call deleteDirectory method to delete directory // recursively FileUtils.deleteDirectory(file); // delete GFG folder file.delete(); }}
Output
Following is the image of C drive where no GFG folder is present.
GFG folder deleted Successfully
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character | [
{
"code": null,
"e": 25250,
"s": 25222,
"text": "\n02 Nov, 2020"
},
{
"code": null,
"e": 25418,
"s": 25250,
"text": "The class named java.io.File represents a file or directory (path names) in the system. This class provides methods to perform various operations on files/directories."
},
{
"code": null,
"e": 25669,
"s": 25418,
"text": "The delete() method of the File class deletes the files and empty directory represented by the current File object. If a directory is not empty or contain files then that cannot be deleted directly. First, empty the directory, then delete the folder."
},
{
"code": null,
"e": 25924,
"s": 25669,
"text": "Suppose there exists a directory with path C:\\\\GFG. The following image displays the files and directories present inside GFG folder. The subdirectory Ritik contains a file named Logistics.xlsx and subdirectory Rohan contains a file named Payments.xlsx. "
},
{
"code": null,
"e": 25938,
"s": 25924,
"text": "GFG Directory"
},
{
"code": null,
"e": 26004,
"s": 25938,
"text": "The following java programs illustrate how to delete a directory."
},
{
"code": null,
"e": 26063,
"s": 26004,
"text": "Method 1: using delete() to delete files and empty folders"
},
{
"code": null,
"e": 26096,
"s": 26063,
"text": "Provide the path of a directory."
},
{
"code": null,
"e": 26179,
"s": 26096,
"text": "Call user-defined method deleteDirectory() to delete all the files and subfolders."
},
{
"code": null,
"e": 26184,
"s": 26179,
"text": "Java"
},
{
"code": "// Java program to delete a directory import java.io.File; class DeleteDirectory { // function to delete subdirectories and files public static void deleteDirectory(File file) { // store all the paths of files and folders present // inside directory for (File subfile : file.listFiles()) { // if it is a subfolder,e.g Rohan and Ritik, // recursiley call function to empty subfolder if (subfile.isDirectory()) { deleteDirectory(subfile); } // delete files and empty subfolders subfile.delete(); } } public static void main(String[] args) { // store file path String filepath = \"C:\\\\GFG\"; File file = new File(filepath); // call deleteDirectory function to delete // subdirectory and files deleteDirectory(file); // delete main GFG folder file.delete(); }}",
"e": 27139,
"s": 26184,
"text": null
},
{
"code": null,
"e": 27146,
"s": 27139,
"text": "Output"
},
{
"code": null,
"e": 27212,
"s": 27146,
"text": "Following is the image of C drive where no GFG folder is present."
},
{
"code": null,
"e": 27244,
"s": 27212,
"text": "GFG folder deleted successfully"
},
{
"code": null,
"e": 27301,
"s": 27244,
"text": "Method 2: using deleteDirectory() method from commons-io"
},
{
"code": null,
"e": 27391,
"s": 27301,
"text": "To use deleteDirectory() method you need to add a commons-io dependency to maven project."
},
{
"code": null,
"e": 27404,
"s": 27391,
"text": "<dependency>"
},
{
"code": null,
"e": 27437,
"s": 27404,
"text": " <groupId>commons-io</groupId>"
},
{
"code": null,
"e": 27476,
"s": 27437,
"text": " <artifactId>commons-io</artifactId>"
},
{
"code": null,
"e": 27502,
"s": 27476,
"text": " <version>2.5</version>"
},
{
"code": null,
"e": 27516,
"s": 27502,
"text": "</dependency>"
},
{
"code": null,
"e": 27521,
"s": 27516,
"text": "Java"
},
{
"code": "// Java program to delete a directory import java.io.File;import org.apache.commons.io.FileUtils; class DelteDirectory { public static void main(String[] args) { // store file path String filepath = \"C:\\\\GFG\"; File file = new File(filepath); // call deleteDirectory method to delete directory // recursively FileUtils.deleteDirectory(file); // delete GFG folder file.delete(); }}",
"e": 27974,
"s": 27521,
"text": null
},
{
"code": null,
"e": 27981,
"s": 27974,
"text": "Output"
},
{
"code": null,
"e": 28047,
"s": 27981,
"text": "Following is the image of C drive where no GFG folder is present."
},
{
"code": null,
"e": 28079,
"s": 28047,
"text": "GFG folder deleted Successfully"
},
{
"code": null,
"e": 28084,
"s": 28079,
"text": "Java"
},
{
"code": null,
"e": 28098,
"s": 28084,
"text": "Java Programs"
},
{
"code": null,
"e": 28103,
"s": 28098,
"text": "Java"
},
{
"code": null,
"e": 28201,
"s": 28103,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28216,
"s": 28201,
"text": "Stream In Java"
},
{
"code": null,
"e": 28237,
"s": 28216,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28256,
"s": 28237,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28286,
"s": 28256,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28332,
"s": 28286,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28358,
"s": 28332,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28392,
"s": 28358,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28439,
"s": 28392,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 28471,
"s": 28439,
"text": "How to Iterate HashMap in Java?"
}
] |
Java | Functions | Question 3 - GeeksforGeeks | 28 Jun, 2021
class Test {public static void swap(Integer i, Integer j) { Integer temp = new Integer(i); i = j; j = temp; } public static void main(String[] args) { Integer i = new Integer(10); Integer j = new Integer(20); swap(i, j); System.out.println("i = " + i + ", j = " + j); }}
(A) i = 10, j = 20(B) i = 20, j = 10(C) i = 10, j = 10(D) i = 20, j = 20Answer: (A)Explanation: Parameters are passed by value in JavaQuiz of this Question
Functions
Java-Functions
Java Quiz
Functions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java | Constructors | Question 3
Java | Constructors | Question 5
Java | Exception Handling | Question 2
Java | final keyword | Question 1
Java | Class and Object | Question 1
Java | Abstract Class and Interface | Question 2
Java | Exception Handling | Question 4
Java | Exception Handling | Question 3
Java | Exception Handling | Question 7
Java | Exception Handling | Question 8 | [
{
"code": null,
"e": 25714,
"s": 25686,
"text": "\n28 Jun, 2021"
},
{
"code": "class Test {public static void swap(Integer i, Integer j) { Integer temp = new Integer(i); i = j; j = temp; } public static void main(String[] args) { Integer i = new Integer(10); Integer j = new Integer(20); swap(i, j); System.out.println(\"i = \" + i + \", j = \" + j); }}",
"e": 26026,
"s": 25714,
"text": null
},
{
"code": null,
"e": 26182,
"s": 26026,
"text": "(A) i = 10, j = 20(B) i = 20, j = 10(C) i = 10, j = 10(D) i = 20, j = 20Answer: (A)Explanation: Parameters are passed by value in JavaQuiz of this Question"
},
{
"code": null,
"e": 26192,
"s": 26182,
"text": "Functions"
},
{
"code": null,
"e": 26207,
"s": 26192,
"text": "Java-Functions"
},
{
"code": null,
"e": 26217,
"s": 26207,
"text": "Java Quiz"
},
{
"code": null,
"e": 26227,
"s": 26217,
"text": "Functions"
},
{
"code": null,
"e": 26325,
"s": 26227,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26358,
"s": 26325,
"text": "Java | Constructors | Question 3"
},
{
"code": null,
"e": 26391,
"s": 26358,
"text": "Java | Constructors | Question 5"
},
{
"code": null,
"e": 26430,
"s": 26391,
"text": "Java | Exception Handling | Question 2"
},
{
"code": null,
"e": 26464,
"s": 26430,
"text": "Java | final keyword | Question 1"
},
{
"code": null,
"e": 26501,
"s": 26464,
"text": "Java | Class and Object | Question 1"
},
{
"code": null,
"e": 26550,
"s": 26501,
"text": "Java | Abstract Class and Interface | Question 2"
},
{
"code": null,
"e": 26589,
"s": 26550,
"text": "Java | Exception Handling | Question 4"
},
{
"code": null,
"e": 26628,
"s": 26589,
"text": "Java | Exception Handling | Question 3"
},
{
"code": null,
"e": 26667,
"s": 26628,
"text": "Java | Exception Handling | Question 7"
}
] |
Difference between Append, Extend and Insert in Python - GeeksforGeeks | 05 Jul, 2021
Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects.
Lists are mutable, and hence, they can be altered even after their creation. Lists have various methods, the most commonly used list method are append(), insert(), extend(), etc. In this article, we are going to discuss the difference between append(), insert(), and, extend() method in Python lists.
It adds an element at the end of the list. The argument passed in the append function is added as a single element at end of the list and the length of the list is increased by 1.
Syntax:
list_name.append(element)
The element can be a string, integer, tuple, or another list.
Example:
Python3
# python program to demonstrate# working of append function # assign listl = ['geeks'] # use methodl.append('for')l.append('geeks') # display listprint(l)
Output:
['geeks', 'for', 'geeks']
This method can be used to insert a value at any desired position. It takes two arguments-element and the index at which the element has to be inserted.
Syntax:
list_name(index,element)
The element can be a string, object, or integer.
Example:
Python3
# python program to demonstrate# working of insert function # assign listl = ['geeks', 'geeks'] # use methodl.insert(1, 'for') # display listprint(l)
Output:
['geeks', 'for', 'geeks']
This method appends each element of the iterable (tuple, string, or list) to the end of the list and increases the length of the list by the number of elements of the iterable passed as an argument.
Syntax:
list_name.extend(iterable)
Example:
Python3
# python program to demonstrate# working of extend function # assign listl = ['hello', 'welcome', 'to'] # use methodl.extend(['geeks', 'for', 'geeks']) # display listprint(l)
Output:
['hello', 'welcome', 'to', 'geeks', 'for', 'geeks']
Comparing the methods in a single program:
Python3
# Python program to demonstrate# comparison between the three methods # assign listslist_1 = [1, 2, 3]list_2 = [1, 2, 3]list_3 = [1, 2, 3] a = [2, 3] # use methodslist_1.append(a)list_2.insert(3, a)list_3.extend(a) # display listsprint(list_1)print(list_2)print(list_3)
Output:
[1, 2, 3, [2, 3]]
[1, 2, 3, [2, 3]]
[1, 2, 3, 2, 3]
rajeev0719singh
python-list
python-list-functions
Difference Between
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
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": 26128,
"s": 26100,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 26408,
"s": 26128,
"text": "Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. "
},
{
"code": null,
"e": 26709,
"s": 26408,
"text": "Lists are mutable, and hence, they can be altered even after their creation. Lists have various methods, the most commonly used list method are append(), insert(), extend(), etc. In this article, we are going to discuss the difference between append(), insert(), and, extend() method in Python lists."
},
{
"code": null,
"e": 26889,
"s": 26709,
"text": "It adds an element at the end of the list. The argument passed in the append function is added as a single element at end of the list and the length of the list is increased by 1."
},
{
"code": null,
"e": 26897,
"s": 26889,
"text": "Syntax:"
},
{
"code": null,
"e": 26923,
"s": 26897,
"text": "list_name.append(element)"
},
{
"code": null,
"e": 26985,
"s": 26923,
"text": "The element can be a string, integer, tuple, or another list."
},
{
"code": null,
"e": 26994,
"s": 26985,
"text": "Example:"
},
{
"code": null,
"e": 27002,
"s": 26994,
"text": "Python3"
},
{
"code": "# python program to demonstrate# working of append function # assign listl = ['geeks'] # use methodl.append('for')l.append('geeks') # display listprint(l)",
"e": 27157,
"s": 27002,
"text": null
},
{
"code": null,
"e": 27165,
"s": 27157,
"text": "Output:"
},
{
"code": null,
"e": 27191,
"s": 27165,
"text": "['geeks', 'for', 'geeks']"
},
{
"code": null,
"e": 27344,
"s": 27191,
"text": "This method can be used to insert a value at any desired position. It takes two arguments-element and the index at which the element has to be inserted."
},
{
"code": null,
"e": 27352,
"s": 27344,
"text": "Syntax:"
},
{
"code": null,
"e": 27377,
"s": 27352,
"text": "list_name(index,element)"
},
{
"code": null,
"e": 27426,
"s": 27377,
"text": "The element can be a string, object, or integer."
},
{
"code": null,
"e": 27435,
"s": 27426,
"text": "Example:"
},
{
"code": null,
"e": 27443,
"s": 27435,
"text": "Python3"
},
{
"code": "# python program to demonstrate# working of insert function # assign listl = ['geeks', 'geeks'] # use methodl.insert(1, 'for') # display listprint(l)",
"e": 27593,
"s": 27443,
"text": null
},
{
"code": null,
"e": 27601,
"s": 27593,
"text": "Output:"
},
{
"code": null,
"e": 27627,
"s": 27601,
"text": "['geeks', 'for', 'geeks']"
},
{
"code": null,
"e": 27826,
"s": 27627,
"text": "This method appends each element of the iterable (tuple, string, or list) to the end of the list and increases the length of the list by the number of elements of the iterable passed as an argument."
},
{
"code": null,
"e": 27834,
"s": 27826,
"text": "Syntax:"
},
{
"code": null,
"e": 27861,
"s": 27834,
"text": "list_name.extend(iterable)"
},
{
"code": null,
"e": 27870,
"s": 27861,
"text": "Example:"
},
{
"code": null,
"e": 27878,
"s": 27870,
"text": "Python3"
},
{
"code": "# python program to demonstrate# working of extend function # assign listl = ['hello', 'welcome', 'to'] # use methodl.extend(['geeks', 'for', 'geeks']) # display listprint(l)",
"e": 28053,
"s": 27878,
"text": null
},
{
"code": null,
"e": 28061,
"s": 28053,
"text": "Output:"
},
{
"code": null,
"e": 28113,
"s": 28061,
"text": "['hello', 'welcome', 'to', 'geeks', 'for', 'geeks']"
},
{
"code": null,
"e": 28156,
"s": 28113,
"text": "Comparing the methods in a single program:"
},
{
"code": null,
"e": 28164,
"s": 28156,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# comparison between the three methods # assign listslist_1 = [1, 2, 3]list_2 = [1, 2, 3]list_3 = [1, 2, 3] a = [2, 3] # use methodslist_1.append(a)list_2.insert(3, a)list_3.extend(a) # display listsprint(list_1)print(list_2)print(list_3)",
"e": 28434,
"s": 28164,
"text": null
},
{
"code": null,
"e": 28442,
"s": 28434,
"text": "Output:"
},
{
"code": null,
"e": 28494,
"s": 28442,
"text": "[1, 2, 3, [2, 3]]\n[1, 2, 3, [2, 3]]\n[1, 2, 3, 2, 3]"
},
{
"code": null,
"e": 28510,
"s": 28494,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 28522,
"s": 28510,
"text": "python-list"
},
{
"code": null,
"e": 28544,
"s": 28522,
"text": "python-list-functions"
},
{
"code": null,
"e": 28563,
"s": 28544,
"text": "Difference Between"
},
{
"code": null,
"e": 28570,
"s": 28563,
"text": "Python"
},
{
"code": null,
"e": 28582,
"s": 28570,
"text": "python-list"
},
{
"code": null,
"e": 28680,
"s": 28582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28741,
"s": 28680,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28809,
"s": 28741,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 28867,
"s": 28809,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 28922,
"s": 28867,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 28988,
"s": 28922,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 29016,
"s": 28988,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29066,
"s": 29016,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29088,
"s": 29066,
"text": "Python map() function"
}
] |
How to hide axis titles in plotly express figure with facets in Python? - GeeksforGeeks | 28 Nov, 2021
In this article, we will learn how to hide axis titles in a plotly express figure with facets in Python.
We can hide the axis by setting the axis title as blank by iterating through for loop. We are hiding the axis only for X-axis and Y-axis so we have to compare this condition in each iteration
Syntax:
for axis in fig.layout:
if type(fig.layout[axis]) == go.layout.YAxis:
fig.layout[axis].title.text = ''
if type(fig.layout[axis]) == go.layout.XAxis:
fig.layout[axis].title.text = ''
Example 1:
Date vs Value data
Python3
import pandas as pdimport numpy as npimport plotly.express as pximport stringimport plotly.graph_objects as go # create a dataframecols = ['a', 'b', 'c', 'd', 'e']n = 50 df = pd.DataFrame({'Date': pd.date_range('2021-1-1', periods=n)}) # create data with vastly different rangesfor col in cols: start = np.random.choice([1, 10, 100, 1000, 100000]) s = np.random.normal(loc=0, scale=0.01*start, size=n) df[col] = start + s.cumsum() # melt data columns from wide to longdfm = df.melt("Date") # make the plotfig = px.line( data_frame=dfm, x='Date', y='value', facet_col='variable', facet_col_wrap=6, height=500, width=1000, title='Geeksforgeeks', labels={ 'Date': 'Date', 'value': 'Value', 'variable': 'Plot no.' }) # hide subplot y-axis titles and x-axis titlesfor axis in fig.layout: if type(fig.layout[axis]) == go.layout.YAxis: fig.layout[axis].title.text = '' if type(fig.layout[axis]) == go.layout.XAxis: fig.layout[axis].title.text = '' # ensure that each chart has its own y rage and tick labelsfig.update_yaxes(matches=None, showticklabels=True, visible=True) fig.show()
Output:
Example 2:
Temperature vs City data
Python3
import pandas as pdimport numpy as npimport plotly.express as pximport stringimport plotly.graph_objects as go # create a dataframecols = ['city-A', 'city-B', 'city-C', 'city-D']n = 50 df = pd.DataFrame({'Date': pd.date_range('2021-6-1', periods=n)}) # create data with vastly different rangesfor col in cols: start = np.random.choice([1, 10, 100, 1000, 100000]) s = np.random.normal(loc=0, scale=0.01*start, size=n) df[col] = start + s.cumsum() # melt data columns from wide to longdfm = df.melt("Date") # make the plotfig = px.line( data_frame=dfm, x='Date', y='value', facet_col='variable', facet_col_wrap=6, height=500, width=1300, title='Geeksforgeeks', labels={ 'Date': 'Date', 'value': 'Value', 'variable': 'CITY' }) # hide subplot y-axis titles and x-axis titlesfor axis in fig.layout: if type(fig.layout[axis]) == go.layout.YAxis: fig.layout[axis].title.text = '' if type(fig.layout[axis]) == go.layout.XAxis: fig.layout[axis].title.text = '' # ensure that each chart has its own y rage and tick labelsfig.update_yaxes(matches=None, showticklabels=True, visible=True) fig.show()
Output:
Picked
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 25643,
"s": 25537,
"text": "In this article, we will learn how to hide axis titles in a plotly express figure with facets in Python. "
},
{
"code": null,
"e": 25835,
"s": 25643,
"text": "We can hide the axis by setting the axis title as blank by iterating through for loop. We are hiding the axis only for X-axis and Y-axis so we have to compare this condition in each iteration"
},
{
"code": null,
"e": 25844,
"s": 25835,
"text": "Syntax: "
},
{
"code": null,
"e": 26048,
"s": 25844,
"text": "for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.YAxis:\n fig.layout[axis].title.text = '' \n if type(fig.layout[axis]) == go.layout.XAxis:\n fig.layout[axis].title.text = ''"
},
{
"code": null,
"e": 26059,
"s": 26048,
"text": "Example 1:"
},
{
"code": null,
"e": 26078,
"s": 26059,
"text": "Date vs Value data"
},
{
"code": null,
"e": 26086,
"s": 26078,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as npimport plotly.express as pximport stringimport plotly.graph_objects as go # create a dataframecols = ['a', 'b', 'c', 'd', 'e']n = 50 df = pd.DataFrame({'Date': pd.date_range('2021-1-1', periods=n)}) # create data with vastly different rangesfor col in cols: start = np.random.choice([1, 10, 100, 1000, 100000]) s = np.random.normal(loc=0, scale=0.01*start, size=n) df[col] = start + s.cumsum() # melt data columns from wide to longdfm = df.melt(\"Date\") # make the plotfig = px.line( data_frame=dfm, x='Date', y='value', facet_col='variable', facet_col_wrap=6, height=500, width=1000, title='Geeksforgeeks', labels={ 'Date': 'Date', 'value': 'Value', 'variable': 'Plot no.' }) # hide subplot y-axis titles and x-axis titlesfor axis in fig.layout: if type(fig.layout[axis]) == go.layout.YAxis: fig.layout[axis].title.text = '' if type(fig.layout[axis]) == go.layout.XAxis: fig.layout[axis].title.text = '' # ensure that each chart has its own y rage and tick labelsfig.update_yaxes(matches=None, showticklabels=True, visible=True) fig.show()",
"e": 27253,
"s": 26086,
"text": null
},
{
"code": null,
"e": 27261,
"s": 27253,
"text": "Output:"
},
{
"code": null,
"e": 27272,
"s": 27261,
"text": "Example 2:"
},
{
"code": null,
"e": 27297,
"s": 27272,
"text": "Temperature vs City data"
},
{
"code": null,
"e": 27305,
"s": 27297,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as npimport plotly.express as pximport stringimport plotly.graph_objects as go # create a dataframecols = ['city-A', 'city-B', 'city-C', 'city-D']n = 50 df = pd.DataFrame({'Date': pd.date_range('2021-6-1', periods=n)}) # create data with vastly different rangesfor col in cols: start = np.random.choice([1, 10, 100, 1000, 100000]) s = np.random.normal(loc=0, scale=0.01*start, size=n) df[col] = start + s.cumsum() # melt data columns from wide to longdfm = df.melt(\"Date\") # make the plotfig = px.line( data_frame=dfm, x='Date', y='value', facet_col='variable', facet_col_wrap=6, height=500, width=1300, title='Geeksforgeeks', labels={ 'Date': 'Date', 'value': 'Value', 'variable': 'CITY' }) # hide subplot y-axis titles and x-axis titlesfor axis in fig.layout: if type(fig.layout[axis]) == go.layout.YAxis: fig.layout[axis].title.text = '' if type(fig.layout[axis]) == go.layout.XAxis: fig.layout[axis].title.text = '' # ensure that each chart has its own y rage and tick labelsfig.update_yaxes(matches=None, showticklabels=True, visible=True) fig.show()",
"e": 28483,
"s": 27305,
"text": null
},
{
"code": null,
"e": 28491,
"s": 28483,
"text": "Output:"
},
{
"code": null,
"e": 28498,
"s": 28491,
"text": "Picked"
},
{
"code": null,
"e": 28512,
"s": 28498,
"text": "Python-Plotly"
},
{
"code": null,
"e": 28519,
"s": 28512,
"text": "Python"
},
{
"code": null,
"e": 28617,
"s": 28519,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28649,
"s": 28617,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28691,
"s": 28649,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28733,
"s": 28691,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28760,
"s": 28733,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28816,
"s": 28760,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28838,
"s": 28816,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28877,
"s": 28838,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28908,
"s": 28877,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28937,
"s": 28908,
"text": "Create a directory in Python"
}
] |
Bubble Plots in Matplotlib. Learn to plot bubble plots with... | by Rashida Nasrin Sucky | Towards Data Science | Bubble plots are an improved version of the scatter plot. In a scatter plot, there are two dimensions x, and y. In a bubble plot, there are three dimensions x, y, and z. Where the third dimension z denotes weight. That way, bubble plots give more information visually than a two dimensional scatter plot.
For this tutorial, I will use the dataset that contains Canadian immigration information. It has the data from 1980 to 2013 and it includes the number of immigrants from 195 countries. import the necessary packages and the dataset:
import numpy as np import pandas as pd df = pd.read_excel('https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/Data_Files/Canada.xlsx', sheet_name='Canada by Citizenship', skiprows=range(20), skipfooter=2)
The dataset is too big. So, I can not show a screenshot here. Let’s see the name of the columns.
df.columns#Output:Index([ 'Type', 'Coverage', 'OdName', 'AREA', 'AreaName', 'REG', 'RegName', 'DEV', 'DevName', 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013], dtype='object')
We are not going to use a lot of the columns. I just dropped those columns and set the name of the countries (‘OdName’) as the index.
df = df.drop(columns = ['Type', 'Coverage', 'AREA', 'AreaName', 'REG', 'RegName', 'DEV', 'DevName',]).set_index('OdName')df.head()
I chose the data of Ireland and Brazil for this exercise. There is no special reason. I chose them randomly.
Ireland = df.loc['Ireland']Brazil = df.loc['Brazil']
There are a few different ways to normalize the data. We normalize the data to bring the data in a similar range. Ireland and Brazil immigration data have different ranges. I needed to bring them to the range from 0 to 1. I simply divided the Ireland data by the maximum value of the Ireland data series. I did the same to the data Series of Brazil.
i_normal = Ireland / Ireland.max()b_normal = Brazil / Brazil.max()
We will plot the Ireland and Bazil data against the years. It will be useful to have the years on a list.
years = list(range(1980, 2014))
Just to see the difference, let’s plot the scatter plot first.
import matplotlib.pyplot as pltplt.figure(figsize=(14, 8))plt.scatter(years, Ireland, color='blue')plt.scatter(years, Brazil, color='orange')plt.xlabel("Years", size=14)plt.ylabel("Number of immigrants", size=14)plt.show()
Now, plot the bubble plot. We have to input the size that we defined before.
plt.figure(figsize=(12, 8))plt.scatter(years, Brazil, color='darkblue', alpha=0.5, s = b_normal * 2000)plt.scatter(years, Ireland, color='purple', alpha=0.5, s = i_normal * 2000, )plt.xlabel("Years", size=14)plt.ylabel("Number of immigrants", size=14)
We can get an idea about the number of immigrants by the size of the bubbles. The smaller the bubbles, the smaller the number of immigrants.
We can make this plot multicolored as well. To make it a bit meaningful, we need the data series’ sorted. You will see the reason very soon.
c_br = sorted(Brazil)c_fr = sorted(France)
Now we will pass these values to change the colors.
plt.figure(figsize=(12, 8))plt.scatter(years, Brazil, c=c_br, alpha=0.5, s = b_normal * 2000)plt.scatter(years, Ireland, c=c_fr, alpha=0.5, s = i_normal * 2000, )plt.xlabel("Years", size=14)plt.ylabel("Number of immigrants", size=14)
Now we added another dimension, color. Color changes by the number of immigrants. But it is not doing that good when we are plotting two variables. Because in this process we did not explicitly define the color for the individual variables. But it does a good job when we plot one variable in the y-axis. Let’s plot the number of immigrants from Brazil per year to see the trend over the years.
plt.figure(figsize=(12, 8))plt.scatter(years, Brazil, c=c_br, alpha=0.5, s = b_normal * 2000)plt.xlabel("Years", size=14)plt.ylabel("Number of immigrants of Brazil", size=14)
I am sure, you can see the change in colors with the number of immigrants very clearly here.
That was all for the bubble plot in Matplotlib. I hope it was helpful.
Here is another cool visualization tutorial:
towardsdatascience.com
Recommended Reading:
Basic Plots in Matplotlib: Visualization in Python
Understand the Data With Univariate And Multivariate Charts and Plots in Python
How to Present the Relationships Amongst Multiple Variables in Python
Indexing and Slicing of 1D, 2D and 3D Arrays in Numpy
Data Analysis With Pivot Table in Pandas
Exploratory Data Analysis For Data Modeling | [
{
"code": null,
"e": 477,
"s": 172,
"text": "Bubble plots are an improved version of the scatter plot. In a scatter plot, there are two dimensions x, and y. In a bubble plot, there are three dimensions x, y, and z. Where the third dimension z denotes weight. That way, bubble plots give more information visually than a two dimensional scatter plot."
},
{
"code": null,
"e": 709,
"s": 477,
"text": "For this tutorial, I will use the dataset that contains Canadian immigration information. It has the data from 1980 to 2013 and it includes the number of immigrants from 195 countries. import the necessary packages and the dataset:"
},
{
"code": null,
"e": 1025,
"s": 709,
"text": "import numpy as np import pandas as pd df = pd.read_excel('https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/Data_Files/Canada.xlsx', sheet_name='Canada by Citizenship', skiprows=range(20), skipfooter=2)"
},
{
"code": null,
"e": 1122,
"s": 1025,
"text": "The dataset is too big. So, I can not show a screenshot here. Let’s see the name of the columns."
},
{
"code": null,
"e": 1727,
"s": 1122,
"text": "df.columns#Output:Index([ 'Type', 'Coverage', 'OdName', 'AREA', 'AreaName', 'REG', 'RegName', 'DEV', 'DevName', 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013], dtype='object')"
},
{
"code": null,
"e": 1861,
"s": 1727,
"text": "We are not going to use a lot of the columns. I just dropped those columns and set the name of the countries (‘OdName’) as the index."
},
{
"code": null,
"e": 1997,
"s": 1861,
"text": "df = df.drop(columns = ['Type', 'Coverage', 'AREA', 'AreaName', 'REG', 'RegName', 'DEV', 'DevName',]).set_index('OdName')df.head()"
},
{
"code": null,
"e": 2106,
"s": 1997,
"text": "I chose the data of Ireland and Brazil for this exercise. There is no special reason. I chose them randomly."
},
{
"code": null,
"e": 2159,
"s": 2106,
"text": "Ireland = df.loc['Ireland']Brazil = df.loc['Brazil']"
},
{
"code": null,
"e": 2509,
"s": 2159,
"text": "There are a few different ways to normalize the data. We normalize the data to bring the data in a similar range. Ireland and Brazil immigration data have different ranges. I needed to bring them to the range from 0 to 1. I simply divided the Ireland data by the maximum value of the Ireland data series. I did the same to the data Series of Brazil."
},
{
"code": null,
"e": 2576,
"s": 2509,
"text": "i_normal = Ireland / Ireland.max()b_normal = Brazil / Brazil.max()"
},
{
"code": null,
"e": 2682,
"s": 2576,
"text": "We will plot the Ireland and Bazil data against the years. It will be useful to have the years on a list."
},
{
"code": null,
"e": 2714,
"s": 2682,
"text": "years = list(range(1980, 2014))"
},
{
"code": null,
"e": 2777,
"s": 2714,
"text": "Just to see the difference, let’s plot the scatter plot first."
},
{
"code": null,
"e": 3000,
"s": 2777,
"text": "import matplotlib.pyplot as pltplt.figure(figsize=(14, 8))plt.scatter(years, Ireland, color='blue')plt.scatter(years, Brazil, color='orange')plt.xlabel(\"Years\", size=14)plt.ylabel(\"Number of immigrants\", size=14)plt.show()"
},
{
"code": null,
"e": 3077,
"s": 3000,
"text": "Now, plot the bubble plot. We have to input the size that we defined before."
},
{
"code": null,
"e": 3447,
"s": 3077,
"text": "plt.figure(figsize=(12, 8))plt.scatter(years, Brazil, color='darkblue', alpha=0.5, s = b_normal * 2000)plt.scatter(years, Ireland, color='purple', alpha=0.5, s = i_normal * 2000, )plt.xlabel(\"Years\", size=14)plt.ylabel(\"Number of immigrants\", size=14)"
},
{
"code": null,
"e": 3588,
"s": 3447,
"text": "We can get an idea about the number of immigrants by the size of the bubbles. The smaller the bubbles, the smaller the number of immigrants."
},
{
"code": null,
"e": 3729,
"s": 3588,
"text": "We can make this plot multicolored as well. To make it a bit meaningful, we need the data series’ sorted. You will see the reason very soon."
},
{
"code": null,
"e": 3772,
"s": 3729,
"text": "c_br = sorted(Brazil)c_fr = sorted(France)"
},
{
"code": null,
"e": 3824,
"s": 3772,
"text": "Now we will pass these values to change the colors."
},
{
"code": null,
"e": 4174,
"s": 3824,
"text": "plt.figure(figsize=(12, 8))plt.scatter(years, Brazil, c=c_br, alpha=0.5, s = b_normal * 2000)plt.scatter(years, Ireland, c=c_fr, alpha=0.5, s = i_normal * 2000, )plt.xlabel(\"Years\", size=14)plt.ylabel(\"Number of immigrants\", size=14)"
},
{
"code": null,
"e": 4569,
"s": 4174,
"text": "Now we added another dimension, color. Color changes by the number of immigrants. But it is not doing that good when we are plotting two variables. Because in this process we did not explicitly define the color for the individual variables. But it does a good job when we plot one variable in the y-axis. Let’s plot the number of immigrants from Brazil per year to see the trend over the years."
},
{
"code": null,
"e": 4794,
"s": 4569,
"text": "plt.figure(figsize=(12, 8))plt.scatter(years, Brazil, c=c_br, alpha=0.5, s = b_normal * 2000)plt.xlabel(\"Years\", size=14)plt.ylabel(\"Number of immigrants of Brazil\", size=14)"
},
{
"code": null,
"e": 4887,
"s": 4794,
"text": "I am sure, you can see the change in colors with the number of immigrants very clearly here."
},
{
"code": null,
"e": 4958,
"s": 4887,
"text": "That was all for the bubble plot in Matplotlib. I hope it was helpful."
},
{
"code": null,
"e": 5003,
"s": 4958,
"text": "Here is another cool visualization tutorial:"
},
{
"code": null,
"e": 5026,
"s": 5003,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5047,
"s": 5026,
"text": "Recommended Reading:"
},
{
"code": null,
"e": 5098,
"s": 5047,
"text": "Basic Plots in Matplotlib: Visualization in Python"
},
{
"code": null,
"e": 5178,
"s": 5098,
"text": "Understand the Data With Univariate And Multivariate Charts and Plots in Python"
},
{
"code": null,
"e": 5248,
"s": 5178,
"text": "How to Present the Relationships Amongst Multiple Variables in Python"
},
{
"code": null,
"e": 5302,
"s": 5248,
"text": "Indexing and Slicing of 1D, 2D and 3D Arrays in Numpy"
},
{
"code": null,
"e": 5343,
"s": 5302,
"text": "Data Analysis With Pivot Table in Pandas"
}
] |
Build XGBoost / LightGBM models on large datasets — what are the possible solutions? | by Shiu-Tang Li | Towards Data Science | XGBoost and LightGBM have been dominating all recent kaggle competitions for tabular data. Simply go to any competition page (tabular data) and check out the kernels and you’ll see. In these competitions, the data is not ‘huge’ — well, don’t tell me the data you’re handling is huge if it can be trained on your laptop. For these cases, Jupyter notebook is enough for XGBoost and LightGBM model constructions.
When the data become larger, but not super large, while you still want to stick with Jupyter notebooks, say, to build the models —one way is to use some memory reduction tricks (For example, ArjanGroen’s code: https://www.kaggle.com/arjanso/reducing-dataframe-memory-size-by-65); or use cloud services, say rent an EC2 on AWS. For example, the r5.24xlarge instances have 768 GiB Memory costing $6 / hour, which I think it can already handle a lot of data that your boss think they’re really “big”.
But what if the data is even bigger?
We need distributed Machine Learning tools. As far as I know, if we’d like to use scalable XGBoost or LightGBM, we have these options available:
1 XGBoost4j on Scala-Spark2 LightGBM on Spark (PySpark / Scala / R)3 XGBoost with H2O.ai4 XGBoost on Amazon SageMaker
I would like to point out some of the issues of each tool based on my personal experience, and provide some resources if you’d like to use them. I’m also happy to learn from you if you also had the similar issues / how you get them solved! Please comment below.
Before I dive into these tools, there’re a few things good to know beforehand.
XGBoost is a very fast and accurate ML algorithm, but it’s now challenged by LightGBM — which runs even faster (for some datasets, it’s 10X faster based on their benchmark), with comparable model accuracy, and more hyperparameters for users to tune. The key difference in speed is because XGBoost split the tree nodes one level at a time, and LightGBM does that one node at a time.
So XGBoost developers later improved their algorithms to catch up with LightGBM, allowing users to also run XGBoost in split-by-leaf mode (grow_policy = ‘lossguide’). Now XGBoost is much faster with this improvement, but LightGBM is still about 1.3X — 1.5X the speed of XGB based on my tests on a few datasets. (Welcome to share your test outcomes!)
The readers can go with either option with their own preference. One more thing to add here: XGBoost has a feature that LightGBM lacks — “monotonic constraint”. It will sacrifice some model accuracy and increase training time, but may improve model interpretability. (Reference: https://xgboost.readthedocs.io/en/latest/tutorials/monotonic.html and https://github.com/dotnet/machinelearning/issues/1651)
For random forest algorithm, the more trees built, the less variance the model is. But up to some point, you can’t really improve the model further by adding in more trees.
XGBoost and LightGBM do not work this way. the model accuracy keeps improving when number of trees increases, but after certain point the performance begins to drop — a sign of overfitting; and the performance gets worse with more trees built.
In order to find the ‘sweet spot’, you can do cross validations or simply do training-validation set splitting, and then use early stopping time to find where it should stop training; or, you can build a few models with different number of trees (say 50, 100, 200), and then pick the best one among them.
If you don’t care about extreme performance, you can set a higher learning rate, build only 10–50 trees (say). It may under-fit a bit but you still have a pretty accurate model, and this way you can save time finding the optimal number of trees. Another benefit with this approach is the model is simpler (fewer trees built).
If the reader plans to go with this option, https://xgboost.readthedocs.io/en/latest/jvm/xgboost4j_spark_tutorial.html is a good starting point. I’d like point out a few issues here (as of this article is posted):
XGBoost4j doesn’t support Pyspark.XGBoost4j doesn’t support split-by-leaf mode, making it way slower. https://github.com/dmlc/xgboost/issues/3724Because it’s on Spark, all missing values have to be imputed (vector assembler doesn’t allow missing values). And this may reduce model accuracy. http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/gbm-faq/missing_values.htmlEarly stopping may still contain bugs. If you follow their latest releases in https://github.com/dmlc/xgboost/releases, you’ll find they’re still fixing these bugs recently.
XGBoost4j doesn’t support Pyspark.
XGBoost4j doesn’t support split-by-leaf mode, making it way slower. https://github.com/dmlc/xgboost/issues/3724
Because it’s on Spark, all missing values have to be imputed (vector assembler doesn’t allow missing values). And this may reduce model accuracy. http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/gbm-faq/missing_values.html
Early stopping may still contain bugs. If you follow their latest releases in https://github.com/dmlc/xgboost/releases, you’ll find they’re still fixing these bugs recently.
The major issues based on my personal experience:
Lack of documentation and good examples. https://github.com/Azure/mmlspark/blob/master/docs/lightgbm.mdAll missing values have to be imputed (similar to XGBoost4j)I also had issues in “Early stopping” parameter in spark cross validator. (To test if it’s working properly, pick a smaller dataset, pick a very large number of rounds with early stopping = 10, and see how long it takes to train the model. After it’s trained, compare the model accuracy with the one built using Python. If it overfits badly, it’s likely that early stopping is not working at all.)
Lack of documentation and good examples. https://github.com/Azure/mmlspark/blob/master/docs/lightgbm.md
All missing values have to be imputed (similar to XGBoost4j)
I also had issues in “Early stopping” parameter in spark cross validator. (To test if it’s working properly, pick a smaller dataset, pick a very large number of rounds with early stopping = 10, and see how long it takes to train the model. After it’s trained, compare the model accuracy with the one built using Python. If it overfits badly, it’s likely that early stopping is not working at all.)
Some example codes (not including vector assembler):
from mmlspark import LightGBMClassifierfrom pyspark.ml.evaluation import BinaryClassificationEvaluatorfrom pyspark.ml.tuning import CrossValidator, ParamGridBuilderlgb_estimator = LightGBMClassifier(learningRate=0.1, numIterations=1000, earlyStoppingRound=10, labelCol="label")paramGrid = ParamGridBuilder().addGrid(lgb_estimator.numLeaves, [30, 50]).build()eval = BinaryClassificationEvaluator(labelCol="label",metricName="areaUnderROC")crossval = CrossValidator(estimator=lgb_estimator, estimatorParamMaps=paramGrid, evaluator=eval, numFolds=3) cvModel = crossval.fit(train_df[["features", "label"]])
This is my personal favorite solution. The model can be built using H2O.ai, integrated in a Pysparkling Water (H2O.ai + PySpark) pipeline:https://www.slideshare.net/0xdata/productionizing-h2o-models-using-sparkling-water-by-jakub-hava
It’s easy to build a model with optimized number of rounds with cross validations -
# binary classificationfeatures = ['A', 'B', 'C']train['label'] = train['label'].asfactor() # train is an H2O framecv_xgb = H2OXGBoostEstimator( ntrees = 1000, learn_rate = 0.1, max_leaves = 50, stopping_rounds = 10, stopping_metric = "AUC", score_tree_interval = 1, tree_method="hist", grow_policy="lossguide", nfolds=5, seed=0)cv_xgb.train(x = features, y = 'label', training_frame = train)
And the XGBoost model can be saved and used in Python with cv_xgb.save_mojo() . Use h2o.save_model() if you’d like to save the model in h2o format instead.
My only complaint about it is that the saved model (the one saved with save.mojo) can’t be used with SHAP package to generate SHAP feature importance (But XGBoost feature importance, .get_fscore() , works fine). Seems like there’re some issues with the original XGBoost package.https://github.com/slundberg/shap/issues/464https://github.com/dmlc/xgboost/issues/4276
(Updates: seems like they have just implemented SHAP in their latest release- https://github.com/h2oai/h2o-3/blob/373ca6b1bc7d194c6c70e1070f2f6f416f56b3d0/Changes.md)
This is a pretty new solution by AWS. The two main features are automatic hyperparameter tuning with Bayesian optimization, and the model can be deployed as an endpoint. A few examples can be found on their Github: https://github.com/awslabs/amazon-sagemaker-examples/tree/master/introduction_to_applying_machine_learning. Here are some of my concerns with it:
The parameter tuning tools are less user (data scientists)-friendly compared to other solutions:https://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/xgboost_direct_marketing/hpo_xgboost_direct_marketing_sagemaker_APIs.ipynb andhttps://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/analyze_results/HPO_Analyze_TuningJob_Results.ipynbWhether Bayesian optimization is the best option to tune XGB parameters is still unknown. If you check out the papers, gradient boosting trees are not mentioned / tested. https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-how-it-works.htmlThe parameter is tuned with a single validation set, not cross validations.I haven’t figured out how to use the model artifact trained with its built-in XGBoost algorithm in Python XGBoost.
The parameter tuning tools are less user (data scientists)-friendly compared to other solutions:https://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/xgboost_direct_marketing/hpo_xgboost_direct_marketing_sagemaker_APIs.ipynb andhttps://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/analyze_results/HPO_Analyze_TuningJob_Results.ipynb
Whether Bayesian optimization is the best option to tune XGB parameters is still unknown. If you check out the papers, gradient boosting trees are not mentioned / tested. https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-how-it-works.html
The parameter is tuned with a single validation set, not cross validations.
I haven’t figured out how to use the model artifact trained with its built-in XGBoost algorithm in Python XGBoost.
But other than these issues, we can still leverage its endpoint feature. You can train your XGB model anywhere, put it in XGBoost image from Amazon ECR (Elastic Container Registry), and then deploy it as an endpoint.
* * * * *
XGBoost / LightGBM are rather new ML tools, and they both have the potentials to become stronger. The developers already did a fantastic job creating these tools to make people’s life easier. I point out some of my observations and share my experience here, with the hope that they can become even better and more easy-to-use tools. | [
{
"code": null,
"e": 581,
"s": 171,
"text": "XGBoost and LightGBM have been dominating all recent kaggle competitions for tabular data. Simply go to any competition page (tabular data) and check out the kernels and you’ll see. In these competitions, the data is not ‘huge’ — well, don’t tell me the data you’re handling is huge if it can be trained on your laptop. For these cases, Jupyter notebook is enough for XGBoost and LightGBM model constructions."
},
{
"code": null,
"e": 1079,
"s": 581,
"text": "When the data become larger, but not super large, while you still want to stick with Jupyter notebooks, say, to build the models —one way is to use some memory reduction tricks (For example, ArjanGroen’s code: https://www.kaggle.com/arjanso/reducing-dataframe-memory-size-by-65); or use cloud services, say rent an EC2 on AWS. For example, the r5.24xlarge instances have 768 GiB Memory costing $6 / hour, which I think it can already handle a lot of data that your boss think they’re really “big”."
},
{
"code": null,
"e": 1116,
"s": 1079,
"text": "But what if the data is even bigger?"
},
{
"code": null,
"e": 1261,
"s": 1116,
"text": "We need distributed Machine Learning tools. As far as I know, if we’d like to use scalable XGBoost or LightGBM, we have these options available:"
},
{
"code": null,
"e": 1379,
"s": 1261,
"text": "1 XGBoost4j on Scala-Spark2 LightGBM on Spark (PySpark / Scala / R)3 XGBoost with H2O.ai4 XGBoost on Amazon SageMaker"
},
{
"code": null,
"e": 1641,
"s": 1379,
"text": "I would like to point out some of the issues of each tool based on my personal experience, and provide some resources if you’d like to use them. I’m also happy to learn from you if you also had the similar issues / how you get them solved! Please comment below."
},
{
"code": null,
"e": 1720,
"s": 1641,
"text": "Before I dive into these tools, there’re a few things good to know beforehand."
},
{
"code": null,
"e": 2102,
"s": 1720,
"text": "XGBoost is a very fast and accurate ML algorithm, but it’s now challenged by LightGBM — which runs even faster (for some datasets, it’s 10X faster based on their benchmark), with comparable model accuracy, and more hyperparameters for users to tune. The key difference in speed is because XGBoost split the tree nodes one level at a time, and LightGBM does that one node at a time."
},
{
"code": null,
"e": 2452,
"s": 2102,
"text": "So XGBoost developers later improved their algorithms to catch up with LightGBM, allowing users to also run XGBoost in split-by-leaf mode (grow_policy = ‘lossguide’). Now XGBoost is much faster with this improvement, but LightGBM is still about 1.3X — 1.5X the speed of XGB based on my tests on a few datasets. (Welcome to share your test outcomes!)"
},
{
"code": null,
"e": 2856,
"s": 2452,
"text": "The readers can go with either option with their own preference. One more thing to add here: XGBoost has a feature that LightGBM lacks — “monotonic constraint”. It will sacrifice some model accuracy and increase training time, but may improve model interpretability. (Reference: https://xgboost.readthedocs.io/en/latest/tutorials/monotonic.html and https://github.com/dotnet/machinelearning/issues/1651)"
},
{
"code": null,
"e": 3029,
"s": 2856,
"text": "For random forest algorithm, the more trees built, the less variance the model is. But up to some point, you can’t really improve the model further by adding in more trees."
},
{
"code": null,
"e": 3273,
"s": 3029,
"text": "XGBoost and LightGBM do not work this way. the model accuracy keeps improving when number of trees increases, but after certain point the performance begins to drop — a sign of overfitting; and the performance gets worse with more trees built."
},
{
"code": null,
"e": 3578,
"s": 3273,
"text": "In order to find the ‘sweet spot’, you can do cross validations or simply do training-validation set splitting, and then use early stopping time to find where it should stop training; or, you can build a few models with different number of trees (say 50, 100, 200), and then pick the best one among them."
},
{
"code": null,
"e": 3904,
"s": 3578,
"text": "If you don’t care about extreme performance, you can set a higher learning rate, build only 10–50 trees (say). It may under-fit a bit but you still have a pretty accurate model, and this way you can save time finding the optimal number of trees. Another benefit with this approach is the model is simpler (fewer trees built)."
},
{
"code": null,
"e": 4118,
"s": 3904,
"text": "If the reader plans to go with this option, https://xgboost.readthedocs.io/en/latest/jvm/xgboost4j_spark_tutorial.html is a good starting point. I’d like point out a few issues here (as of this article is posted):"
},
{
"code": null,
"e": 4669,
"s": 4118,
"text": "XGBoost4j doesn’t support Pyspark.XGBoost4j doesn’t support split-by-leaf mode, making it way slower. https://github.com/dmlc/xgboost/issues/3724Because it’s on Spark, all missing values have to be imputed (vector assembler doesn’t allow missing values). And this may reduce model accuracy. http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/gbm-faq/missing_values.htmlEarly stopping may still contain bugs. If you follow their latest releases in https://github.com/dmlc/xgboost/releases, you’ll find they’re still fixing these bugs recently."
},
{
"code": null,
"e": 4704,
"s": 4669,
"text": "XGBoost4j doesn’t support Pyspark."
},
{
"code": null,
"e": 4816,
"s": 4704,
"text": "XGBoost4j doesn’t support split-by-leaf mode, making it way slower. https://github.com/dmlc/xgboost/issues/3724"
},
{
"code": null,
"e": 5049,
"s": 4816,
"text": "Because it’s on Spark, all missing values have to be imputed (vector assembler doesn’t allow missing values). And this may reduce model accuracy. http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/gbm-faq/missing_values.html"
},
{
"code": null,
"e": 5223,
"s": 5049,
"text": "Early stopping may still contain bugs. If you follow their latest releases in https://github.com/dmlc/xgboost/releases, you’ll find they’re still fixing these bugs recently."
},
{
"code": null,
"e": 5273,
"s": 5223,
"text": "The major issues based on my personal experience:"
},
{
"code": null,
"e": 5834,
"s": 5273,
"text": "Lack of documentation and good examples. https://github.com/Azure/mmlspark/blob/master/docs/lightgbm.mdAll missing values have to be imputed (similar to XGBoost4j)I also had issues in “Early stopping” parameter in spark cross validator. (To test if it’s working properly, pick a smaller dataset, pick a very large number of rounds with early stopping = 10, and see how long it takes to train the model. After it’s trained, compare the model accuracy with the one built using Python. If it overfits badly, it’s likely that early stopping is not working at all.)"
},
{
"code": null,
"e": 5938,
"s": 5834,
"text": "Lack of documentation and good examples. https://github.com/Azure/mmlspark/blob/master/docs/lightgbm.md"
},
{
"code": null,
"e": 5999,
"s": 5938,
"text": "All missing values have to be imputed (similar to XGBoost4j)"
},
{
"code": null,
"e": 6397,
"s": 5999,
"text": "I also had issues in “Early stopping” parameter in spark cross validator. (To test if it’s working properly, pick a smaller dataset, pick a very large number of rounds with early stopping = 10, and see how long it takes to train the model. After it’s trained, compare the model accuracy with the one built using Python. If it overfits badly, it’s likely that early stopping is not working at all.)"
},
{
"code": null,
"e": 6450,
"s": 6397,
"text": "Some example codes (not including vector assembler):"
},
{
"code": null,
"e": 7238,
"s": 6450,
"text": "from mmlspark import LightGBMClassifierfrom pyspark.ml.evaluation import BinaryClassificationEvaluatorfrom pyspark.ml.tuning import CrossValidator, ParamGridBuilderlgb_estimator = LightGBMClassifier(learningRate=0.1, numIterations=1000, earlyStoppingRound=10, labelCol=\"label\")paramGrid = ParamGridBuilder().addGrid(lgb_estimator.numLeaves, [30, 50]).build()eval = BinaryClassificationEvaluator(labelCol=\"label\",metricName=\"areaUnderROC\")crossval = CrossValidator(estimator=lgb_estimator, estimatorParamMaps=paramGrid, evaluator=eval, numFolds=3) cvModel = crossval.fit(train_df[[\"features\", \"label\"]])"
},
{
"code": null,
"e": 7473,
"s": 7238,
"text": "This is my personal favorite solution. The model can be built using H2O.ai, integrated in a Pysparkling Water (H2O.ai + PySpark) pipeline:https://www.slideshare.net/0xdata/productionizing-h2o-models-using-sparkling-water-by-jakub-hava"
},
{
"code": null,
"e": 7557,
"s": 7473,
"text": "It’s easy to build a model with optimized number of rounds with cross validations -"
},
{
"code": null,
"e": 7981,
"s": 7557,
"text": "# binary classificationfeatures = ['A', 'B', 'C']train['label'] = train['label'].asfactor() # train is an H2O framecv_xgb = H2OXGBoostEstimator( ntrees = 1000, learn_rate = 0.1, max_leaves = 50, stopping_rounds = 10, stopping_metric = \"AUC\", score_tree_interval = 1, tree_method=\"hist\", grow_policy=\"lossguide\", nfolds=5, seed=0)cv_xgb.train(x = features, y = 'label', training_frame = train)"
},
{
"code": null,
"e": 8137,
"s": 7981,
"text": "And the XGBoost model can be saved and used in Python with cv_xgb.save_mojo() . Use h2o.save_model() if you’d like to save the model in h2o format instead."
},
{
"code": null,
"e": 8503,
"s": 8137,
"text": "My only complaint about it is that the saved model (the one saved with save.mojo) can’t be used with SHAP package to generate SHAP feature importance (But XGBoost feature importance, .get_fscore() , works fine). Seems like there’re some issues with the original XGBoost package.https://github.com/slundberg/shap/issues/464https://github.com/dmlc/xgboost/issues/4276"
},
{
"code": null,
"e": 8670,
"s": 8503,
"text": "(Updates: seems like they have just implemented SHAP in their latest release- https://github.com/h2oai/h2o-3/blob/373ca6b1bc7d194c6c70e1070f2f6f416f56b3d0/Changes.md)"
},
{
"code": null,
"e": 9031,
"s": 8670,
"text": "This is a pretty new solution by AWS. The two main features are automatic hyperparameter tuning with Bayesian optimization, and the model can be deployed as an endpoint. A few examples can be found on their Github: https://github.com/awslabs/amazon-sagemaker-examples/tree/master/introduction_to_applying_machine_learning. Here are some of my concerns with it:"
},
{
"code": null,
"e": 9879,
"s": 9031,
"text": "The parameter tuning tools are less user (data scientists)-friendly compared to other solutions:https://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/xgboost_direct_marketing/hpo_xgboost_direct_marketing_sagemaker_APIs.ipynb andhttps://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/analyze_results/HPO_Analyze_TuningJob_Results.ipynbWhether Bayesian optimization is the best option to tune XGB parameters is still unknown. If you check out the papers, gradient boosting trees are not mentioned / tested. https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-how-it-works.htmlThe parameter is tuned with a single validation set, not cross validations.I haven’t figured out how to use the model artifact trained with its built-in XGBoost algorithm in Python XGBoost."
},
{
"code": null,
"e": 10279,
"s": 9879,
"text": "The parameter tuning tools are less user (data scientists)-friendly compared to other solutions:https://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/xgboost_direct_marketing/hpo_xgboost_direct_marketing_sagemaker_APIs.ipynb andhttps://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/analyze_results/HPO_Analyze_TuningJob_Results.ipynb"
},
{
"code": null,
"e": 10539,
"s": 10279,
"text": "Whether Bayesian optimization is the best option to tune XGB parameters is still unknown. If you check out the papers, gradient boosting trees are not mentioned / tested. https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-how-it-works.html"
},
{
"code": null,
"e": 10615,
"s": 10539,
"text": "The parameter is tuned with a single validation set, not cross validations."
},
{
"code": null,
"e": 10730,
"s": 10615,
"text": "I haven’t figured out how to use the model artifact trained with its built-in XGBoost algorithm in Python XGBoost."
},
{
"code": null,
"e": 10947,
"s": 10730,
"text": "But other than these issues, we can still leverage its endpoint feature. You can train your XGB model anywhere, put it in XGBoost image from Amazon ECR (Elastic Container Registry), and then deploy it as an endpoint."
},
{
"code": null,
"e": 10957,
"s": 10947,
"text": "* * * * *"
}
] |
SQL | EXISTS - GeeksforGeeks | 27 Apr, 2017
The EXISTS condition in SQL is used to check whether the result of a correlated nested query is empty (contains no tuples) or not. The result of EXISTS is a boolean value True or False. It can be used in a SELECT, UPDATE, INSERT or DELETE statement.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name(s)
FROM table_name
WHERE condition);
Examples:Consider the following two relation “Customers” and “Orders”.
Queries
Using EXISTS condition with SELECT statementTo fetch the first and last name of the customers who placed atleast one order.SELECT fname, lname
FROM Customers
WHERE EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);Output:Using NOT with EXISTSFetch last and first name of the customers who has not placed any order.SELECT lname, fname
FROM Customer
WHERE NOT EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);Output:Using EXISTS condition with DELETE statementDelete the record of all the customer from Order Table whose last name is ‘Mehra’.DELETE
FROM Orders
WHERE EXISTS (SELECT *
FROM customers
WHERE Customers.customer_id = Orders.cid
AND Customers.lname = 'Mehra');SELECT * FROM Orders;Output:Using EXISTS condition with UPDATE statementUpdate the lname as ‘Kumari’ of customer in Customer Table whose customer_id is 401.UPDATE Customers
SET lname = 'Kumari'
WHERE EXISTS (SELECT *
FROM Customers
WHERE customer_id = 401);SELECT * FROM Customers;Output:
Using EXISTS condition with SELECT statementTo fetch the first and last name of the customers who placed atleast one order.SELECT fname, lname
FROM Customers
WHERE EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);Output:
SELECT fname, lname
FROM Customers
WHERE EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);
Output:
Using NOT with EXISTSFetch last and first name of the customers who has not placed any order.SELECT lname, fname
FROM Customer
WHERE NOT EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);Output:
SELECT lname, fname
FROM Customer
WHERE NOT EXISTS (SELECT *
FROM Orders
WHERE Customers.customer_id = Orders.c_id);
Output:
Using EXISTS condition with DELETE statementDelete the record of all the customer from Order Table whose last name is ‘Mehra’.DELETE
FROM Orders
WHERE EXISTS (SELECT *
FROM customers
WHERE Customers.customer_id = Orders.cid
AND Customers.lname = 'Mehra');SELECT * FROM Orders;Output:
DELETE
FROM Orders
WHERE EXISTS (SELECT *
FROM customers
WHERE Customers.customer_id = Orders.cid
AND Customers.lname = 'Mehra');
SELECT * FROM Orders;
Using EXISTS condition with UPDATE statementUpdate the lname as ‘Kumari’ of customer in Customer Table whose customer_id is 401.UPDATE Customers
SET lname = 'Kumari'
WHERE EXISTS (SELECT *
FROM Customers
WHERE customer_id = 401);SELECT * FROM Customers;Output:
UPDATE Customers
SET lname = 'Kumari'
WHERE EXISTS (SELECT *
FROM Customers
WHERE customer_id = 401);
SELECT * FROM Customers;
Output:
This article is contributed by Anuj Chauhan. 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.
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Trigger | Student Database
Introduction of B-Tree
CTE in SQL
Difference between Clustered and Non-clustered index
SQL Interview Questions
Introduction of ER Model
Data Preprocessing in Data Mining
Introduction of DBMS (Database Management System) | Set 1
SQL | Views
Difference between DELETE, DROP and TRUNCATE | [
{
"code": null,
"e": 25676,
"s": 25648,
"text": "\n27 Apr, 2017"
},
{
"code": null,
"e": 25926,
"s": 25676,
"text": "The EXISTS condition in SQL is used to check whether the result of a correlated nested query is empty (contains no tuples) or not. The result of EXISTS is a boolean value True or False. It can be used in a SELECT, UPDATE, INSERT or DELETE statement."
},
{
"code": null,
"e": 25934,
"s": 25926,
"text": "Syntax:"
},
{
"code": null,
"e": 26054,
"s": 25934,
"text": "SELECT column_name(s) \nFROM table_name\nWHERE EXISTS \n (SELECT column_name(s) \n FROM table_name\n WHERE condition);\n"
},
{
"code": null,
"e": 26125,
"s": 26054,
"text": "Examples:Consider the following two relation “Customers” and “Orders”."
},
{
"code": null,
"e": 26133,
"s": 26125,
"text": "Queries"
},
{
"code": null,
"e": 27277,
"s": 26133,
"text": "Using EXISTS condition with SELECT statementTo fetch the first and last name of the customers who placed atleast one order.SELECT fname, lname \nFROM Customers \nWHERE EXISTS (SELECT * \n FROM Orders \n WHERE Customers.customer_id = Orders.c_id);Output:Using NOT with EXISTSFetch last and first name of the customers who has not placed any order.SELECT lname, fname\nFROM Customer\nWHERE NOT EXISTS (SELECT * \n FROM Orders \n WHERE Customers.customer_id = Orders.c_id);Output:Using EXISTS condition with DELETE statementDelete the record of all the customer from Order Table whose last name is ‘Mehra’.DELETE \nFROM Orders\nWHERE EXISTS (SELECT *\n FROM customers\n WHERE Customers.customer_id = Orders.cid\n AND Customers.lname = 'Mehra');SELECT * FROM Orders;Output:Using EXISTS condition with UPDATE statementUpdate the lname as ‘Kumari’ of customer in Customer Table whose customer_id is 401.UPDATE Customers\nSET lname = 'Kumari'\nWHERE EXISTS (SELECT *\n FROM Customers\n WHERE customer_id = 401);SELECT * FROM Customers;Output:"
},
{
"code": null,
"e": 27553,
"s": 27277,
"text": "Using EXISTS condition with SELECT statementTo fetch the first and last name of the customers who placed atleast one order.SELECT fname, lname \nFROM Customers \nWHERE EXISTS (SELECT * \n FROM Orders \n WHERE Customers.customer_id = Orders.c_id);Output:"
},
{
"code": null,
"e": 27699,
"s": 27553,
"text": "SELECT fname, lname \nFROM Customers \nWHERE EXISTS (SELECT * \n FROM Orders \n WHERE Customers.customer_id = Orders.c_id);"
},
{
"code": null,
"e": 27707,
"s": 27699,
"text": "Output:"
},
{
"code": null,
"e": 27962,
"s": 27707,
"text": "Using NOT with EXISTSFetch last and first name of the customers who has not placed any order.SELECT lname, fname\nFROM Customer\nWHERE NOT EXISTS (SELECT * \n FROM Orders \n WHERE Customers.customer_id = Orders.c_id);Output:"
},
{
"code": null,
"e": 28117,
"s": 27962,
"text": "SELECT lname, fname\nFROM Customer\nWHERE NOT EXISTS (SELECT * \n FROM Orders \n WHERE Customers.customer_id = Orders.c_id);"
},
{
"code": null,
"e": 28125,
"s": 28117,
"text": "Output:"
},
{
"code": null,
"e": 28452,
"s": 28125,
"text": "Using EXISTS condition with DELETE statementDelete the record of all the customer from Order Table whose last name is ‘Mehra’.DELETE \nFROM Orders\nWHERE EXISTS (SELECT *\n FROM customers\n WHERE Customers.customer_id = Orders.cid\n AND Customers.lname = 'Mehra');SELECT * FROM Orders;Output:"
},
{
"code": null,
"e": 28625,
"s": 28452,
"text": "DELETE \nFROM Orders\nWHERE EXISTS (SELECT *\n FROM customers\n WHERE Customers.customer_id = Orders.cid\n AND Customers.lname = 'Mehra');"
},
{
"code": null,
"e": 28647,
"s": 28625,
"text": "SELECT * FROM Orders;"
},
{
"code": null,
"e": 28936,
"s": 28647,
"text": "Using EXISTS condition with UPDATE statementUpdate the lname as ‘Kumari’ of customer in Customer Table whose customer_id is 401.UPDATE Customers\nSET lname = 'Kumari'\nWHERE EXISTS (SELECT *\n FROM Customers\n WHERE customer_id = 401);SELECT * FROM Customers;Output:"
},
{
"code": null,
"e": 29066,
"s": 28936,
"text": "UPDATE Customers\nSET lname = 'Kumari'\nWHERE EXISTS (SELECT *\n FROM Customers\n WHERE customer_id = 401);"
},
{
"code": null,
"e": 29091,
"s": 29066,
"text": "SELECT * FROM Customers;"
},
{
"code": null,
"e": 29099,
"s": 29091,
"text": "Output:"
},
{
"code": null,
"e": 29399,
"s": 29099,
"text": "This article is contributed by Anuj Chauhan. 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": 29524,
"s": 29399,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29529,
"s": 29524,
"text": "DBMS"
},
{
"code": null,
"e": 29534,
"s": 29529,
"text": "DBMS"
},
{
"code": null,
"e": 29632,
"s": 29534,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29663,
"s": 29632,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 29686,
"s": 29663,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 29697,
"s": 29686,
"text": "CTE in SQL"
},
{
"code": null,
"e": 29750,
"s": 29697,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 29774,
"s": 29750,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 29799,
"s": 29774,
"text": "Introduction of ER Model"
},
{
"code": null,
"e": 29833,
"s": 29799,
"text": "Data Preprocessing in Data Mining"
},
{
"code": null,
"e": 29891,
"s": 29833,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 29903,
"s": 29891,
"text": "SQL | Views"
}
] |
Predicting Titanic Survivors (A Kaggle Competition) | by Auggie Heschmeyer | Towards Data Science | The purpose of this case study is to document the process I went through to create my predictions for submission in my first Kaggle competition, Titanic: Machine Learning from Disaster. For the uninitiated, Kaggle is a popular data science website that houses thousands of public datasets, offers courses and generally serves as a community hub for the analytically-minded. They also host machine learning competitions with various objectives. The objective of this particular competition was to build a classification model that could successfully determine whether a Titanic passenger lived or died.
Let’s get started!
The first step in the process is always to load in the data as well as the necessary packages. In R, the programming language I am using, packages are collections of algorithms that allow users to perform specified tasks. There are packages for creating beautiful plots, building stock portfolios and pretty much anything else you can imagine. Here, I loaded a number of packages that allow me to utilize a handful of powerful machine learning (ML) models.
lapply(c(“caret”, “h2o”, “pROC”, “randomForest”, “readr”, “tidyverse”, “xgboost”), library, character.only = TRUE) h2o.init() h2o.no_progress() set.seed(123) train <- read_csv(“~/Downloads/train.csv”) test <- read_csv(“~/Downloads/test.csv”)
The competition dataset came in two files: train and test. As you may be able to guess, the former is used to train the ML models and the test is used to make the predictions that are ultimately submitted.
After getting my data into R, it’s time to explore the shape of the data.
train %>% glimpse()## Observations: 891 ## Variables: 12 ## $ PassengerId <dbl> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1... ## $ Survived <dbl> 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1... ## $ Pclass <dbl> 3, 1, 3, 1, 3, 3, 1, 3, 3, 2, 3, 1, 3, 3, 3, 2, 3, 2... ## $ Name <chr> “Braund, Mr. Owen Harris”, “Cumings, Mrs. John Bradl... ## $ Sex <chr> “male”, “female”, “female”, “female”, “male”, “male”... ## $ Age <dbl> 22, 38, 26, 35, 35, NA, 54, 2, 27, 14, 4, 58, 20, 39... ## $ SibSp <dbl> 1, 1, 0, 1, 0, 0, 0, 3, 0, 1, 1, 0, 0, 1, 0, 0, 4, 0... ## $ Parch <dbl> 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 0, 0, 5, 0, 0, 1, 0... ## $ Ticket <chr> “A/5 21171”, “PC 17599”, “STON/O2. 3101282”, “113803... ## $ Fare <dbl> 7.2500, 71.2833, 7.9250, 53.1000, 8.0500, 8.4583, 51... ## $ Cabin <chr> NA, “C85”, NA, “C123”, NA, NA, “E46”, NA, NA, NA, “G... ## $ Embarked <chr> “S”, “C”, “S”, “S”, “S”, “Q”, “S”, “S”, “S”, “C”, “S...test %>% glimpse()## Observations: 418 ## Variables: 11 ## $ PassengerId <dbl> 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 90... ## $ Pclass <dbl> 3, 3, 2, 3, 3, 3, 3, 2, 3, 3, 3, 1, 1, 2, 1, 2, 2, 3... ## $ Name <chr> “Kelly, Mr. James”, “Wilkes, Mrs. James (Ellen Needs... ## $ Sex <chr> “male”, “female”, “male”, “male”, “female”, “male”, ... ## $ Age <dbl> 34.5, 47.0, 62.0, 27.0, 22.0, 14.0, 30.0, 26.0, 18.0... ## $ SibSp <dbl> 0, 1, 0, 0, 1, 0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 1, 0, 0... ## $ Parch <dbl> 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0... ## $ Ticket <chr> “330911”, “363272”, “240276”, “315154”, “3101298”, “... ## $ Fare <dbl> 7.8292, 7.0000, 9.6875, 8.6625, 12.2875, 9.2250, 7.6... ## $ Cabin <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, “B45... ## $ Embarked <chr> “Q”, “S”, “Q”, “S”, “S”, “S”, “Q”, “S”, “C”, “S”, “S...
What the above code says is that the training data has 891 rows with 12 different variables. These variables include things like the name of the passenger, their sex and age, how much they paid for their ticket and where they boarded, among other things. The most important variable here is the one named “Survived,” a list of 1’s and 0’s that indicate whether a passenger lived or died, respectively. The testing data features 418 rows and lacks the “Survived” variable as that is what the competition asks us to predict.
While there is plenty of information contained within the data as it exists now, not all of it is usable in its current form. To extract as much useable information as possible, I will have to transform some of these variables.
The first variable I will look at is “Name.” As far as I know, the iceberg that sunk the Titanic didn’t have a personal vendetta against any of the passengers, so simply using the full names of the passengers won’t provide any useful information. What may, however, is the passengers’ titles. What titles like “Mr.,” “Mrs.” or “Countess” might help us determine is if passengers’ social status (i.e. Were they commoners or nobility?) had any impact on their survival.
To get these titles, I have to extract them from “Name,” which is the below code does.
titles <- c(unique(str_extract(str_extract(train$Name, “\\,\\s[A-Za-z]+”), “[A-Za-z]+”))) titles <- replace(titles, titles == “the”, “Countess”) titles## [1] “Mr” “Mrs” “Miss” “Master” “Don” “Rev” ## [7] “Dr” “Mme” “Ms” “Major” “Lady” “Sir” ## [13] “Mlle” “Col” “Capt” “Countess” “Jonkheer”
If you were wondering, “Jonkheer” was an honorific used by Dutch nobility. There was one Jonkheer on board the Titanic, Johan George Reuchlin, and, spoiler alert, he died. ̄\_(ツ)_/ ̄
In addition to using this list of titles to create a new variable, I also am going to extract the Deck from “Cabin” and create a variable named “Family_Size” that is simply a combination of “SibSp,’ a count of siblings and spouses on board, and ”Parch,” a count of parents and children on board. I also will clean up a few of the other variables to make them easier for the ML models to understand.
train <- train %>% mutate(Survived = factor(Survived), Sex = factor(recode(Sex, male = 1, female = 0)), Pclass = factor(Pclass), Embarked = factor(Embarked), Deck = factor(replace_na(substr(train$Cabin, 1, 1), “Unknown”)), Title = factor(str_extract(train$Name, paste(titles, collapse = “|”))), Family_Size = SibSp + Parch) %>% select(-c(Cabin, Name, Ticket)) test <- test %>% mutate(Sex = factor(recode(Sex, male = 1, female = 0)), Pclass = factor(Pclass), Embarked = factor(Embarked), Deck = factor(replace_na(substr(test$Cabin, 1, 1), “Unknown”)), Title = factor(str_extract(test$Name, paste(titles, collapse = “|”))), Family_Size = SibSp + Parch, Fare = ifelse(is.na(Fare), mean(Fare, na.rm = TRUE), Fare)) %>% select(-c(Cabin, Name, Ticket))
One thing that I didn’t point out earlier when examining the data was just how many passengers’ ages were not recorded. Of the 1309 passengers whose data we have, 266 had no age. That missing information will be problematic later, so I feel it’s necessary to replace those empty values with a guess.
To keep things brief, what the below code does is combine the training and testing data, pull out the records that have ages and fit a Random Forest (RF) model that determines the relationship between a passenger’s age and the other variables. Finally, it will fill all of the missing ages with the best guess as to what their age might be.
Side note: to go into a description of what an RF model is would completely derail this case study. If you’re interested in learning more about RF models and how they work, check out this website.
# Combining the training and test data and selecting only the rows with ages age <- train %>% select(-Survived) %>% rbind(test) %>% filter(!is.na(Age)) %>% filter(!is.na(Embarked)) # Building a prediction model age_rf_model <- randomForest(Age ~ . — PassengerId, age, ntree = 5000, mtry = 9, na.action = na.exclude) # Determining the accuracy of the model age %>% select(Age) %>% add_column(Pred = predict(age_rf_model, age)) %>% na.omit() %>% mutate(Error = Age — Pred, Error_Pct = Error/Age) %>% summarize(RMSE = sqrt(mean(Error2)), MAPE = mean(abs(Error_Pct)))## # A tibble: 1 x 2 ## RMSE MAPE ## <dbl> <dbl> ## 1 7.30 0.302# Using the model to predict passenger age train <- train %>% mutate(Age = ifelse(is.na(Age), round(predict(age_rf_model, train)), Age)) test <- rbind(train[1, c(1, 3:12)], test) test <- test[-1, ] test <- test %>% mutate(Age = ifelse(is.na(Age), round(predict(age_rf_model, test)), Age))
To check how accurate the RF model’s predictions are, I calculated the Root Mean Squared Error (RMSE) and Mean Absolute Percent Error (MAPE) of the predictions to gauge the quality of those predictions. See my earlier article for a brief description of these two metrics.
Long story short: both measures of error are low. The MAPE tells me that the average prediction has an error of only .3%, so while not perfect, I feel it’s acceptable for my ultimate goal of predicting survival.
Now that the data is clean, it is time for me to start training the ML models with the data. Since I want to make sure that my models perform well on unseen data, I am going to divide my training data up into a smaller set of training and test data. This way, I can assess the accuracy of the models before taking them to the actual, Kaggle-provided testing data (which, remember, I can’t assess the accuracy of because the data lacks the “Survived” variable).
train_1 <- stratified(train, c(“Survived”, “Deck”, “Title”), size = 0.7, replace = FALSE) train_2 <- setdiff(train, train_1)
I’m going to use four different models, each with their own way of making predictions: a linear model, a Random Forest model, an XGBoost (eXtreme Gradient Boosting) model and H2O’s AutoML. Again, feel free to click the hyperlinks for a description of what these models are and what they’re doing.
To make what’s going on below easier to understand, imagine that instead of predicting Titanic survivors, we wanted to win a Mixed Martial Arts tournament. We only have enough time to master one martial art before the tournament begins, so we need to figure out which we should study to have the best chance of winning. We know who the competitors will be (i.e. our testing data), but we’re not sure which martial art will serve us best. What is going on below is we are running simulations where we learn four different martial arts (let’s say boxing, jujutsu, muay tai and tae kwon do) and seeing how we might do against competitors similar to those that we’ll see in the tournament (i.e. our training data).
# Linear Model — — glm_model <- glm(Survived ~ . — PassengerId, family = “binomial”, train_1) # Random Forest — — rf_model <- randomForest(Survived ~ . — PassengerId, train_1, ntree = 10000, mtry = 3, na.action = na.exclude) # XGBoost — — dummy_1 <- dummyVars(Survived ~ ., train_1[,2:12]) train_1_dummy <- predict(dummy_1, train_1) dummy_2 <- dummyVars(Survived ~ ., train_2[,2:12]) train_2_dummy <- predict(dummy_2, train_2) dtrain <- xgb.DMatrix(data = train_1_dummy, label = as.vector(train_1$Survived)) dtest <- xgb.DMatrix(data = train_2_dummy, label = as.vector(train_2$Survived)) watchlist <- list(train = dtrain, test = dtest) xgb_model <- xgb.train( data = dtrain, watchlist = watchlist, booster = “gbtree”, max.depth = 3, nthread = 2, nrounds = 5000, objective = “binary:logistic”, early_stopping_rounds = 500, print_every_n = 500 ) # H2O — — train_1_h2o <- train_1 %>% select(-PassengerId) %>% mutate(Pclass = factor(Pclass, ordered = FALSE)) %>% as.h2o train_2_h2o <- train_2 %>% select(-PassengerId) %>% mutate(Pclass = factor(Pclass, ordered = FALSE)) %>% as.h2o y <- “Survived” x <- setdiff(colnames(train_1_h2o), y) split <- h2o.splitFrame(train_1_h2o, ratios = c(.70, .15)) t1 <- split[[1]] t2 <- split[[2]] t3 <- split[[3]] h2o_model <- h2o.automl( x = x, y = y, train = t1, validation_frame = t2, leaderboard_frame = t3, nfolds = 5, stopping_metric = “AUC”, max_runtime_secs = 120 ) h2o_leader <- h2o_model@leader
To continue the above metaphor, no one martial art is going to be best against every competitor, so we’re going to try and find the one which performs best. For martial arts, the metric in which you’d measure that would probably be the number of wins. For Titanic predictions, I’m going to measure that with accuracy (mostly because that’s what Kaggle uses to score this competition).
To determine that accuracy, I will generate what is called a confidence matrix. Simply put, this is a 2x2 box that shows actual values (called “Reference” in the output) along the x-axis and the predicted values along the y-axis. This allows you to see four variables:
· True Positives: Prediction = 1, Actual = 1
· True Negatives: Prediction = 0, Actual = 0
· False Positives: Prediction = 1, Actual = 0
· False Negatives: Prediction = 0, Actual = 1
Accuracy is a measure of how many True Positives and True Negatives there are out of all the predictions.
compare_set <- train_2 %>% add_column(GLM_Pred = predict(glm_model, train_2, type = “response”)) %>% add_column(RF_Pred = predict(rf_model, train_2)) %>% add_column(XGB_Pred = predict(xgb_model, train_2_dummy)) %>% add_column(H2O_Pred = h2o.predict(h2o_leader, newdata = train_2_h2o) %>% as_tibble() %>% pull(predict)) %>% mutate_at(vars(GLM_Pred, XGB_Pred), list(~factor(as.numeric(. > 0.5)))) for (i in 13:16) { conmat <- confusionMatrix(compare_set$Survived, compare_set[[i]], positive = “1”) print(colnames(compare_set[, i])) print(conmat$table) print(conmat$overall[1]) }## [1] “GLM_Pred” ## Reference ## Prediction 0 1 ## 0 141 21 ## 1 23 75 ## Accuracy ## 0.8307692 ## [1] “RF_Pred” ## Reference ## Prediction 0 1 ## 0 149 13 ## 1 26 72 ## Accuracy ## 0.85 ## [1] “XGB_Pred” ## Reference ## Prediction 0 1 ## 0 147 15 ## 1 20 79 ## Accuracy ## 0.8659004 ## [1] “H2O_Pred” ## Reference ## Prediction 0 1 ## 0 151 11 ## 1 38 61 ## Accuracy ## 0.8122605
As you can see, in terms of pure accuracy, the XGBoost model performs the best by correctly predicting 86.6% of all the survivors in the training data. However, accuracy isn’t always the best measure. If you look at the confidence matrix for XGBoost, you will see that there were 15 False Negatives. The RF model, while not performing quite as well in terms of accuracy, had only 13 False Negatives. Why this may be important depends on the situation.
Imagine you are a doctor tasked with determining whether a patient has a particular disease. Assume that the treatment is harmless if given to someone who doesn’t have the disease, but without the treatment, people with the disease are guaranteed to die. Given the numbers above, the RF model would have saved two more lives than the XGBoost model. The takeaway here is that one should never simply look at the accuracy and make the final judgment based on that.
And so I won’t here!
Instead, I will make predictions using both the RF and XGBoost models. And since a third submission to the competition costs me nothing, I’ll also make a prediction with the linear model because its accuracy isn’t far behind the other two.
Now that I have my trained models (or fighters if you’d prefer that metaphor), it’s time to put them to work. I’m going to use them on the testing data, data that the models have never seen before.
# XGBoost dummy_test <- dummyVars(PassengerId ~ ., test) test_dummy <- predict(dummy_test, test) submission_xgboost <- test %>% add_column(Survived = predict(xgb_model, test_dummy)) %>% mutate(Survived = as.numeric(Survived > 0.5)) %>% select(PassengerId, Survived) # Random Forest submission_rf <- test %>% add_column(Survived = predict(rf_model, test)) %>% select(PassengerId, Survived) # Linear Model submission_glm <- test %>% add_column(Survived = predict(glm_model, test)) %>% mutate(Survived = as.numeric(Survived > 0.5)) %>% select(PassengerId, Survived)
Let’s take a look at how each model predicted the survival of the first 10 passengers in the testing data.
submission_xgboost %>% left_join(submission_rf, by = “PassengerId”) %>% left_join(submission_glm, by = “PassengerId”) %>% rename(XGBoost = Survived.x, RF = Survived.y, Linear = Survived) %>% head(10)## # A tibble: 10 x 4 ## PassengerId XGBoost RF Linear ## <dbl> <dbl> <fct> <dbl> ## 1 892 0 0 0 ## 2 893 0 0 0 ## 3 894 0 0 0 ## 4 895 0 0 0 ## 5 896 0 0 1 ## 6 897 0 0 0 ## 7 898 0 0 1 ## 8 899 0 0 0 ## 9 900 1 1 1 ## 10 901 0 0 0
As you can see, all three models predicted that Passenger 900 survived. The linear model also predicted that Passengers 896 and 898 survived.
Now that I have my predictions, it’s time to submit them to Kaggle and see how they did. First, I have to export these predictions to a CSV file so that I can upload them.
write_csv(submission_xgboost, “~/Downloads/Submission XGBoost.csv”) write_csv(submission_rf, “~/Downloads/Submission RF.csv”) write_csv(submission_glm, “~/Downloads/Submission GLM.csv”)
After uploading the CSV, Kaggle generates my final score for each submission. So, let’s see how I did.
Wow! Look at that dark horse victory! Totally unexpected! Despite performing third of the three models on the training data, the Linear Model actually performed the best of all of the models on the testing data. I honestly did not see that coming. It just goes to show that you can do all of the training in the world and sometimes the win simply comes down to luck.
To be objective, a score of 78.9% isn’t all that impressive considering there are other submissions that got a perfect score. But given that this was my first competition and I came in 3149th out of 11098 competitors (better than 71.6% of other participants), I feel that this was a satisfactory effort.
Thank you for reading along. I hope to see you in the next case study. | [
{
"code": null,
"e": 773,
"s": 171,
"text": "The purpose of this case study is to document the process I went through to create my predictions for submission in my first Kaggle competition, Titanic: Machine Learning from Disaster. For the uninitiated, Kaggle is a popular data science website that houses thousands of public datasets, offers courses and generally serves as a community hub for the analytically-minded. They also host machine learning competitions with various objectives. The objective of this particular competition was to build a classification model that could successfully determine whether a Titanic passenger lived or died."
},
{
"code": null,
"e": 792,
"s": 773,
"text": "Let’s get started!"
},
{
"code": null,
"e": 1249,
"s": 792,
"text": "The first step in the process is always to load in the data as well as the necessary packages. In R, the programming language I am using, packages are collections of algorithms that allow users to perform specified tasks. There are packages for creating beautiful plots, building stock portfolios and pretty much anything else you can imagine. Here, I loaded a number of packages that allow me to utilize a handful of powerful machine learning (ML) models."
},
{
"code": null,
"e": 1492,
"s": 1249,
"text": "lapply(c(“caret”, “h2o”, “pROC”, “randomForest”, “readr”, “tidyverse”, “xgboost”), library, character.only = TRUE) h2o.init() h2o.no_progress() set.seed(123) train <- read_csv(“~/Downloads/train.csv”) test <- read_csv(“~/Downloads/test.csv”)"
},
{
"code": null,
"e": 1698,
"s": 1492,
"text": "The competition dataset came in two files: train and test. As you may be able to guess, the former is used to train the ML models and the test is used to make the predictions that are ultimately submitted."
},
{
"code": null,
"e": 1772,
"s": 1698,
"text": "After getting my data into R, it’s time to explore the shape of the data."
},
{
"code": null,
"e": 3576,
"s": 1772,
"text": "train %>% glimpse()## Observations: 891 ## Variables: 12 ## $ PassengerId <dbl> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1... ## $ Survived <dbl> 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1... ## $ Pclass <dbl> 3, 1, 3, 1, 3, 3, 1, 3, 3, 2, 3, 1, 3, 3, 3, 2, 3, 2... ## $ Name <chr> “Braund, Mr. Owen Harris”, “Cumings, Mrs. John Bradl... ## $ Sex <chr> “male”, “female”, “female”, “female”, “male”, “male”... ## $ Age <dbl> 22, 38, 26, 35, 35, NA, 54, 2, 27, 14, 4, 58, 20, 39... ## $ SibSp <dbl> 1, 1, 0, 1, 0, 0, 0, 3, 0, 1, 1, 0, 0, 1, 0, 0, 4, 0... ## $ Parch <dbl> 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 0, 0, 5, 0, 0, 1, 0... ## $ Ticket <chr> “A/5 21171”, “PC 17599”, “STON/O2. 3101282”, “113803... ## $ Fare <dbl> 7.2500, 71.2833, 7.9250, 53.1000, 8.0500, 8.4583, 51... ## $ Cabin <chr> NA, “C85”, NA, “C123”, NA, NA, “E46”, NA, NA, NA, “G... ## $ Embarked <chr> “S”, “C”, “S”, “S”, “S”, “Q”, “S”, “S”, “S”, “C”, “S...test %>% glimpse()## Observations: 418 ## Variables: 11 ## $ PassengerId <dbl> 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 90... ## $ Pclass <dbl> 3, 3, 2, 3, 3, 3, 3, 2, 3, 3, 3, 1, 1, 2, 1, 2, 2, 3... ## $ Name <chr> “Kelly, Mr. James”, “Wilkes, Mrs. James (Ellen Needs... ## $ Sex <chr> “male”, “female”, “male”, “male”, “female”, “male”, ... ## $ Age <dbl> 34.5, 47.0, 62.0, 27.0, 22.0, 14.0, 30.0, 26.0, 18.0... ## $ SibSp <dbl> 0, 1, 0, 0, 1, 0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 1, 0, 0... ## $ Parch <dbl> 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0... ## $ Ticket <chr> “330911”, “363272”, “240276”, “315154”, “3101298”, “... ## $ Fare <dbl> 7.8292, 7.0000, 9.6875, 8.6625, 12.2875, 9.2250, 7.6... ## $ Cabin <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, “B45... ## $ Embarked <chr> “Q”, “S”, “Q”, “S”, “S”, “S”, “Q”, “S”, “C”, “S”, “S..."
},
{
"code": null,
"e": 4099,
"s": 3576,
"text": "What the above code says is that the training data has 891 rows with 12 different variables. These variables include things like the name of the passenger, their sex and age, how much they paid for their ticket and where they boarded, among other things. The most important variable here is the one named “Survived,” a list of 1’s and 0’s that indicate whether a passenger lived or died, respectively. The testing data features 418 rows and lacks the “Survived” variable as that is what the competition asks us to predict."
},
{
"code": null,
"e": 4327,
"s": 4099,
"text": "While there is plenty of information contained within the data as it exists now, not all of it is usable in its current form. To extract as much useable information as possible, I will have to transform some of these variables."
},
{
"code": null,
"e": 4795,
"s": 4327,
"text": "The first variable I will look at is “Name.” As far as I know, the iceberg that sunk the Titanic didn’t have a personal vendetta against any of the passengers, so simply using the full names of the passengers won’t provide any useful information. What may, however, is the passengers’ titles. What titles like “Mr.,” “Mrs.” or “Countess” might help us determine is if passengers’ social status (i.e. Were they commoners or nobility?) had any impact on their survival."
},
{
"code": null,
"e": 4882,
"s": 4795,
"text": "To get these titles, I have to extract them from “Name,” which is the below code does."
},
{
"code": null,
"e": 5175,
"s": 4882,
"text": "titles <- c(unique(str_extract(str_extract(train$Name, “\\\\,\\\\s[A-Za-z]+”), “[A-Za-z]+”))) titles <- replace(titles, titles == “the”, “Countess”) titles## [1] “Mr” “Mrs” “Miss” “Master” “Don” “Rev” ## [7] “Dr” “Mme” “Ms” “Major” “Lady” “Sir” ## [13] “Mlle” “Col” “Capt” “Countess” “Jonkheer”"
},
{
"code": null,
"e": 5359,
"s": 5175,
"text": "If you were wondering, “Jonkheer” was an honorific used by Dutch nobility. There was one Jonkheer on board the Titanic, Johan George Reuchlin, and, spoiler alert, he died. ̄\\_(ツ)_/ ̄"
},
{
"code": null,
"e": 5758,
"s": 5359,
"text": "In addition to using this list of titles to create a new variable, I also am going to extract the Deck from “Cabin” and create a variable named “Family_Size” that is simply a combination of “SibSp,’ a count of siblings and spouses on board, and ”Parch,” a count of parents and children on board. I also will clean up a few of the other variables to make them easier for the ML models to understand."
},
{
"code": null,
"e": 6514,
"s": 5758,
"text": "train <- train %>% mutate(Survived = factor(Survived), Sex = factor(recode(Sex, male = 1, female = 0)), Pclass = factor(Pclass), Embarked = factor(Embarked), Deck = factor(replace_na(substr(train$Cabin, 1, 1), “Unknown”)), Title = factor(str_extract(train$Name, paste(titles, collapse = “|”))), Family_Size = SibSp + Parch) %>% select(-c(Cabin, Name, Ticket)) test <- test %>% mutate(Sex = factor(recode(Sex, male = 1, female = 0)), Pclass = factor(Pclass), Embarked = factor(Embarked), Deck = factor(replace_na(substr(test$Cabin, 1, 1), “Unknown”)), Title = factor(str_extract(test$Name, paste(titles, collapse = “|”))), Family_Size = SibSp + Parch, Fare = ifelse(is.na(Fare), mean(Fare, na.rm = TRUE), Fare)) %>% select(-c(Cabin, Name, Ticket))"
},
{
"code": null,
"e": 6814,
"s": 6514,
"text": "One thing that I didn’t point out earlier when examining the data was just how many passengers’ ages were not recorded. Of the 1309 passengers whose data we have, 266 had no age. That missing information will be problematic later, so I feel it’s necessary to replace those empty values with a guess."
},
{
"code": null,
"e": 7155,
"s": 6814,
"text": "To keep things brief, what the below code does is combine the training and testing data, pull out the records that have ages and fit a Random Forest (RF) model that determines the relationship between a passenger’s age and the other variables. Finally, it will fill all of the missing ages with the best guess as to what their age might be."
},
{
"code": null,
"e": 7352,
"s": 7155,
"text": "Side note: to go into a description of what an RF model is would completely derail this case study. If you’re interested in learning more about RF models and how they work, check out this website."
},
{
"code": null,
"e": 8276,
"s": 7352,
"text": "# Combining the training and test data and selecting only the rows with ages age <- train %>% select(-Survived) %>% rbind(test) %>% filter(!is.na(Age)) %>% filter(!is.na(Embarked)) # Building a prediction model age_rf_model <- randomForest(Age ~ . — PassengerId, age, ntree = 5000, mtry = 9, na.action = na.exclude) # Determining the accuracy of the model age %>% select(Age) %>% add_column(Pred = predict(age_rf_model, age)) %>% na.omit() %>% mutate(Error = Age — Pred, Error_Pct = Error/Age) %>% summarize(RMSE = sqrt(mean(Error2)), MAPE = mean(abs(Error_Pct)))## # A tibble: 1 x 2 ## RMSE MAPE ## <dbl> <dbl> ## 1 7.30 0.302# Using the model to predict passenger age train <- train %>% mutate(Age = ifelse(is.na(Age), round(predict(age_rf_model, train)), Age)) test <- rbind(train[1, c(1, 3:12)], test) test <- test[-1, ] test <- test %>% mutate(Age = ifelse(is.na(Age), round(predict(age_rf_model, test)), Age))"
},
{
"code": null,
"e": 8548,
"s": 8276,
"text": "To check how accurate the RF model’s predictions are, I calculated the Root Mean Squared Error (RMSE) and Mean Absolute Percent Error (MAPE) of the predictions to gauge the quality of those predictions. See my earlier article for a brief description of these two metrics."
},
{
"code": null,
"e": 8760,
"s": 8548,
"text": "Long story short: both measures of error are low. The MAPE tells me that the average prediction has an error of only .3%, so while not perfect, I feel it’s acceptable for my ultimate goal of predicting survival."
},
{
"code": null,
"e": 9221,
"s": 8760,
"text": "Now that the data is clean, it is time for me to start training the ML models with the data. Since I want to make sure that my models perform well on unseen data, I am going to divide my training data up into a smaller set of training and test data. This way, I can assess the accuracy of the models before taking them to the actual, Kaggle-provided testing data (which, remember, I can’t assess the accuracy of because the data lacks the “Survived” variable)."
},
{
"code": null,
"e": 9346,
"s": 9221,
"text": "train_1 <- stratified(train, c(“Survived”, “Deck”, “Title”), size = 0.7, replace = FALSE) train_2 <- setdiff(train, train_1)"
},
{
"code": null,
"e": 9643,
"s": 9346,
"text": "I’m going to use four different models, each with their own way of making predictions: a linear model, a Random Forest model, an XGBoost (eXtreme Gradient Boosting) model and H2O’s AutoML. Again, feel free to click the hyperlinks for a description of what these models are and what they’re doing."
},
{
"code": null,
"e": 10354,
"s": 9643,
"text": "To make what’s going on below easier to understand, imagine that instead of predicting Titanic survivors, we wanted to win a Mixed Martial Arts tournament. We only have enough time to master one martial art before the tournament begins, so we need to figure out which we should study to have the best chance of winning. We know who the competitors will be (i.e. our testing data), but we’re not sure which martial art will serve us best. What is going on below is we are running simulations where we learn four different martial arts (let’s say boxing, jujutsu, muay tai and tae kwon do) and seeing how we might do against competitors similar to those that we’ll see in the tournament (i.e. our training data)."
},
{
"code": null,
"e": 11801,
"s": 10354,
"text": "# Linear Model — — glm_model <- glm(Survived ~ . — PassengerId, family = “binomial”, train_1) # Random Forest — — rf_model <- randomForest(Survived ~ . — PassengerId, train_1, ntree = 10000, mtry = 3, na.action = na.exclude) # XGBoost — — dummy_1 <- dummyVars(Survived ~ ., train_1[,2:12]) train_1_dummy <- predict(dummy_1, train_1) dummy_2 <- dummyVars(Survived ~ ., train_2[,2:12]) train_2_dummy <- predict(dummy_2, train_2) dtrain <- xgb.DMatrix(data = train_1_dummy, label = as.vector(train_1$Survived)) dtest <- xgb.DMatrix(data = train_2_dummy, label = as.vector(train_2$Survived)) watchlist <- list(train = dtrain, test = dtest) xgb_model <- xgb.train( data = dtrain, watchlist = watchlist, booster = “gbtree”, max.depth = 3, nthread = 2, nrounds = 5000, objective = “binary:logistic”, early_stopping_rounds = 500, print_every_n = 500 ) # H2O — — train_1_h2o <- train_1 %>% select(-PassengerId) %>% mutate(Pclass = factor(Pclass, ordered = FALSE)) %>% as.h2o train_2_h2o <- train_2 %>% select(-PassengerId) %>% mutate(Pclass = factor(Pclass, ordered = FALSE)) %>% as.h2o y <- “Survived” x <- setdiff(colnames(train_1_h2o), y) split <- h2o.splitFrame(train_1_h2o, ratios = c(.70, .15)) t1 <- split[[1]] t2 <- split[[2]] t3 <- split[[3]] h2o_model <- h2o.automl( x = x, y = y, train = t1, validation_frame = t2, leaderboard_frame = t3, nfolds = 5, stopping_metric = “AUC”, max_runtime_secs = 120 ) h2o_leader <- h2o_model@leader"
},
{
"code": null,
"e": 12186,
"s": 11801,
"text": "To continue the above metaphor, no one martial art is going to be best against every competitor, so we’re going to try and find the one which performs best. For martial arts, the metric in which you’d measure that would probably be the number of wins. For Titanic predictions, I’m going to measure that with accuracy (mostly because that’s what Kaggle uses to score this competition)."
},
{
"code": null,
"e": 12455,
"s": 12186,
"text": "To determine that accuracy, I will generate what is called a confidence matrix. Simply put, this is a 2x2 box that shows actual values (called “Reference” in the output) along the x-axis and the predicted values along the y-axis. This allows you to see four variables:"
},
{
"code": null,
"e": 12500,
"s": 12455,
"text": "· True Positives: Prediction = 1, Actual = 1"
},
{
"code": null,
"e": 12545,
"s": 12500,
"text": "· True Negatives: Prediction = 0, Actual = 0"
},
{
"code": null,
"e": 12591,
"s": 12545,
"text": "· False Positives: Prediction = 1, Actual = 0"
},
{
"code": null,
"e": 12637,
"s": 12591,
"text": "· False Negatives: Prediction = 0, Actual = 1"
},
{
"code": null,
"e": 12743,
"s": 12637,
"text": "Accuracy is a measure of how many True Positives and True Negatives there are out of all the predictions."
},
{
"code": null,
"e": 13841,
"s": 12743,
"text": "compare_set <- train_2 %>% add_column(GLM_Pred = predict(glm_model, train_2, type = “response”)) %>% add_column(RF_Pred = predict(rf_model, train_2)) %>% add_column(XGB_Pred = predict(xgb_model, train_2_dummy)) %>% add_column(H2O_Pred = h2o.predict(h2o_leader, newdata = train_2_h2o) %>% as_tibble() %>% pull(predict)) %>% mutate_at(vars(GLM_Pred, XGB_Pred), list(~factor(as.numeric(. > 0.5)))) for (i in 13:16) { conmat <- confusionMatrix(compare_set$Survived, compare_set[[i]], positive = “1”) print(colnames(compare_set[, i])) print(conmat$table) print(conmat$overall[1]) }## [1] “GLM_Pred” ## Reference ## Prediction 0 1 ## 0 141 21 ## 1 23 75 ## Accuracy ## 0.8307692 ## [1] “RF_Pred” ## Reference ## Prediction 0 1 ## 0 149 13 ## 1 26 72 ## Accuracy ## 0.85 ## [1] “XGB_Pred” ## Reference ## Prediction 0 1 ## 0 147 15 ## 1 20 79 ## Accuracy ## 0.8659004 ## [1] “H2O_Pred” ## Reference ## Prediction 0 1 ## 0 151 11 ## 1 38 61 ## Accuracy ## 0.8122605"
},
{
"code": null,
"e": 14293,
"s": 13841,
"text": "As you can see, in terms of pure accuracy, the XGBoost model performs the best by correctly predicting 86.6% of all the survivors in the training data. However, accuracy isn’t always the best measure. If you look at the confidence matrix for XGBoost, you will see that there were 15 False Negatives. The RF model, while not performing quite as well in terms of accuracy, had only 13 False Negatives. Why this may be important depends on the situation."
},
{
"code": null,
"e": 14756,
"s": 14293,
"text": "Imagine you are a doctor tasked with determining whether a patient has a particular disease. Assume that the treatment is harmless if given to someone who doesn’t have the disease, but without the treatment, people with the disease are guaranteed to die. Given the numbers above, the RF model would have saved two more lives than the XGBoost model. The takeaway here is that one should never simply look at the accuracy and make the final judgment based on that."
},
{
"code": null,
"e": 14777,
"s": 14756,
"text": "And so I won’t here!"
},
{
"code": null,
"e": 15017,
"s": 14777,
"text": "Instead, I will make predictions using both the RF and XGBoost models. And since a third submission to the competition costs me nothing, I’ll also make a prediction with the linear model because its accuracy isn’t far behind the other two."
},
{
"code": null,
"e": 15215,
"s": 15017,
"text": "Now that I have my trained models (or fighters if you’d prefer that metaphor), it’s time to put them to work. I’m going to use them on the testing data, data that the models have never seen before."
},
{
"code": null,
"e": 15784,
"s": 15215,
"text": "# XGBoost dummy_test <- dummyVars(PassengerId ~ ., test) test_dummy <- predict(dummy_test, test) submission_xgboost <- test %>% add_column(Survived = predict(xgb_model, test_dummy)) %>% mutate(Survived = as.numeric(Survived > 0.5)) %>% select(PassengerId, Survived) # Random Forest submission_rf <- test %>% add_column(Survived = predict(rf_model, test)) %>% select(PassengerId, Survived) # Linear Model submission_glm <- test %>% add_column(Survived = predict(glm_model, test)) %>% mutate(Survived = as.numeric(Survived > 0.5)) %>% select(PassengerId, Survived)"
},
{
"code": null,
"e": 15891,
"s": 15784,
"text": "Let’s take a look at how each model predicted the survival of the first 10 passengers in the testing data."
},
{
"code": null,
"e": 16519,
"s": 15891,
"text": "submission_xgboost %>% left_join(submission_rf, by = “PassengerId”) %>% left_join(submission_glm, by = “PassengerId”) %>% rename(XGBoost = Survived.x, RF = Survived.y, Linear = Survived) %>% head(10)## # A tibble: 10 x 4 ## PassengerId XGBoost RF Linear ## <dbl> <dbl> <fct> <dbl> ## 1 892 0 0 0 ## 2 893 0 0 0 ## 3 894 0 0 0 ## 4 895 0 0 0 ## 5 896 0 0 1 ## 6 897 0 0 0 ## 7 898 0 0 1 ## 8 899 0 0 0 ## 9 900 1 1 1 ## 10 901 0 0 0"
},
{
"code": null,
"e": 16661,
"s": 16519,
"text": "As you can see, all three models predicted that Passenger 900 survived. The linear model also predicted that Passengers 896 and 898 survived."
},
{
"code": null,
"e": 16833,
"s": 16661,
"text": "Now that I have my predictions, it’s time to submit them to Kaggle and see how they did. First, I have to export these predictions to a CSV file so that I can upload them."
},
{
"code": null,
"e": 17019,
"s": 16833,
"text": "write_csv(submission_xgboost, “~/Downloads/Submission XGBoost.csv”) write_csv(submission_rf, “~/Downloads/Submission RF.csv”) write_csv(submission_glm, “~/Downloads/Submission GLM.csv”)"
},
{
"code": null,
"e": 17122,
"s": 17019,
"text": "After uploading the CSV, Kaggle generates my final score for each submission. So, let’s see how I did."
},
{
"code": null,
"e": 17489,
"s": 17122,
"text": "Wow! Look at that dark horse victory! Totally unexpected! Despite performing third of the three models on the training data, the Linear Model actually performed the best of all of the models on the testing data. I honestly did not see that coming. It just goes to show that you can do all of the training in the world and sometimes the win simply comes down to luck."
},
{
"code": null,
"e": 17793,
"s": 17489,
"text": "To be objective, a score of 78.9% isn’t all that impressive considering there are other submissions that got a perfect score. But given that this was my first competition and I came in 3149th out of 11098 competitors (better than 71.6% of other participants), I feel that this was a satisfactory effort."
}
] |
Difference between passing pointer to pointer and address of pointer to any function - GeeksforGeeks | 26 Apr, 2021
In this article, the differences between passing “pointer to pointer” and “address of pointer” to a function. In C or C++ Programming Language, it is known that pointers hold the address of the variables or any memory location. If pointers are pointed to the memory location, it can be used to change the value of the variable.
As for functions, any pointer can be passed by itself, or by the address of the pointer. But If the memory location of the pointer is to be changed permanently out of the function, it must be captured with a reference or double-pointer within the function i.e., with the assumption any memory is created inside the local function.
Afterward, it is pointed to the pointer captured by the function without any reference or any double-pointer. In this situation, there is no change inside the main function because it was not captured by reference or double-pointer inside the function definition.
Program 1:
C++
// C++ program to illustrate the// concepts pointers #include <iostream>#include <stdlib.h>using namespace std; // Function to assign the value of// pointer ptr to another locationvoid foo(int* ptr){ int b = 2; // ptr= (int*)malloc(sizeof(int)); // It can be executed instead of // the ptr=&b but nothing change ptr = &b;} // Driver Codeint main(){ int a = 5; int* ptr = &a; cout << "Before the function ptr: " << *ptr << endl; foo(ptr); cout << "After the function ptr: " << *ptr << endl; return 0;}
Before the function ptr: 5
After the function ptr: 5
Explanation: The reason why there is no change in the output is that it is created a copy pointer for the function. So, the change in the address of the pointer does not reflect out of the function. References or double-pointer can be used for this.
Program 2:
C++
// C++ program to illustrate the// concepts of pointer #include <iostream>#include <stdlib.h>using namespace std; // Function to change the pointer ptrvoid foo(int* ptr){ int b = 2; // The change will only be for // the new value of the ptr *ptr = b;} // Driver Codeint main(){ int a = 5; int* ptr = &a; cout << "Before the function, " << "new value of the ptr: " << *ptr << endl; // Function Call foo(ptr); cout << "After the function, " << "new value of the ptr: " << *ptr << endl; return 0;}
Before the function, new value of the ptr: 5
After the function, new value of the ptr: 2
Explanation:
If it is wanted to replace the memory stored in ptr when the foo() function is complete, ptr must be captured with the reference or double-pointer in the foo() function.
Program 3:
C++
// C++ program to illustrate the// concepts of pointer#include <iostream>#include <stdlib.h>using namespace std; // Function to change the value of// the pointers ptr1void foo(int** ptr1){ int b = 2; // ptr = &b; // For this assignment, the // captured value will be like // void foo(int* &ptr) *ptr1 = &b;} // Driver Codeint main(){ int a = 5; int* ptr = &a; cout << "Before the function, " << "new value of the ptr: " << *ptr << endl; // Function Call foo(&ptr); cout << "After the function, " << "new value of the ptr: " << *ptr << endl; return 0;}
Before the function, new value of the ptr: 5
After the function, new value of the ptr: 2
Explanation:
CPP-Basics
Memory Management
Pointers
C++
C++ Programs
Difference Between
Pointers
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Sorting a Map by value in C++ STL | [
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 25695,
"s": 25367,
"text": "In this article, the differences between passing “pointer to pointer” and “address of pointer” to a function. In C or C++ Programming Language, it is known that pointers hold the address of the variables or any memory location. If pointers are pointed to the memory location, it can be used to change the value of the variable."
},
{
"code": null,
"e": 26026,
"s": 25695,
"text": "As for functions, any pointer can be passed by itself, or by the address of the pointer. But If the memory location of the pointer is to be changed permanently out of the function, it must be captured with a reference or double-pointer within the function i.e., with the assumption any memory is created inside the local function."
},
{
"code": null,
"e": 26290,
"s": 26026,
"text": "Afterward, it is pointed to the pointer captured by the function without any reference or any double-pointer. In this situation, there is no change inside the main function because it was not captured by reference or double-pointer inside the function definition."
},
{
"code": null,
"e": 26301,
"s": 26290,
"text": "Program 1:"
},
{
"code": null,
"e": 26305,
"s": 26301,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// concepts pointers #include <iostream>#include <stdlib.h>using namespace std; // Function to assign the value of// pointer ptr to another locationvoid foo(int* ptr){ int b = 2; // ptr= (int*)malloc(sizeof(int)); // It can be executed instead of // the ptr=&b but nothing change ptr = &b;} // Driver Codeint main(){ int a = 5; int* ptr = &a; cout << \"Before the function ptr: \" << *ptr << endl; foo(ptr); cout << \"After the function ptr: \" << *ptr << endl; return 0;}",
"e": 26866,
"s": 26305,
"text": null
},
{
"code": null,
"e": 26920,
"s": 26866,
"text": "Before the function ptr: 5\nAfter the function ptr: 5\n"
},
{
"code": null,
"e": 27170,
"s": 26920,
"text": "Explanation: The reason why there is no change in the output is that it is created a copy pointer for the function. So, the change in the address of the pointer does not reflect out of the function. References or double-pointer can be used for this."
},
{
"code": null,
"e": 27181,
"s": 27170,
"text": "Program 2:"
},
{
"code": null,
"e": 27185,
"s": 27181,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// concepts of pointer #include <iostream>#include <stdlib.h>using namespace std; // Function to change the pointer ptrvoid foo(int* ptr){ int b = 2; // The change will only be for // the new value of the ptr *ptr = b;} // Driver Codeint main(){ int a = 5; int* ptr = &a; cout << \"Before the function, \" << \"new value of the ptr: \" << *ptr << endl; // Function Call foo(ptr); cout << \"After the function, \" << \"new value of the ptr: \" << *ptr << endl; return 0;}",
"e": 27760,
"s": 27185,
"text": null
},
{
"code": null,
"e": 27850,
"s": 27760,
"text": "Before the function, new value of the ptr: 5\nAfter the function, new value of the ptr: 2\n"
},
{
"code": null,
"e": 27863,
"s": 27850,
"text": "Explanation:"
},
{
"code": null,
"e": 28033,
"s": 27863,
"text": "If it is wanted to replace the memory stored in ptr when the foo() function is complete, ptr must be captured with the reference or double-pointer in the foo() function."
},
{
"code": null,
"e": 28044,
"s": 28033,
"text": "Program 3:"
},
{
"code": null,
"e": 28048,
"s": 28044,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// concepts of pointer#include <iostream>#include <stdlib.h>using namespace std; // Function to change the value of// the pointers ptr1void foo(int** ptr1){ int b = 2; // ptr = &b; // For this assignment, the // captured value will be like // void foo(int* &ptr) *ptr1 = &b;} // Driver Codeint main(){ int a = 5; int* ptr = &a; cout << \"Before the function, \" << \"new value of the ptr: \" << *ptr << endl; // Function Call foo(&ptr); cout << \"After the function, \" << \"new value of the ptr: \" << *ptr << endl; return 0;}",
"e": 28683,
"s": 28048,
"text": null
},
{
"code": null,
"e": 28773,
"s": 28683,
"text": "Before the function, new value of the ptr: 5\nAfter the function, new value of the ptr: 2\n"
},
{
"code": null,
"e": 28786,
"s": 28773,
"text": "Explanation:"
},
{
"code": null,
"e": 28797,
"s": 28786,
"text": "CPP-Basics"
},
{
"code": null,
"e": 28815,
"s": 28797,
"text": "Memory Management"
},
{
"code": null,
"e": 28824,
"s": 28815,
"text": "Pointers"
},
{
"code": null,
"e": 28828,
"s": 28824,
"text": "C++"
},
{
"code": null,
"e": 28841,
"s": 28828,
"text": "C++ Programs"
},
{
"code": null,
"e": 28860,
"s": 28841,
"text": "Difference Between"
},
{
"code": null,
"e": 28869,
"s": 28860,
"text": "Pointers"
},
{
"code": null,
"e": 28873,
"s": 28869,
"text": "CPP"
},
{
"code": null,
"e": 28971,
"s": 28873,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28999,
"s": 28971,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29019,
"s": 28999,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 29052,
"s": 29019,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 29076,
"s": 29052,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 29101,
"s": 29076,
"text": "std::string class in C++"
},
{
"code": null,
"e": 29136,
"s": 29101,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29180,
"s": 29136,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 29206,
"s": 29180,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 29265,
"s": 29206,
"text": "How to return multiple values from a function in C or C++?"
}
] |
How to convert a string in to a function in JavaScript? | To convert a string in to function "eval()" method should be used. This method takes a string as a parameter and converts it into a function.
eval(string);
In the following example, in a string itself, a property called 'age' is assigned with a function. Later on, using eval() function the property age is converted into a function and displayed as shown in the output.
Live Demo
<html>
<body>
<script>
var string = '{"name":"Ram", "age":"function() {return 27;}", "city":"New jersey"}';
var fun = JSON.parse(string);
fun.age = eval("(" + fun.age + ")");
document.write(fun.name + " "+ "of Age" + " "+ fun.age()+ " " + "from city" +" "+ fun.city);
</script>
</body>
</html>
Ram of Age 27 from city New jersey | [
{
"code": null,
"e": 1204,
"s": 1062,
"text": "To convert a string in to function \"eval()\" method should be used. This method takes a string as a parameter and converts it into a function."
},
{
"code": null,
"e": 1218,
"s": 1204,
"text": "eval(string);"
},
{
"code": null,
"e": 1433,
"s": 1218,
"text": "In the following example, in a string itself, a property called 'age' is assigned with a function. Later on, using eval() function the property age is converted into a function and displayed as shown in the output."
},
{
"code": null,
"e": 1444,
"s": 1433,
"text": " Live Demo"
},
{
"code": null,
"e": 1750,
"s": 1444,
"text": "<html>\n<body>\n<script>\n var string = '{\"name\":\"Ram\", \"age\":\"function() {return 27;}\", \"city\":\"New jersey\"}';\n var fun = JSON.parse(string);\n fun.age = eval(\"(\" + fun.age + \")\");\n document.write(fun.name + \" \"+ \"of Age\" + \" \"+ fun.age()+ \" \" + \"from city\" +\" \"+ fun.city);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1785,
"s": 1750,
"text": "Ram of Age 27 from city New jersey"
}
] |
Material Design Lite - Checkboxes | MDL provides a range of CSS classes to apply various predefined visual and behavioral
enhancements and display the different types of checkboxes. The following table lists down
the available classes and their effects.
mdl-checkbox
Identifies label as an MDL component and is required on label element.
mdl-js-checkbox
Sets basic MDL behavior to label and is required on label element.
mdl-checkbox__input
Sets basic MDL behavior to checkbox and is required on input element (checkbox).
mdl-checkbox__label
Sets basic MDL behavior to caption and is required on span element (caption).
mdl-js-ripple-effect
Sets ripple click effect and is optional; goes on the label element and not on the input element (checkbox).
The following example will help you understand the use of the mdl-slider classes to show
the different types of check boxes.
<html>
<head>
<script
src = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js">
</script>
<link rel = "stylesheet"
href = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css">
<link rel = "stylesheet"
href = "https://fonts.googleapis.com/icon?family=Material+Icons">
<script langauage = "javascript">
function showMessage(value) {
document.getElementById("message").innerHTML = value;
}
</script>
</head>
<body>
<table>
<tr><td>Default CheckBox</td><td>CheckBox with Ripple Effect</td>
<td>Disabled CheckBox</td></tr>
<tr>
<td>
<label class = "mdl-checkbox mdl-js-checkbox" for = "checkbox1">
<input type = "checkbox" id = "checkbox1"
class = "mdl-checkbox__input" checked>
<span class = "mdl-checkbox__label">Married</span>
</label>
</td>
<td>
<label class = "mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect"
for = "checkbox2">
<input type = "checkbox" id = "checkbox2" class = "mdl-checkbox__input">
<span class = "mdl-checkbox__label">Single</span>
</label>
</td>
<td>
<label class = "mdl-checkbox mdl-js-checkbox" for = "checkbox3">
<input type = "checkbox" id = "checkbox3"
class = "mdl-checkbox__input" disabled>
<span class = "mdl-checkbox__label">Don't know (Disabled)</span>
</label>
</td>
</tr>
</table>
</body>
</html>
Verify the result.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2104,
"s": 1886,
"text": "MDL provides a range of CSS classes to apply various predefined visual and behavioral\nenhancements and display the different types of checkboxes. The following table lists down\nthe available classes and their effects."
},
{
"code": null,
"e": 2117,
"s": 2104,
"text": "mdl-checkbox"
},
{
"code": null,
"e": 2188,
"s": 2117,
"text": "Identifies label as an MDL component and is required on label element."
},
{
"code": null,
"e": 2204,
"s": 2188,
"text": "mdl-js-checkbox"
},
{
"code": null,
"e": 2271,
"s": 2204,
"text": "Sets basic MDL behavior to label and is required on label element."
},
{
"code": null,
"e": 2291,
"s": 2271,
"text": "mdl-checkbox__input"
},
{
"code": null,
"e": 2372,
"s": 2291,
"text": "Sets basic MDL behavior to checkbox and is required on input element (checkbox)."
},
{
"code": null,
"e": 2392,
"s": 2372,
"text": "mdl-checkbox__label"
},
{
"code": null,
"e": 2470,
"s": 2392,
"text": "Sets basic MDL behavior to caption and is required on span element (caption)."
},
{
"code": null,
"e": 2491,
"s": 2470,
"text": "mdl-js-ripple-effect"
},
{
"code": null,
"e": 2600,
"s": 2491,
"text": "Sets ripple click effect and is optional; goes on the label element and not on the input element (checkbox)."
},
{
"code": null,
"e": 2725,
"s": 2600,
"text": "The following example will help you understand the use of the mdl-slider classes to show\nthe different types of check boxes."
},
{
"code": null,
"e": 4562,
"s": 2725,
"text": "<html>\n <head>\n <script \n src = \"https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js\">\n </script>\n <link rel = \"stylesheet\" \n href = \"https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css\">\n <link rel = \"stylesheet\" \n href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\t \n \n <script langauage = \"javascript\">\n function showMessage(value) {\n document.getElementById(\"message\").innerHTML = value;\n }\t \n </script>\n </head>\n \n <body>\n <table>\n <tr><td>Default CheckBox</td><td>CheckBox with Ripple Effect</td>\n <td>Disabled CheckBox</td></tr>\n \n <tr>\n <td> \n <label class = \"mdl-checkbox mdl-js-checkbox\" for = \"checkbox1\">\n <input type = \"checkbox\" id = \"checkbox1\" \n class = \"mdl-checkbox__input\" checked>\n <span class = \"mdl-checkbox__label\">Married</span>\n </label>\n </td>\n \n <td>\n <label class = \"mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect\" \n for = \"checkbox2\">\n <input type = \"checkbox\" id = \"checkbox2\" class = \"mdl-checkbox__input\">\n <span class = \"mdl-checkbox__label\">Single</span>\n </label>\t \n </td>\n \n <td>\n <label class = \"mdl-checkbox mdl-js-checkbox\" for = \"checkbox3\">\n <input type = \"checkbox\" id = \"checkbox3\" \n class = \"mdl-checkbox__input\" disabled>\n <span class = \"mdl-checkbox__label\">Don't know (Disabled)</span>\n </label>\t \n </td>\n </tr>\n </table> \n \n </body>\n</html>"
},
{
"code": null,
"e": 4581,
"s": 4562,
"text": "Verify the result."
},
{
"code": null,
"e": 4588,
"s": 4581,
"text": " Print"
},
{
"code": null,
"e": 4599,
"s": 4588,
"text": " Add Notes"
}
] |
Two water Jug problem | Practice | GeeksforGeeks | You are at the side of a river. You are given a m litre jug and a n litre jug where 0 < m < n. Both the jugs are initially empty. The jugs don’t have markings to allow measuring smaller quantities. You have to use the jugs to measure d litres of water where d < n. Determine the minimum no of operations to be performed to obtain d litres of water in one of jug.
The operations you can perform are:
Empty a Jug
Fill a Jug
Pour water from one jug to the other until one of the jugs is either empty or full.
Empty a Jug
Fill a Jug
Pour water from one jug to the other until one of the jugs is either empty or full.
Example 1:
Input: m = 3, n = 5, d = 4
Output: 6
Explanation: Operations are as follow-
1. Fill up the 5 litre jug.
2. Then fill up the 3 litre jug using 5 litre
jug. Now 5 litre jug contains 2 litre water.
3. Empty the 3 litre jug.
4. Now pour the 2 litre of water from 5 litre
jug to 3 litre jug.
5. Now 3 litre jug contains 2 litre of water
and 5 litre jug is empty. Now fill up the
5 litre jug.
6. Now fill one litre of water from 5 litre jug
to 3 litre jug. Now we have 4 litre water in
5 litre jug.
Example 2:
Input: m = 8, n = 56, d = 46
Output: -1
Explanation: Not possible to fill any one of
the jug with 46 litre of water.
Your Task:
You don't need to read or print anything. Your task is to complete the function minSteps() which takes m, n and d ans input parameter and returns the minimum number of operation to fill d litre of water in any of the two jug.
Expected Time Comeplxity: O(d)
Expected Space Complexity: O(1)
Constraints:
1 ≤ n ≤ m ≤ 100
1 ≤ d ≤ 100
0
yashmandaviya7021 week ago
in case any one want to print the path of operations as in explanation :
vector<string> bfsfill(int a,int b,int c){ queue<string> q; unordered_map<string,int> level; unordered_map<string,string> parent; string f = "0_0"; parent[f] = "-1"; level[f] = 0; q.push(f); while(!q.empty()){ auto cv = q.front(); q.pop(); stringstream ss(cv); string s1,s2; getline(ss,s1,'_'); getline(ss,s2,'_'); int x = stoi(s1),y = stoi(s2); if((x==c && y==0)||(x==0 && y==c)) break; // /* // x,y -> a,y // x,y -> x,b // x,y -> 0,y // x,y -> x,0 // x,y -> a,y-(a-x) if(x+y>=a) // x,y -> x-(b-y),b if(x+y>=b) // x,y -> x+y,0 if(x+y<=a) // x,y -> 0,x+y if(x+y<=b) // */ if(x<a && level.find(to_string(a)+"_"+to_string(y))==level.end()){ level[to_string(a)+"_"+to_string(y)] = level[cv]+1; parent[to_string(a)+"_"+to_string(y)] = cv; q.push(to_string(a)+"_"+to_string(y)); } if(y<b && level.find(to_string(x)+"_"+to_string(b))==level.end()){ level[to_string(x)+"_"+to_string(b)] = level[cv]+1; parent[to_string(x)+"_"+to_string(b)] = cv; q.push(to_string(x)+"_"+to_string(b)); } if(level.find(to_string(0)+"_"+to_string(y))==level.end()){ level[to_string(0)+"_"+to_string(y)] = level[cv]+1; parent[to_string(0)+"_"+to_string(y)] = cv; q.push(to_string(0)+"_"+to_string(y)); } if(level.find(to_string(x)+"_"+to_string(0))==level.end()){ level[to_string(x)+"_"+to_string(0)] = level[cv]+1; parent[to_string(x)+"_"+to_string(0)] = cv; q.push(to_string(x)+"_"+to_string(0)); } if(x+y>=a && level.find(to_string(a)+"_"+to_string(y-a+x))==level.end()){ level[to_string(a)+"_"+to_string(y-a+x)] = level[cv]+1; parent[to_string(a)+"_"+to_string(y-a+x)] = cv; q.push(to_string(a)+"_"+to_string(y-a+x)); } if(x+y>=b && level.find(to_string(x-b+y)+"_"+to_string(b))==level.end()){ level[to_string(x-b+y)+"_"+to_string(b)] = level[cv]+1; parent[to_string(x-b+y)+"_"+to_string(b)] = cv; q.push(to_string(x-b+y)+"_"+to_string(b)); } if(x+y<=a && level.find(to_string(x+y)+"_"+to_string(0))==level.end()){ level[to_string(x+y)+"_"+to_string(0)] = level[cv]+1; parent[to_string(x+y)+"_"+to_string(0)] = cv; q.push(to_string(x+y)+"_"+to_string(0)); } if(x+y<=b && level.find(to_string(0)+"_"+to_string(x+y))==level.end()){ level[to_string(0)+"_"+to_string(x+y)] = level[cv]+1; parent[to_string(0)+"_"+to_string(x+y)] = cv; q.push(to_string(0)+"_"+to_string(x+y)); } } vector<string> ans; int l1 = INT_MAX,l2 = INT_MAX; if(level.find(to_string(0)+"_"+to_string(c))!=level.end()) l1 = level[to_string(0)+"_"+to_string(c)]; if(level.find(to_string(c)+"_"+to_string(0))!=level.end()) l2 = level[to_string(c)+"_"+to_string(0)]; if(l1<l2){ string aa = to_string(0)+"_"+to_string(c); while(level[aa]!=0){ ans.push_back(aa); aa=parent[aa]; } } else{ string aa = to_string(c)+"_"+to_string(0); while(level[aa]!=0){ ans.push_back(aa); aa=parent[aa]; } } reverse(ans.begin(),ans.end()); return ans; }
+2
putyavka3 weeks ago
Time: 0.02/1.12 sec
int minSteps(int m, int n, int d) {
if (d == m || d == n) return 1;
if (m == n) return -1;
int k = m, c = 2, c1 = 0, c2 = 0;
while (k) { // pour from small to big
if (d == k) { c1 = c; break; }
if (k < m) c += 4; else c += 2;
k += m;
if (k >= n) k -= n;
}
if (!c1) return -1;
k = n - m, c = 2;
while (k) { // pour from big to small
if (d == k) { c2 = c; break; }
c += 2; k -= m;
if (k < 0) { c += 2; k += n; }
}
return min(c1, c2);
}
0
rp213 weeks ago
There may be an issue with the given time complexity. Nonetheless most intuitive and easiest approach is BFS(for shortest paths in unweighted graph).
-1
subhamkumar0321 month ago
class Solution{
public:
int gcd(int a, int b)
{
if (b==0)
return a;
return gcd(b, a%b);
}
int pour(int fromCap, int toCap, int d)
{
int from = fromCap;
int to = 0;
int step = 1;
while (from != d && to != d)
{
int temp = min(from, toCap - to);
to += temp;
from -= temp;
step++;
if (from == d || to == d)
break;
if (from == 0)
{
from = fromCap;
step++;
}
if (to == toCap)
{
to = 0;
step++;
}
}
return step;
}
int minSteps(int m, int n, int d)
{
if (m > n)
swap(m, n);
if (d > n)
return -1;
if ((d % gcd(n,m)) != 0)
return -1;
return min(pour(n,m,d),pour(m,n,d));
}
};
0
prabhxjott2 months ago
38 78 100
Why is it giving -1 for this testCase ?
0
agrimjain2411
This comment was deleted.
0
diptendunandi5 months ago
int m,n,N;
int get_index(int i, int j){
return i*N+j;
}
pair<int,int> get_cor(int index){
return {index/N,index%N};
}
void check(queue <int> &q, unordered_map<int,bool> &vis, int i ,int j){
if (i<0 || j<0 || i>m || j>n) return;
int idx = get_index(i,j);
if(vis.find(idx)!=vis.end()) return ;
vis[idx] = true;
q.push(idx);
}
int minSteps(int m, int n, int d)
{
if(m > n) swap(m,n);
if(d>n) return -1;
this->m = m;
this-> n = n;
this-> N = n+10;
unordered_map<int,bool> mp;
mp[0] = true;
queue<int> q;
q.push(0);
int level = 0;
while(!q.empty()){
int t = q.size();
for(int k =0;k<t;k++){
auto p =get_cor(q.front());
q.pop();
int i = p.first, j = p.second;
if(i==d || j==d) return level;
check(q,mp,i,0);
check(q,mp,0,j);
check(q,mp,m,j);
check(q,mp,i,n);
check(q,mp,0,i+j);
check(q,mp,i+j,0);
check(q,mp,i - (n-j),n);
check(q,mp,m, j - (m - i));
}
level++;
}
return -1;
}
0
himanshujain4576 months ago
Very Simple Approach:
int minSteps(int m, int n, int d){ int c1=m,c2=0,cnt=1,cnt2=1; if(d>m and d>n) return -1; map<pair<int,int>,int>mp;
//CASE1:always pour water from jug 1 to jug2 if at any stage jug1 become empty fill it again or if jug2 fill fully empty it again until one of the jug have d litre of water while(c1!=d and c2!=d) { mp[{c1,c2}]++; int remain=n-c2; if(remain>=c1) { cnt++; c2+=c1; c1=0; } else { c2+=remain; c1-=remain; cnt++; }
//if at any stage c1 or c2 become equals to d then break the loop if(c1==d||c2==d) break; if(c1==0) { c1=m; cnt++; } if(c2==n) { c2=0; cnt++; }
//if at any stage same procedure starts following again then break the loop if(mp.find({c1,c2})!=mp.end()) { cnt=-1; break; } }
//CASE2:always pour water from jug 2 to jug1 if at any stage jug2 become empty fill it again or if jug1 fill fully empty it again until one of the jug have d litre of water mp.clear(); c1=0; c2=n; while(c1!=d and c2!=d) { mp[{c1,c2}]++; int remain=m-c1; if(remain>=c2) { cnt2++; c1+=c2;; c2=0; } else { cnt2++; c1+=remain; c2-=remain; }
//if at any stage c1 or c2 become equals to d then break the loop if(c1==d||c2==d) break; if(c1==m) { c1=0; cnt2++; } if(c2==0) { c2=n; cnt2++; }
//if at any stage same procedure starts following again then break the loop if(mp.find({c1,c2})!=mp.end()) { cnt2=-1; break; } } if(cnt==-1 and cnt2==-1)return -1; if(cnt==-1)return cnt2; if(cnt2==-1)return cnt; return min(cnt,cnt2); }
0
perumallayaswanth20008 months ago
Can some one help me to answer this question.
For this test case i am getting answer as 108 but i am getting 110
46 65 23
This is my code. Please do read comments for better understanding.My approach is starting with both empty jugs performing all operations on each jug and bfs. If i got the required water in any jug at any point of time i return the bfs call count.
class Solution
{
public int minSteps(int m, int n, int d){
Pair pair=new Pair(0,0);
Queue<Pair>q= new LinkedList<>();
q.add(pair);
return bfs(q,m,n,d,-1);
}
int bfs(Queue<Pair>q,int m,int n,int d,int c){
ArrayList<String>al=new ArrayList<>();
while(!q.isEmpty()){
int size=q.size();
c++;
while(size-->0){
Pair popped=q.poll();
if(popped.u==d || popped.v==d)
return c;
//empty jug1
Pair emptyu=new Pair(0,popped.v);
String eu=Integer.toString(emptyu.u)+Integer.toString(emptyu.v);
if(popped.u!=0 && !al.contains(eu)){
q.add(emptyu);
al.add(eu);
}
//empty jug2
Pair emptyv=new Pair(popped.u,0);
String ev=Integer.toString(emptyv.u)+Integer.toString(emptyv.v);
if(popped.v!=0 && !al.contains(ev)){
q.add(emptyv);
al.add(ev);
}
//fill jug1
Pair fillu=new Pair(m,popped.v);
String fu=Integer.toString(fillu.u)+Integer.toString(fillu.v);
if(popped.u!=m && !al.contains(fu)){
q.add(fillu);
al.add(fu);
}
//fill jug2
Pair fillv=new Pair(popped.u,n);
String fv=Integer.toString(fillv.u)+Integer.toString(fillv.v);
if(popped.v!=n && !al.contains(fv)){
q.add(fillv);
al.add(fv);
}
//transfer from jug1 to jug2
int vremain=n-popped.v;
if(popped.u!=0 && vremain>0){
String su1=Integer.toString(0)+Integer.toString(popped.v+popped.u);
String su2=Integer.toString(popped.u-vremain)+Integer.toString(n);
//if jug2 has more space than jug1
if(vremain>popped.u && !al.contains(su1)){
q.add(new Pair(0,popped.v+popped.u));
al.add(su1);
}
//if jug1 has more space than jug2
else if(vremain<popped.u && !al.contains(su2)){
q.add(new Pair(popped.u-vremain,n));
al.add(su2);
}
}
//transfer from jug2 to jug1
int uremain=m-popped.u;
if(popped.v!=0 && uremain>0){
String su3=Integer.toString(popped.v+popped.u)+Integer.toString(0);
String su4=Integer.toString(m)+Integer.toString(popped.v-uremain);
if(uremain>popped.v && !al.contains(su3)){
q.add(new Pair(popped.v+popped.u,0));
al.add(su3);
}
else if(uremain<popped.v && !al.contains(su4)){
q.add(new Pair(m,popped.v-uremain));
al.add(su4);
}
}
}
}
return -1;
}
}
class Pair{
int u;
int v;
Pair(int u,int v){
this.u=u;
this.v=v;
}
}
0
geminicode9 months ago
Was anyone able to submit in python??
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": 637,
"s": 238,
"text": "You are at the side of a river. You are given a m litre jug and a n litre jug where 0 < m < n. Both the jugs are initially empty. The jugs don’t have markings to allow measuring smaller quantities. You have to use the jugs to measure d litres of water where d < n. Determine the minimum no of operations to be performed to obtain d litres of water in one of jug.\nThe operations you can perform are:"
},
{
"code": null,
"e": 746,
"s": 637,
"text": "\nEmpty a Jug\nFill a Jug\nPour water from one jug to the other until one of the jugs is either empty or full.\n"
},
{
"code": null,
"e": 758,
"s": 746,
"text": "Empty a Jug"
},
{
"code": null,
"e": 769,
"s": 758,
"text": "Fill a Jug"
},
{
"code": null,
"e": 853,
"s": 769,
"text": "Pour water from one jug to the other until one of the jugs is either empty or full."
},
{
"code": null,
"e": 866,
"s": 855,
"text": "Example 1:"
},
{
"code": null,
"e": 1383,
"s": 866,
"text": "Input: m = 3, n = 5, d = 4\nOutput: 6\nExplanation: Operations are as follow-\n1. Fill up the 5 litre jug.\n2. Then fill up the 3 litre jug using 5 litre\n jug. Now 5 litre jug contains 2 litre water.\n3. Empty the 3 litre jug.\n4. Now pour the 2 litre of water from 5 litre \n jug to 3 litre jug.\n5. Now 3 litre jug contains 2 litre of water \n and 5 litre jug is empty. Now fill up the \n 5 litre jug.\n6. Now fill one litre of water from 5 litre jug \n to 3 litre jug. Now we have 4 litre water in \n 5 litre jug.\n"
},
{
"code": null,
"e": 1394,
"s": 1383,
"text": "Example 2:"
},
{
"code": null,
"e": 1513,
"s": 1394,
"text": "Input: m = 8, n = 56, d = 46\nOutput: -1\nExplanation: Not possible to fill any one of \nthe jug with 46 litre of water.\n"
},
{
"code": null,
"e": 1754,
"s": 1515,
"text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function minSteps() which takes m, n and d ans input parameter and returns the minimum number of operation to fill d litre of water in any of the two jug.\n "
},
{
"code": null,
"e": 1859,
"s": 1754,
"text": "Expected Time Comeplxity: O(d)\nExpected Space Complexity: O(1)\n\nConstraints:\n1 ≤ n ≤ m ≤ 100\n1 ≤ d ≤ 100"
},
{
"code": null,
"e": 1861,
"s": 1859,
"text": "0"
},
{
"code": null,
"e": 1888,
"s": 1861,
"text": "yashmandaviya7021 week ago"
},
{
"code": null,
"e": 1961,
"s": 1888,
"text": "in case any one want to print the path of operations as in explanation :"
},
{
"code": null,
"e": 5107,
"s": 1961,
"text": "vector<string> bfsfill(int a,int b,int c){ queue<string> q; unordered_map<string,int> level; unordered_map<string,string> parent; string f = \"0_0\"; parent[f] = \"-1\"; level[f] = 0; q.push(f); while(!q.empty()){ auto cv = q.front(); q.pop(); stringstream ss(cv); string s1,s2; getline(ss,s1,'_'); getline(ss,s2,'_'); int x = stoi(s1),y = stoi(s2); if((x==c && y==0)||(x==0 && y==c)) break; // /* // x,y -> a,y // x,y -> x,b // x,y -> 0,y // x,y -> x,0 // x,y -> a,y-(a-x) if(x+y>=a) // x,y -> x-(b-y),b if(x+y>=b) // x,y -> x+y,0 if(x+y<=a) // x,y -> 0,x+y if(x+y<=b) // */ if(x<a && level.find(to_string(a)+\"_\"+to_string(y))==level.end()){ level[to_string(a)+\"_\"+to_string(y)] = level[cv]+1; parent[to_string(a)+\"_\"+to_string(y)] = cv; q.push(to_string(a)+\"_\"+to_string(y)); } if(y<b && level.find(to_string(x)+\"_\"+to_string(b))==level.end()){ level[to_string(x)+\"_\"+to_string(b)] = level[cv]+1; parent[to_string(x)+\"_\"+to_string(b)] = cv; q.push(to_string(x)+\"_\"+to_string(b)); } if(level.find(to_string(0)+\"_\"+to_string(y))==level.end()){ level[to_string(0)+\"_\"+to_string(y)] = level[cv]+1; parent[to_string(0)+\"_\"+to_string(y)] = cv; q.push(to_string(0)+\"_\"+to_string(y)); } if(level.find(to_string(x)+\"_\"+to_string(0))==level.end()){ level[to_string(x)+\"_\"+to_string(0)] = level[cv]+1; parent[to_string(x)+\"_\"+to_string(0)] = cv; q.push(to_string(x)+\"_\"+to_string(0)); } if(x+y>=a && level.find(to_string(a)+\"_\"+to_string(y-a+x))==level.end()){ level[to_string(a)+\"_\"+to_string(y-a+x)] = level[cv]+1; parent[to_string(a)+\"_\"+to_string(y-a+x)] = cv; q.push(to_string(a)+\"_\"+to_string(y-a+x)); } if(x+y>=b && level.find(to_string(x-b+y)+\"_\"+to_string(b))==level.end()){ level[to_string(x-b+y)+\"_\"+to_string(b)] = level[cv]+1; parent[to_string(x-b+y)+\"_\"+to_string(b)] = cv; q.push(to_string(x-b+y)+\"_\"+to_string(b)); } if(x+y<=a && level.find(to_string(x+y)+\"_\"+to_string(0))==level.end()){ level[to_string(x+y)+\"_\"+to_string(0)] = level[cv]+1; parent[to_string(x+y)+\"_\"+to_string(0)] = cv; q.push(to_string(x+y)+\"_\"+to_string(0)); } if(x+y<=b && level.find(to_string(0)+\"_\"+to_string(x+y))==level.end()){ level[to_string(0)+\"_\"+to_string(x+y)] = level[cv]+1; parent[to_string(0)+\"_\"+to_string(x+y)] = cv; q.push(to_string(0)+\"_\"+to_string(x+y)); } } vector<string> ans; int l1 = INT_MAX,l2 = INT_MAX; if(level.find(to_string(0)+\"_\"+to_string(c))!=level.end()) l1 = level[to_string(0)+\"_\"+to_string(c)]; if(level.find(to_string(c)+\"_\"+to_string(0))!=level.end()) l2 = level[to_string(c)+\"_\"+to_string(0)]; if(l1<l2){ string aa = to_string(0)+\"_\"+to_string(c); while(level[aa]!=0){ ans.push_back(aa); aa=parent[aa]; } } else{ string aa = to_string(c)+\"_\"+to_string(0); while(level[aa]!=0){ ans.push_back(aa); aa=parent[aa]; } } reverse(ans.begin(),ans.end()); return ans; }"
},
{
"code": null,
"e": 5110,
"s": 5107,
"text": "+2"
},
{
"code": null,
"e": 5130,
"s": 5110,
"text": "putyavka3 weeks ago"
},
{
"code": null,
"e": 5150,
"s": 5130,
"text": "Time: 0.02/1.12 sec"
},
{
"code": null,
"e": 5680,
"s": 5150,
"text": "int minSteps(int m, int n, int d) {\n if (d == m || d == n) return 1;\n if (m == n) return -1;\n int k = m, c = 2, c1 = 0, c2 = 0;\n while (k) { // pour from small to big\n if (d == k) { c1 = c; break; }\n if (k < m) c += 4; else c += 2;\n k += m;\n if (k >= n) k -= n;\n }\n if (!c1) return -1;\n k = n - m, c = 2;\n while (k) { // pour from big to small\n if (d == k) { c2 = c; break; }\n c += 2; k -= m;\n if (k < 0) { c += 2; k += n; }\n }\n return min(c1, c2);\n}"
},
{
"code": null,
"e": 5682,
"s": 5680,
"text": "0"
},
{
"code": null,
"e": 5698,
"s": 5682,
"text": "rp213 weeks ago"
},
{
"code": null,
"e": 5848,
"s": 5698,
"text": "There may be an issue with the given time complexity. Nonetheless most intuitive and easiest approach is BFS(for shortest paths in unweighted graph)."
},
{
"code": null,
"e": 5851,
"s": 5848,
"text": "-1"
},
{
"code": null,
"e": 5877,
"s": 5851,
"text": "subhamkumar0321 month ago"
},
{
"code": null,
"e": 6725,
"s": 5877,
"text": "class Solution{\n\tpublic:\n\tint gcd(int a, int b)\n\t{\n\t if (b==0)\n\t return a;\n\t return gcd(b, a%b);\n\t}\n\tint pour(int fromCap, int toCap, int d)\n\t{\n\t int from = fromCap;\n\t int to = 0;\n\t int step = 1;\n\t while (from != d && to != d)\n\t {\n\t int temp = min(from, toCap - to);\n\t to += temp;\n\t from -= temp;\n\t step++;\n\t \n\t if (from == d || to == d)\n\t break;\n\t if (from == 0)\n\t {\n\t from = fromCap;\n\t step++;\n\t }\n\t if (to == toCap)\n\t {\n\t to = 0;\n\t step++;\n\t }\n\t }\n\t return step;\n\t}\n\tint minSteps(int m, int n, int d)\n\t{\n\t if (m > n)\n\t swap(m, n);\n\t if (d > n)\n\t return -1;\n\t if ((d % gcd(n,m)) != 0)\n\t return -1;\n return min(pour(n,m,d),pour(m,n,d));\n\t}\n};"
},
{
"code": null,
"e": 6727,
"s": 6725,
"text": "0"
},
{
"code": null,
"e": 6750,
"s": 6727,
"text": "prabhxjott2 months ago"
},
{
"code": null,
"e": 6760,
"s": 6750,
"text": "38 78 100"
},
{
"code": null,
"e": 6800,
"s": 6760,
"text": "Why is it giving -1 for this testCase ?"
},
{
"code": null,
"e": 6802,
"s": 6800,
"text": "0"
},
{
"code": null,
"e": 6816,
"s": 6802,
"text": "agrimjain2411"
},
{
"code": null,
"e": 6842,
"s": 6816,
"text": "This comment was deleted."
},
{
"code": null,
"e": 6844,
"s": 6842,
"text": "0"
},
{
"code": null,
"e": 6870,
"s": 6844,
"text": "diptendunandi5 months ago"
},
{
"code": null,
"e": 8044,
"s": 6870,
"text": "\tint m,n,N;\n\tint get_index(int i, int j){\n\t return i*N+j;\n\t}\n\tpair<int,int> get_cor(int index){\n\t return {index/N,index%N};\n\t}\n\tvoid check(queue <int> &q, unordered_map<int,bool> &vis, int i ,int j){\n\t if (i<0 || j<0 || i>m || j>n) return;\n\t int idx = get_index(i,j);\n\t if(vis.find(idx)!=vis.end()) return ;\n\t vis[idx] = true;\n\t q.push(idx);\n\t}\n\tint minSteps(int m, int n, int d)\n\t{\n\t if(m > n) swap(m,n);\n\t if(d>n) return -1;\n\t this->m = m;\n\t this-> n = n;\n\t this-> N = n+10;\n\t unordered_map<int,bool> mp;\n\t mp[0] = true;\n\t queue<int> q;\n\t q.push(0);\n\t int level = 0;\n\t while(!q.empty()){\n\t int t = q.size();\n\t for(int k =0;k<t;k++){\n\t auto p =get_cor(q.front());\n\t q.pop();\n\t int i = p.first, j = p.second;\n\t if(i==d || j==d) return level;\n\t check(q,mp,i,0);\n\t check(q,mp,0,j);\n\t check(q,mp,m,j);\n\t check(q,mp,i,n);\n\t check(q,mp,0,i+j);\n\t check(q,mp,i+j,0);\n\t check(q,mp,i - (n-j),n);\n\t check(q,mp,m, j - (m - i));\n\t }\n\t level++;\n\t }\n\t return -1;\n \n\t}"
},
{
"code": null,
"e": 8046,
"s": 8044,
"text": "0"
},
{
"code": null,
"e": 8074,
"s": 8046,
"text": "himanshujain4576 months ago"
},
{
"code": null,
"e": 8096,
"s": 8074,
"text": "Very Simple Approach:"
},
{
"code": null,
"e": 8224,
"s": 8096,
"text": "int minSteps(int m, int n, int d){ int c1=m,c2=0,cnt=1,cnt2=1; if(d>m and d>n) return -1; map<pair<int,int>,int>mp;"
},
{
"code": null,
"e": 8659,
"s": 8224,
"text": "//CASE1:always pour water from jug 1 to jug2 if at any stage jug1 become empty fill it again or if jug2 fill fully empty it again until one of the jug have d litre of water while(c1!=d and c2!=d) { mp[{c1,c2}]++; int remain=n-c2; if(remain>=c1) { cnt++; c2+=c1; c1=0; } else { c2+=remain; c1-=remain; cnt++; }"
},
{
"code": null,
"e": 8886,
"s": 8659,
"text": "//if at any stage c1 or c2 become equals to d then break the loop if(c1==d||c2==d) break; if(c1==0) { c1=m; cnt++; } if(c2==n) { c2=0; cnt++; }"
},
{
"code": null,
"e": 9065,
"s": 8886,
"text": "//if at any stage same procedure starts following again then break the loop if(mp.find({c1,c2})!=mp.end()) { cnt=-1; break; } }"
},
{
"code": null,
"e": 9541,
"s": 9065,
"text": "//CASE2:always pour water from jug 2 to jug1 if at any stage jug2 become empty fill it again or if jug1 fill fully empty it again until one of the jug have d litre of water mp.clear(); c1=0; c2=n; while(c1!=d and c2!=d) { mp[{c1,c2}]++; int remain=m-c1; if(remain>=c2) { cnt2++; c1+=c2;; c2=0; } else { cnt2++; c1+=remain; c2-=remain; }"
},
{
"code": null,
"e": 9772,
"s": 9541,
"text": "//if at any stage c1 or c2 become equals to d then break the loop if(c1==d||c2==d) break; if(c1==m) { c1=0; cnt2++; } if(c2==0) { c2=n; cnt2++; }"
},
{
"code": null,
"e": 10078,
"s": 9774,
"text": "//if at any stage same procedure starts following again then break the loop if(mp.find({c1,c2})!=mp.end()) { cnt2=-1; break; } } if(cnt==-1 and cnt2==-1)return -1; if(cnt==-1)return cnt2; if(cnt2==-1)return cnt; return min(cnt,cnt2); }"
},
{
"code": null,
"e": 10080,
"s": 10078,
"text": "0"
},
{
"code": null,
"e": 10114,
"s": 10080,
"text": "perumallayaswanth20008 months ago"
},
{
"code": null,
"e": 10160,
"s": 10114,
"text": "Can some one help me to answer this question."
},
{
"code": null,
"e": 10227,
"s": 10160,
"text": "For this test case i am getting answer as 108 but i am getting 110"
},
{
"code": null,
"e": 10236,
"s": 10227,
"text": "46 65 23"
},
{
"code": null,
"e": 10483,
"s": 10236,
"text": "This is my code. Please do read comments for better understanding.My approach is starting with both empty jugs performing all operations on each jug and bfs. If i got the required water in any jug at any point of time i return the bfs call count."
},
{
"code": null,
"e": 13909,
"s": 10483,
"text": "class Solution\n{\n public int minSteps(int m, int n, int d){\n Pair pair=new Pair(0,0);\n Queue<Pair>q= new LinkedList<>();\n q.add(pair);\n return bfs(q,m,n,d,-1);\n }\n \n int bfs(Queue<Pair>q,int m,int n,int d,int c){\n ArrayList<String>al=new ArrayList<>();\n while(!q.isEmpty()){\n int size=q.size();\n c++;\n while(size-->0){\n Pair popped=q.poll();\n if(popped.u==d || popped.v==d)\n return c;\n \n //empty jug1\n Pair emptyu=new Pair(0,popped.v);\n String eu=Integer.toString(emptyu.u)+Integer.toString(emptyu.v);\n if(popped.u!=0 && !al.contains(eu)){\n q.add(emptyu);\n al.add(eu);\n }\n \n //empty jug2\n Pair emptyv=new Pair(popped.u,0);\n String ev=Integer.toString(emptyv.u)+Integer.toString(emptyv.v);\n if(popped.v!=0 && !al.contains(ev)){\n q.add(emptyv);\n al.add(ev);\n }\n \n //fill jug1\n Pair fillu=new Pair(m,popped.v);\n String fu=Integer.toString(fillu.u)+Integer.toString(fillu.v);\n if(popped.u!=m && !al.contains(fu)){\n q.add(fillu);\n al.add(fu);\n }\n \n //fill jug2\n Pair fillv=new Pair(popped.u,n);\n String fv=Integer.toString(fillv.u)+Integer.toString(fillv.v);\n if(popped.v!=n && !al.contains(fv)){\n q.add(fillv);\n al.add(fv);\n }\n \n \n //transfer from jug1 to jug2\n int vremain=n-popped.v;\n if(popped.u!=0 && vremain>0){\n String su1=Integer.toString(0)+Integer.toString(popped.v+popped.u);\n String su2=Integer.toString(popped.u-vremain)+Integer.toString(n); \n //if jug2 has more space than jug1\n if(vremain>popped.u && !al.contains(su1)){\n q.add(new Pair(0,popped.v+popped.u));\n al.add(su1);\n }\n //if jug1 has more space than jug2\n else if(vremain<popped.u && !al.contains(su2)){\n q.add(new Pair(popped.u-vremain,n));\n al.add(su2);\n }\n }\n \n //transfer from jug2 to jug1\n int uremain=m-popped.u;\n if(popped.v!=0 && uremain>0){\n String su3=Integer.toString(popped.v+popped.u)+Integer.toString(0);\n String su4=Integer.toString(m)+Integer.toString(popped.v-uremain); \n if(uremain>popped.v && !al.contains(su3)){\n q.add(new Pair(popped.v+popped.u,0));\n al.add(su3);\n }\n \n else if(uremain<popped.v && !al.contains(su4)){\n q.add(new Pair(m,popped.v-uremain));\n al.add(su4);\n }\n }\n }\n }\n return -1;\n }\n}\n\nclass Pair{\n int u;\n int v;\n Pair(int u,int v){\n this.u=u;\n this.v=v;\n }\n}"
},
{
"code": null,
"e": 13913,
"s": 13911,
"text": "0"
},
{
"code": null,
"e": 13936,
"s": 13913,
"text": "geminicode9 months ago"
},
{
"code": null,
"e": 13974,
"s": 13936,
"text": "Was anyone able to submit in python??"
},
{
"code": null,
"e": 14120,
"s": 13974,
"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": 14156,
"s": 14120,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 14166,
"s": 14156,
"text": "\nProblem\n"
},
{
"code": null,
"e": 14176,
"s": 14166,
"text": "\nContest\n"
},
{
"code": null,
"e": 14239,
"s": 14176,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 14424,
"s": 14239,
"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": 14708,
"s": 14424,
"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": 14854,
"s": 14708,
"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": 14931,
"s": 14854,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 14972,
"s": 14931,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 15000,
"s": 14972,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 15071,
"s": 15000,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 15258,
"s": 15071,
"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."
}
] |
Sort Dataframe according to row frequency in Pandas | 24 Feb, 2021
In this article, we will discuss how to use count() and sort_values() in pandas. So the count in pandas counts the frequency of elements in the dataframe column and then sort sorts the dataframe according to element frequency.
count(): This method will show you the number of values for each column in your DataFrame.
sort_values(): This method helps us to sort our dataframe. In this method, we pass the column and our data frame is sorted according to this column.
Example 1: Program to sort data frame in descending order according to the element frequency.
Python
# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({'Name': ['Mukul', 'Rohan', 'Mukul', 'Manoj', 'Kamal', 'Rohan', 'Robin'], 'age': [22, 22, 21, 20, 21, 24, 20]}) # print dataframeprint(df) # use count() and sort()df = df.groupby(['Name'])['age'].count().reset_index( name='Count').sort_values(['Count'], ascending=False) # print dataframeprint(df)
Output:
Example 2: Program to sort data frame in ascending order according to the element frequency.
Python
# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({'Name': ['Mukul', 'Rohan', 'Mukul', 'Manoj', 'Kamal', 'Rohan', 'Robin'], 'age': [22, 22, 21, 20, 21, 24, 20]}) # print dataframeprint(df) # use count() and sort()df = df.groupby(['Name'])['age'].count().reset_index( name='Count').sort_values(['Count'], ascending=True) # print dataframeprint(df)
Output:
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Technical Scripter 2020
Python
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": "\n24 Feb, 2021"
},
{
"code": null,
"e": 255,
"s": 28,
"text": "In this article, we will discuss how to use count() and sort_values() in pandas. So the count in pandas counts the frequency of elements in the dataframe column and then sort sorts the dataframe according to element frequency."
},
{
"code": null,
"e": 346,
"s": 255,
"text": "count(): This method will show you the number of values for each column in your DataFrame."
},
{
"code": null,
"e": 495,
"s": 346,
"text": "sort_values(): This method helps us to sort our dataframe. In this method, we pass the column and our data frame is sorted according to this column."
},
{
"code": null,
"e": 589,
"s": 495,
"text": "Example 1: Program to sort data frame in descending order according to the element frequency."
},
{
"code": null,
"e": 596,
"s": 589,
"text": "Python"
},
{
"code": "# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({'Name': ['Mukul', 'Rohan', 'Mukul', 'Manoj', 'Kamal', 'Rohan', 'Robin'], 'age': [22, 22, 21, 20, 21, 24, 20]}) # print dataframeprint(df) # use count() and sort()df = df.groupby(['Name'])['age'].count().reset_index( name='Count').sort_values(['Count'], ascending=False) # print dataframeprint(df)",
"e": 1036,
"s": 596,
"text": null
},
{
"code": null,
"e": 1044,
"s": 1036,
"text": "Output:"
},
{
"code": null,
"e": 1137,
"s": 1044,
"text": "Example 2: Program to sort data frame in ascending order according to the element frequency."
},
{
"code": null,
"e": 1144,
"s": 1137,
"text": "Python"
},
{
"code": "# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({'Name': ['Mukul', 'Rohan', 'Mukul', 'Manoj', 'Kamal', 'Rohan', 'Robin'], 'age': [22, 22, 21, 20, 21, 24, 20]}) # print dataframeprint(df) # use count() and sort()df = df.groupby(['Name'])['age'].count().reset_index( name='Count').sort_values(['Count'], ascending=True) # print dataframeprint(df)",
"e": 1583,
"s": 1144,
"text": null
},
{
"code": null,
"e": 1591,
"s": 1583,
"text": "Output:"
},
{
"code": null,
"e": 1598,
"s": 1591,
"text": "Picked"
},
{
"code": null,
"e": 1622,
"s": 1598,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1645,
"s": 1622,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 1659,
"s": 1645,
"text": "Python-pandas"
},
{
"code": null,
"e": 1683,
"s": 1659,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1690,
"s": 1683,
"text": "Python"
},
{
"code": null,
"e": 1709,
"s": 1690,
"text": "Technical Scripter"
}
] |
Python NLTK | nltk.tokenizer.word_tokenize() | 12 Jun, 2019
With the help of nltk.tokenize.word_tokenize() method, we are able to extract the tokens from string of characters by using tokenize.word_tokenize() method. It actually returns the syllables from a single word. A single word can contain one or two syllables.
Syntax : tokenize.word_tokenize()Return : Return the list of syllables of words.
Example #1 :In this example we can see that by using tokenize.word_tokenize() method, we are able to extract the syllables from stream of words or sentences.
# import SyllableTokenizer() method from nltkfrom nltk import word_tokenize # Create a reference variable for Class word_tokenizetk = SyllableTokenizer() # Create a string inputgfg = "Antidisestablishmentarianism" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)
Output :
[‘An’, ‘ti’, ‘dis’, ‘es’, ‘ta’, ‘blish’, ‘men’, ‘ta’, ‘ria’, ‘nism’]
Example #2 :
# import SyllableTokenizer() method from nltkfrom nltk.tokenize import word_tokenize # Create a reference variable for Class word_tokenizetk = SyllableTokenizer() # Create a string inputgfg = "Gametophyte" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)
Output :
[‘Ga’, ‘me’, ‘to’, ‘phy’, ‘te’]
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
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
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jun, 2019"
},
{
"code": null,
"e": 311,
"s": 52,
"text": "With the help of nltk.tokenize.word_tokenize() method, we are able to extract the tokens from string of characters by using tokenize.word_tokenize() method. It actually returns the syllables from a single word. A single word can contain one or two syllables."
},
{
"code": null,
"e": 392,
"s": 311,
"text": "Syntax : tokenize.word_tokenize()Return : Return the list of syllables of words."
},
{
"code": null,
"e": 550,
"s": 392,
"text": "Example #1 :In this example we can see that by using tokenize.word_tokenize() method, we are able to extract the syllables from stream of words or sentences."
},
{
"code": "# import SyllableTokenizer() method from nltkfrom nltk import word_tokenize # Create a reference variable for Class word_tokenizetk = SyllableTokenizer() # Create a string inputgfg = \"Antidisestablishmentarianism\" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)",
"e": 837,
"s": 550,
"text": null
},
{
"code": null,
"e": 846,
"s": 837,
"text": "Output :"
},
{
"code": null,
"e": 915,
"s": 846,
"text": "[‘An’, ‘ti’, ‘dis’, ‘es’, ‘ta’, ‘blish’, ‘men’, ‘ta’, ‘ria’, ‘nism’]"
},
{
"code": null,
"e": 928,
"s": 915,
"text": "Example #2 :"
},
{
"code": "# import SyllableTokenizer() method from nltkfrom nltk.tokenize import word_tokenize # Create a reference variable for Class word_tokenizetk = SyllableTokenizer() # Create a string inputgfg = \"Gametophyte\" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)",
"e": 1207,
"s": 928,
"text": null
},
{
"code": null,
"e": 1216,
"s": 1207,
"text": "Output :"
},
{
"code": null,
"e": 1248,
"s": 1216,
"text": "[‘Ga’, ‘me’, ‘to’, ‘phy’, ‘te’]"
},
{
"code": null,
"e": 1260,
"s": 1248,
"text": "Python-nltk"
},
{
"code": null,
"e": 1267,
"s": 1260,
"text": "Python"
},
{
"code": null,
"e": 1365,
"s": 1267,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1407,
"s": 1365,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1429,
"s": 1407,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1455,
"s": 1429,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1487,
"s": 1455,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1516,
"s": 1487,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1543,
"s": 1516,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1564,
"s": 1543,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1600,
"s": 1564,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 1623,
"s": 1600,
"text": "Introduction To PYTHON"
}
] |
Matplotlib.axes.Axes.remove() in Python | 19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.remove() function in axes module of matplotlib library is used to remove the artist from the figure if possible.
Syntax:
Axes.remove(self)
Below examples illustrate the matplotlib.axes.Axes.remove() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, axs = plt.subplots()axs.plot([1, 2, 3])axs.remove() fig.suptitle('matplotlib.axes.Axes.remove()\ function Example', fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, (axs, axs2) = plt.subplots(2, 1)gs = axs2.get_gridspec() axs.remove() axbig = fig.add_subplot(gs[1:, -1])axbig.annotate("Removed one Axes", (0.4, 0.5), xycoords ='axes fraction', va ='center') fig.suptitle('matplotlib.axes.Axes.remove()\ function Example', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
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": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 450,
"s": 328,
"text": "The Axes.remove() function in axes module of matplotlib library is used to remove the artist from the figure if possible."
},
{
"code": null,
"e": 458,
"s": 450,
"text": "Syntax:"
},
{
"code": null,
"e": 477,
"s": 458,
"text": "Axes.remove(self)\n"
},
{
"code": null,
"e": 566,
"s": 477,
"text": "Below examples illustrate the matplotlib.axes.Axes.remove() function in matplotlib.axes:"
},
{
"code": null,
"e": 577,
"s": 566,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, axs = plt.subplots()axs.plot([1, 2, 3])axs.remove() fig.suptitle('matplotlib.axes.Axes.remove()\\ function Example', fontweight =\"bold\") plt.show()",
"e": 803,
"s": 577,
"text": null
},
{
"code": null,
"e": 811,
"s": 803,
"text": "Output:"
},
{
"code": null,
"e": 822,
"s": 811,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, (axs, axs2) = plt.subplots(2, 1)gs = axs2.get_gridspec() axs.remove() axbig = fig.add_subplot(gs[1:, -1])axbig.annotate(\"Removed one Axes\", (0.4, 0.5), xycoords ='axes fraction', va ='center') fig.suptitle('matplotlib.axes.Axes.remove()\\ function Example', fontweight =\"bold\")plt.show()",
"e": 1236,
"s": 822,
"text": null
},
{
"code": null,
"e": 1244,
"s": 1236,
"text": "Output:"
},
{
"code": null,
"e": 1262,
"s": 1244,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1269,
"s": 1262,
"text": "Python"
},
{
"code": null,
"e": 1367,
"s": 1269,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1399,
"s": 1367,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1426,
"s": 1399,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1447,
"s": 1426,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1478,
"s": 1447,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1534,
"s": 1478,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1557,
"s": 1534,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1599,
"s": 1557,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1641,
"s": 1599,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1680,
"s": 1641,
"text": "Python | datetime.timedelta() function"
}
] |
Express.js req.query Property | 08 Jul, 2020
The req.query property is an object containing the property for each query string parameter in the route.
Syntax:
req.query
Parameter: No parameters.
Return Value: String
Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install express module. You can install this package by using this command.npm install express
npm install express
After installing the express module, you can check your express version in command prompt using the command.npm version express
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Example 1: Filename: index.js
var express = require('express');var app = express(); var PORT = 3000; app.get('/profile', function (req, res) { console.log(req.query.name); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000
Now open your browser and go to http://localhost:3000/profile?name=Gourav, now you can see the following output on your console:Server listening on PORT 3000
Gourav
The project structure will look like this:
Make sure you have installed express module using the following command:npm install express
npm install express
Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000
node index.js
Output:
Server listening on PORT 3000
Now open your browser and go to http://localhost:3000/profile?name=Gourav, now you can see the following output on your console:Server listening on PORT 3000
Gourav
Server listening on PORT 3000
Gourav
Example 2: Filename: index.js
var express = require('express');var app = express(); var PORT = 3000; app.get('/user', function (req, res) { console.log("Name: ", req.query.name); console.log("Age:", req.query.age); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Run index.js file using below command:
node index.js
Output: Now open your browser and make GET request to http://localhost:3000/user?name=Gourav&age=11, now you can see the following output on your console:
Server listening on PORT 3000
Name: Gourav
Age: 11
Reference: https://expressjs.com/en/4x/api.html#req.query
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Windows
JWT Authentication with Node.js
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2020"
},
{
"code": null,
"e": 158,
"s": 52,
"text": "The req.query property is an object containing the property for each query string parameter in the route."
},
{
"code": null,
"e": 166,
"s": 158,
"text": "Syntax:"
},
{
"code": null,
"e": 176,
"s": 166,
"text": "req.query"
},
{
"code": null,
"e": 202,
"s": 176,
"text": "Parameter: No parameters."
},
{
"code": null,
"e": 223,
"s": 202,
"text": "Return Value: String"
},
{
"code": null,
"e": 255,
"s": 223,
"text": "Installation of express module:"
},
{
"code": null,
"e": 650,
"s": 255,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 771,
"s": 650,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install express"
},
{
"code": null,
"e": 791,
"s": 771,
"text": "npm install express"
},
{
"code": null,
"e": 919,
"s": 791,
"text": "After installing the express module, you can check your express version in command prompt using the command.npm version express"
},
{
"code": null,
"e": 939,
"s": 919,
"text": "npm version express"
},
{
"code": null,
"e": 1087,
"s": 939,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 1101,
"s": 1087,
"text": "node index.js"
},
{
"code": null,
"e": 1131,
"s": 1101,
"text": "Example 1: Filename: index.js"
},
{
"code": "var express = require('express');var app = express(); var PORT = 3000; app.get('/profile', function (req, res) { console.log(req.query.name); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 1407,
"s": 1131,
"text": null
},
{
"code": null,
"e": 1433,
"s": 1407,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 1820,
"s": 1433,
"text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow open your browser and go to http://localhost:3000/profile?name=Gourav, now you can see the following output on your console:Server listening on PORT 3000\nGourav\n"
},
{
"code": null,
"e": 1863,
"s": 1820,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 1955,
"s": 1863,
"text": "Make sure you have installed express module using the following command:npm install express"
},
{
"code": null,
"e": 1975,
"s": 1955,
"text": "npm install express"
},
{
"code": null,
"e": 2064,
"s": 1975,
"text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n"
},
{
"code": null,
"e": 2078,
"s": 2064,
"text": "node index.js"
},
{
"code": null,
"e": 2086,
"s": 2078,
"text": "Output:"
},
{
"code": null,
"e": 2117,
"s": 2086,
"text": "Server listening on PORT 3000\n"
},
{
"code": null,
"e": 2283,
"s": 2117,
"text": "Now open your browser and go to http://localhost:3000/profile?name=Gourav, now you can see the following output on your console:Server listening on PORT 3000\nGourav\n"
},
{
"code": null,
"e": 2321,
"s": 2283,
"text": "Server listening on PORT 3000\nGourav\n"
},
{
"code": null,
"e": 2351,
"s": 2321,
"text": "Example 2: Filename: index.js"
},
{
"code": "var express = require('express');var app = express(); var PORT = 3000; app.get('/user', function (req, res) { console.log(\"Name: \", req.query.name); console.log(\"Age:\", req.query.age); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 2671,
"s": 2351,
"text": null
},
{
"code": null,
"e": 2710,
"s": 2671,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 2724,
"s": 2710,
"text": "node index.js"
},
{
"code": null,
"e": 2879,
"s": 2724,
"text": "Output: Now open your browser and make GET request to http://localhost:3000/user?name=Gourav&age=11, now you can see the following output on your console:"
},
{
"code": null,
"e": 2931,
"s": 2879,
"text": "Server listening on PORT 3000\nName: Gourav\nAge: 11\n"
},
{
"code": null,
"e": 2989,
"s": 2931,
"text": "Reference: https://expressjs.com/en/4x/api.html#req.query"
},
{
"code": null,
"e": 3000,
"s": 2989,
"text": "Express.js"
},
{
"code": null,
"e": 3008,
"s": 3000,
"text": "Node.js"
},
{
"code": null,
"e": 3025,
"s": 3008,
"text": "Web Technologies"
},
{
"code": null,
"e": 3123,
"s": 3025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3158,
"s": 3123,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 3190,
"s": 3158,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 3260,
"s": 3190,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 3287,
"s": 3260,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 3312,
"s": 3287,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 3374,
"s": 3312,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3435,
"s": 3374,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3485,
"s": 3435,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3528,
"s": 3485,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Inshackle – Tool for Instagram Hacks in Kali Linux | 13 Jun, 2022
Inshackle – Instagram Hacks: is an open-source intelligence tool available freely on GitHub. Inshackle is written in bash language. Inshackle is used to perform reconnaissance on Instagram accounts and profiles. Inshackle is very helpful when you want to get information about any Instagram profile that a normal user cannot see. The tool can be used to increase followers, download stories of the profiles, track unfollows etc. As this tool is open source so you can contribute to this tool. Inshackle gives you the location, timestamp of posts posted by Instagram users. Inshackle is a powerful tool for manipulating social media using linux technology.
Inshackle can be used to Unfollow Tracker.
Inshackle can be used to Increase Followers.
Inshackle can be used to Download: Stories, Saved Content, Following/followers list, Profile Info.
Inshackle can be used to Unfollow all your following.
Step 1: Open your kali linux operating system and use the following command to install the tool.
git clone https://github.com/thelinuxchoice/inshackle
Step 2: Now use the following command to move into the directory of the tool.
cd inshackle
Step 3: Now use the following command to run the tool.
bash inshackle.sh
The tool has been downloaded and running successfully. Now we will see examples to use the tool.
Example 1: Use the Inshackle tool to increase followers.
choose option 2
2
Now login with your username and password.
The tool has started increasing followers.
This is how you can increase your followers.
krishna_97
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 713,
"s": 52,
"text": "Inshackle – Instagram Hacks: is an open-source intelligence tool available freely on GitHub. Inshackle is written in bash language. Inshackle is used to perform reconnaissance on Instagram accounts and profiles. Inshackle is very helpful when you want to get information about any Instagram profile that a normal user cannot see. The tool can be used to increase followers, download stories of the profiles, track unfollows etc. As this tool is open source so you can contribute to this tool. Inshackle gives you the location, timestamp of posts posted by Instagram users. Inshackle is a powerful tool for manipulating social media using linux technology."
},
{
"code": null,
"e": 756,
"s": 713,
"text": "Inshackle can be used to Unfollow Tracker."
},
{
"code": null,
"e": 801,
"s": 756,
"text": "Inshackle can be used to Increase Followers."
},
{
"code": null,
"e": 900,
"s": 801,
"text": "Inshackle can be used to Download: Stories, Saved Content, Following/followers list, Profile Info."
},
{
"code": null,
"e": 954,
"s": 900,
"text": "Inshackle can be used to Unfollow all your following."
},
{
"code": null,
"e": 1051,
"s": 954,
"text": "Step 1: Open your kali linux operating system and use the following command to install the tool."
},
{
"code": null,
"e": 1105,
"s": 1051,
"text": "git clone https://github.com/thelinuxchoice/inshackle"
},
{
"code": null,
"e": 1183,
"s": 1105,
"text": "Step 2: Now use the following command to move into the directory of the tool."
},
{
"code": null,
"e": 1196,
"s": 1183,
"text": "cd inshackle"
},
{
"code": null,
"e": 1251,
"s": 1196,
"text": "Step 3: Now use the following command to run the tool."
},
{
"code": null,
"e": 1269,
"s": 1251,
"text": "bash inshackle.sh"
},
{
"code": null,
"e": 1366,
"s": 1269,
"text": "The tool has been downloaded and running successfully. Now we will see examples to use the tool."
},
{
"code": null,
"e": 1423,
"s": 1366,
"text": "Example 1: Use the Inshackle tool to increase followers."
},
{
"code": null,
"e": 1439,
"s": 1423,
"text": "choose option 2"
},
{
"code": null,
"e": 1441,
"s": 1439,
"text": "2"
},
{
"code": null,
"e": 1484,
"s": 1441,
"text": "Now login with your username and password."
},
{
"code": null,
"e": 1527,
"s": 1484,
"text": "The tool has started increasing followers."
},
{
"code": null,
"e": 1572,
"s": 1527,
"text": "This is how you can increase your followers."
},
{
"code": null,
"e": 1583,
"s": 1572,
"text": "krishna_97"
},
{
"code": null,
"e": 1594,
"s": 1583,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1606,
"s": 1594,
"text": "Linux-Tools"
},
{
"code": null,
"e": 1617,
"s": 1606,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1715,
"s": 1617,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1741,
"s": 1715,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1776,
"s": 1741,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1813,
"s": 1776,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1842,
"s": 1813,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1876,
"s": 1842,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1913,
"s": 1876,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1950,
"s": 1913,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 1989,
"s": 1950,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 2029,
"s": 1989,
"text": "Array Basics in Shell Scripting | Set 1"
}
] |
HTML DOM Window localStorage Properties | 25 Nov, 2021
HTML DOM Window localStorage Properties allow you to store value pairs in web browsers using objects. It is a read-only
property. This object is not expired even if the browser is closed. So, the data is never lost.
Return Values: It returns a Storage object.
Syntax:
SAVING data to localStorage using:localStorage.setItem("key", "value");
SAVING data to localStorage using:
localStorage.setItem("key", "value");
READING data from localStorage using:var name = localStorage.getItem("key");
READING data from localStorage using:
var name = localStorage.getItem("key");
REMOVING data from localStorage using:localStorage.removeItem("key");
REMOVING data from localStorage using:
localStorage.removeItem("key");
Example1: This example describes the Save, Read and Remove data to localStorage.
HTML
<!DOCTYPE html><html> <head> <title> HTML DOM Window localStorage Properties </title> <script> //Saving data locally function save() { var fieldValue = document.getElementById('textfield').value; localStorage.setItem('text', fieldValue); } // Reading data function get() { var storedValue = localStorage.getItem('text'); if(storedValue) { document.getElementById('textfield').value = storedValue; } } // Removing stored data function remove() { document.getElementById('textfield').value = ''; localStorage.removeItem('text'); } </script></head> <body onload="get()"> <p1> Type something in the text field and It will Get stored locally by Browser </p1> <input type="text" id="textfield" /> <input type="button" value="save" onclick="save()" /> <input type="button" value="clear" onclick="remove()" /> <p2> when you reopen or reload this page, your text is still there. </p2> <p3> <br>click on clear to remove it.</p3></body> </html>
Output:
Window localStorage
Example 2: This example describes the check storage type and saves data.
HTML
<!DOCTYPE html><html> <head> <title>HTML DOM Window localStorage Properties</title></head> <body> <div id="SHOW"></div> <script> if(typeof(Storage) !== "undefined") { localStorage.setItem("name", "GeeksforGeeks"); document.getElementById("SHOW").innerHTML = localStorage.getItem("name"); } else { document.getElementById("SHOW").innerHTML = "YOUR BROWSER DOES NOT" + "SUPPORT LOCALSTORAGE PROPERTY"; } </script></body> </html>
Output:
Window localStorage Property
Supported Browsers: The browser supported by DOM Window localStorage are listed below:
Google Chrome 4.0
Internet Explorer 8.0
Microsoft Edge 12.0
Firefox 3.5
Opera 10.5
Safari 4.0
bhaskargeeksforgeeks
ManasChhabra2
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "HTML DOM Window localStorage Properties allow you to store value pairs in web browsers using objects. It is a read-only"
},
{
"code": null,
"e": 244,
"s": 148,
"text": "property. This object is not expired even if the browser is closed. So, the data is never lost."
},
{
"code": null,
"e": 289,
"s": 244,
"text": "Return Values: It returns a Storage object."
},
{
"code": null,
"e": 297,
"s": 289,
"text": "Syntax:"
},
{
"code": null,
"e": 369,
"s": 297,
"text": "SAVING data to localStorage using:localStorage.setItem(\"key\", \"value\");"
},
{
"code": null,
"e": 404,
"s": 369,
"text": "SAVING data to localStorage using:"
},
{
"code": null,
"e": 442,
"s": 404,
"text": "localStorage.setItem(\"key\", \"value\");"
},
{
"code": null,
"e": 519,
"s": 442,
"text": "READING data from localStorage using:var name = localStorage.getItem(\"key\");"
},
{
"code": null,
"e": 557,
"s": 519,
"text": "READING data from localStorage using:"
},
{
"code": null,
"e": 597,
"s": 557,
"text": "var name = localStorage.getItem(\"key\");"
},
{
"code": null,
"e": 667,
"s": 597,
"text": "REMOVING data from localStorage using:localStorage.removeItem(\"key\");"
},
{
"code": null,
"e": 706,
"s": 667,
"text": "REMOVING data from localStorage using:"
},
{
"code": null,
"e": 738,
"s": 706,
"text": "localStorage.removeItem(\"key\");"
},
{
"code": null,
"e": 819,
"s": 738,
"text": "Example1: This example describes the Save, Read and Remove data to localStorage."
},
{
"code": null,
"e": 824,
"s": 819,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML DOM Window localStorage Properties </title> <script> //Saving data locally function save() { var fieldValue = document.getElementById('textfield').value; localStorage.setItem('text', fieldValue); } // Reading data function get() { var storedValue = localStorage.getItem('text'); if(storedValue) { document.getElementById('textfield').value = storedValue; } } // Removing stored data function remove() { document.getElementById('textfield').value = ''; localStorage.removeItem('text'); } </script></head> <body onload=\"get()\"> <p1> Type something in the text field and It will Get stored locally by Browser </p1> <input type=\"text\" id=\"textfield\" /> <input type=\"button\" value=\"save\" onclick=\"save()\" /> <input type=\"button\" value=\"clear\" onclick=\"remove()\" /> <p2> when you reopen or reload this page, your text is still there. </p2> <p3> <br>click on clear to remove it.</p3></body> </html>",
"e": 1941,
"s": 824,
"text": null
},
{
"code": null,
"e": 1949,
"s": 1941,
"text": "Output:"
},
{
"code": null,
"e": 1969,
"s": 1949,
"text": "Window localStorage"
},
{
"code": null,
"e": 2042,
"s": 1969,
"text": "Example 2: This example describes the check storage type and saves data."
},
{
"code": null,
"e": 2047,
"s": 2042,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML DOM Window localStorage Properties</title></head> <body> <div id=\"SHOW\"></div> <script> if(typeof(Storage) !== \"undefined\") { localStorage.setItem(\"name\", \"GeeksforGeeks\"); document.getElementById(\"SHOW\").innerHTML = localStorage.getItem(\"name\"); } else { document.getElementById(\"SHOW\").innerHTML = \"YOUR BROWSER DOES NOT\" + \"SUPPORT LOCALSTORAGE PROPERTY\"; } </script></body> </html>",
"e": 2535,
"s": 2047,
"text": null
},
{
"code": null,
"e": 2543,
"s": 2535,
"text": "Output:"
},
{
"code": null,
"e": 2572,
"s": 2543,
"text": "Window localStorage Property"
},
{
"code": null,
"e": 2659,
"s": 2572,
"text": "Supported Browsers: The browser supported by DOM Window localStorage are listed below:"
},
{
"code": null,
"e": 2677,
"s": 2659,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 2699,
"s": 2677,
"text": "Internet Explorer 8.0"
},
{
"code": null,
"e": 2719,
"s": 2699,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 2731,
"s": 2719,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 2742,
"s": 2731,
"text": "Opera 10.5"
},
{
"code": null,
"e": 2753,
"s": 2742,
"text": "Safari 4.0"
},
{
"code": null,
"e": 2774,
"s": 2753,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 2788,
"s": 2774,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 2797,
"s": 2788,
"text": "HTML-DOM"
},
{
"code": null,
"e": 2804,
"s": 2797,
"text": "Picked"
},
{
"code": null,
"e": 2809,
"s": 2804,
"text": "HTML"
},
{
"code": null,
"e": 2826,
"s": 2809,
"text": "Web Technologies"
},
{
"code": null,
"e": 2831,
"s": 2826,
"text": "HTML"
}
] |
Longest increasing subarray | 19 Jan, 2022
Given an array containing n numbers. The problem is to find the length of the longest contiguous subarray such that every element in the subarray is strictly greater than its previous element in the same subarray. Time Complexity should be O(n).
Examples:
Input : arr[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}
Output : 5
The subarray is {3, 5, 7, 8, 9}
Input : arr[] = {12, 13, 1, 5, 4, 7, 8, 10, 10, 11}
Output : 4
The subarray is {4, 7, 8, 10}
Algorithm:
lenOfLongIncSubArr(arr, n)
Declare max = 1, len = 1
for i = 1 to n-1
if arr[i] > arr[i-1]
len++
else
if max < len
max = len
len = 1
if max < len
max = len
return max
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find the length of// longest increasing contiguous subarray#include <bits/stdc++.h> using namespace std; // function to find the length of longest increasing// contiguous subarrayint lenOfLongIncSubArr(int arr[], int n){ // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1; // traverse the array from the 2nd element for (int i=1; i<n; i++) { // if current element if greater than previous // element, then this element helps in building // up the previous increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less than the length // of the current increasing subarray. If true, // then update 'max' if (max < len) max = len; // reset 'len' to 1 as from this element // again the length of the new increasing // subarray is being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) max = len; // required maximum length return max;} // Driver program to test aboveint main(){ int arr[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Length = " << lenOfLongIncSubArr(arr, n); return 0; }
// JAVA Code to find length of// Longest increasing subarrayimport java.util.*; class GFG { // function to find the length of longest // increasing contiguous subarray public static int lenOfLongIncSubArr(int arr[], int n) { // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1; // traverse the array from the 2nd element for (int i=1; i<n; i++) { // if current element if greater than // previous element, then this element // helps in building up the previous // increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less // than the length of the current // increasing subarray. If true, // than update 'max' if (max < len) max = len; // reset 'len' to 1 as from this // element again the length of the // new increasing subarray is being // calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) max = len; // required maximum length return max; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}; int n = arr.length; System.out.println("Length = " + lenOfLongIncSubArr(arr, n)); } } // This code is contributed by Arnav Kr. Mandal.
# Python 3 implementation to find the length of# longest increasing contiguous subarray # function to find the length of longest# increasing contiguous subarraydef lenOfLongIncSubArr(arr, n) : # 'max' to store the length of longest # increasing subarray # 'len' to store the lengths of longest # increasing subarray at different # instants of time m = 1 l = 1 # traverse the array from the 2nd element for i in range(1, n) : # if current element if greater than previous # element, then this element helps in building # up the previous increasing subarray encountered # so far if (arr[i] > arr[i-1]) : l =l + 1 else : # check if 'max' length is less than the length # of the current increasing subarray. If true, # then update 'max' if (m < l) : m = l # reset 'len' to 1 as from this element # again the length of the new increasing # subarray is being calculated l = 1 # comparing the length of the last # increasing subarray with 'max' if (m < l) : m = l # required maximum length return m # Driver program to test above arr = [5, 6, 3, 5, 7, 8, 9, 1, 2]n = len(arr)print("Length = ", lenOfLongIncSubArr(arr, n)) # This code is contributed# by Nikita Tiwari.
// C# Code to find length of// Longest increasing subarrayusing System; class GFG { // function to find the length of longest // increasing contiguous subarray public static int lenOfLongIncSubArr(int[] arr, int n) { // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1; // traverse the array from the 2nd element for (int i = 1; i < n; i++) { // if current element if greater than // previous element, then this element // helps in building up the previous // increasing subarray encountered // so far if (arr[i] > arr[i - 1]) len++; else { // check if 'max' length is less // than the length of the current // increasing subarray. If true, // than update 'max' if (max < len) max = len; // reset 'len' to 1 as from this // element again the length of the // new increasing subarray is being // calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) max = len; // required maximum length return max; } /* Driver program to test above function */ public static void Main() { int[] arr = { 5, 6, 3, 5, 7, 8, 9, 1, 2 }; int n = arr.Length; Console.WriteLine("Length = " + lenOfLongIncSubArr(arr, n)); }} // This code is contributed by Sam007
<?php// PHP implementation to find the length of// longest increasing contiguous subarray // function to find the length of// longest increasing contiguous// subarrayfunction lenOfLongIncSubArr($arr, $n){ // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time $max = 1; $len = 1; // traverse the array from // the 2nd element for ($i = 1; $i < $n; $i++) { // if current element if // greater than previous // element, then this element // helps in building up the // previous increasing subarray // encountered so far if ($arr[$i] > $arr[$i-1]) $len++; else { // check if 'max' length is // less than the length // of the current increasing // subarray. If true, // then update 'max' if ($max < $len) $max = $len; // reset 'len' to 1 as // from this element // again the length of // the new increasing // subarray is being // calculated $len = 1; } } // comparing the length of the last // increasing subarray with 'max' if ($max < $len) $max = $len; // required maximum length return $max;} // Driver Code $arr = array(5, 6, 3, 5, 7, 8, 9, 1, 2); $n = sizeof($arr); echo "Length = ", lenOfLongIncSubArr($arr, $n); // This code is contributed by nitin mittal.?>
<script> // Javascript implementation to find the length of// longest increasing contiguous subarray // function to find the length of longest increasing// contiguous subarrayfunction lenOfLongIncSubArr(arr, n){ // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time var max = 1, len = 1; // traverse the array from the 2nd element for (var i=1; i<n; i++) { // if current element if greater than previous // element, then this element helps in building // up the previous increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less than the length // of the current increasing subarray. If true, // then update 'max' if (max < len) { max = len; } // reset 'len' to 1 as from this element // again the length of the new increasing // subarray is being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) { max = len; } // required maximum length return max;} // Driver program to test abovevar arr = [5, 6, 3, 5, 7, 8, 9, 1, 2];var n = arr.length;document.write("Length = " + lenOfLongIncSubArr(arr, n));// This code is contributed by shivani.</script>
Output:
Length = 5
Time Complexity: O(n)
How to print the subarray? We can print the subarray by keeping track of the index with the largest length.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find the length of// longest increasing contiguous subarray#include <bits/stdc++.h>using namespace std; // function to find the length of longest increasing// contiguous subarrayvoid printLogestIncSubArr(int arr[], int n){ // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1, maxIndex = 0; // traverse the array from the 2nd element for (int i=1; i<n; i++) { // if current element if greater than previous // element, then this element helps in building // up the previous increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less than the length // of the current increasing subarray. If true, // then update 'max' if (max < len) { max = len; // index assign the starting index of // longest increasing contiguous subarray. maxIndex = i - max; } // reset 'len' to 1 as from this element // again the length of the new increasing // subarray is being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) { max = len; maxIndex = n - max; } // Print the elements of longest increasing // contiguous subarray. for (int i=maxIndex; i<max+maxIndex; i++) cout << arr[i] << " ";} // Driver program to test aboveint main(){ int arr[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}; int n = sizeof(arr) / sizeof(arr[0]); printLogestIncSubArr(arr, n); return 0; }// This code is contributed by Dharmendra kumar
// JAVA Code For Longest increasing subarrayimport java.util.*; class GFG { // function to find the length of longest // increasing contiguous subarray public static void printLogestIncSubArr(int arr[], int n) { // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1, maxIndex = 0; // traverse the array from the 2nd element for (int i = 1; i < n; i++) { // if current element if greater than // previous element, then this element // helps in building up the previous // increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less // than the length of the current // increasing subarray. If true, // then update 'max' if (max < len) { max = len; // index assign the starting // index of longest increasing // contiguous subarray. maxIndex = i - max; } // reset 'len' to 1 as from this // element again the length of the // new increasing subarray is // being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) { max = len; maxIndex = n - max; } // Print the elements of longest // increasing contiguous subarray. for (int i = maxIndex; i < max+maxIndex; i++) System.out.print(arr[i] + " "); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}; int n = arr.length; printLogestIncSubArr(arr, n); }} // This code is contributed by Arnav Kr. Mandal.
# Python 3 implementation to find the length of# longest increasing contiguous subarray # function to find the length of longest increasing# contiguous subarraydef printLogestIncSubArr( arr, n) : # 'max' to store the length of longest # increasing subarray # 'len' to store the lengths of longest # increasing subarray at different # instants of time m = 1 l = 1 maxIndex = 0 # traverse the array from the 2nd element for i in range(1, n) : # if current element if greater than previous # element, then this element helps in building # up the previous increasing subarray # encountered so far if (arr[i] > arr[i-1]) : l =l + 1 else : # check if 'max' length is less than the length # of the current increasing subarray. If true, # then update 'max' if (m < l) : m = l # index assign the starting index of # longest increasing contiguous subarray. maxIndex = i - m # reset 'len' to 1 as from this element # again the length of the new increasing # subarray is being calculated l = 1 # comparing the length of the last # increasing subarray with 'max' if (m < l) : m = l maxIndex = n - m # Print the elements of longest # increasing contiguous subarray. for i in range(maxIndex, (m+maxIndex)) : print(arr[i] , end=" ") # Driver program to test abovearr = [5, 6, 3, 5, 7, 8, 9, 1, 2]n = len(arr)printLogestIncSubArr(arr, n) # This code is contributed# by Nikita Tiwari
// C# Code to print// Longest increasing subarrayusing System; class GFG { // function to find the length of longest // increasing contiguous subarray public static void printLogestIncSubArr(int[] arr, int n) { // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1, maxIndex = 0; // traverse the array from the 2nd element for (int i = 1; i < n; i++) { // if current element if greater than // previous element, then this element // helps in building up the previous // increasing subarray encountered // so far if (arr[i] > arr[i - 1]) len++; else { // check if 'max' length is less // than the length of the current // increasing subarray. If true, // then update 'max' if (max < len) { max = len; // index assign the starting // index of longest increasing // contiguous subarray. maxIndex = i - max; } // reset 'len' to 1 as from this // element again the length of the // new increasing subarray is // being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) { max = len; maxIndex = n - max; } // Print the elements of longest // increasing contiguous subarray. for (int i = maxIndex; i < max + maxIndex; i++) Console.Write(arr[i] + " "); } /* Driver program to test above function */ public static void Main() { int[] arr = { 5, 6, 3, 5, 7, 8, 9, 1, 2 }; int n = arr.Length; printLogestIncSubArr(arr, n); }} // This code is contributed by Sam007
<?php// PHP implementation to find// the length of longest increasing// contiguous subarray // function to find the length of// longest increasing contiguous subarrayfunction printLogestIncSubArr(&$arr, $n){ // 'max' to store the length of // longest increasing subarray // 'len' to store the lengths of // longest increasing subarray at // different instants of time $max = 1; $len = 1; $maxIndex = 0; // traverse the array from // the 2nd element for ($i = 1; $i < $n; $i++) { // if current element if greater // than previous element, then // this element helps in building // up the previous increasing // subarray encountered so far if ($arr[$i] > $arr[$i - 1]) $len++; else { // check if 'max' length is less // than the length of the current // increasing subarray. If true, // then update 'max' if ($max < $len) { $max = $len; // index assign the starting // index of longest increasing // contiguous subarray. $maxIndex = $i - $max; } // reset 'len' to 1 as from this // element again the length of // the new increasing subarray // is being calculated $len = 1; } } // comparing the length of // the last increasing // subarray with 'max' if ($max < $len) { $max = $len; $maxIndex = $n - $max; } // Print the elements of // longest increasing // contiguous subarray. for ($i = $maxIndex; $i < ($max + $maxIndex); $i++) echo($arr[$i] . " ") ; } // Driver Code$arr = array(5, 6, 3, 5, 7, 8, 9, 1, 2);$n = sizeof($arr);printLogestIncSubArr($arr, $n); // This code is contributed// by Shivi_Aggarwal?>
<script> // Javascript implementation to find the length of// longest increasing contiguous subarray // function to find the length of longest increasing// contiguous subarrayfunction printLogestIncSubArr(arr, n){ // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time var max = 1, len = 1, maxIndex = 0; // traverse the array from the 2nd element for (var i=1; i<n; i++) { // if current element if greater than previous // element, then this element helps in building // up the previous increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less than the length // of the current increasing subarray. If true, // then update 'max' if (max < len) { max = len; // index assign the starting index of // longest increasing contiguous subarray. maxIndex = i - max; } // reset 'len' to 1 as from this element // again the length of the new increasing // subarray is being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) { max = len; maxIndex = n - max; } // Print the elements of longest increasing // contiguous subarray. for (var i=maxIndex; i<max+maxIndex; i++) document.write( arr[i] + " ");} // Driver program to test abovevar arr = [5, 6, 3, 5, 7, 8, 9, 1, 2];var n = arr.length;printLogestIncSubArr(arr, n); // This code is contributed by rrrtnx.</script>
Output:
3 5 7 8 9
This article is contributed by Ayush Jauhari. 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.
nitin mittal
Shivi_Aggarwal
rrrtnx
shivanisinghss2110
sumitgumber28
Amazon
Arrays
Amazon
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Python | Using 2D arrays/lists the right way
Find the smallest positive integer value that cannot be represented as sum of any subset of a given array
Find a triplet that sum to a given value
Product of Array except itself
Introduction to Arrays
Linked List vs Array
Median of two sorted arrays of same size
Stack Data Structure (Introduction and Program)
Smallest subarray with sum greater than a given value | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 298,
"s": 52,
"text": "Given an array containing n numbers. The problem is to find the length of the longest contiguous subarray such that every element in the subarray is strictly greater than its previous element in the same subarray. Time Complexity should be O(n)."
},
{
"code": null,
"e": 310,
"s": 298,
"text": "Examples: "
},
{
"code": null,
"e": 492,
"s": 310,
"text": "Input : arr[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}\nOutput : 5\nThe subarray is {3, 5, 7, 8, 9}\n\nInput : arr[] = {12, 13, 1, 5, 4, 7, 8, 10, 10, 11}\nOutput : 4\nThe subarray is {4, 7, 8, 10} "
},
{
"code": null,
"e": 505,
"s": 492,
"text": "Algorithm: "
},
{
"code": null,
"e": 740,
"s": 505,
"text": "lenOfLongIncSubArr(arr, n)\n Declare max = 1, len = 1\n for i = 1 to n-1\n if arr[i] > arr[i-1]\n len++\n else\n if max < len\n max = len\n len = 1\n if max < len\n max = len\n return max "
},
{
"code": null,
"e": 744,
"s": 740,
"text": "C++"
},
{
"code": null,
"e": 749,
"s": 744,
"text": "Java"
},
{
"code": null,
"e": 757,
"s": 749,
"text": "Python3"
},
{
"code": null,
"e": 760,
"s": 757,
"text": "C#"
},
{
"code": null,
"e": 764,
"s": 760,
"text": "PHP"
},
{
"code": null,
"e": 775,
"s": 764,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the length of// longest increasing contiguous subarray#include <bits/stdc++.h> using namespace std; // function to find the length of longest increasing// contiguous subarrayint lenOfLongIncSubArr(int arr[], int n){ // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1; // traverse the array from the 2nd element for (int i=1; i<n; i++) { // if current element if greater than previous // element, then this element helps in building // up the previous increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less than the length // of the current increasing subarray. If true, // then update 'max' if (max < len) max = len; // reset 'len' to 1 as from this element // again the length of the new increasing // subarray is being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) max = len; // required maximum length return max;} // Driver program to test aboveint main(){ int arr[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Length = \" << lenOfLongIncSubArr(arr, n); return 0; }",
"e": 2347,
"s": 775,
"text": null
},
{
"code": "// JAVA Code to find length of// Longest increasing subarrayimport java.util.*; class GFG { // function to find the length of longest // increasing contiguous subarray public static int lenOfLongIncSubArr(int arr[], int n) { // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1; // traverse the array from the 2nd element for (int i=1; i<n; i++) { // if current element if greater than // previous element, then this element // helps in building up the previous // increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less // than the length of the current // increasing subarray. If true, // than update 'max' if (max < len) max = len; // reset 'len' to 1 as from this // element again the length of the // new increasing subarray is being // calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) max = len; // required maximum length return max; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}; int n = arr.length; System.out.println(\"Length = \" + lenOfLongIncSubArr(arr, n)); } } // This code is contributed by Arnav Kr. Mandal.",
"e": 4307,
"s": 2347,
"text": null
},
{
"code": "# Python 3 implementation to find the length of# longest increasing contiguous subarray # function to find the length of longest# increasing contiguous subarraydef lenOfLongIncSubArr(arr, n) : # 'max' to store the length of longest # increasing subarray # 'len' to store the lengths of longest # increasing subarray at different # instants of time m = 1 l = 1 # traverse the array from the 2nd element for i in range(1, n) : # if current element if greater than previous # element, then this element helps in building # up the previous increasing subarray encountered # so far if (arr[i] > arr[i-1]) : l =l + 1 else : # check if 'max' length is less than the length # of the current increasing subarray. If true, # then update 'max' if (m < l) : m = l # reset 'len' to 1 as from this element # again the length of the new increasing # subarray is being calculated l = 1 # comparing the length of the last # increasing subarray with 'max' if (m < l) : m = l # required maximum length return m # Driver program to test above arr = [5, 6, 3, 5, 7, 8, 9, 1, 2]n = len(arr)print(\"Length = \", lenOfLongIncSubArr(arr, n)) # This code is contributed# by Nikita Tiwari.",
"e": 5714,
"s": 4307,
"text": null
},
{
"code": "// C# Code to find length of// Longest increasing subarrayusing System; class GFG { // function to find the length of longest // increasing contiguous subarray public static int lenOfLongIncSubArr(int[] arr, int n) { // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1; // traverse the array from the 2nd element for (int i = 1; i < n; i++) { // if current element if greater than // previous element, then this element // helps in building up the previous // increasing subarray encountered // so far if (arr[i] > arr[i - 1]) len++; else { // check if 'max' length is less // than the length of the current // increasing subarray. If true, // than update 'max' if (max < len) max = len; // reset 'len' to 1 as from this // element again the length of the // new increasing subarray is being // calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) max = len; // required maximum length return max; } /* Driver program to test above function */ public static void Main() { int[] arr = { 5, 6, 3, 5, 7, 8, 9, 1, 2 }; int n = arr.Length; Console.WriteLine(\"Length = \" + lenOfLongIncSubArr(arr, n)); }} // This code is contributed by Sam007",
"e": 7571,
"s": 5714,
"text": null
},
{
"code": "<?php// PHP implementation to find the length of// longest increasing contiguous subarray // function to find the length of// longest increasing contiguous// subarrayfunction lenOfLongIncSubArr($arr, $n){ // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time $max = 1; $len = 1; // traverse the array from // the 2nd element for ($i = 1; $i < $n; $i++) { // if current element if // greater than previous // element, then this element // helps in building up the // previous increasing subarray // encountered so far if ($arr[$i] > $arr[$i-1]) $len++; else { // check if 'max' length is // less than the length // of the current increasing // subarray. If true, // then update 'max' if ($max < $len) $max = $len; // reset 'len' to 1 as // from this element // again the length of // the new increasing // subarray is being // calculated $len = 1; } } // comparing the length of the last // increasing subarray with 'max' if ($max < $len) $max = $len; // required maximum length return $max;} // Driver Code $arr = array(5, 6, 3, 5, 7, 8, 9, 1, 2); $n = sizeof($arr); echo \"Length = \", lenOfLongIncSubArr($arr, $n); // This code is contributed by nitin mittal.?>",
"e": 9212,
"s": 7571,
"text": null
},
{
"code": "<script> // Javascript implementation to find the length of// longest increasing contiguous subarray // function to find the length of longest increasing// contiguous subarrayfunction lenOfLongIncSubArr(arr, n){ // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time var max = 1, len = 1; // traverse the array from the 2nd element for (var i=1; i<n; i++) { // if current element if greater than previous // element, then this element helps in building // up the previous increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less than the length // of the current increasing subarray. If true, // then update 'max' if (max < len) { max = len; } // reset 'len' to 1 as from this element // again the length of the new increasing // subarray is being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) { max = len; } // required maximum length return max;} // Driver program to test abovevar arr = [5, 6, 3, 5, 7, 8, 9, 1, 2];var n = arr.length;document.write(\"Length = \" + lenOfLongIncSubArr(arr, n));// This code is contributed by shivani.</script>",
"e": 10774,
"s": 9212,
"text": null
},
{
"code": null,
"e": 10784,
"s": 10774,
"text": "Output: "
},
{
"code": null,
"e": 10795,
"s": 10784,
"text": "Length = 5"
},
{
"code": null,
"e": 10817,
"s": 10795,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 10926,
"s": 10817,
"text": "How to print the subarray? We can print the subarray by keeping track of the index with the largest length. "
},
{
"code": null,
"e": 10930,
"s": 10926,
"text": "C++"
},
{
"code": null,
"e": 10935,
"s": 10930,
"text": "Java"
},
{
"code": null,
"e": 10943,
"s": 10935,
"text": "Python3"
},
{
"code": null,
"e": 10946,
"s": 10943,
"text": "C#"
},
{
"code": null,
"e": 10950,
"s": 10946,
"text": "PHP"
},
{
"code": null,
"e": 10961,
"s": 10950,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the length of// longest increasing contiguous subarray#include <bits/stdc++.h>using namespace std; // function to find the length of longest increasing// contiguous subarrayvoid printLogestIncSubArr(int arr[], int n){ // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1, maxIndex = 0; // traverse the array from the 2nd element for (int i=1; i<n; i++) { // if current element if greater than previous // element, then this element helps in building // up the previous increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less than the length // of the current increasing subarray. If true, // then update 'max' if (max < len) { max = len; // index assign the starting index of // longest increasing contiguous subarray. maxIndex = i - max; } // reset 'len' to 1 as from this element // again the length of the new increasing // subarray is being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) { max = len; maxIndex = n - max; } // Print the elements of longest increasing // contiguous subarray. for (int i=maxIndex; i<max+maxIndex; i++) cout << arr[i] << \" \";} // Driver program to test aboveint main(){ int arr[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}; int n = sizeof(arr) / sizeof(arr[0]); printLogestIncSubArr(arr, n); return 0; }// This code is contributed by Dharmendra kumar",
"e": 12895,
"s": 10961,
"text": null
},
{
"code": "// JAVA Code For Longest increasing subarrayimport java.util.*; class GFG { // function to find the length of longest // increasing contiguous subarray public static void printLogestIncSubArr(int arr[], int n) { // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1, maxIndex = 0; // traverse the array from the 2nd element for (int i = 1; i < n; i++) { // if current element if greater than // previous element, then this element // helps in building up the previous // increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less // than the length of the current // increasing subarray. If true, // then update 'max' if (max < len) { max = len; // index assign the starting // index of longest increasing // contiguous subarray. maxIndex = i - max; } // reset 'len' to 1 as from this // element again the length of the // new increasing subarray is // being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) { max = len; maxIndex = n - max; } // Print the elements of longest // increasing contiguous subarray. for (int i = maxIndex; i < max+maxIndex; i++) System.out.print(arr[i] + \" \"); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {5, 6, 3, 5, 7, 8, 9, 1, 2}; int n = arr.length; printLogestIncSubArr(arr, n); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 15200,
"s": 12895,
"text": null
},
{
"code": "# Python 3 implementation to find the length of# longest increasing contiguous subarray # function to find the length of longest increasing# contiguous subarraydef printLogestIncSubArr( arr, n) : # 'max' to store the length of longest # increasing subarray # 'len' to store the lengths of longest # increasing subarray at different # instants of time m = 1 l = 1 maxIndex = 0 # traverse the array from the 2nd element for i in range(1, n) : # if current element if greater than previous # element, then this element helps in building # up the previous increasing subarray # encountered so far if (arr[i] > arr[i-1]) : l =l + 1 else : # check if 'max' length is less than the length # of the current increasing subarray. If true, # then update 'max' if (m < l) : m = l # index assign the starting index of # longest increasing contiguous subarray. maxIndex = i - m # reset 'len' to 1 as from this element # again the length of the new increasing # subarray is being calculated l = 1 # comparing the length of the last # increasing subarray with 'max' if (m < l) : m = l maxIndex = n - m # Print the elements of longest # increasing contiguous subarray. for i in range(maxIndex, (m+maxIndex)) : print(arr[i] , end=\" \") # Driver program to test abovearr = [5, 6, 3, 5, 7, 8, 9, 1, 2]n = len(arr)printLogestIncSubArr(arr, n) # This code is contributed# by Nikita Tiwari",
"e": 16915,
"s": 15200,
"text": null
},
{
"code": "// C# Code to print// Longest increasing subarrayusing System; class GFG { // function to find the length of longest // increasing contiguous subarray public static void printLogestIncSubArr(int[] arr, int n) { // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time int max = 1, len = 1, maxIndex = 0; // traverse the array from the 2nd element for (int i = 1; i < n; i++) { // if current element if greater than // previous element, then this element // helps in building up the previous // increasing subarray encountered // so far if (arr[i] > arr[i - 1]) len++; else { // check if 'max' length is less // than the length of the current // increasing subarray. If true, // then update 'max' if (max < len) { max = len; // index assign the starting // index of longest increasing // contiguous subarray. maxIndex = i - max; } // reset 'len' to 1 as from this // element again the length of the // new increasing subarray is // being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) { max = len; maxIndex = n - max; } // Print the elements of longest // increasing contiguous subarray. for (int i = maxIndex; i < max + maxIndex; i++) Console.Write(arr[i] + \" \"); } /* Driver program to test above function */ public static void Main() { int[] arr = { 5, 6, 3, 5, 7, 8, 9, 1, 2 }; int n = arr.Length; printLogestIncSubArr(arr, n); }} // This code is contributed by Sam007",
"e": 19086,
"s": 16915,
"text": null
},
{
"code": "<?php// PHP implementation to find// the length of longest increasing// contiguous subarray // function to find the length of// longest increasing contiguous subarrayfunction printLogestIncSubArr(&$arr, $n){ // 'max' to store the length of // longest increasing subarray // 'len' to store the lengths of // longest increasing subarray at // different instants of time $max = 1; $len = 1; $maxIndex = 0; // traverse the array from // the 2nd element for ($i = 1; $i < $n; $i++) { // if current element if greater // than previous element, then // this element helps in building // up the previous increasing // subarray encountered so far if ($arr[$i] > $arr[$i - 1]) $len++; else { // check if 'max' length is less // than the length of the current // increasing subarray. If true, // then update 'max' if ($max < $len) { $max = $len; // index assign the starting // index of longest increasing // contiguous subarray. $maxIndex = $i - $max; } // reset 'len' to 1 as from this // element again the length of // the new increasing subarray // is being calculated $len = 1; } } // comparing the length of // the last increasing // subarray with 'max' if ($max < $len) { $max = $len; $maxIndex = $n - $max; } // Print the elements of // longest increasing // contiguous subarray. for ($i = $maxIndex; $i < ($max + $maxIndex); $i++) echo($arr[$i] . \" \") ; } // Driver Code$arr = array(5, 6, 3, 5, 7, 8, 9, 1, 2);$n = sizeof($arr);printLogestIncSubArr($arr, $n); // This code is contributed// by Shivi_Aggarwal?>",
"e": 21042,
"s": 19086,
"text": null
},
{
"code": "<script> // Javascript implementation to find the length of// longest increasing contiguous subarray // function to find the length of longest increasing// contiguous subarrayfunction printLogestIncSubArr(arr, n){ // 'max' to store the length of longest // increasing subarray // 'len' to store the lengths of longest // increasing subarray at different // instants of time var max = 1, len = 1, maxIndex = 0; // traverse the array from the 2nd element for (var i=1; i<n; i++) { // if current element if greater than previous // element, then this element helps in building // up the previous increasing subarray encountered // so far if (arr[i] > arr[i-1]) len++; else { // check if 'max' length is less than the length // of the current increasing subarray. If true, // then update 'max' if (max < len) { max = len; // index assign the starting index of // longest increasing contiguous subarray. maxIndex = i - max; } // reset 'len' to 1 as from this element // again the length of the new increasing // subarray is being calculated len = 1; } } // comparing the length of the last // increasing subarray with 'max' if (max < len) { max = len; maxIndex = n - max; } // Print the elements of longest increasing // contiguous subarray. for (var i=maxIndex; i<max+maxIndex; i++) document.write( arr[i] + \" \");} // Driver program to test abovevar arr = [5, 6, 3, 5, 7, 8, 9, 1, 2];var n = arr.length;printLogestIncSubArr(arr, n); // This code is contributed by rrrtnx.</script>",
"e": 22890,
"s": 21042,
"text": null
},
{
"code": null,
"e": 22900,
"s": 22890,
"text": "Output: "
},
{
"code": null,
"e": 22911,
"s": 22900,
"text": "3 5 7 8 9 "
},
{
"code": null,
"e": 23333,
"s": 22911,
"text": "This article is contributed by Ayush Jauhari. 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": 23346,
"s": 23333,
"text": "nitin mittal"
},
{
"code": null,
"e": 23361,
"s": 23346,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 23368,
"s": 23361,
"text": "rrrtnx"
},
{
"code": null,
"e": 23387,
"s": 23368,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 23401,
"s": 23387,
"text": "sumitgumber28"
},
{
"code": null,
"e": 23408,
"s": 23401,
"text": "Amazon"
},
{
"code": null,
"e": 23415,
"s": 23408,
"text": "Arrays"
},
{
"code": null,
"e": 23422,
"s": 23415,
"text": "Amazon"
},
{
"code": null,
"e": 23429,
"s": 23422,
"text": "Arrays"
},
{
"code": null,
"e": 23527,
"s": 23429,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 23559,
"s": 23527,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 23604,
"s": 23559,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 23710,
"s": 23604,
"text": "Find the smallest positive integer value that cannot be represented as sum of any subset of a given array"
},
{
"code": null,
"e": 23751,
"s": 23710,
"text": "Find a triplet that sum to a given value"
},
{
"code": null,
"e": 23782,
"s": 23751,
"text": "Product of Array except itself"
},
{
"code": null,
"e": 23805,
"s": 23782,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 23826,
"s": 23805,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 23867,
"s": 23826,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 23915,
"s": 23867,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Extracting Image Metadat using Exif Tool in Linux | 12 Mar, 2021
Exif stands for Exchangeable image file format. It is a standard that specifies the formats for images, sound, and ancillary tags used by cameras, scanners, and other systems handling image and sound files recorded by cameras. Developed by Japan Electronic Industries Development Association (JEIDA).
Metadata contained in images and other files can give a lot of information that can not be seen by our eyes. For example, see the image of this beach. When you see an image, it seems like a normal image, but it contains metadata.
Exif tool is used to get the metadata contained in an image such as:
The camera used to capture the image such as the phone manufacturer and model number.
Date and time, when the image was taken
Geolocation attached to that image.
Use of flash.
ISO speed rating.
Use of Metadata:
Metadata, or data that describes files such as photos or videos, is useful during detection by investigators because they are often overlooked by other targeted objects. Now, many social media platforms have removed this problem by removing metadata from files but there are still many images online and this data has been completely omitted.
Required Installations:
For Linux OS
apt install exif
For MacOS
brew install exif
Note: exif tool that comes pre-installed in Kali Linux.
To view more information about the tool, you can use :
man exif
OR
exif --help
Extracting Metadata:
exif image.jpg
If you get a “corrupt data” error, there may be two cases:
No metadata in the file
Or you’re scanning a file other than JPG.
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 329,
"s": 28,
"text": "Exif stands for Exchangeable image file format. It is a standard that specifies the formats for images, sound, and ancillary tags used by cameras, scanners, and other systems handling image and sound files recorded by cameras. Developed by Japan Electronic Industries Development Association (JEIDA)."
},
{
"code": null,
"e": 559,
"s": 329,
"text": "Metadata contained in images and other files can give a lot of information that can not be seen by our eyes. For example, see the image of this beach. When you see an image, it seems like a normal image, but it contains metadata."
},
{
"code": null,
"e": 628,
"s": 559,
"text": "Exif tool is used to get the metadata contained in an image such as:"
},
{
"code": null,
"e": 714,
"s": 628,
"text": "The camera used to capture the image such as the phone manufacturer and model number."
},
{
"code": null,
"e": 754,
"s": 714,
"text": "Date and time, when the image was taken"
},
{
"code": null,
"e": 790,
"s": 754,
"text": "Geolocation attached to that image."
},
{
"code": null,
"e": 804,
"s": 790,
"text": "Use of flash."
},
{
"code": null,
"e": 822,
"s": 804,
"text": "ISO speed rating."
},
{
"code": null,
"e": 839,
"s": 822,
"text": "Use of Metadata:"
},
{
"code": null,
"e": 1182,
"s": 839,
"text": "Metadata, or data that describes files such as photos or videos, is useful during detection by investigators because they are often overlooked by other targeted objects. Now, many social media platforms have removed this problem by removing metadata from files but there are still many images online and this data has been completely omitted."
},
{
"code": null,
"e": 1206,
"s": 1182,
"text": "Required Installations:"
},
{
"code": null,
"e": 1219,
"s": 1206,
"text": "For Linux OS"
},
{
"code": null,
"e": 1236,
"s": 1219,
"text": "apt install exif"
},
{
"code": null,
"e": 1246,
"s": 1236,
"text": "For MacOS"
},
{
"code": null,
"e": 1265,
"s": 1246,
"text": "brew install exif "
},
{
"code": null,
"e": 1322,
"s": 1265,
"text": " Note: exif tool that comes pre-installed in Kali Linux."
},
{
"code": null,
"e": 1377,
"s": 1322,
"text": "To view more information about the tool, you can use :"
},
{
"code": null,
"e": 1386,
"s": 1377,
"text": "man exif"
},
{
"code": null,
"e": 1389,
"s": 1386,
"text": "OR"
},
{
"code": null,
"e": 1401,
"s": 1389,
"text": "exif --help"
},
{
"code": null,
"e": 1422,
"s": 1401,
"text": "Extracting Metadata:"
},
{
"code": null,
"e": 1437,
"s": 1422,
"text": "exif image.jpg"
},
{
"code": null,
"e": 1496,
"s": 1437,
"text": "If you get a “corrupt data” error, there may be two cases:"
},
{
"code": null,
"e": 1520,
"s": 1496,
"text": "No metadata in the file"
},
{
"code": null,
"e": 1562,
"s": 1520,
"text": "Or you’re scanning a file other than JPG."
},
{
"code": null,
"e": 1574,
"s": 1562,
"text": "Linux-Tools"
},
{
"code": null,
"e": 1585,
"s": 1574,
"text": "Linux-Unix"
}
] |
Generate all rotations of a number | 23 Jun, 2022
Given an integer n, the task is to generate all the left shift numbers possible. A left shift number is a number that is generated when all the digits of the number are shifted one position to the left and the digit at the first position is shifted to the last.Examples:
Input: n = 123 Output: 231 312Input: n = 1445 Output: 4451 4514 5144
Approach:
Assume n = 123.
Multiply n with 10 i.e. n = n * 10 = 1230.
Add the first digit to the resultant number i.e. 1230 + 1 = 1231.
Subtract (first digit) * 10k from the resultant number where k is the number of digits in the original number (in this case, k = 3).
1231 – 1000 = 231 is the left shift number of the original number.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of digits of nint numberOfDigits(int n){ int cnt = 0; while (n > 0) { cnt++; n /= 10; } return cnt;} // Function to print the left shift numbersvoid cal(int num){ int digits = numberOfDigits(num); int powTen = pow(10, digits - 1); for (int i = 0; i < digits - 1; i++) { int firstDigit = num / powTen; // Formula to calculate left shift // from previous number int left = ((num * 10) + firstDigit) - (firstDigit * powTen * 10); cout << left << " "; // Update the original number num = left; }} // Driver Codeint main(){ int num = 1445; cal(num); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the count of digits of nstatic int numberOfDigits(int n){ int cnt = 0; while (n > 0) { cnt++; n /= 10; } return cnt;} // Function to print the left shift numbersstatic void cal(int num){ int digits = numberOfDigits(num); int powTen = (int) Math.pow(10, digits - 1); for (int i = 0; i < digits - 1; i++) { int firstDigit = num / powTen; // Formula to calculate left shift // from previous number int left = ((num * 10) + firstDigit) - (firstDigit * powTen * 10); System.out.print(left + " "); // Update the original number num = left; }} // Driver Codepublic static void main(String[] args){ int num = 1445; cal(num);}} // This code is contributed by// PrinciRaj1992
# Python3 implementation of the approach # function to return the count of digit of ndef numberofDigits(n): cnt = 0 while n > 0: cnt += 1 n //= 10 return cnt # function to print the left shift numbersdef cal(num): digit = numberofDigits(num) powTen = pow(10, digit - 1) for i in range(digit - 1): firstDigit = num // powTen # formula to calculate left shift # from previous number left = (num * 10 + firstDigit - (firstDigit * powTen * 10)) print(left, end = " ") # Update the original number num = left # Driver codenum = 1445cal(num) # This code is contributed# by Mohit Kumar
// C# implementation of the approachusing System; public class GFG{ // Function to return the count of digits of nstatic int numberOfDigits(int n){ int cnt = 0; while (n > 0) { cnt++; n /= 10; } return cnt;} // Function to print the left shift numbersstatic void cal(int num){ int digits = numberOfDigits(num); int powTen = (int)Math.Pow(10, digits - 1); for (int i = 0; i < digits - 1; i++) { int firstDigit = num / powTen; // Formula to calculate left shift // from previous number int left = ((num * 10) + firstDigit) - (firstDigit * powTen * 10); Console.Write(left + " "); // Update the original number num = left; }} // Driver Code static public void Main (){ int num = 1445; cal(num); }} // This code is contributed by akt_mit....
<?php// PHP implementation of the approach // Function to return the count// of digits of nfunction numberOfDigits($n){ $cnt = 0; while ($n > 0) { $cnt++; $n = floor($n / 10); } return $cnt;} // Function to print the left shift numbersfunction cal($num){ $digits = numberOfDigits($num); $powTen = pow(10, $digits - 1); for ($i = 0; $i < $digits - 1; $i++) { $firstDigit = floor($num / $powTen); // Formula to calculate left shift // from previous number $left = (($num * 10) + $firstDigit) - ($firstDigit * $powTen * 10); echo $left, " "; // Update the original number $num = $left; }} // Driver Code$num = 1445;cal($num); // This code is contributed by Ryuga?>
<script> // Javascript implementation of the approach // Function to return the count of digits of n function numberOfDigits(n) { let cnt = 0; while (n > 0) { cnt++; n = parseInt(n / 10, 10); } return cnt; } // Function to print the left shift numbers function cal(num) { let digits = numberOfDigits(num); let powTen = Math.pow(10, digits - 1); for (let i = 0; i < digits - 1; i++) { let firstDigit = parseInt(num / powTen, 10); // Formula to calculate left shift // from previous number let left = ((num * 10) + firstDigit) - (firstDigit * powTen * 10); document.write(left + " "); // Update the original number num = left; } } let num = 1445; cal(num); </script>
4451 4514 5144
Time Complexity: O(log10n)Auxiliary Space: O(1), since no extra space has been taken.
mohit kumar 29
ankthon
jit_t
princiraj1992
SUNIL PATIL 2
rameshtravel07
sachinvinod1904
rishav1329
Akamai
number-digits
rotation
Mathematical
Mathematical
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": 327,
"s": 54,
"text": "Given an integer n, the task is to generate all the left shift numbers possible. A left shift number is a number that is generated when all the digits of the number are shifted one position to the left and the digit at the first position is shifted to the last.Examples: "
},
{
"code": null,
"e": 398,
"s": 327,
"text": "Input: n = 123 Output: 231 312Input: n = 1445 Output: 4451 4514 5144 "
},
{
"code": null,
"e": 412,
"s": 400,
"text": "Approach: "
},
{
"code": null,
"e": 428,
"s": 412,
"text": "Assume n = 123."
},
{
"code": null,
"e": 471,
"s": 428,
"text": "Multiply n with 10 i.e. n = n * 10 = 1230."
},
{
"code": null,
"e": 537,
"s": 471,
"text": "Add the first digit to the resultant number i.e. 1230 + 1 = 1231."
},
{
"code": null,
"e": 670,
"s": 537,
"text": "Subtract (first digit) * 10k from the resultant number where k is the number of digits in the original number (in this case, k = 3)."
},
{
"code": null,
"e": 737,
"s": 670,
"text": "1231 – 1000 = 231 is the left shift number of the original number."
},
{
"code": null,
"e": 790,
"s": 737,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 794,
"s": 790,
"text": "C++"
},
{
"code": null,
"e": 799,
"s": 794,
"text": "Java"
},
{
"code": null,
"e": 807,
"s": 799,
"text": "Python3"
},
{
"code": null,
"e": 810,
"s": 807,
"text": "C#"
},
{
"code": null,
"e": 814,
"s": 810,
"text": "PHP"
},
{
"code": null,
"e": 825,
"s": 814,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of digits of nint numberOfDigits(int n){ int cnt = 0; while (n > 0) { cnt++; n /= 10; } return cnt;} // Function to print the left shift numbersvoid cal(int num){ int digits = numberOfDigits(num); int powTen = pow(10, digits - 1); for (int i = 0; i < digits - 1; i++) { int firstDigit = num / powTen; // Formula to calculate left shift // from previous number int left = ((num * 10) + firstDigit) - (firstDigit * powTen * 10); cout << left << \" \"; // Update the original number num = left; }} // Driver Codeint main(){ int num = 1445; cal(num); return 0;}",
"e": 1619,
"s": 825,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the count of digits of nstatic int numberOfDigits(int n){ int cnt = 0; while (n > 0) { cnt++; n /= 10; } return cnt;} // Function to print the left shift numbersstatic void cal(int num){ int digits = numberOfDigits(num); int powTen = (int) Math.pow(10, digits - 1); for (int i = 0; i < digits - 1; i++) { int firstDigit = num / powTen; // Formula to calculate left shift // from previous number int left = ((num * 10) + firstDigit) - (firstDigit * powTen * 10); System.out.print(left + \" \"); // Update the original number num = left; }} // Driver Codepublic static void main(String[] args){ int num = 1445; cal(num);}} // This code is contributed by// PrinciRaj1992",
"e": 2510,
"s": 1619,
"text": null
},
{
"code": "# Python3 implementation of the approach # function to return the count of digit of ndef numberofDigits(n): cnt = 0 while n > 0: cnt += 1 n //= 10 return cnt # function to print the left shift numbersdef cal(num): digit = numberofDigits(num) powTen = pow(10, digit - 1) for i in range(digit - 1): firstDigit = num // powTen # formula to calculate left shift # from previous number left = (num * 10 + firstDigit - (firstDigit * powTen * 10)) print(left, end = \" \") # Update the original number num = left # Driver codenum = 1445cal(num) # This code is contributed# by Mohit Kumar",
"e": 3228,
"s": 2510,
"text": null
},
{
"code": "// C# implementation of the approachusing System; public class GFG{ // Function to return the count of digits of nstatic int numberOfDigits(int n){ int cnt = 0; while (n > 0) { cnt++; n /= 10; } return cnt;} // Function to print the left shift numbersstatic void cal(int num){ int digits = numberOfDigits(num); int powTen = (int)Math.Pow(10, digits - 1); for (int i = 0; i < digits - 1; i++) { int firstDigit = num / powTen; // Formula to calculate left shift // from previous number int left = ((num * 10) + firstDigit) - (firstDigit * powTen * 10); Console.Write(left + \" \"); // Update the original number num = left; }} // Driver Code static public void Main (){ int num = 1445; cal(num); }} // This code is contributed by akt_mit.... ",
"e": 4106,
"s": 3228,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the count// of digits of nfunction numberOfDigits($n){ $cnt = 0; while ($n > 0) { $cnt++; $n = floor($n / 10); } return $cnt;} // Function to print the left shift numbersfunction cal($num){ $digits = numberOfDigits($num); $powTen = pow(10, $digits - 1); for ($i = 0; $i < $digits - 1; $i++) { $firstDigit = floor($num / $powTen); // Formula to calculate left shift // from previous number $left = (($num * 10) + $firstDigit) - ($firstDigit * $powTen * 10); echo $left, \" \"; // Update the original number $num = $left; }} // Driver Code$num = 1445;cal($num); // This code is contributed by Ryuga?>",
"e": 4903,
"s": 4106,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the count of digits of n function numberOfDigits(n) { let cnt = 0; while (n > 0) { cnt++; n = parseInt(n / 10, 10); } return cnt; } // Function to print the left shift numbers function cal(num) { let digits = numberOfDigits(num); let powTen = Math.pow(10, digits - 1); for (let i = 0; i < digits - 1; i++) { let firstDigit = parseInt(num / powTen, 10); // Formula to calculate left shift // from previous number let left = ((num * 10) + firstDigit) - (firstDigit * powTen * 10); document.write(left + \" \"); // Update the original number num = left; } } let num = 1445; cal(num); </script>",
"e": 5792,
"s": 4903,
"text": null
},
{
"code": null,
"e": 5807,
"s": 5792,
"text": "4451 4514 5144"
},
{
"code": null,
"e": 5895,
"s": 5809,
"text": "Time Complexity: O(log10n)Auxiliary Space: O(1), since no extra space has been taken."
},
{
"code": null,
"e": 5910,
"s": 5895,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 5918,
"s": 5910,
"text": "ankthon"
},
{
"code": null,
"e": 5924,
"s": 5918,
"text": "jit_t"
},
{
"code": null,
"e": 5938,
"s": 5924,
"text": "princiraj1992"
},
{
"code": null,
"e": 5952,
"s": 5938,
"text": "SUNIL PATIL 2"
},
{
"code": null,
"e": 5967,
"s": 5952,
"text": "rameshtravel07"
},
{
"code": null,
"e": 5983,
"s": 5967,
"text": "sachinvinod1904"
},
{
"code": null,
"e": 5994,
"s": 5983,
"text": "rishav1329"
},
{
"code": null,
"e": 6001,
"s": 5994,
"text": "Akamai"
},
{
"code": null,
"e": 6015,
"s": 6001,
"text": "number-digits"
},
{
"code": null,
"e": 6024,
"s": 6015,
"text": "rotation"
},
{
"code": null,
"e": 6037,
"s": 6024,
"text": "Mathematical"
},
{
"code": null,
"e": 6050,
"s": 6037,
"text": "Mathematical"
}
] |
Python – Escape reserved characters in Strings List | 09 Jul, 2021
Given List of Strings, escape reserved characters in each String.
Input : test_list = [“Gf-g”, “be)s(t”] Output : [‘Gf\\-g’, ‘be\\)s\\(t’] Explanation : All reserved character elements escaped, by adding double \\.
Input : test_list = [“Gf-g”] Output : [‘Gf\\-g’] Explanation : All reserved character elements escaped, by adding double \\.
Method #1 : Using join() + list comprehension
In this, we construct the dictionary to map each of reserved character to its escaped version, and then perform the task of replacement in list comprehension and join the result to form Strings.
Python3
# Python3 code to demonstrate working of# Escape reserved characters in Strings List# Using list comprehension + join() # initializing listtest_list = ["Gf-g", "is*", "be)s(t"] # printing stringprint("The original list : " + str(test_list)) # the reserved stringreserved_str = """? & | ! { } [ ] ( ) ^ ~ * : \ " ' + -""" # the mapped escaped valuesesc_dict = { chr : f"\\{chr}" for chr in reserved_str} # performing transformation using join and list comprehensionres = [ ''.join(esc_dict.get(chr, chr) for chr in sub) for sub in test_list] # printing resultsprint("The resultant escaped String : " + str(res))
The original list : ['Gf-g', 'is*', 'be)s(t']
The resultant escaped String : ['Gf\\-g', 'is\\*', 'be\\)s\\(t']
Method #2 : Using maketrans() + translate() + zip()
In this, the escaping is made by pairing using zip() and maketrans() rather than dictionary for mapping. The translation is done using the result of maketrans().
Python3
# Python3 code to demonstrate working of# Escape reserved characters in Strings List# Using maketrans() + translate() + zip() # initializing listtest_list = ["Gf-g", "is*", "be)s(t"] # printing stringprint("The original list : " + str(test_list)) # reserved_charsreserved_chars = '''?&|!{}[]()^~*:\\"'+-''' # the escaping logicmapper = ['\\' + ele for ele in reserved_chars]result_mapping = str.maketrans(dict(zip(reserved_chars, mapper))) # reforming resultres = [sub.translate(result_mapping) for sub in test_list] # printing resultsprint("The resultant escaped String : " + str(res))
The original list : ['Gf-g', 'is*', 'be)s(t']
The resultant escaped String : ['Gf\\-g', 'is\\*', 'be\\)s\\(t']
sagar0719kumar
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 94,
"s": 28,
"text": "Given List of Strings, escape reserved characters in each String."
},
{
"code": null,
"e": 243,
"s": 94,
"text": "Input : test_list = [“Gf-g”, “be)s(t”] Output : [‘Gf\\\\-g’, ‘be\\\\)s\\\\(t’] Explanation : All reserved character elements escaped, by adding double \\\\."
},
{
"code": null,
"e": 370,
"s": 243,
"text": "Input : test_list = [“Gf-g”] Output : [‘Gf\\\\-g’] Explanation : All reserved character elements escaped, by adding double \\\\. "
},
{
"code": null,
"e": 416,
"s": 370,
"text": "Method #1 : Using join() + list comprehension"
},
{
"code": null,
"e": 611,
"s": 416,
"text": "In this, we construct the dictionary to map each of reserved character to its escaped version, and then perform the task of replacement in list comprehension and join the result to form Strings."
},
{
"code": null,
"e": 619,
"s": 611,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Escape reserved characters in Strings List# Using list comprehension + join() # initializing listtest_list = [\"Gf-g\", \"is*\", \"be)s(t\"] # printing stringprint(\"The original list : \" + str(test_list)) # the reserved stringreserved_str = \"\"\"? & | ! { } [ ] ( ) ^ ~ * : \\ \" ' + -\"\"\" # the mapped escaped valuesesc_dict = { chr : f\"\\\\{chr}\" for chr in reserved_str} # performing transformation using join and list comprehensionres = [ ''.join(esc_dict.get(chr, chr) for chr in sub) for sub in test_list] # printing resultsprint(\"The resultant escaped String : \" + str(res))",
"e": 1230,
"s": 619,
"text": null
},
{
"code": null,
"e": 1341,
"s": 1230,
"text": "The original list : ['Gf-g', 'is*', 'be)s(t']\nThe resultant escaped String : ['Gf\\\\-g', 'is\\\\*', 'be\\\\)s\\\\(t']"
},
{
"code": null,
"e": 1393,
"s": 1341,
"text": "Method #2 : Using maketrans() + translate() + zip()"
},
{
"code": null,
"e": 1555,
"s": 1393,
"text": "In this, the escaping is made by pairing using zip() and maketrans() rather than dictionary for mapping. The translation is done using the result of maketrans()."
},
{
"code": null,
"e": 1563,
"s": 1555,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Escape reserved characters in Strings List# Using maketrans() + translate() + zip() # initializing listtest_list = [\"Gf-g\", \"is*\", \"be)s(t\"] # printing stringprint(\"The original list : \" + str(test_list)) # reserved_charsreserved_chars = '''?&|!{}[]()^~*:\\\\\"'+-''' # the escaping logicmapper = ['\\\\' + ele for ele in reserved_chars]result_mapping = str.maketrans(dict(zip(reserved_chars, mapper))) # reforming resultres = [sub.translate(result_mapping) for sub in test_list] # printing resultsprint(\"The resultant escaped String : \" + str(res))",
"e": 2150,
"s": 1563,
"text": null
},
{
"code": null,
"e": 2261,
"s": 2150,
"text": "The original list : ['Gf-g', 'is*', 'be)s(t']\nThe resultant escaped String : ['Gf\\\\-g', 'is\\\\*', 'be\\\\)s\\\\(t']"
},
{
"code": null,
"e": 2276,
"s": 2261,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2299,
"s": 2276,
"text": "Python string-programs"
},
{
"code": null,
"e": 2306,
"s": 2299,
"text": "Python"
},
{
"code": null,
"e": 2322,
"s": 2306,
"text": "Python Programs"
}
] |
How To Reset Identity Column Values In SQL | 11 May, 2022
Identity column of a table is a column whose value increases automatically. A user generally cannot insert a value into an identity column. A table can have only one column that is defined with the identity attribute.
Syntax :
IDENTITY [ ( seed , increment ) ]
Default value of identity is IDENTITY (1,1).
Seed : The seed represents the starting value of an ID and the default value of seed is 1.
Increment : It will represent the incremental value of the ID and the default value of increment is 1.
For Example :
Step 1 : Create a table named school.
CREATE TABLE school (
student_id INT IDENTITY,
student_name VARCHAR(200),
marks INT
);
Here, the ‘student_id’ column of the table starts from 1 as the default value of seed is 1 and each row is incremented by 1.
Step 2 : Insert some value into a table.
INSERT INTO school (student_name, marks) VALUES ('Sahil', 100);
INSERT INTO school (student_name, marks) VALUES ('Raj', 78);
INSERT INTO school (student_name, marks) VALUES ('Navneet', 80);
INSERT INTO school (student_name, marks) VALUES ('Rahul', 75);
INSERT INTO school (student_name, marks) VALUES ('Sudeep', 82);
INSERT INTO school (student_name, marks) VALUES ('Azaan', 75);
Step 3 : To see the records in the table ‘school’ , we can use the following code:
SELECT * FROM school;
Output :
Step 4 : Lets delete a record.
DELETE FROM school WHERE student_id = 4;
Step 5 : To see the records in the table.
SELECT * FROM school;
Output :
Now, you can see that the student_id column is not in order, So you have to reset the Identity Column.
Here, to reset the Identity column in SQL Server you can use DBCC CHECKIDENT method.
Syntax :
DBCC CHECKIDENT ('table_name', RESEED, new_value);
Note : If we reset the existing records in the table and insert new records, then it will show an error.
So, we need to :
Create a new table as a backup of the main table (i.e. school).
Delete all the data from the main table.
And now reset the identity column.
Re-insert all the data from the backup table to main table.
Step 6 : Create backup table named ‘new_school’ .
CREATE TABLE new_school AS SELECT student_id, student_name, marks FROM school;
Step 7 : Delete all the data from school.
DELETE FROM school;
Step 8 : Reset the Identity column.
DBCC CHECKIDENT ('school', RESEED, 0);
Step 9 : Re-insert all the data from the backup table to main table.
INSERT INTO school (student_name, marks) SELECT student_name, marks FROM new_school ORDER BY student_id ASC;
Step 10 : See the records of the table.
SELECT * FROM school;
Output :
This is how you can reset Identity Column values in SQL .
sagartomar9927
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 270,
"s": 52,
"text": "Identity column of a table is a column whose value increases automatically. A user generally cannot insert a value into an identity column. A table can have only one column that is defined with the identity attribute."
},
{
"code": null,
"e": 279,
"s": 270,
"text": "Syntax :"
},
{
"code": null,
"e": 313,
"s": 279,
"text": "IDENTITY [ ( seed , increment ) ]"
},
{
"code": null,
"e": 358,
"s": 313,
"text": "Default value of identity is IDENTITY (1,1)."
},
{
"code": null,
"e": 449,
"s": 358,
"text": "Seed : The seed represents the starting value of an ID and the default value of seed is 1."
},
{
"code": null,
"e": 552,
"s": 449,
"text": "Increment : It will represent the incremental value of the ID and the default value of increment is 1."
},
{
"code": null,
"e": 566,
"s": 552,
"text": "For Example :"
},
{
"code": null,
"e": 604,
"s": 566,
"text": "Step 1 : Create a table named school."
},
{
"code": null,
"e": 691,
"s": 604,
"text": "CREATE TABLE school (\nstudent_id INT IDENTITY,\nstudent_name VARCHAR(200),\nmarks INT\n);"
},
{
"code": null,
"e": 816,
"s": 691,
"text": "Here, the ‘student_id’ column of the table starts from 1 as the default value of seed is 1 and each row is incremented by 1."
},
{
"code": null,
"e": 857,
"s": 816,
"text": "Step 2 : Insert some value into a table."
},
{
"code": null,
"e": 1237,
"s": 857,
"text": "INSERT INTO school (student_name, marks) VALUES ('Sahil', 100);\nINSERT INTO school (student_name, marks) VALUES ('Raj', 78);\nINSERT INTO school (student_name, marks) VALUES ('Navneet', 80);\nINSERT INTO school (student_name, marks) VALUES ('Rahul', 75);\nINSERT INTO school (student_name, marks) VALUES ('Sudeep', 82);\nINSERT INTO school (student_name, marks) VALUES ('Azaan', 75);"
},
{
"code": null,
"e": 1320,
"s": 1237,
"text": "Step 3 : To see the records in the table ‘school’ , we can use the following code:"
},
{
"code": null,
"e": 1342,
"s": 1320,
"text": "SELECT * FROM school;"
},
{
"code": null,
"e": 1351,
"s": 1342,
"text": "Output :"
},
{
"code": null,
"e": 1382,
"s": 1351,
"text": "Step 4 : Lets delete a record."
},
{
"code": null,
"e": 1423,
"s": 1382,
"text": "DELETE FROM school WHERE student_id = 4;"
},
{
"code": null,
"e": 1465,
"s": 1423,
"text": "Step 5 : To see the records in the table."
},
{
"code": null,
"e": 1487,
"s": 1465,
"text": "SELECT * FROM school;"
},
{
"code": null,
"e": 1496,
"s": 1487,
"text": "Output :"
},
{
"code": null,
"e": 1600,
"s": 1496,
"text": "Now, you can see that the student_id column is not in order, So you have to reset the Identity Column. "
},
{
"code": null,
"e": 1686,
"s": 1600,
"text": "Here, to reset the Identity column in SQL Server you can use DBCC CHECKIDENT method."
},
{
"code": null,
"e": 1695,
"s": 1686,
"text": "Syntax :"
},
{
"code": null,
"e": 1746,
"s": 1695,
"text": "DBCC CHECKIDENT ('table_name', RESEED, new_value);"
},
{
"code": null,
"e": 1851,
"s": 1746,
"text": "Note : If we reset the existing records in the table and insert new records, then it will show an error."
},
{
"code": null,
"e": 1868,
"s": 1851,
"text": "So, we need to :"
},
{
"code": null,
"e": 1932,
"s": 1868,
"text": "Create a new table as a backup of the main table (i.e. school)."
},
{
"code": null,
"e": 1973,
"s": 1932,
"text": "Delete all the data from the main table."
},
{
"code": null,
"e": 2008,
"s": 1973,
"text": "And now reset the identity column."
},
{
"code": null,
"e": 2068,
"s": 2008,
"text": "Re-insert all the data from the backup table to main table."
},
{
"code": null,
"e": 2118,
"s": 2068,
"text": "Step 6 : Create backup table named ‘new_school’ ."
},
{
"code": null,
"e": 2197,
"s": 2118,
"text": "CREATE TABLE new_school AS SELECT student_id, student_name, marks FROM school;"
},
{
"code": null,
"e": 2239,
"s": 2197,
"text": "Step 7 : Delete all the data from school."
},
{
"code": null,
"e": 2259,
"s": 2239,
"text": "DELETE FROM school;"
},
{
"code": null,
"e": 2295,
"s": 2259,
"text": "Step 8 : Reset the Identity column."
},
{
"code": null,
"e": 2334,
"s": 2295,
"text": "DBCC CHECKIDENT ('school', RESEED, 0);"
},
{
"code": null,
"e": 2403,
"s": 2334,
"text": "Step 9 : Re-insert all the data from the backup table to main table."
},
{
"code": null,
"e": 2512,
"s": 2403,
"text": "INSERT INTO school (student_name, marks) SELECT student_name, marks FROM new_school ORDER BY student_id ASC;"
},
{
"code": null,
"e": 2552,
"s": 2512,
"text": "Step 10 : See the records of the table."
},
{
"code": null,
"e": 2574,
"s": 2552,
"text": "SELECT * FROM school;"
},
{
"code": null,
"e": 2583,
"s": 2574,
"text": "Output :"
},
{
"code": null,
"e": 2641,
"s": 2583,
"text": "This is how you can reset Identity Column values in SQL ."
},
{
"code": null,
"e": 2656,
"s": 2641,
"text": "sagartomar9927"
},
{
"code": null,
"e": 2665,
"s": 2656,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2676,
"s": 2665,
"text": "SQL-Server"
},
{
"code": null,
"e": 2680,
"s": 2676,
"text": "SQL"
},
{
"code": null,
"e": 2684,
"s": 2680,
"text": "SQL"
}
] |
Python | Uncommon elements in Lists of List | 16 Aug, 2021
This particular article aims at achieving the task of finding uncommon two list, in which each element is in itself a list. This is also a useful utility as this kind of task can come in life of programmer if he is in the world of development. Lets discuss some ways to achieve this task.
Method 1 : Naive Method This is the simplest method to achieve this task and uses the brute force approach of executing a loop and to check if one list contains similar list as of the other list, not including that.
Python3
# Python 3 code to demonstrate# Uncommon elements in List# using naive method # initializing liststest_list1 = [ [1, 2], [3, 4], [5, 6] ]test_list2 = [ [3, 4], [5, 7], [1, 2] ] # printing both listsprint ("The original list 1 : " + str(test_list1))print ("The original list 2 : " + str(test_list2)) # using naive method# Uncommon elements in Listres_list = []for i in test_list1: if i not in test_list2: res_list.append(i)for i in test_list2: if i not in test_list1: res_list.append(i) # printing the uncommonprint ("The uncommon of two lists is : " + str(res_list))
The original list 1 : [[1, 2], [3, 4], [5, 6]]
The original list 2 : [[3, 4], [5, 7], [1, 2]]
The uncommon of two lists is : [[5, 6], [5, 7]]
Method 2 : Using set() + map() and ^ The most efficient and recommended method to perform this task is using the combination of set() and map() to achieve it. Firstly converting inner lists to tuples using map, and outer lists to set, use of ^ operator can perform the set symmetric difference and hence perform this task. Further if it is required to get in lists of list fashion, we can convert outer and inner containers back to list using map().
Python3
# Python 3 code to demonstrate# Uncommon elements in Lists of List# using map() + set() + ^ # initializing liststest_list1 = [ [1, 2], [3, 4], [5, 6] ]test_list2 = [ [3, 4], [5, 7], [1, 2] ] # printing both listsprint ("The original list 1 : " + str(test_list1))print ("The original list 2 : " + str(test_list2)) # using map() + set() + ^# Uncommon elements in Lists of Listres_set = set(map(tuple, test_list1)) ^ set(map(tuple, test_list2))res_list = list(map(list, res_set)) # printing the uncommonprint ("The uncommon of two lists is : " + str(res_list))
The original list 1 : [[1, 2], [3, 4], [5, 6]]
The original list 2 : [[3, 4], [5, 7], [1, 2]]
The uncommon of two lists is : [[5, 6], [5, 7]]
as5853535
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Deque in Python
Python program to convert a list to string
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 343,
"s": 54,
"text": "This particular article aims at achieving the task of finding uncommon two list, in which each element is in itself a list. This is also a useful utility as this kind of task can come in life of programmer if he is in the world of development. Lets discuss some ways to achieve this task."
},
{
"code": null,
"e": 560,
"s": 343,
"text": "Method 1 : Naive Method This is the simplest method to achieve this task and uses the brute force approach of executing a loop and to check if one list contains similar list as of the other list, not including that. "
},
{
"code": null,
"e": 568,
"s": 560,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# Uncommon elements in List# using naive method # initializing liststest_list1 = [ [1, 2], [3, 4], [5, 6] ]test_list2 = [ [3, 4], [5, 7], [1, 2] ] # printing both listsprint (\"The original list 1 : \" + str(test_list1))print (\"The original list 2 : \" + str(test_list2)) # using naive method# Uncommon elements in Listres_list = []for i in test_list1: if i not in test_list2: res_list.append(i)for i in test_list2: if i not in test_list1: res_list.append(i) # printing the uncommonprint (\"The uncommon of two lists is : \" + str(res_list))",
"e": 1163,
"s": 568,
"text": null
},
{
"code": null,
"e": 1305,
"s": 1163,
"text": "The original list 1 : [[1, 2], [3, 4], [5, 6]]\nThe original list 2 : [[3, 4], [5, 7], [1, 2]]\nThe uncommon of two lists is : [[5, 6], [5, 7]]"
},
{
"code": null,
"e": 1758,
"s": 1307,
"text": " Method 2 : Using set() + map() and ^ The most efficient and recommended method to perform this task is using the combination of set() and map() to achieve it. Firstly converting inner lists to tuples using map, and outer lists to set, use of ^ operator can perform the set symmetric difference and hence perform this task. Further if it is required to get in lists of list fashion, we can convert outer and inner containers back to list using map()."
},
{
"code": null,
"e": 1766,
"s": 1758,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# Uncommon elements in Lists of List# using map() + set() + ^ # initializing liststest_list1 = [ [1, 2], [3, 4], [5, 6] ]test_list2 = [ [3, 4], [5, 7], [1, 2] ] # printing both listsprint (\"The original list 1 : \" + str(test_list1))print (\"The original list 2 : \" + str(test_list2)) # using map() + set() + ^# Uncommon elements in Lists of Listres_set = set(map(tuple, test_list1)) ^ set(map(tuple, test_list2))res_list = list(map(list, res_set)) # printing the uncommonprint (\"The uncommon of two lists is : \" + str(res_list))",
"e": 2324,
"s": 1766,
"text": null
},
{
"code": null,
"e": 2466,
"s": 2324,
"text": "The original list 1 : [[1, 2], [3, 4], [5, 6]]\nThe original list 2 : [[3, 4], [5, 7], [1, 2]]\nThe uncommon of two lists is : [[5, 6], [5, 7]]"
},
{
"code": null,
"e": 2478,
"s": 2468,
"text": "as5853535"
},
{
"code": null,
"e": 2499,
"s": 2478,
"text": "Python list-programs"
},
{
"code": null,
"e": 2506,
"s": 2499,
"text": "Python"
},
{
"code": null,
"e": 2522,
"s": 2506,
"text": "Python Programs"
},
{
"code": null,
"e": 2620,
"s": 2522,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2650,
"s": 2620,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2695,
"s": 2650,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2717,
"s": 2695,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2735,
"s": 2717,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2751,
"s": 2735,
"text": "Deque in Python"
},
{
"code": null,
"e": 2794,
"s": 2751,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2828,
"s": 2794,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 2867,
"s": 2828,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2904,
"s": 2867,
"text": "Python Program for Fibonacci numbers"
}
] |
Shell Script to Read Data From a File | 20 Apr, 2021
File reading is quite an important task in a Programmer’s life as it makes some tasks quite comfortable and automates certain repetitive and time-consuming things. File reading is quite an interesting concept to learn as it gives insight into quite a lot of things that can be done in the Programming world. In Linux, we have shell scripting that can do it with just a few lines.
We need to print the contents of a file after reading through it. Firstly, we will need a file to work with so a user input that gets a filename or path. Next, we need to iterate through the file and display the content character by character. The while loops and certain arguments can be used to do it more efficiently.
To read a file, we need a file in the first place. We will simply read from the user input the path to the file or the file name if the file is in the same directory. We are using the read command to input the file path also we are making use of -p argument to pass in a prompt to the user as a text message giving concise information before the user actually types in anything. After the input has been stored in a preferable variable name we then move towards the actual reading of the file.
To read in from a file, we are going to use while loop that reads in from a stream of characters of the file. We used to read and then a variable that stores the current character. We output the character using echo. But the argument we have passed in to read i.e. n1 will allow us to read the file character by character *Note that if you don’t include the argument -n1 you will read the file line by line.* We will continue to loop through unless we are at the EOF or End of File as depicted in the done statement, We can also say the file stream has ended at EOF. If you want to go by more characters we can increment the -n to any desirable number.
Example 1: Script to read file character by character.
#!/bin/bash
read -p "Enter file name : " filename
while read -n1 character
do
echo $character
done < $filename
Output:
Example 2: Read line by line:
#!/bin/bash
read -p "Enter file name : " filename
while read line
do
echo $line
done < $filename
Output:
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 433,
"s": 53,
"text": "File reading is quite an important task in a Programmer’s life as it makes some tasks quite comfortable and automates certain repetitive and time-consuming things. File reading is quite an interesting concept to learn as it gives insight into quite a lot of things that can be done in the Programming world. In Linux, we have shell scripting that can do it with just a few lines."
},
{
"code": null,
"e": 755,
"s": 433,
"text": "We need to print the contents of a file after reading through it. Firstly, we will need a file to work with so a user input that gets a filename or path. Next, we need to iterate through the file and display the content character by character. The while loops and certain arguments can be used to do it more efficiently. "
},
{
"code": null,
"e": 1249,
"s": 755,
"text": "To read a file, we need a file in the first place. We will simply read from the user input the path to the file or the file name if the file is in the same directory. We are using the read command to input the file path also we are making use of -p argument to pass in a prompt to the user as a text message giving concise information before the user actually types in anything. After the input has been stored in a preferable variable name we then move towards the actual reading of the file."
},
{
"code": null,
"e": 1904,
"s": 1249,
"text": "To read in from a file, we are going to use while loop that reads in from a stream of characters of the file. We used to read and then a variable that stores the current character. We output the character using echo. But the argument we have passed in to read i.e. n1 will allow us to read the file character by character *Note that if you don’t include the argument -n1 you will read the file line by line.* We will continue to loop through unless we are at the EOF or End of File as depicted in the done statement, We can also say the file stream has ended at EOF. If you want to go by more characters we can increment the -n to any desirable number. "
},
{
"code": null,
"e": 1959,
"s": 1904,
"text": "Example 1: Script to read file character by character."
},
{
"code": null,
"e": 2071,
"s": 1959,
"text": "#!/bin/bash\nread -p \"Enter file name : \" filename\nwhile read -n1 character\ndo \necho $character\ndone < $filename"
},
{
"code": null,
"e": 2079,
"s": 2071,
"text": "Output:"
},
{
"code": null,
"e": 2109,
"s": 2079,
"text": "Example 2: Read line by line:"
},
{
"code": null,
"e": 2207,
"s": 2109,
"text": "#!/bin/bash\nread -p \"Enter file name : \" filename\nwhile read line\ndo \necho $line\ndone < $filename"
},
{
"code": null,
"e": 2215,
"s": 2207,
"text": "Output:"
},
{
"code": null,
"e": 2222,
"s": 2215,
"text": "Picked"
},
{
"code": null,
"e": 2235,
"s": 2222,
"text": "Shell Script"
},
{
"code": null,
"e": 2246,
"s": 2235,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2344,
"s": 2246,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2370,
"s": 2344,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2405,
"s": 2370,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2442,
"s": 2405,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2471,
"s": 2442,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2505,
"s": 2471,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 2542,
"s": 2505,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2579,
"s": 2542,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 2618,
"s": 2579,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 2658,
"s": 2618,
"text": "Array Basics in Shell Scripting | Set 1"
}
] |
SQL Query to Find the Sum of all Values in a Column | 13 Apr, 2021
In this article, we will look into the process of querying the sum of all values in a column of a database table. But before finding the sum of all values in a column, let us create a table with some columns and data. In this article, we will be using the Microsoft SQL Server as our database.
Use the below syntax to create a table inside the database
Syntax :
create table table_name( column_name 1 data type ( size ) ,
column_name 2 data type ( size) ,
. . . . column_name n data type ( size ) )
For the sake of illustration, we will be creating a department table and operate on the same. The department table will have 3 fields namely deptid, deptname, totalemployees. To do so use the below statement:
CREATE TABLE department( deptid integer ,
deptname varchar(20) ,
totalemployees integer );
This will create the table. To insert values into the table we need to use the INSERT statement. So let us see add some data to the department table that we created:
Note: We have to insert values according to the table created. For example, we created a department table with deptid as integer, deptname as varchar, and totalemployees as an integer. So, we need to insert an integer, a character, and an integer respectively.
Now let us insert some rows into the department table using the below query:
INSERT INTO department values(1,'IT',32);
INSERT INTO department values(2,'CSE',56);
INSERT INTO department values(1,'ECE',28);
Output:
Following the same pattern we have inserted some rows into the table, now let us print the data available in the table using the SELECT statement as shown below:
SELECT * FROM department;
Note: Here * represents all. If we execute this query, the entire table will be displayed.
Output :
For this, we need to use the sum() function. We have to pass the column name as a parameter.
This sum() function can be used with the SELECT query for retrieving data from the table.
The below example shows to find the sum of all values in a column.
Example :
SELECT SUM(totalemployees) FROM department;
Output :
Conclusion: Using the sum() function we can get the sum of values in a column using the column name.
SQL-Query
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 323,
"s": 28,
"text": "In this article, we will look into the process of querying the sum of all values in a column of a database table. But before finding the sum of all values in a column, let us create a table with some columns and data. In this article, we will be using the Microsoft SQL Server as our database. "
},
{
"code": null,
"e": 382,
"s": 323,
"text": "Use the below syntax to create a table inside the database"
},
{
"code": null,
"e": 391,
"s": 382,
"text": "Syntax :"
},
{
"code": null,
"e": 546,
"s": 391,
"text": "create table table_name( column_name 1 data type ( size ) ,\n column_name 2 data type ( size) ,\n . . . . column_name n data type ( size ) )"
},
{
"code": null,
"e": 755,
"s": 546,
"text": "For the sake of illustration, we will be creating a department table and operate on the same. The department table will have 3 fields namely deptid, deptname, totalemployees. To do so use the below statement:"
},
{
"code": null,
"e": 881,
"s": 755,
"text": "CREATE TABLE department( deptid integer ,\n deptname varchar(20) ,\n totalemployees integer );"
},
{
"code": null,
"e": 1047,
"s": 881,
"text": "This will create the table. To insert values into the table we need to use the INSERT statement. So let us see add some data to the department table that we created:"
},
{
"code": null,
"e": 1309,
"s": 1047,
"text": "Note: We have to insert values according to the table created. For example, we created a department table with deptid as integer, deptname as varchar, and totalemployees as an integer. So, we need to insert an integer, a character, and an integer respectively. "
},
{
"code": null,
"e": 1386,
"s": 1309,
"text": "Now let us insert some rows into the department table using the below query:"
},
{
"code": null,
"e": 1514,
"s": 1386,
"text": "INSERT INTO department values(1,'IT',32);\nINSERT INTO department values(2,'CSE',56);\nINSERT INTO department values(1,'ECE',28);"
},
{
"code": null,
"e": 1522,
"s": 1514,
"text": "Output:"
},
{
"code": null,
"e": 1684,
"s": 1522,
"text": "Following the same pattern we have inserted some rows into the table, now let us print the data available in the table using the SELECT statement as shown below:"
},
{
"code": null,
"e": 1710,
"s": 1684,
"text": "SELECT * FROM department;"
},
{
"code": null,
"e": 1801,
"s": 1710,
"text": "Note: Here * represents all. If we execute this query, the entire table will be displayed."
},
{
"code": null,
"e": 1810,
"s": 1801,
"text": "Output :"
},
{
"code": null,
"e": 1903,
"s": 1810,
"text": "For this, we need to use the sum() function. We have to pass the column name as a parameter."
},
{
"code": null,
"e": 1993,
"s": 1903,
"text": "This sum() function can be used with the SELECT query for retrieving data from the table."
},
{
"code": null,
"e": 2060,
"s": 1993,
"text": "The below example shows to find the sum of all values in a column."
},
{
"code": null,
"e": 2070,
"s": 2060,
"text": "Example :"
},
{
"code": null,
"e": 2114,
"s": 2070,
"text": "SELECT SUM(totalemployees) FROM department;"
},
{
"code": null,
"e": 2123,
"s": 2114,
"text": "Output :"
},
{
"code": null,
"e": 2224,
"s": 2123,
"text": "Conclusion: Using the sum() function we can get the sum of values in a column using the column name."
},
{
"code": null,
"e": 2234,
"s": 2224,
"text": "SQL-Query"
},
{
"code": null,
"e": 2239,
"s": 2234,
"text": "DBMS"
},
{
"code": null,
"e": 2243,
"s": 2239,
"text": "SQL"
},
{
"code": null,
"e": 2248,
"s": 2243,
"text": "DBMS"
},
{
"code": null,
"e": 2252,
"s": 2248,
"text": "SQL"
}
] |
Find if a number is part of AP whose first element and difference are given | 27 Sep, 2021
Given three non-negative integers a, d and x. Here, a is the first element, d is the difference of an AP (Arithmetic Progression). We need to find if x is part of the given AP or not.
Examples :
Input : a = 1, d = 3, x = 7
Output : Yes
7 is part of given AP, 1 + 3 + 3 = 7
Input : a = 10, d = 0, x = 10
Output : Yes
Firstly, in case d = 0, we should output Yes if a = x else answer is No. For non-zero d, if x belongs to sequence x = a + n * d where n is non-negative integer, only if (n – a) / d is non-negative integer.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if x exist// or not in the given AP.#include <bits/stdc++.h>using namespace std; // returns yes if exist else no.bool isMember(int a, int d, int x){ // If difference is 0, then x must // be same as a. if (d == 0) return (x == a); // Else difference between x and a // must be divisible by d. return ((x - a) % d == 0 && (x - a) / d >= 0);} // Driver code.int main(){ int a = 1, x = 7, d = 3; if (isMember(a, d, x)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to check if x exist// or not in the given AP.class GFG { // returns yes if exist else no. static boolean isMember(int a, int d, int x) { // If difference is 0, then x must // be same as a. if (d == 0) return (x == a); // Else difference between x and a // must be divisible by d. return ((x - a) % d == 0 && (x - a) / d >= 0); } // Driver code. public static void main(String args[]) { int a = 1, x = 7, d = 3; if (isMember(a, d, x)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Nikita Tiwari
# Python3 code to check if x exist# or not in the given AP. def isMember(a, d, x): # If difference is 0, then x # must be same as a. if d == 0: return x == a # Else difference between x # and a must be divisible by d. return ((x - a) % d == 0 and int((x - a) / d) >= 0) # Driver codea = 1x = 7d = 3 if isMember(a, d, x): print( "Yes")else: print("No") # This code is contributed by "Abhishek Sharma 44"
// C# program to check if x exist// or not in the given AP.using System;class GFG { // returns yes if exist else no. static bool isMember(int a, int d, int x) { // If difference is 0, then x must // be same as a. if (d == 0) return (x == a); // Else difference between x and a // must be divisible by d. return ((x - a) % d == 0 && (x - a) / d >= 0); } // Driver code. public static void Main() { int a = 1, x = 7, d = 3; if (isMember(a, d, x)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m.
<?php// PHP program to check // if x exist or not in// the given AP. // returns yes if exist// else no.function isMember($a, $d, $x){ // If difference is 0, then // x must be same as a if ($d == 0) return ($x == $a); // Else difference between x// and a must be divisible by d.return (($x - $a) % $d == 0 && ($x - $a) / $d >= 0);} // Driver code.$a = 1; $x = 7; $d = 3;if (isMember($a, $d, $x)) echo "Yes";else echo "No"; // This code is contributed by aj_36?>
<script> // Javascript program to check if x exist // or not in the given AP. // returns yes if exist else no. function isMember(a, d, x) { // If difference is 0, then x must // be same as a. if (d == 0) return (x == a); // Else difference between x and a // must be divisible by d. return ((x - a) % d == 0 && (x - a) / d >= 0); } let a = 1, x = 7, d = 3; if (isMember(a, d, x)) document.write("Yes"); else document.write("No"); // This code is contributed by divyeshrabadiya07.</script>
Output :
Yes
jit_t
asheshkumar
divyeshrabadiya07
shubhambonde2000
arithmetic progression
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Merge two sorted arrays with O(1) extra space
Segment Tree | Set 1 (Sum of given range)
Fizz Buzz Implementation
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 236,
"s": 52,
"text": "Given three non-negative integers a, d and x. Here, a is the first element, d is the difference of an AP (Arithmetic Progression). We need to find if x is part of the given AP or not."
},
{
"code": null,
"e": 248,
"s": 236,
"text": "Examples : "
},
{
"code": null,
"e": 370,
"s": 248,
"text": "Input : a = 1, d = 3, x = 7\nOutput : Yes\n7 is part of given AP, 1 + 3 + 3 = 7\n\nInput : a = 10, d = 0, x = 10\nOutput : Yes"
},
{
"code": null,
"e": 577,
"s": 370,
"text": "Firstly, in case d = 0, we should output Yes if a = x else answer is No. For non-zero d, if x belongs to sequence x = a + n * d where n is non-negative integer, only if (n – a) / d is non-negative integer. "
},
{
"code": null,
"e": 581,
"s": 577,
"text": "C++"
},
{
"code": null,
"e": 586,
"s": 581,
"text": "Java"
},
{
"code": null,
"e": 594,
"s": 586,
"text": "Python3"
},
{
"code": null,
"e": 597,
"s": 594,
"text": "C#"
},
{
"code": null,
"e": 601,
"s": 597,
"text": "PHP"
},
{
"code": null,
"e": 612,
"s": 601,
"text": "Javascript"
},
{
"code": "// C++ program to check if x exist// or not in the given AP.#include <bits/stdc++.h>using namespace std; // returns yes if exist else no.bool isMember(int a, int d, int x){ // If difference is 0, then x must // be same as a. if (d == 0) return (x == a); // Else difference between x and a // must be divisible by d. return ((x - a) % d == 0 && (x - a) / d >= 0);} // Driver code.int main(){ int a = 1, x = 7, d = 3; if (isMember(a, d, x)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 1149,
"s": 612,
"text": null
},
{
"code": "// Java program to check if x exist// or not in the given AP.class GFG { // returns yes if exist else no. static boolean isMember(int a, int d, int x) { // If difference is 0, then x must // be same as a. if (d == 0) return (x == a); // Else difference between x and a // must be divisible by d. return ((x - a) % d == 0 && (x - a) / d >= 0); } // Driver code. public static void main(String args[]) { int a = 1, x = 7, d = 3; if (isMember(a, d, x)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Nikita Tiwari",
"e": 1829,
"s": 1149,
"text": null
},
{
"code": "# Python3 code to check if x exist# or not in the given AP. def isMember(a, d, x): # If difference is 0, then x # must be same as a. if d == 0: return x == a # Else difference between x # and a must be divisible by d. return ((x - a) % d == 0 and int((x - a) / d) >= 0) # Driver codea = 1x = 7d = 3 if isMember(a, d, x): print( \"Yes\")else: print(\"No\") # This code is contributed by \"Abhishek Sharma 44\"",
"e": 2280,
"s": 1829,
"text": null
},
{
"code": "// C# program to check if x exist// or not in the given AP.using System;class GFG { // returns yes if exist else no. static bool isMember(int a, int d, int x) { // If difference is 0, then x must // be same as a. if (d == 0) return (x == a); // Else difference between x and a // must be divisible by d. return ((x - a) % d == 0 && (x - a) / d >= 0); } // Driver code. public static void Main() { int a = 1, x = 7, d = 3; if (isMember(a, d, x)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.",
"e": 2944,
"s": 2280,
"text": null
},
{
"code": "<?php// PHP program to check // if x exist or not in// the given AP. // returns yes if exist// else no.function isMember($a, $d, $x){ // If difference is 0, then // x must be same as a if ($d == 0) return ($x == $a); // Else difference between x// and a must be divisible by d.return (($x - $a) % $d == 0 && ($x - $a) / $d >= 0);} // Driver code.$a = 1; $x = 7; $d = 3;if (isMember($a, $d, $x)) echo \"Yes\";else echo \"No\"; // This code is contributed by aj_36?>",
"e": 3435,
"s": 2944,
"text": null
},
{
"code": "<script> // Javascript program to check if x exist // or not in the given AP. // returns yes if exist else no. function isMember(a, d, x) { // If difference is 0, then x must // be same as a. if (d == 0) return (x == a); // Else difference between x and a // must be divisible by d. return ((x - a) % d == 0 && (x - a) / d >= 0); } let a = 1, x = 7, d = 3; if (isMember(a, d, x)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by divyeshrabadiya07.</script>",
"e": 4038,
"s": 3435,
"text": null
},
{
"code": null,
"e": 4048,
"s": 4038,
"text": "Output : "
},
{
"code": null,
"e": 4052,
"s": 4048,
"text": "Yes"
},
{
"code": null,
"e": 4060,
"s": 4054,
"text": "jit_t"
},
{
"code": null,
"e": 4072,
"s": 4060,
"text": "asheshkumar"
},
{
"code": null,
"e": 4090,
"s": 4072,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 4107,
"s": 4090,
"text": "shubhambonde2000"
},
{
"code": null,
"e": 4130,
"s": 4107,
"text": "arithmetic progression"
},
{
"code": null,
"e": 4137,
"s": 4130,
"text": "series"
},
{
"code": null,
"e": 4150,
"s": 4137,
"text": "Mathematical"
},
{
"code": null,
"e": 4169,
"s": 4150,
"text": "School Programming"
},
{
"code": null,
"e": 4182,
"s": 4169,
"text": "Mathematical"
},
{
"code": null,
"e": 4189,
"s": 4182,
"text": "series"
},
{
"code": null,
"e": 4287,
"s": 4189,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4319,
"s": 4287,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 4363,
"s": 4319,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 4409,
"s": 4363,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 4451,
"s": 4409,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 4476,
"s": 4451,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 4494,
"s": 4476,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4519,
"s": 4494,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4535,
"s": 4519,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 4558,
"s": 4535,
"text": "Introduction To PYTHON"
}
] |
Reverse array in groups | Practice | GeeksforGeeks | Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K.
Example 1:
Input:
N = 5, K = 3
arr[] = {1,2,3,4,5}
Output: 3 2 1 5 4
Explanation: First group consists of elements
1, 2, 3. Second group consists of 4,5.
Example 2:
Input:
N = 4, K = 3
arr[] = {5,6,8,9}
Output: 8 6 5 9
Your Task:
You don't need to read input or print anything. The task is to complete the function reverseInGroups() which takes the array, N and K as input parameters and modifies the array in-place.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N, K ≤ 107
1 ≤ A[i] ≤ 1018
0
atulharsh274Premium7 hours ago
// c++ solution
int l = 0 , r = min(k , n); while(l<=n){ reverse(arr.begin()+l , arr.begin()+r); l = l+k; r = min(n , r+k); }
0
nikhil_deore
This comment was deleted.
0
abuzart199912 hours ago
for(int i = 0;i < n; i += k){ if(n - i - 1 < k){ Collections.reverse(arr.subList(i,n)); } else{ Collections.reverse(arr.subList(i,i+k)); } }
0
swetkrmis18 hours ago
class Solution{public: //Function to reverse every sub-array group of size k. void reverseInGroups(vector<long long>& arr, int n, int k){ vector<int>v; int i=0; int l=i; int w=k; while(k<=n){ for(i;i<k;i++){ v.insert(v.begin(),arr[i]); } i=l; int j=0; for(i;i<k;i++){ arr[i]=v[j]; j++; } i=l; i=i+w; k=k+w; l=i; v.clear(); } w=i; if(i<n){ for(i;i<n;i++){ v.insert(v.begin(),arr[i]); } int j=0; i=w; for(i;i<n;i++){ arr[i]=v[j]; j++; } } }};
0
vinayakunde9620011 day ago
// C++ code
// Time : 0.51/2.07
void reverseInGroups(vector<long long>& arr, int n, int k){ // code here int s = 0,e = k; while(e<n){ reverse(arr.begin()+s,arr.begin()+e); s += k; e += k; } if((n-s)>1) reverse(arr.begin()+s,arr.begin()+n); }
0
aferd74f71 day ago
PYTHON SOLUTION
class Solution: #Function to reverse every sub-array group of size k.def reverseInGroups(self, arr, N, K):
ans=[] t=0 while(N>0): if(N<K): temp=arr[t:] temp.reverse() for i in temp: ans.append(i) N-=K else: temp=arr[t:t+K] temp.reverse() for i in temp: ans.append(i) t+=K N-=K arr.clear() for i in ans: arr.append(i)
0
abhikeshz0kb2 days ago
void reverseInGroups(vector<long long>& v, int n, int k){ int d=0,i;
for(i=0;i<n&&i+k<n;i=d)
{
d=i+k;
reverse(v.begin()+i,v.begin()+d);
}
reverse(v.begin()+i,v.begin()+n);
}
0
gandhi2520002 days ago
class Solution { //Function to reverse every sub-array group of size k. void reverseInGroups(ArrayList<Integer> arr, int n, int k) { // code here for(int i=0;i<n;i+=k){ if(n-i-1<k) Collections.reverse(arr.subList( i,n)); else Collections.reverse(arr.subList( i,i+k )); } }}
0
harshbhagwani903 days ago
Expected time complexity=o(n) but most of the solution does not satisfy this .(beacause soln are in o(n*k))
0
abhinayabhi1413 days ago
class Solution { //Function to reverse every sub-array group of size k. void swap(ArrayList<Integer> arr , int lo , int hi){ while(lo < hi){ Collections.swap(arr , lo , hi); lo++; hi--; } } void reverseInGroups(ArrayList<Integer> arr, int n, int k) { // code here int i ; for(i = 0 ; i+k < n ; i += k){ int l = i; int r = i + k - 1; swap(arr , l , r); } if(i + k != n){ swap(arr , i , n-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": 332,
"s": 238,
"text": "Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K."
},
{
"code": null,
"e": 345,
"s": 334,
"text": "Example 1:"
},
{
"code": null,
"e": 488,
"s": 345,
"text": "Input:\nN = 5, K = 3\narr[] = {1,2,3,4,5}\nOutput: 3 2 1 5 4\nExplanation: First group consists of elements\n1, 2, 3. Second group consists of 4,5."
},
{
"code": null,
"e": 501,
"s": 490,
"text": "Example 2:"
},
{
"code": null,
"e": 556,
"s": 501,
"text": "Input:\nN = 4, K = 3\narr[] = {5,6,8,9}\nOutput: 8 6 5 9\n"
},
{
"code": null,
"e": 757,
"s": 558,
"text": "Your Task:\nYou don't need to read input or print anything. The task is to complete the function reverseInGroups() which takes the array, N and K as input parameters and modifies the array in-place. "
},
{
"code": null,
"e": 821,
"s": 759,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 867,
"s": 823,
"text": "Constraints:\n1 ≤ N, K ≤ 107\n1 ≤ A[i] ≤ 1018"
},
{
"code": null,
"e": 869,
"s": 867,
"text": "0"
},
{
"code": null,
"e": 900,
"s": 869,
"text": "atulharsh274Premium7 hours ago"
},
{
"code": null,
"e": 916,
"s": 900,
"text": "// c++ solution"
},
{
"code": null,
"e": 1106,
"s": 916,
"text": " int l = 0 , r = min(k , n); while(l<=n){ reverse(arr.begin()+l , arr.begin()+r); l = l+k; r = min(n , r+k); }"
},
{
"code": null,
"e": 1108,
"s": 1106,
"text": "0"
},
{
"code": null,
"e": 1121,
"s": 1108,
"text": "nikhil_deore"
},
{
"code": null,
"e": 1147,
"s": 1121,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1149,
"s": 1147,
"text": "0"
},
{
"code": null,
"e": 1173,
"s": 1149,
"text": "abuzart199912 hours ago"
},
{
"code": null,
"e": 1399,
"s": 1173,
"text": "for(int i = 0;i < n; i += k){ if(n - i - 1 < k){ Collections.reverse(arr.subList(i,n)); } else{ Collections.reverse(arr.subList(i,i+k)); } }"
},
{
"code": null,
"e": 1401,
"s": 1399,
"text": "0"
},
{
"code": null,
"e": 1423,
"s": 1401,
"text": "swetkrmis18 hours ago"
},
{
"code": null,
"e": 2178,
"s": 1423,
"text": "class Solution{public: //Function to reverse every sub-array group of size k. void reverseInGroups(vector<long long>& arr, int n, int k){ vector<int>v; int i=0; int l=i; int w=k; while(k<=n){ for(i;i<k;i++){ v.insert(v.begin(),arr[i]); } i=l; int j=0; for(i;i<k;i++){ arr[i]=v[j]; j++; } i=l; i=i+w; k=k+w; l=i; v.clear(); } w=i; if(i<n){ for(i;i<n;i++){ v.insert(v.begin(),arr[i]); } int j=0; i=w; for(i;i<n;i++){ arr[i]=v[j]; j++; } } }};"
},
{
"code": null,
"e": 2180,
"s": 2178,
"text": "0"
},
{
"code": null,
"e": 2207,
"s": 2180,
"text": "vinayakunde9620011 day ago"
},
{
"code": null,
"e": 2219,
"s": 2207,
"text": "// C++ code"
},
{
"code": null,
"e": 2239,
"s": 2219,
"text": "// Time : 0.51/2.07"
},
{
"code": null,
"e": 2517,
"s": 2241,
"text": " void reverseInGroups(vector<long long>& arr, int n, int k){ // code here int s = 0,e = k; while(e<n){ reverse(arr.begin()+s,arr.begin()+e); s += k; e += k; } if((n-s)>1) reverse(arr.begin()+s,arr.begin()+n); }"
},
{
"code": null,
"e": 2519,
"s": 2517,
"text": "0"
},
{
"code": null,
"e": 2538,
"s": 2519,
"text": "aferd74f71 day ago"
},
{
"code": null,
"e": 2555,
"s": 2538,
"text": "PYTHON SOLUTION "
},
{
"code": null,
"e": 2662,
"s": 2555,
"text": "class Solution: #Function to reverse every sub-array group of size k.def reverseInGroups(self, arr, N, K):"
},
{
"code": null,
"e": 3031,
"s": 2662,
"text": " ans=[] t=0 while(N>0): if(N<K): temp=arr[t:] temp.reverse() for i in temp: ans.append(i) N-=K else: temp=arr[t:t+K] temp.reverse() for i in temp: ans.append(i) t+=K N-=K arr.clear() for i in ans: arr.append(i)"
},
{
"code": null,
"e": 3033,
"s": 3031,
"text": "0"
},
{
"code": null,
"e": 3056,
"s": 3033,
"text": "abhikeshz0kb2 days ago"
},
{
"code": null,
"e": 3292,
"s": 3056,
"text": "void reverseInGroups(vector<long long>& v, int n, int k){ int d=0,i;\n for(i=0;i<n&&i+k<n;i=d)\n {\n d=i+k;\n reverse(v.begin()+i,v.begin()+d);\n }\n reverse(v.begin()+i,v.begin()+n);\n }"
},
{
"code": null,
"e": 3294,
"s": 3292,
"text": "0"
},
{
"code": null,
"e": 3317,
"s": 3294,
"text": "gandhi2520002 days ago"
},
{
"code": null,
"e": 3684,
"s": 3317,
"text": "class Solution { //Function to reverse every sub-array group of size k. void reverseInGroups(ArrayList<Integer> arr, int n, int k) { // code here for(int i=0;i<n;i+=k){ if(n-i-1<k) Collections.reverse(arr.subList( i,n)); else Collections.reverse(arr.subList( i,i+k )); } }}"
},
{
"code": null,
"e": 3686,
"s": 3684,
"text": "0"
},
{
"code": null,
"e": 3712,
"s": 3686,
"text": "harshbhagwani903 days ago"
},
{
"code": null,
"e": 3820,
"s": 3712,
"text": "Expected time complexity=o(n) but most of the solution does not satisfy this .(beacause soln are in o(n*k))"
},
{
"code": null,
"e": 3822,
"s": 3820,
"text": "0"
},
{
"code": null,
"e": 3847,
"s": 3822,
"text": "abhinayabhi1413 days ago"
},
{
"code": null,
"e": 4361,
"s": 3847,
"text": "class Solution { //Function to reverse every sub-array group of size k. void swap(ArrayList<Integer> arr , int lo , int hi){ while(lo < hi){ Collections.swap(arr , lo , hi); lo++; hi--; } } void reverseInGroups(ArrayList<Integer> arr, int n, int k) { // code here int i ; for(i = 0 ; i+k < n ; i += k){ int l = i; int r = i + k - 1; swap(arr , l , r); } if(i + k != n){ swap(arr , i , n-1); } }}"
},
{
"code": null,
"e": 4507,
"s": 4361,
"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": 4543,
"s": 4507,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4553,
"s": 4543,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4563,
"s": 4553,
"text": "\nContest\n"
},
{
"code": null,
"e": 4626,
"s": 4563,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4811,
"s": 4626,
"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": 5095,
"s": 4811,
"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": 5241,
"s": 5095,
"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": 5318,
"s": 5241,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 5359,
"s": 5318,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 5387,
"s": 5359,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 5458,
"s": 5387,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 5645,
"s": 5458,
"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."
}
] |
Get name of current method being executed in Java | 08 Nov, 2018
Getting name of currently executing method is useful for handling exceptions and debugging purposes.Below are different methods to get currently executing method :
Using Throwable Stack Trace :Using Throwable Class : In Java, Throwable class is the superclass of all exceptions and errors in java.lang package. Java Throwable class provides several methods like addSuppressed(), getMessage(), getStackTrace(), getSuppressed(), toString(), printStackTrace() etc.We can get an array of stack trace elements representing the stack trace pertaining to throwable by calling getStackTrace() on a Throwable instance. At 0th index element of the array represents the top of the stack, which is the latest method call in the sequence.// Java program to demonstrate// Getting name of current method // using Throwable Classpublic class GFG { public static void foo() { // getStackTrace() method return // current method name at 0th index String nameofCurrMethod = new Throwable() .getStackTrace()[0] .getMethodName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: fooUsing Exception ClassWe can also use Exception class which extends Throwable class.// Java program to demonstrate// Getting name of current method // using Throwable Class public class GFG { public static void foo() { // getStackTrace() method return current // method name at 0th index String nameofCurrMethod = new Exception() .getStackTrace()[0] .getMethodName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: fooUsing getEnclosingMethod() methodBy Object Class : We can use Class.getEnclosingMethod(), this method returns a Method object representing the instantly enclosing method of the prime class. But this come with a expressive overhead as it involves creating a new anonymous inner class behind the scenes.// Java program to demonstrate// Getting name of current method // using Object Classpublic class GFG { // create a static method foo public static void foo() { // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = new Object() {} .getClass() .getEnclosingMethod() .getName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: fooBy Inner Class : We can also define a inner class within a method to get Class reference.// Java program to demonstrate// Getting name of current method // using Inner Class public class GFG { // create a static method foo public static void foo() { // Local inner class class Inner { }; // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = Inner.class .getEnclosingMethod() .getName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo
//This java program on our machine because inner class
// have some restriction for security purpose
Using Thread Stack Trace : The Thread.getStackTrace() method returns array of stack trace elements. The second element of the returned array of stack trace contains name of method of current thread.// Java program to demonstrate// Getting name of current method // using Thread.getStackTrace() public class GFG { // create a static method foo public static void foo() { // Thread.currentThread() return current method name // at 1st index in Stack Trace String nameofCurrMethod = Thread.currentThread() .getStackTrace()[1] .getMethodName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo
Using Throwable Stack Trace :Using Throwable Class : In Java, Throwable class is the superclass of all exceptions and errors in java.lang package. Java Throwable class provides several methods like addSuppressed(), getMessage(), getStackTrace(), getSuppressed(), toString(), printStackTrace() etc.We can get an array of stack trace elements representing the stack trace pertaining to throwable by calling getStackTrace() on a Throwable instance. At 0th index element of the array represents the top of the stack, which is the latest method call in the sequence.// Java program to demonstrate// Getting name of current method // using Throwable Classpublic class GFG { public static void foo() { // getStackTrace() method return // current method name at 0th index String nameofCurrMethod = new Throwable() .getStackTrace()[0] .getMethodName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: fooUsing Exception ClassWe can also use Exception class which extends Throwable class.// Java program to demonstrate// Getting name of current method // using Throwable Class public class GFG { public static void foo() { // getStackTrace() method return current // method name at 0th index String nameofCurrMethod = new Exception() .getStackTrace()[0] .getMethodName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo
Using Throwable Class : In Java, Throwable class is the superclass of all exceptions and errors in java.lang package. Java Throwable class provides several methods like addSuppressed(), getMessage(), getStackTrace(), getSuppressed(), toString(), printStackTrace() etc.We can get an array of stack trace elements representing the stack trace pertaining to throwable by calling getStackTrace() on a Throwable instance. At 0th index element of the array represents the top of the stack, which is the latest method call in the sequence.// Java program to demonstrate// Getting name of current method // using Throwable Classpublic class GFG { public static void foo() { // getStackTrace() method return // current method name at 0th index String nameofCurrMethod = new Throwable() .getStackTrace()[0] .getMethodName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo
// Java program to demonstrate// Getting name of current method // using Throwable Classpublic class GFG { public static void foo() { // getStackTrace() method return // current method name at 0th index String nameofCurrMethod = new Throwable() .getStackTrace()[0] .getMethodName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}
Output:
Name of current method: foo
Using Exception ClassWe can also use Exception class which extends Throwable class.// Java program to demonstrate// Getting name of current method // using Throwable Class public class GFG { public static void foo() { // getStackTrace() method return current // method name at 0th index String nameofCurrMethod = new Exception() .getStackTrace()[0] .getMethodName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo
// Java program to demonstrate// Getting name of current method // using Throwable Class public class GFG { public static void foo() { // getStackTrace() method return current // method name at 0th index String nameofCurrMethod = new Exception() .getStackTrace()[0] .getMethodName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}
Output:
Name of current method: foo
Using getEnclosingMethod() methodBy Object Class : We can use Class.getEnclosingMethod(), this method returns a Method object representing the instantly enclosing method of the prime class. But this come with a expressive overhead as it involves creating a new anonymous inner class behind the scenes.// Java program to demonstrate// Getting name of current method // using Object Classpublic class GFG { // create a static method foo public static void foo() { // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = new Object() {} .getClass() .getEnclosingMethod() .getName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: fooBy Inner Class : We can also define a inner class within a method to get Class reference.// Java program to demonstrate// Getting name of current method // using Inner Class public class GFG { // create a static method foo public static void foo() { // Local inner class class Inner { }; // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = Inner.class .getEnclosingMethod() .getName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo
//This java program on our machine because inner class
// have some restriction for security purpose
By Object Class : We can use Class.getEnclosingMethod(), this method returns a Method object representing the instantly enclosing method of the prime class. But this come with a expressive overhead as it involves creating a new anonymous inner class behind the scenes.// Java program to demonstrate// Getting name of current method // using Object Classpublic class GFG { // create a static method foo public static void foo() { // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = new Object() {} .getClass() .getEnclosingMethod() .getName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo
// Java program to demonstrate// Getting name of current method // using Object Classpublic class GFG { // create a static method foo public static void foo() { // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = new Object() {} .getClass() .getEnclosingMethod() .getName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}
Output:
Name of current method: foo
By Inner Class : We can also define a inner class within a method to get Class reference.// Java program to demonstrate// Getting name of current method // using Inner Class public class GFG { // create a static method foo public static void foo() { // Local inner class class Inner { }; // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = Inner.class .getEnclosingMethod() .getName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo
//This java program on our machine because inner class
// have some restriction for security purpose
// Java program to demonstrate// Getting name of current method // using Inner Class public class GFG { // create a static method foo public static void foo() { // Local inner class class Inner { }; // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = Inner.class .getEnclosingMethod() .getName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}
Output:
Name of current method: foo
//This java program on our machine because inner class
// have some restriction for security purpose
Using Thread Stack Trace : The Thread.getStackTrace() method returns array of stack trace elements. The second element of the returned array of stack trace contains name of method of current thread.// Java program to demonstrate// Getting name of current method // using Thread.getStackTrace() public class GFG { // create a static method foo public static void foo() { // Thread.currentThread() return current method name // at 1st index in Stack Trace String nameofCurrMethod = Thread.currentThread() .getStackTrace()[1] .getMethodName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo
// Java program to demonstrate// Getting name of current method // using Thread.getStackTrace() public class GFG { // create a static method foo public static void foo() { // Thread.currentThread() return current method name // at 1st index in Stack Trace String nameofCurrMethod = Thread.currentThread() .getStackTrace()[1] .getMethodName(); System.out.println("Name of current method: " + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}
Output:
Name of current method: foo
Java-Exception Handling
Java-Exceptions
Java-lang package
Technical Scripter 2018
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": "\n08 Nov, 2018"
},
{
"code": null,
"e": 216,
"s": 52,
"text": "Getting name of currently executing method is useful for handling exceptions and debugging purposes.Below are different methods to get currently executing method :"
},
{
"code": null,
"e": 4875,
"s": 216,
"text": "Using Throwable Stack Trace :Using Throwable Class : In Java, Throwable class is the superclass of all exceptions and errors in java.lang package. Java Throwable class provides several methods like addSuppressed(), getMessage(), getStackTrace(), getSuppressed(), toString(), printStackTrace() etc.We can get an array of stack trace elements representing the stack trace pertaining to throwable by calling getStackTrace() on a Throwable instance. At 0th index element of the array represents the top of the stack, which is the latest method call in the sequence.// Java program to demonstrate// Getting name of current method // using Throwable Classpublic class GFG { public static void foo() { // getStackTrace() method return // current method name at 0th index String nameofCurrMethod = new Throwable() .getStackTrace()[0] .getMethodName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: fooUsing Exception ClassWe can also use Exception class which extends Throwable class.// Java program to demonstrate// Getting name of current method // using Throwable Class public class GFG { public static void foo() { // getStackTrace() method return current // method name at 0th index String nameofCurrMethod = new Exception() .getStackTrace()[0] .getMethodName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: fooUsing getEnclosingMethod() methodBy Object Class : We can use Class.getEnclosingMethod(), this method returns a Method object representing the instantly enclosing method of the prime class. But this come with a expressive overhead as it involves creating a new anonymous inner class behind the scenes.// Java program to demonstrate// Getting name of current method // using Object Classpublic class GFG { // create a static method foo public static void foo() { // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = new Object() {} .getClass() .getEnclosingMethod() .getName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: fooBy Inner Class : We can also define a inner class within a method to get Class reference.// Java program to demonstrate// Getting name of current method // using Inner Class public class GFG { // create a static method foo public static void foo() { // Local inner class class Inner { }; // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = Inner.class .getEnclosingMethod() .getName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo\n//This java program on our machine because inner class\n// have some restriction for security purpose \nUsing Thread Stack Trace : The Thread.getStackTrace() method returns array of stack trace elements. The second element of the returned array of stack trace contains name of method of current thread.// Java program to demonstrate// Getting name of current method // using Thread.getStackTrace() public class GFG { // create a static method foo public static void foo() { // Thread.currentThread() return current method name // at 1st index in Stack Trace String nameofCurrMethod = Thread.currentThread() .getStackTrace()[1] .getMethodName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo"
},
{
"code": null,
"e": 6732,
"s": 4875,
"text": "Using Throwable Stack Trace :Using Throwable Class : In Java, Throwable class is the superclass of all exceptions and errors in java.lang package. Java Throwable class provides several methods like addSuppressed(), getMessage(), getStackTrace(), getSuppressed(), toString(), printStackTrace() etc.We can get an array of stack trace elements representing the stack trace pertaining to throwable by calling getStackTrace() on a Throwable instance. At 0th index element of the array represents the top of the stack, which is the latest method call in the sequence.// Java program to demonstrate// Getting name of current method // using Throwable Classpublic class GFG { public static void foo() { // getStackTrace() method return // current method name at 0th index String nameofCurrMethod = new Throwable() .getStackTrace()[0] .getMethodName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: fooUsing Exception ClassWe can also use Exception class which extends Throwable class.// Java program to demonstrate// Getting name of current method // using Throwable Class public class GFG { public static void foo() { // getStackTrace() method return current // method name at 0th index String nameofCurrMethod = new Exception() .getStackTrace()[0] .getMethodName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo"
},
{
"code": null,
"e": 7869,
"s": 6732,
"text": "Using Throwable Class : In Java, Throwable class is the superclass of all exceptions and errors in java.lang package. Java Throwable class provides several methods like addSuppressed(), getMessage(), getStackTrace(), getSuppressed(), toString(), printStackTrace() etc.We can get an array of stack trace elements representing the stack trace pertaining to throwable by calling getStackTrace() on a Throwable instance. At 0th index element of the array represents the top of the stack, which is the latest method call in the sequence.// Java program to demonstrate// Getting name of current method // using Throwable Classpublic class GFG { public static void foo() { // getStackTrace() method return // current method name at 0th index String nameofCurrMethod = new Throwable() .getStackTrace()[0] .getMethodName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo"
},
{
"code": "// Java program to demonstrate// Getting name of current method // using Throwable Classpublic class GFG { public static void foo() { // getStackTrace() method return // current method name at 0th index String nameofCurrMethod = new Throwable() .getStackTrace()[0] .getMethodName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}",
"e": 8440,
"s": 7869,
"text": null
},
{
"code": null,
"e": 8448,
"s": 8440,
"text": "Output:"
},
{
"code": null,
"e": 8476,
"s": 8448,
"text": "Name of current method: foo"
},
{
"code": null,
"e": 9168,
"s": 8476,
"text": "Using Exception ClassWe can also use Exception class which extends Throwable class.// Java program to demonstrate// Getting name of current method // using Throwable Class public class GFG { public static void foo() { // getStackTrace() method return current // method name at 0th index String nameofCurrMethod = new Exception() .getStackTrace()[0] .getMethodName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo"
},
{
"code": "// Java program to demonstrate// Getting name of current method // using Throwable Class public class GFG { public static void foo() { // getStackTrace() method return current // method name at 0th index String nameofCurrMethod = new Exception() .getStackTrace()[0] .getMethodName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}",
"e": 9743,
"s": 9168,
"text": null
},
{
"code": null,
"e": 9751,
"s": 9743,
"text": "Output:"
},
{
"code": null,
"e": 9779,
"s": 9751,
"text": "Name of current method: foo"
},
{
"code": null,
"e": 11717,
"s": 9779,
"text": "Using getEnclosingMethod() methodBy Object Class : We can use Class.getEnclosingMethod(), this method returns a Method object representing the instantly enclosing method of the prime class. But this come with a expressive overhead as it involves creating a new anonymous inner class behind the scenes.// Java program to demonstrate// Getting name of current method // using Object Classpublic class GFG { // create a static method foo public static void foo() { // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = new Object() {} .getClass() .getEnclosingMethod() .getName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: fooBy Inner Class : We can also define a inner class within a method to get Class reference.// Java program to demonstrate// Getting name of current method // using Inner Class public class GFG { // create a static method foo public static void foo() { // Local inner class class Inner { }; // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = Inner.class .getEnclosingMethod() .getName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo\n//This java program on our machine because inner class\n// have some restriction for security purpose \n"
},
{
"code": null,
"e": 12701,
"s": 11717,
"text": "By Object Class : We can use Class.getEnclosingMethod(), this method returns a Method object representing the instantly enclosing method of the prime class. But this come with a expressive overhead as it involves creating a new anonymous inner class behind the scenes.// Java program to demonstrate// Getting name of current method // using Object Classpublic class GFG { // create a static method foo public static void foo() { // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = new Object() {} .getClass() .getEnclosingMethod() .getName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo"
},
{
"code": "// Java program to demonstrate// Getting name of current method // using Object Classpublic class GFG { // create a static method foo public static void foo() { // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = new Object() {} .getClass() .getEnclosingMethod() .getName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}",
"e": 13383,
"s": 12701,
"text": null
},
{
"code": null,
"e": 13391,
"s": 13383,
"text": "Output:"
},
{
"code": null,
"e": 13419,
"s": 13391,
"text": "Name of current method: foo"
},
{
"code": null,
"e": 14341,
"s": 13419,
"text": "By Inner Class : We can also define a inner class within a method to get Class reference.// Java program to demonstrate// Getting name of current method // using Inner Class public class GFG { // create a static method foo public static void foo() { // Local inner class class Inner { }; // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = Inner.class .getEnclosingMethod() .getName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo\n//This java program on our machine because inner class\n// have some restriction for security purpose \n"
},
{
"code": "// Java program to demonstrate// Getting name of current method // using Inner Class public class GFG { // create a static method foo public static void foo() { // Local inner class class Inner { }; // this method return a Method object representing // the instantly enclosing method of the method class String nameofCurrMethod = Inner.class .getEnclosingMethod() .getName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}",
"e": 15035,
"s": 14341,
"text": null
},
{
"code": null,
"e": 15043,
"s": 15035,
"text": "Output:"
},
{
"code": null,
"e": 15176,
"s": 15043,
"text": "Name of current method: foo\n//This java program on our machine because inner class\n// have some restriction for security purpose \n"
},
{
"code": null,
"e": 16042,
"s": 15176,
"text": "Using Thread Stack Trace : The Thread.getStackTrace() method returns array of stack trace elements. The second element of the returned array of stack trace contains name of method of current thread.// Java program to demonstrate// Getting name of current method // using Thread.getStackTrace() public class GFG { // create a static method foo public static void foo() { // Thread.currentThread() return current method name // at 1st index in Stack Trace String nameofCurrMethod = Thread.currentThread() .getStackTrace()[1] .getMethodName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}Output:Name of current method: foo"
},
{
"code": "// Java program to demonstrate// Getting name of current method // using Thread.getStackTrace() public class GFG { // create a static method foo public static void foo() { // Thread.currentThread() return current method name // at 1st index in Stack Trace String nameofCurrMethod = Thread.currentThread() .getStackTrace()[1] .getMethodName(); System.out.println(\"Name of current method: \" + nameofCurrMethod); } public static void main(String[] args) { // call function foo(); }}",
"e": 16676,
"s": 16042,
"text": null
},
{
"code": null,
"e": 16684,
"s": 16676,
"text": "Output:"
},
{
"code": null,
"e": 16712,
"s": 16684,
"text": "Name of current method: foo"
},
{
"code": null,
"e": 16736,
"s": 16712,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 16752,
"s": 16736,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 16770,
"s": 16752,
"text": "Java-lang package"
},
{
"code": null,
"e": 16794,
"s": 16770,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 16799,
"s": 16794,
"text": "Java"
},
{
"code": null,
"e": 16818,
"s": 16799,
"text": "Technical Scripter"
},
{
"code": null,
"e": 16823,
"s": 16818,
"text": "Java"
}
] |
Instance variable as final in Java | 21 Sep, 2017
Instance variable: As we all know that when the value of variable is varied from object to object then that type of variable is known as instance variable. The instance variable is declared inside a class but not within any method, constructor, block etc. If we don’t initialize an instance variable, then JVM automatically provide default value according to the data type of that instance variable.But if we declare an instance variable as final, then we must have to take care about the behavior of instance variable.
There is no requirement as such to make the variable final. However, when it is true that you explicitly intend to never change the variable, it is often good practice to make it final
We have to use instance variable as final in the creation of immutable class.
Important points about final instance variable:
Initialization of variable Mandatory : If the instance variable declared as final, then we have to perform initialization explicitly whether we are using it or not and JVM won’t provide any default value for the final instance variable.// Java program to illustrate the behavior // of final instance variableclass Test { final int x; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:error: variable x not initialized in the default constructor
Initialization before constructor completion : For final instance variable we have to perform initialization before constructor completion. We can initialize a final instance variable at the time of declaration.// Java program to illustrate that // final instance variable// should be declared at the // time of declarationclass Test { final int x = 10; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10
Initialize inside a non-static or instance block : We can also initialize a final instance variable inside a non-static or instance block also.// Java program to illustrate // that final instance variable// can be initialize within instance blockclass Test { final int x; { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10
Initialization in default constructor : Inside default constructor we can also initialize a final instance variable.// Java program to illustrate that // final instance variable// can be initialized // in the default constructorclass Test { final int x; Test() { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10
Initialization of variable Mandatory : If the instance variable declared as final, then we have to perform initialization explicitly whether we are using it or not and JVM won’t provide any default value for the final instance variable.// Java program to illustrate the behavior // of final instance variableclass Test { final int x; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:error: variable x not initialized in the default constructor
// Java program to illustrate the behavior // of final instance variableclass Test { final int x; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}
Output:
error: variable x not initialized in the default constructor
Initialization before constructor completion : For final instance variable we have to perform initialization before constructor completion. We can initialize a final instance variable at the time of declaration.// Java program to illustrate that // final instance variable// should be declared at the // time of declarationclass Test { final int x = 10; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10
// Java program to illustrate that // final instance variable// should be declared at the // time of declarationclass Test { final int x = 10; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}
Output:
10
Initialize inside a non-static or instance block : We can also initialize a final instance variable inside a non-static or instance block also.// Java program to illustrate // that final instance variable// can be initialize within instance blockclass Test { final int x; { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10
// Java program to illustrate // that final instance variable// can be initialize within instance blockclass Test { final int x; { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}
Output:
10
Initialization in default constructor : Inside default constructor we can also initialize a final instance variable.// Java program to illustrate that // final instance variable// can be initialized // in the default constructorclass Test { final int x; Test() { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10
// Java program to illustrate that // final instance variable// can be initialized // in the default constructorclass Test { final int x; Test() { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}
Output:
10
The above mentioned are the only possible places to perform initialization for final instance variable. If we try to perform initialization anywhere else then we will get compile time error.
// Java program to illustrate // that we cant declare// final instance variable // within any static blocksclass Test { final int x; public static void main(String[] args) { x = 10; Test t = new Test(); System.out.println(t.x); }}
Output:
error: non-static variable x cannot be referenced from a static context
// Java program to illustrate that we// cant declare or initialize// final instance variable within any methodsclass Test { final int x; public void m() { x = 10; }}
Output:
error: cannot assign a value to final variable x
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Java-final keyword
Java
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": "\n21 Sep, 2017"
},
{
"code": null,
"e": 572,
"s": 52,
"text": "Instance variable: As we all know that when the value of variable is varied from object to object then that type of variable is known as instance variable. The instance variable is declared inside a class but not within any method, constructor, block etc. If we don’t initialize an instance variable, then JVM automatically provide default value according to the data type of that instance variable.But if we declare an instance variable as final, then we must have to take care about the behavior of instance variable."
},
{
"code": null,
"e": 757,
"s": 572,
"text": "There is no requirement as such to make the variable final. However, when it is true that you explicitly intend to never change the variable, it is often good practice to make it final"
},
{
"code": null,
"e": 835,
"s": 757,
"text": "We have to use instance variable as final in the creation of immutable class."
},
{
"code": null,
"e": 883,
"s": 835,
"text": "Important points about final instance variable:"
},
{
"code": null,
"e": 2716,
"s": 883,
"text": "Initialization of variable Mandatory : If the instance variable declared as final, then we have to perform initialization explicitly whether we are using it or not and JVM won’t provide any default value for the final instance variable.// Java program to illustrate the behavior // of final instance variableclass Test { final int x; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:error: variable x not initialized in the default constructor\nInitialization before constructor completion : For final instance variable we have to perform initialization before constructor completion. We can initialize a final instance variable at the time of declaration.// Java program to illustrate that // final instance variable// should be declared at the // time of declarationclass Test { final int x = 10; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10\nInitialize inside a non-static or instance block : We can also initialize a final instance variable inside a non-static or instance block also.// Java program to illustrate // that final instance variable// can be initialize within instance blockclass Test { final int x; { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10\nInitialization in default constructor : Inside default constructor we can also initialize a final instance variable.// Java program to illustrate that // final instance variable// can be initialized // in the default constructorclass Test { final int x; Test() { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10\n"
},
{
"code": null,
"e": 3234,
"s": 2716,
"text": "Initialization of variable Mandatory : If the instance variable declared as final, then we have to perform initialization explicitly whether we are using it or not and JVM won’t provide any default value for the final instance variable.// Java program to illustrate the behavior // of final instance variableclass Test { final int x; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:error: variable x not initialized in the default constructor\n"
},
{
"code": "// Java program to illustrate the behavior // of final instance variableclass Test { final int x; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}",
"e": 3448,
"s": 3234,
"text": null
},
{
"code": null,
"e": 3456,
"s": 3448,
"text": "Output:"
},
{
"code": null,
"e": 3518,
"s": 3456,
"text": "error: variable x not initialized in the default constructor\n"
},
{
"code": null,
"e": 3998,
"s": 3518,
"text": "Initialization before constructor completion : For final instance variable we have to perform initialization before constructor completion. We can initialize a final instance variable at the time of declaration.// Java program to illustrate that // final instance variable// should be declared at the // time of declarationclass Test { final int x = 10; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10\n"
},
{
"code": "// Java program to illustrate that // final instance variable// should be declared at the // time of declarationclass Test { final int x = 10; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}",
"e": 4257,
"s": 3998,
"text": null
},
{
"code": null,
"e": 4265,
"s": 4257,
"text": "Output:"
},
{
"code": null,
"e": 4269,
"s": 4265,
"text": "10\n"
},
{
"code": null,
"e": 4692,
"s": 4269,
"text": "Initialize inside a non-static or instance block : We can also initialize a final instance variable inside a non-static or instance block also.// Java program to illustrate // that final instance variable// can be initialize within instance blockclass Test { final int x; { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10\n"
},
{
"code": "// Java program to illustrate // that final instance variable// can be initialize within instance blockclass Test { final int x; { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}",
"e": 4962,
"s": 4692,
"text": null
},
{
"code": null,
"e": 4970,
"s": 4962,
"text": "Output:"
},
{
"code": null,
"e": 4974,
"s": 4970,
"text": "10\n"
},
{
"code": null,
"e": 5389,
"s": 4974,
"text": "Initialization in default constructor : Inside default constructor we can also initialize a final instance variable.// Java program to illustrate that // final instance variable// can be initialized // in the default constructorclass Test { final int x; Test() { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}Output:10\n"
},
{
"code": "// Java program to illustrate that // final instance variable// can be initialized // in the default constructorclass Test { final int x; Test() { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); }}",
"e": 5678,
"s": 5389,
"text": null
},
{
"code": null,
"e": 5686,
"s": 5678,
"text": "Output:"
},
{
"code": null,
"e": 5690,
"s": 5686,
"text": "10\n"
},
{
"code": null,
"e": 5881,
"s": 5690,
"text": "The above mentioned are the only possible places to perform initialization for final instance variable. If we try to perform initialization anywhere else then we will get compile time error."
},
{
"code": "// Java program to illustrate // that we cant declare// final instance variable // within any static blocksclass Test { final int x; public static void main(String[] args) { x = 10; Test t = new Test(); System.out.println(t.x); }}",
"e": 6145,
"s": 5881,
"text": null
},
{
"code": null,
"e": 6153,
"s": 6145,
"text": "Output:"
},
{
"code": null,
"e": 6226,
"s": 6153,
"text": "error: non-static variable x cannot be referenced from a static context\n"
},
{
"code": "// Java program to illustrate that we// cant declare or initialize// final instance variable within any methodsclass Test { final int x; public void m() { x = 10; }}",
"e": 6412,
"s": 6226,
"text": null
},
{
"code": null,
"e": 6420,
"s": 6412,
"text": "Output:"
},
{
"code": null,
"e": 6470,
"s": 6420,
"text": "error: cannot assign a value to final variable x\n"
},
{
"code": null,
"e": 6776,
"s": 6470,
"text": "This article is contributed by Bishal Kumar Dubey. 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": 6900,
"s": 6776,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 6919,
"s": 6900,
"text": "Java-final keyword"
},
{
"code": null,
"e": 6924,
"s": 6919,
"text": "Java"
},
{
"code": null,
"e": 6929,
"s": 6924,
"text": "Java"
},
{
"code": null,
"e": 7027,
"s": 6929,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7042,
"s": 7027,
"text": "Stream In Java"
},
{
"code": null,
"e": 7063,
"s": 7042,
"text": "Introduction to Java"
},
{
"code": null,
"e": 7084,
"s": 7063,
"text": "Constructors in Java"
},
{
"code": null,
"e": 7103,
"s": 7084,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 7120,
"s": 7103,
"text": "Generics in Java"
},
{
"code": null,
"e": 7150,
"s": 7120,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 7176,
"s": 7150,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 7192,
"s": 7176,
"text": "Strings in Java"
},
{
"code": null,
"e": 7229,
"s": 7192,
"text": "Differences between JDK, JRE and JVM"
}
] |
Pseudo Random Number Generator (PRNG) | 06 Sep, 2019
Pseudo Random Number Generator(PRNG) refers to an algorithm that uses mathematical formulas to produce sequences of random numbers. PRNGs generate a sequence of numbers approximating the properties of random numbers.
A PRNG starts from an arbitrary starting state using a seed state. Many numbers are generated in a short time and can also be reproduced later, if the starting point in the sequence is known. Hence, the numbers are deterministic and efficient.
Why do we need PRNG?
With the advent of computers, programmers recognized the need for a means of introducing randomness into a computer program. However, surprising as it may seem, it is difficult to get a computer to do something by chance as computer follows the given instructions blindly and is therefore completely predictable. It is not possible to generate truly random numbers from deterministic thing like computers so PRNG is a technique developed to generate random numbers using a computer.
How PRNG works?
Linear Congruential Generator is most common and oldest algorithm for generating pseudo-randomized numbers. The generator is defined by the recurrence relation:
Xn+1 = (aXn + c) mod m
where X is the sequence of pseudo-random values
m, 0 < m - modulus
a, 0 < a < m - multiplier
c, 0 ≤ c < m - increment
x0, 0 ≤ x0 < m - the seed or start value
We generate the next random integer using the previous random integer, the integer constants, and the integer modulus. To get started, the algorithm requires an initial Seed, which must be provided by some means. The appearance of randomness is provided by performing modulo arithmetic..
Characteristics of PRNG
Efficient: PRNG can produce many numbers in a short time and is advantageous for applications that need many numbers
Deterministic: A given sequence of numbers can be reproduced at a later date if the starting point in the sequence is known.Determinism is handy if you need to replay the same sequence of numbers again at a later stage.
Periodic: PRNGs are periodic, which means that the sequence will eventually repeat itself. While periodicity is hardly ever a desirable characteristic, modern PRNGs have a period that is so long that it can be ignored for most practical purposes
Applications of PRNG
PRNGs are suitable for applications where many random numbers are required and where it is useful that the same sequence can be replayed easily. Popular examples of such applications are simulation and modeling applications. PRNGs are not suitable for applications where it is important that the numbers are really unpredictable, such as data encryption and gambling.
Pseudo Random Number Generator using srand()
#include<stdio.h>#include<stdlib.h>#include<time.h> int main(){ srand(time(NULL)); int i; for(i = 0; i<5; i++) printf("%d\t", rand()%10);}
Output 1:
3 7 0 9 8
Output 2:
7 6 8 1 4
Explanation: srand() sets the seed which is used by rand() to generate random numbers.time(NULL) return no. of second from JAN 1, 1971 i.e every time we run program we have difference of few seconds which gives the program new seed.
Widely used PRNG algorithms : Lagged Fibonacci generators, linear feedback shift registers, Blum Blum Shub.
Quiz on Random Numbers
This article is contributed by Yash Singla. 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.
etrigan76
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Coin Change | DP-7
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Sep, 2019"
},
{
"code": null,
"e": 271,
"s": 54,
"text": "Pseudo Random Number Generator(PRNG) refers to an algorithm that uses mathematical formulas to produce sequences of random numbers. PRNGs generate a sequence of numbers approximating the properties of random numbers."
},
{
"code": null,
"e": 515,
"s": 271,
"text": "A PRNG starts from an arbitrary starting state using a seed state. Many numbers are generated in a short time and can also be reproduced later, if the starting point in the sequence is known. Hence, the numbers are deterministic and efficient."
},
{
"code": null,
"e": 536,
"s": 515,
"text": "Why do we need PRNG?"
},
{
"code": null,
"e": 1019,
"s": 536,
"text": "With the advent of computers, programmers recognized the need for a means of introducing randomness into a computer program. However, surprising as it may seem, it is difficult to get a computer to do something by chance as computer follows the given instructions blindly and is therefore completely predictable. It is not possible to generate truly random numbers from deterministic thing like computers so PRNG is a technique developed to generate random numbers using a computer."
},
{
"code": null,
"e": 1035,
"s": 1019,
"text": "How PRNG works?"
},
{
"code": null,
"e": 1196,
"s": 1035,
"text": "Linear Congruential Generator is most common and oldest algorithm for generating pseudo-randomized numbers. The generator is defined by the recurrence relation:"
},
{
"code": null,
"e": 1383,
"s": 1196,
"text": "Xn+1 = (aXn + c) mod m\nwhere X is the sequence of pseudo-random values\nm, 0 < m - modulus \na, 0 < a < m - multiplier\nc, 0 ≤ c < m - increment\nx0, 0 ≤ x0 < m - the seed or start value"
},
{
"code": null,
"e": 1671,
"s": 1383,
"text": "We generate the next random integer using the previous random integer, the integer constants, and the integer modulus. To get started, the algorithm requires an initial Seed, which must be provided by some means. The appearance of randomness is provided by performing modulo arithmetic.."
},
{
"code": null,
"e": 1695,
"s": 1671,
"text": "Characteristics of PRNG"
},
{
"code": null,
"e": 1812,
"s": 1695,
"text": "Efficient: PRNG can produce many numbers in a short time and is advantageous for applications that need many numbers"
},
{
"code": null,
"e": 2032,
"s": 1812,
"text": "Deterministic: A given sequence of numbers can be reproduced at a later date if the starting point in the sequence is known.Determinism is handy if you need to replay the same sequence of numbers again at a later stage."
},
{
"code": null,
"e": 2278,
"s": 2032,
"text": "Periodic: PRNGs are periodic, which means that the sequence will eventually repeat itself. While periodicity is hardly ever a desirable characteristic, modern PRNGs have a period that is so long that it can be ignored for most practical purposes"
},
{
"code": null,
"e": 2299,
"s": 2278,
"text": "Applications of PRNG"
},
{
"code": null,
"e": 2667,
"s": 2299,
"text": "PRNGs are suitable for applications where many random numbers are required and where it is useful that the same sequence can be replayed easily. Popular examples of such applications are simulation and modeling applications. PRNGs are not suitable for applications where it is important that the numbers are really unpredictable, such as data encryption and gambling."
},
{
"code": null,
"e": 2712,
"s": 2667,
"text": "Pseudo Random Number Generator using srand()"
},
{
"code": "#include<stdio.h>#include<stdlib.h>#include<time.h> int main(){ srand(time(NULL)); int i; for(i = 0; i<5; i++) printf(\"%d\\t\", rand()%10);}",
"e": 2861,
"s": 2712,
"text": null
},
{
"code": null,
"e": 2871,
"s": 2861,
"text": "Output 1:"
},
{
"code": null,
"e": 2886,
"s": 2871,
"text": "3 7 0 9 8\n"
},
{
"code": null,
"e": 2896,
"s": 2886,
"text": "Output 2:"
},
{
"code": null,
"e": 2911,
"s": 2896,
"text": "7 6 8 1 4\n"
},
{
"code": null,
"e": 3144,
"s": 2911,
"text": "Explanation: srand() sets the seed which is used by rand() to generate random numbers.time(NULL) return no. of second from JAN 1, 1971 i.e every time we run program we have difference of few seconds which gives the program new seed."
},
{
"code": null,
"e": 3252,
"s": 3144,
"text": "Widely used PRNG algorithms : Lagged Fibonacci generators, linear feedback shift registers, Blum Blum Shub."
},
{
"code": null,
"e": 3275,
"s": 3252,
"text": "Quiz on Random Numbers"
},
{
"code": null,
"e": 3574,
"s": 3275,
"text": "This article is contributed by Yash Singla. 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": 3699,
"s": 3574,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3709,
"s": 3699,
"text": "etrigan76"
},
{
"code": null,
"e": 3722,
"s": 3709,
"text": "Mathematical"
},
{
"code": null,
"e": 3735,
"s": 3722,
"text": "Mathematical"
},
{
"code": null,
"e": 3833,
"s": 3735,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3863,
"s": 3833,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 3906,
"s": 3863,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3966,
"s": 3906,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 3981,
"s": 3966,
"text": "C++ Data Types"
},
{
"code": null,
"e": 4005,
"s": 3981,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 4024,
"s": 4005,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 4045,
"s": 4024,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4059,
"s": 4045,
"text": "Prime Numbers"
},
{
"code": null,
"e": 4101,
"s": 4059,
"text": "Program to find GCD or HCF of two numbers"
}
] |
In-Place Merge Sort | 16 Jun, 2022
Implement Merge Sort i.e. standard implementation keeping the sorting algorithm as in-place. In-place means it does not occupy extra memory for merge operation as in the standard case.
Examples:
Input: arr[] = {2, 3, 4, 1} Output: 1 2 3 4
Input: arr[] = {56, 2, 45} Output: 2 45 56
Approach 1:
Maintain two pointers that point to the start of the segments which have to be merged.
Compare the elements at which the pointers are present.
If element1 < element2 then element1 is at right position, simply increase pointer1.
Else shift all the elements between element1 and element2(including element1 but excluding element2) right by 1 and then place the element2 in the previous place(i.e. before shifting right) of element1. Increment all the pointers by 1.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program in-place Merge Sort#include <iostream>using namespace std; // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]// Inplace Implementationvoid merge(int arr[], int start, int mid, int end){ int start2 = mid + 1; // If the direct merge is already sorted if (arr[mid] <= arr[start2]) { return; } // Two pointers to maintain start // of both arrays to merge while (start <= mid && start2 <= end) { // If element 1 is in right place if (arr[start] <= arr[start2]) { start++; } else { int value = arr[start2]; int index = start2; // Shift all the elements between element 1 // element 2, right by 1. while (index != start) { arr[index] = arr[index - 1]; index--; } arr[start] = value; // Update all the pointers start++; mid++; start2++; } }} /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} /* UTILITY FUNCTIONS *//* Function to print an array */void printArray(int A[], int size){ int i; for (i = 0; i < size; i++) cout <<" "<< A[i]; cout <<"\n";} /* Driver program to test above functions */int main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = sizeof(arr) / sizeof(arr[0]); mergeSort(arr, 0, arr_size - 1); printArray(arr, arr_size); return 0;} // This code is contributed by shivanisinghss2110
// C++ program in-place Merge Sort#include <stdio.h> // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]// Inplace Implementationvoid merge(int arr[], int start, int mid, int end){ int start2 = mid + 1; // If the direct merge is already sorted if (arr[mid] <= arr[start2]) { return; } // Two pointers to maintain start // of both arrays to merge while (start <= mid && start2 <= end) { // If element 1 is in right place if (arr[start] <= arr[start2]) { start++; } else { int value = arr[start2]; int index = start2; // Shift all the elements between element 1 // element 2, right by 1. while (index != start) { arr[index] = arr[index - 1]; index--; } arr[start] = value; // Update all the pointers start++; mid++; start2++; } }} /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} /* UTILITY FUNCTIONS *//* Function to print an array */void printArray(int A[], int size){ int i; for (i = 0; i < size; i++) printf("%d ", A[i]); printf("\n");} /* Driver program to test above functions */int main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = sizeof(arr) / sizeof(arr[0]); mergeSort(arr, 0, arr_size - 1); printArray(arr, arr_size); return 0;}
// Java program in-place Merge Sort public class GFG { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] // Inplace Implementation static void merge(int arr[], int start, int mid, int end) { int start2 = mid + 1; // If the direct merge is already sorted if (arr[mid] <= arr[start2]) { return; } // Two pointers to maintain start // of both arrays to merge while (start <= mid && start2 <= end) { // If element 1 is in right place if (arr[start] <= arr[start2]) { start++; } else { int value = arr[start2]; int index = start2; // Shift all the elements between element 1 // element 2, right by 1. while (index != start) { arr[index] = arr[index - 1]; index--; } arr[start] = value; // Update all the pointers start++; mid++; start2++; } } } /* l is for left index and r is right index of the sub-array of arr to be sorted */ static void mergeSort(int arr[], int l, int r) { if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } } /* UTILITY FUNCTIONS */ /* Function to print an array */ static void printArray(int A[], int size) { int i; for (i = 0; i < size; i++) System.out.print(A[i] + " "); System.out.println(); } /* Driver program to test above functions */ public static void main(String[] args) { int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = arr.length; mergeSort(arr, 0, arr_size - 1); printArray(arr, arr_size); } // This code is contributed by ANKITRAI1}
# Python program in-place Merge Sort # Merges two subarrays of arr.# First subarray is arr[l..m]# Second subarray is arr[m+1..r]# Inplace Implementation def merge(arr, start, mid, end): start2 = mid + 1 # If the direct merge is already sorted if (arr[mid] <= arr[start2]): return # Two pointers to maintain start # of both arrays to merge while (start <= mid and start2 <= end): # If element 1 is in right place if (arr[start] <= arr[start2]): start += 1 else: value = arr[start2] index = start2 # Shift all the elements between element 1 # element 2, right by 1. while (index != start): arr[index] = arr[index - 1] index -= 1 arr[start] = value # Update all the pointers start += 1 mid += 1 start2 += 1 '''* l is for left index and r is right index ofthe sub-array of arr to be sorted''' def mergeSort(arr, l, r): if (l < r): # Same as (l + r) / 2, but avoids overflow # for large l and r m = l + (r - l) // 2 # Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m + 1, r) merge(arr, l, m, r) ''' UTILITY FUNCTIONS '''''' Function to print an array ''' def printArray(A, size): for i in range(size): print(A[i], end=" ") print() ''' Driver program to test above functions '''if __name__ == '__main__': arr = [12, 11, 13, 5, 6, 7] arr_size = len(arr) mergeSort(arr, 0, arr_size - 1) printArray(arr, arr_size) # This code is contributed by 29AjayKumar
// C# program in-place Merge Sort// sum.using System; class GFG { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] // Inplace Implementation static void merge(int[] arr, int start, int mid, int end) { int start2 = mid + 1; // If the direct merge is already sorted if (arr[mid] <= arr[start2]) { return; } // Two pointers to maintain start // of both arrays to merge while (start <= mid && start2 <= end) { // If element 1 is in right place if (arr[start] <= arr[start2]) { start++; } else { int value = arr[start2]; int index = start2; // Shift all the elements between element 1 // element 2, right by 1. while (index != start) { arr[index] = arr[index - 1]; index--; } arr[start] = value; // Update all the pointers start++; mid++; start2++; } } } /* l is for left index and r is right index of the sub-array of arr to be sorted */ static void mergeSort(int[] arr, int l, int r) { if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } } /* UTILITY FUNCTIONS */ /* Function to print an array */ static void printArray(int[] A, int size) { int i; for (i = 0; i < size; i++) Console.Write(A[i] + " "); Console.WriteLine(); } /* Driver code */ public static void Main(String[] args) { int[] arr = { 12, 11, 13, 5, 6, 7 }; int arr_size = arr.Length; mergeSort(arr, 0, arr_size - 1); printArray(arr, arr_size); }} // This code is contributed by Princi Singh
<script> // Javascript program in-place Merge Sort // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]// Inplace Implementationfunction merge(arr, start, mid, end){ let start2 = mid + 1; // If the direct merge is already sorted if (arr[mid] <= arr[start2]) { return; } // Two pointers to maintain start // of both arrays to merge while (start <= mid && start2 <= end) { // If element 1 is in right place if (arr[start] <= arr[start2]) { start++; } else { let value = arr[start2]; let index = start2; // Shift all the elements between element 1 // element 2, right by 1. while (index != start) { arr[index] = arr[index - 1]; index--; } arr[start] = value; // Update all the pointers start++; mid++; start2++; } }} /* l is for left index and r is right indexof the sub-array of arr to be sorted */function mergeSort(arr, l, r){ if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r let m = l + Math.floor((r - l) / 2); // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} /* UTILITY FUNCTIONS *//* Function to print an array */function printArray(A, size){ let i; for(i = 0; i < size; i++) document.write(A[i] + " "); document.write("<br>");} // Driver codelet arr = [ 12, 11, 13, 5, 6, 7 ];let arr_size = arr.length; mergeSort(arr, 0, arr_size - 1);printArray(arr, arr_size); // This code is contributed by rag2127 </script>
5 6 7 11 12 13
Note: Time Complexity of above approach is O(n2 * log(n)) because merge is O(n2). Time complexity of standard merge sort is less, O(n Log n).
Approach 2: The idea: We start comparing elements that are far from each other rather than adjacent. Basically we are using shell sorting to merge two sorted arrays with O(1) extra space.
mergeSort():
Calculate mid two split the array in two halves(left sub-array and right sub-array)
Recursively call merge sort on left sub-array and right sub-array to sort them
Call merge function to merge left sub-array and right sub-array
merge():
For every pass, we calculate the gap and compare the elements towards the right of the gap.
Initiate the gap with ceiling value of n/2 where n is the combined length of left and right sub-array.
Every pass, the gap reduces to the ceiling value of gap/2.
Take a pointer i to pass the array.
Swap the ith and (i+gap)th elements if (i+gap)th element is smaller than(or greater than when sorting in decreasing order) ith element.
Stop when (i+gap) reaches n.
Input: 10, 30, 14, 11, 16, 7, 28
Note: Assume left and right subarrays has been sorted so we are merging sorted subarrays [10, 14, 30] and [7, 11, 16, 28]
Start with
gap = ceiling of n/2 = 7/2 = 4
[This gap is for whole merged array]
10, 14, 30, 7, 11, 16, 28
10, 14, 30, 7, 11, 16, 28
10, 14, 30, 7, 11, 16, 28
10, 14, 28, 7, 11, 16, 30
gap = ceiling of 4/2 = 2
10, 14, 28, 7, 11, 16, 30
10, 14, 28, 7, 11, 16, 30
10, 7, 28, 14, 11, 16, 30
10, 7, 11, 14, 28, 16, 30
10, 7, 11, 14, 28, 16, 30
gap = ceiling of 2/2 = 1
10, 7, 11, 14, 28, 16, 30
7, 10, 11, 14, 28, 16, 30
7, 10, 11, 14, 28, 16, 30
7, 10, 11, 14, 28, 16, 30
7, 10, 11, 14, 28, 16, 30
7, 10, 11, 14, 16, 28, 30
Output: 7, 10, 11, 14, 16, 28, 30
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Calculating next gapint nextGap(int gap){ if (gap <= 1) return 0; return (int)ceil(gap / 2.0);} // Function for swappingvoid swap(int nums[], int i, int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp;} // Merging the subarrays using shell sorting// Time Complexity: O(nlog n)// Space Complexity: O(1)void inPlaceMerge(int nums[], int start, int end){ int gap = end - start + 1; for(gap = nextGap(gap); gap > 0; gap = nextGap(gap)) { for(int i = start; i + gap <= end; i++) { int j = i + gap; if (nums[i] > nums[j]) swap(nums, i, j); } }} // merge sort makes log n recursive calls// and each time calls merge()// which takes nlog n steps// Time Complexity: O(n*log n + 2((n/2)*log(n/2)) +// 4((n/4)*log(n/4)) +.....+ 1)// Time Complexity: O(logn*(n*log n))// i.e. O(n*(logn)^2)// Space Complexity: O(1)void mergeSort(int nums[], int s, int e){ if (s == e) return; // Calculating mid to slice the // array in two halves int mid = (s + e) / 2; // Recursive calls to sort left // and right subarrays mergeSort(nums, s, mid); mergeSort(nums, mid + 1, e); inPlaceMerge(nums, s, e);} // Driver Codeint main(){ int nums[] = { 12, 11, 13, 5, 6, 7 }; int nums_size = sizeof(nums) / sizeof(nums[0]); mergeSort(nums, 0, nums_size-1); for(int i = 0; i < nums_size; i++) { cout << nums[i] << " "; } return 0;} // This code is contributed by adityapande88
// Java program for the above approachimport java.io.*;import java.util.*; class InPlaceMerge { // Calculating next gap private static int nextGap(int gap) { if (gap <= 1) return 0; return (int)Math.ceil(gap / 2.0); } // Function for swapping private static void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } // Merging the subarrays using shell sorting // Time Complexity: O(nlog n) // Space Complexity: O(1) private static void inPlaceMerge(int[] nums, int start, int end) { int gap = end - start + 1; for (gap = nextGap(gap); gap > 0; gap = nextGap(gap)) { for (int i = start; i + gap <= end; i++) { int j = i + gap; if (nums[i] > nums[j]) swap(nums, i, j); } } } // merge sort makes log n recursive calls // and each time calls merge() // which takes nlog n steps // Time Complexity: O(n*log n + 2((n/2)*log(n/2)) + // 4((n/4)*log(n/4)) +.....+ 1) // Time Complexity: O(logn*(n*log n)) // i.e. O(n*(logn)^2) // Space Complexity: O(1) private static void mergeSort(int[] nums, int s, int e) { if (s == e) return; // Calculating mid to slice the // array in two halves int mid = (s + e) / 2; // Recursive calls to sort left // and right subarrays mergeSort(nums, s, mid); mergeSort(nums, mid + 1, e); inPlaceMerge(nums, s, e); } // Driver Code public static void main(String[] args) { int[] nums = new int[] { 12, 11, 13, 5, 6, 7 }; mergeSort(nums, 0, nums.length - 1); System.out.println(Arrays.toString(nums)); }}
# Python3 program for the above approachimport math # Calculating next gapdef nextGap(gap): if gap <= 1: return 0 return int(math.ceil(gap / 2)) # Function for swappingdef swap(nums, i, j): temp = nums[i] nums[i] = nums[j] nums[j] = temp # Merging the subarrays using shell sorting# Time Complexity: O(nlog n)# Space Complexity: O(1)def inPlaceMerge(nums,start, end): gap = end - start + 1 gap = nextGap(gap) while gap > 0: i = start while (i + gap) <= end: j = i + gap if nums[i] > nums[j]: swap(nums, i, j) i += 1 gap = nextGap(gap) # merge sort makes log n recursive calls# and each time calls merge()# which takes nlog n steps# Time Complexity: O(n*log n + 2((n/2)*log(n/2)) +# 4((n/4)*log(n/4)) +.....+ 1)# Time Complexity: O(logn*(n*log n))# i.e. O(n*(logn)^2)# Space Complexity: O(1)def mergeSort(nums, s, e): if s == e: return # Calculating mid to slice the # array in two halves mid = (s + e) // 2 # Recursive calls to sort left # and right subarrays mergeSort(nums, s, mid) mergeSort(nums, mid + 1, e) inPlaceMerge(nums, s, e) # UTILITY FUNCTIONS# Function to print an arraydef printArray(A, size): for i in range(size): print(A[i], end = " ") print() # Driver Codeif __name__ == '__main__': arr = [ 12, 11, 13, 5, 6, 7 ] arr_size = len(arr) mergeSort(arr, 0, arr_size - 1) printArray(arr, arr_size) # This code is contributed by adityapande88
// C# program for the above approach // Include namespace systemusing System;using System.Linq; using System.Collections; public class InPlaceMerge{ // Calculating next gap private static int nextGap(int gap) { if (gap <= 1) { return 0; } return (int)Math.Ceiling(gap / 2.0); } // Function for swapping private static void swap(int[] nums, int i, int j) { var temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } // Merging the subarrays using shell sorting // Time Complexity: O(nlog n) // Space Complexity: O(1) private static void inPlaceMerge(int[] nums, int start, int end) { var gap = end - start + 1; for (gap = InPlaceMerge.nextGap(gap); gap > 0; gap = InPlaceMerge.nextGap(gap)) { for (int i = start; i + gap <= end; i++) { var j = i + gap; if (nums[i] > nums[j]) { InPlaceMerge.swap(nums, i, j); } } } } // merge sort makes log n recursive calls // and each time calls merge() // which takes nlog n steps // Time Complexity: O(n*log n + 2((n/2)*log(n/2)) + // 4((n/4)*log(n/4)) +.....+ 1) // Time Complexity: O(logn*(n*log n)) // i.e. O(n*(logn)^2) // Space Complexity: O(1) private static void mergeSort(int[] nums, int s, int e) { if (s == e) { return; } // Calculating mid to slice the // array in two halves var mid = (int)((s + e) / 2); // Recursive calls to sort left // and right subarrays InPlaceMerge.mergeSort(nums, s, mid); InPlaceMerge.mergeSort(nums, mid + 1, e); InPlaceMerge.inPlaceMerge(nums, s, e); } // Driver Code public static void Main(String[] args) { int[] nums = new int[] { 12, 11, 13, 5, 6, 7 }; InPlaceMerge.mergeSort(nums, 0, nums.Length - 1); Console.WriteLine(string.Join(", ", nums)); }} // This code is contributed by mukulsomukesh
<script>// Javascript program for the above approach // Calculating next gapfunction nextGap(gap){ if (gap <= 1) return 0; return Math.floor(Math.ceil(gap / 2.0));} // Function for swappingfunction swap(nums,i,j){ let temp = nums[i]; nums[i] = nums[j]; nums[j] = temp;} // Merging the subarrays using shell sorting // Time Complexity: O(nlog n) // Space Complexity: O(1)function inPlaceMerge(nums,start,end){ let gap = end - start + 1; for (gap = nextGap(gap); gap > 0; gap = nextGap(gap)) { for (let i = start; i + gap <= end; i++) { let j = i + gap; if (nums[i] > nums[j]) swap(nums, i, j); } }} // merge sort makes log n recursive calls // and each time calls merge() // which takes nlog n steps // Time Complexity: O(n*log n + 2((n/2)*log(n/2)) + // 4((n/4)*log(n/4)) +.....+ 1) // Time Complexity: O(logn*(n*log n)) // i.e. O(n*(logn)^2) // Space Complexity: O(1)function mergeSort(nums,s,e){ if (s == e) return; // Calculating mid to slice the // array in two halves let mid = Math.floor((s + e) / 2); // Recursive calls to sort left // and right subarrays mergeSort(nums, s, mid); mergeSort(nums, mid + 1, e); inPlaceMerge(nums, s, e);} // Driver Codelet nums=[12, 11, 13, 5, 6, 7 ];mergeSort(nums, 0, nums.length - 1);document.write((nums).join(" ")); // This code is contributed by avanitrachhadiya2155</script>
5 6 7 11 12 13
Time Complexity: O(log n*nlog n)
Note: mergeSort method makes log n recursive calls and each time merge is called which takes n log n time to merge 2 sorted sub-arrays
Approach 3: Here we use the below technique:
Suppose we have a number A and we want to
convert it to a number B and there is also a
constraint that we can recover number A any
time without using other variable.To achieve
this we choose a number N which is greater
than both numbers and add B*N in A.
so A --> A+B*N
To get number B out of (A+B*N)
we divide (A+B*N) by N (A+B*N)/N = B.
To get number A out of (A+B*N)
we take modulo with N (A+B*N)%N = A.
-> In short by taking modulo
we get old number back and taking divide
we new number.
mergeSort():
Calculate mid two split the array into two halves(left sub-array and right sub-array)
Recursively call merge sort on left sub-array and right sub-array to sort them
Call merge function to merge left sub-array and right sub-array
merge():
We first find the maximum element of both sub-array and increment it one to avoid collision of 0 and maximum element during modulo operation.
The idea is to traverse both sub-arrays from starting simultaneously. One starts from l till m and another starts from m+1 till r. So, We will initialize 3 pointers say i, j, k.
i will move from l till m; j will move from m+1 till r; k will move from l till r.
Now update value a[k] by adding min(a[i],a[j])*maximum_element.
Then also update those elements which are left in both sub-arrays.
After updating all the elements divide all the elements by maximum_element so we get the updated array back.
Below is the implementation of the above approach:
C++
Java
// C++ program in-place Merge Sort#include <bits/stdc++.h>using namespace std; // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]// Inplace Implementationvoid mergeInPlace(int a[], int l, int m, int r){ // increment the maximum_element by one to avoid // collision of 0 and maximum element of array in modulo // operation int mx = max(a[m], a[r]) + 1; int i = l, j = m + 1, k = l; while (i <= m && j <= r && k <= r) { // recover back original element to compare int e1 = a[i] % mx; int e2 = a[j] % mx; if (e1 <= e2) { a[k] += (e1 * mx); i++; k++; } else { a[k] += (e2 * mx); j++; k++; } } // process those elements which are left in the array while (i <= m) { int el = a[i] % mx; a[k] += (el * mx); i++; k++; } while (j <= r) { int el = a[j] % mx; a[k] += (el * mx); j++; k++; } // finally update elements by dividing with maximum // element for (int i = l; i <= r; i++) a[i] /= mx;} /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); mergeInPlace(arr, l, m, r); }} // Driver Codeint main(){ int nums[] = { 12, 11, 13, 5, 6, 7 }; int nums_size = sizeof(nums) / sizeof(nums[0]); mergeSort(nums, 0, nums_size - 1); for (int i = 0; i < nums_size; i++) { cout << nums[i] << " "; } return 0;} // This code is contributed by soham11806959
// Java program in-place Merge Sortimport java.io.*;import java.util.*; class GFG { // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]// Inplace Implementationprivate static void mergeInPlace(int a[], int l, int m, int r){ // increment the maximum_element by one to avoid // collision of 0 and maximum element of array in modulo // operation int mx = Math.max(a[m], a[r]) + 1; int i = l, j = m + 1, k = l; while (i <= m && j <= r && k <= r) { // recover back original element to compare int e1 = a[i] % mx; int e2 = a[j] % mx; if (e1 <= e2) { a[k] += (e1 * mx); i++; k++; } else { a[k] += (e2 * mx); j++; k++; } } // process those elements which are left in the array while (i <= m) { int el = a[i] % mx; a[k] += (el * mx); i++; k++; } while (j <= r) { int el = a[j] % mx; a[k] += (el * mx); j++; k++; } // finally update elements by dividing with maximum // element for (i = l; i <= r; i++) a[i] /= mx;} /* l is for left index and r is right index of the sub-array of arr to be sorted */private static void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); mergeInPlace(arr, l, m, r); }} // Driver Code public static void main(String[] args) { int nums[] = { 12, 11, 13, 5, 6, 7 }; int nums_size = nums.length; mergeSort(nums, 0, nums_size - 1); for (int i = 0; i < nums_size; i++) { System.out.print(nums[i]+" "); } }} // This code is contributed by Pushpesh Raj
5 6 7 11 12 13
Time Complexity: O(n log n)Note: Time Complexity of above approach is O(n2) because merge is O(n). Time complexity of standard merge sort is O(n log n).
Approach 4: Here we use the following technique to perform an in-place merge
Given 2 adjacent sorted sub-arrays within an array (hereafter
named A and B for convenience), appreciate that we can swap
some of the last portion of A with an equal number of elements
from the start of B, such that after the exchange, all of the
elements in A are less than or equal to any element in B.
After this exchange, this leaves with the A containing 2 sorted
sub-arrays, being the first original portion of A, and the first
original portion of B, and sub-array B now containing 2 sorted
sub-arrays, being the final original portion of A followed by
the final original portion of B
We can now recursively call the merge operation with the 2
sub-arrays of A, followed by recursively calling the merge
operation with the 2 sub-arrays of B
We stop the recursion when either A or B are empty, or when
either sub-array is small enough to efficiently merge into
the other sub-array using insertion sort.
The above procedure naturally lends itself to the following implementation of an in-place merge sort.
merge():
Hereafter, for convenience, we’ll refer to the first sub-array as A, and the second sub-array as B
If either A or B are empty, or if the first element B is not less than the last element of A then we’re done
If the length of A is small enough and if it’s length is less than the length of B, then use insertion sort to merge A into B and return
If the length of B is small enough then use insertion sort to merge B into A and return
Find the location in A where we can exchange the remaining portion of A with the first-portion of B, such that all the elements in A are less than or equal to any element in B
Perform the exchange between A and B
Recursively call merge() on the 2 sorted sub-arrays now residing in A
Recursively call merge() on the 2 sorted sub-arrays now residing in B
merge_sort():
Split the array into two halves(left sub-array and right sub-array)
Recursively call merge_sort() on left sub-array and right sub-array to sort them
Call merge function to merge left sub-array and right sub-array
C++
C
// Merge In Place in C++ #include <iostream>using namespace std; #define __INSERT_THRESH 5#define __swap(x, y) (t = *(x), *(x) = *(y), *(y) = t) // Both sorted sub-arrays must be adjacent in 'a'// 'an' is the length of the first sorted section in 'a'// 'bn' is the length of the second sorted section in 'a'static void merge(int* a, size_t an, size_t bn){ int *b = a + an, *e = b + bn, *s, t; // Return right now if we're done if (an == 0 || bn == 0 || !(*b < *(b - 1))) return; // Do insertion sort to merge if size of sub-arrays are // small enough if (an < __INSERT_THRESH && an <= bn) { for (int *p = b, *v; p > a; p--) // Insert Sort A into B for (v = p, s = p - 1; v < e && *v < *s; s = v, v++) __swap(s, v); return; } if (bn < __INSERT_THRESH) { for (int *p = b, *v; p < e; p++) // Insert Sort B into A for (s = p, v = p - 1; s > a && *s < *v; s = v, v--) __swap(s, v); return; } // Find the pivot points. Basically this is just // finding the point in 'a' where we can swap in the // first part of 'b' such that after the swap the last // element in 'a' will be less than or equal to the // least element in 'b' int *pa = a, *pb = b; for (s = a; s < b && pb < e; s++) if (*pb < *pa) pb++; else pa++; pa += b - s; // Swap first part of b with last part of a for (int *la = pa, *fb = b; la < b; la++, fb++) __swap(la, fb); // Now merge the two sub-array pairings merge(a, pa - a, pb - b); merge(b, pb - b, e - pb);} // merge_array_inplace #undef __swap#undef __INSERT_THRESH // Merge Sort Implementationvoid merge_sort(int* a, size_t n){ size_t m = (n + 1) / 2; // Sort first and second halves if (m > 1) merge_sort(a, m); if (n - m > 1) merge_sort(a + m, n - m); // Now merge the two sorted sub-arrays together merge(a, m, n - m);} // Function to print an arrayvoid print_array(int a[], size_t n){ if (n > 0) { cout <<" "<< a[0]; for (size_t i = 1; i < n; i++) cout <<" "<< a[i]; } cout <<"\n";} // Driver program to test sort utilityint main(){ int a[] = { 3, 16, 5, 14, 8, 10, 7, 15, 1, 13, 4, 9, 12, 11, 6, 2 }; size_t n = sizeof(a) / sizeof(a[0]); merge_sort(a, n); print_array(a, n); return 0;} // This code is contributed by shivanisinghss2110
// Merge In Place in C #include <stddef.h>#include <stdio.h> #define __INSERT_THRESH 5#define __swap(x, y) (t = *(x), *(x) = *(y), *(y) = t) // Both sorted sub-arrays must be adjacent in 'a'// 'an' is the length of the first sorted section in 'a'// 'bn' is the length of the second sorted section in 'a'static void merge(int* a, size_t an, size_t bn){ int *b = a + an, *e = b + bn, *s, t; // Return right now if we're done if (an == 0 || bn == 0 || !(*b < *(b - 1))) return; // Do insertion sort to merge if size of sub-arrays are // small enough if (an < __INSERT_THRESH && an <= bn) { for (int *p = b, *v; p > a; p--) // Insert Sort A into B for (v = p, s = p - 1; v < e && *v < *s; s = v, v++) __swap(s, v); return; } if (bn < __INSERT_THRESH) { for (int *p = b, *v; p < e; p++) // Insert Sort B into A for (s = p, v = p - 1; s > a && *s < *v; s = v, v--) __swap(s, v); return; } // Find the pivot points. Basically this is just // finding the point in 'a' where we can swap in the // first part of 'b' such that after the swap the last // element in 'a' will be less than or equal to the // least element in 'b' int *pa = a, *pb = b; for (s = a; s < b && pb < e; s++) if (*pb < *pa) pb++; else pa++; pa += b - s; // Swap first part of b with last part of a for (int *la = pa, *fb = b; la < b; la++, fb++) __swap(la, fb); // Now merge the two sub-array pairings merge(a, pa - a, pb - b); merge(b, pb - b, e - pb);} // merge_array_inplace #undef __swap#undef __INSERT_THRESH // Merge Sort Implementationvoid merge_sort(int* a, size_t n){ size_t m = (n + 1) / 2; // Sort first and second halves if (m > 1) merge_sort(a, m); if (n - m > 1) merge_sort(a + m, n - m); // Now merge the two sorted sub-arrays together merge(a, m, n - m);} // Function to print an arrayvoid print_array(int a[], size_t n){ if (n > 0) { printf("%d", a[0]); for (size_t i = 1; i < n; i++) printf(" %d", a[i]); } printf("\n");} // Driver program to test sort utiliyyint main(){ int a[] = { 3, 16, 5, 14, 8, 10, 7, 15, 1, 13, 4, 9, 12, 11, 6, 2 }; size_t n = sizeof(a) / sizeof(a[0]); merge_sort(a, n); print_array(a, n); return 0;} // Author: Stew Forster ([email protected]) Date: 29// July 2021
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Time Complexity of merge(): Worst Case: O(n^2), Average: O(n log n), Best: O(1)
Time Complexity of merge_sort() function: Overall: O(log n) for the recursion alone, due to always evenly dividing the array in 2
Time Complexity of merge_sort() overall: Worst Case: O(n^2 log n), Average: O(n (log n)^2), Best: O(log n)
The worst-case occurs when every sub-array exchange within merge() results in just _INSERT_THRESH-1 elements being exchanged
ankthon
princi singh
nidhi_biet
29AjayKumar
naveenk2k
ShashwatKhare
mittulmandhan
adityapande88
soham11806959
simranarora5sos
iit2018065
rag2127
stew675
avanitrachhadiya2155
shivanisinghss2110
UtkarshGpta
kashishsoda
surinderdawra388
mukulsomukesh
pushpeshrajdx01
sweetyty
array-merge
Merge Sort
Sorting
Sorting
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Longest Common Prefix using Sorting
Sort a nearly sorted (or K sorted) array
Segregate 0s and 1s in an array
Sorting in Java
Find whether an array is subset of another array
Find all triplets with zero sum
Stability in sorting algorithms
Quick Sort vs Merge Sort | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 237,
"s": 52,
"text": "Implement Merge Sort i.e. standard implementation keeping the sorting algorithm as in-place. In-place means it does not occupy extra memory for merge operation as in the standard case."
},
{
"code": null,
"e": 248,
"s": 237,
"text": "Examples: "
},
{
"code": null,
"e": 292,
"s": 248,
"text": "Input: arr[] = {2, 3, 4, 1} Output: 1 2 3 4"
},
{
"code": null,
"e": 336,
"s": 292,
"text": "Input: arr[] = {56, 2, 45} Output: 2 45 56 "
},
{
"code": null,
"e": 348,
"s": 336,
"text": "Approach 1:"
},
{
"code": null,
"e": 435,
"s": 348,
"text": "Maintain two pointers that point to the start of the segments which have to be merged."
},
{
"code": null,
"e": 491,
"s": 435,
"text": "Compare the elements at which the pointers are present."
},
{
"code": null,
"e": 576,
"s": 491,
"text": "If element1 < element2 then element1 is at right position, simply increase pointer1."
},
{
"code": null,
"e": 812,
"s": 576,
"text": "Else shift all the elements between element1 and element2(including element1 but excluding element2) right by 1 and then place the element2 in the previous place(i.e. before shifting right) of element1. Increment all the pointers by 1."
},
{
"code": null,
"e": 863,
"s": 812,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 867,
"s": 863,
"text": "C++"
},
{
"code": null,
"e": 869,
"s": 867,
"text": "C"
},
{
"code": null,
"e": 874,
"s": 869,
"text": "Java"
},
{
"code": null,
"e": 882,
"s": 874,
"text": "Python3"
},
{
"code": null,
"e": 885,
"s": 882,
"text": "C#"
},
{
"code": null,
"e": 896,
"s": 885,
"text": "Javascript"
},
{
"code": "// C++ program in-place Merge Sort#include <iostream>using namespace std; // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]// Inplace Implementationvoid merge(int arr[], int start, int mid, int end){ int start2 = mid + 1; // If the direct merge is already sorted if (arr[mid] <= arr[start2]) { return; } // Two pointers to maintain start // of both arrays to merge while (start <= mid && start2 <= end) { // If element 1 is in right place if (arr[start] <= arr[start2]) { start++; } else { int value = arr[start2]; int index = start2; // Shift all the elements between element 1 // element 2, right by 1. while (index != start) { arr[index] = arr[index - 1]; index--; } arr[start] = value; // Update all the pointers start++; mid++; start2++; } }} /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} /* UTILITY FUNCTIONS *//* Function to print an array */void printArray(int A[], int size){ int i; for (i = 0; i < size; i++) cout <<\" \"<< A[i]; cout <<\"\\n\";} /* Driver program to test above functions */int main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = sizeof(arr) / sizeof(arr[0]); mergeSort(arr, 0, arr_size - 1); printArray(arr, arr_size); return 0;} // This code is contributed by shivanisinghss2110",
"e": 2765,
"s": 896,
"text": null
},
{
"code": "// C++ program in-place Merge Sort#include <stdio.h> // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]// Inplace Implementationvoid merge(int arr[], int start, int mid, int end){ int start2 = mid + 1; // If the direct merge is already sorted if (arr[mid] <= arr[start2]) { return; } // Two pointers to maintain start // of both arrays to merge while (start <= mid && start2 <= end) { // If element 1 is in right place if (arr[start] <= arr[start2]) { start++; } else { int value = arr[start2]; int index = start2; // Shift all the elements between element 1 // element 2, right by 1. while (index != start) { arr[index] = arr[index - 1]; index--; } arr[start] = value; // Update all the pointers start++; mid++; start2++; } }} /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} /* UTILITY FUNCTIONS *//* Function to print an array */void printArray(int A[], int size){ int i; for (i = 0; i < size; i++) printf(\"%d \", A[i]); printf(\"\\n\");} /* Driver program to test above functions */int main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = sizeof(arr) / sizeof(arr[0]); mergeSort(arr, 0, arr_size - 1); printArray(arr, arr_size); return 0;}",
"e": 4566,
"s": 2765,
"text": null
},
{
"code": "// Java program in-place Merge Sort public class GFG { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] // Inplace Implementation static void merge(int arr[], int start, int mid, int end) { int start2 = mid + 1; // If the direct merge is already sorted if (arr[mid] <= arr[start2]) { return; } // Two pointers to maintain start // of both arrays to merge while (start <= mid && start2 <= end) { // If element 1 is in right place if (arr[start] <= arr[start2]) { start++; } else { int value = arr[start2]; int index = start2; // Shift all the elements between element 1 // element 2, right by 1. while (index != start) { arr[index] = arr[index - 1]; index--; } arr[start] = value; // Update all the pointers start++; mid++; start2++; } } } /* l is for left index and r is right index of the sub-array of arr to be sorted */ static void mergeSort(int arr[], int l, int r) { if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } } /* UTILITY FUNCTIONS */ /* Function to print an array */ static void printArray(int A[], int size) { int i; for (i = 0; i < size; i++) System.out.print(A[i] + \" \"); System.out.println(); } /* Driver program to test above functions */ public static void main(String[] args) { int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = arr.length; mergeSort(arr, 0, arr_size - 1); printArray(arr, arr_size); } // This code is contributed by ANKITRAI1}",
"e": 6733,
"s": 4566,
"text": null
},
{
"code": "# Python program in-place Merge Sort # Merges two subarrays of arr.# First subarray is arr[l..m]# Second subarray is arr[m+1..r]# Inplace Implementation def merge(arr, start, mid, end): start2 = mid + 1 # If the direct merge is already sorted if (arr[mid] <= arr[start2]): return # Two pointers to maintain start # of both arrays to merge while (start <= mid and start2 <= end): # If element 1 is in right place if (arr[start] <= arr[start2]): start += 1 else: value = arr[start2] index = start2 # Shift all the elements between element 1 # element 2, right by 1. while (index != start): arr[index] = arr[index - 1] index -= 1 arr[start] = value # Update all the pointers start += 1 mid += 1 start2 += 1 '''* l is for left index and r is right index ofthe sub-array of arr to be sorted''' def mergeSort(arr, l, r): if (l < r): # Same as (l + r) / 2, but avoids overflow # for large l and r m = l + (r - l) // 2 # Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m + 1, r) merge(arr, l, m, r) ''' UTILITY FUNCTIONS '''''' Function to print an array ''' def printArray(A, size): for i in range(size): print(A[i], end=\" \") print() ''' Driver program to test above functions '''if __name__ == '__main__': arr = [12, 11, 13, 5, 6, 7] arr_size = len(arr) mergeSort(arr, 0, arr_size - 1) printArray(arr, arr_size) # This code is contributed by 29AjayKumar",
"e": 8389,
"s": 6733,
"text": null
},
{
"code": "// C# program in-place Merge Sort// sum.using System; class GFG { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] // Inplace Implementation static void merge(int[] arr, int start, int mid, int end) { int start2 = mid + 1; // If the direct merge is already sorted if (arr[mid] <= arr[start2]) { return; } // Two pointers to maintain start // of both arrays to merge while (start <= mid && start2 <= end) { // If element 1 is in right place if (arr[start] <= arr[start2]) { start++; } else { int value = arr[start2]; int index = start2; // Shift all the elements between element 1 // element 2, right by 1. while (index != start) { arr[index] = arr[index - 1]; index--; } arr[start] = value; // Update all the pointers start++; mid++; start2++; } } } /* l is for left index and r is right index of the sub-array of arr to be sorted */ static void mergeSort(int[] arr, int l, int r) { if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } } /* UTILITY FUNCTIONS */ /* Function to print an array */ static void printArray(int[] A, int size) { int i; for (i = 0; i < size; i++) Console.Write(A[i] + \" \"); Console.WriteLine(); } /* Driver code */ public static void Main(String[] args) { int[] arr = { 12, 11, 13, 5, 6, 7 }; int arr_size = arr.Length; mergeSort(arr, 0, arr_size - 1); printArray(arr, arr_size); }} // This code is contributed by Princi Singh",
"e": 10533,
"s": 8389,
"text": null
},
{
"code": "<script> // Javascript program in-place Merge Sort // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]// Inplace Implementationfunction merge(arr, start, mid, end){ let start2 = mid + 1; // If the direct merge is already sorted if (arr[mid] <= arr[start2]) { return; } // Two pointers to maintain start // of both arrays to merge while (start <= mid && start2 <= end) { // If element 1 is in right place if (arr[start] <= arr[start2]) { start++; } else { let value = arr[start2]; let index = start2; // Shift all the elements between element 1 // element 2, right by 1. while (index != start) { arr[index] = arr[index - 1]; index--; } arr[start] = value; // Update all the pointers start++; mid++; start2++; } }} /* l is for left index and r is right indexof the sub-array of arr to be sorted */function mergeSort(arr, l, r){ if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r let m = l + Math.floor((r - l) / 2); // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} /* UTILITY FUNCTIONS *//* Function to print an array */function printArray(A, size){ let i; for(i = 0; i < size; i++) document.write(A[i] + \" \"); document.write(\"<br>\");} // Driver codelet arr = [ 12, 11, 13, 5, 6, 7 ];let arr_size = arr.length; mergeSort(arr, 0, arr_size - 1);printArray(arr, arr_size); // This code is contributed by rag2127 </script>",
"e": 12343,
"s": 10533,
"text": null
},
{
"code": null,
"e": 12359,
"s": 12343,
"text": "5 6 7 11 12 13 "
},
{
"code": null,
"e": 12501,
"s": 12359,
"text": "Note: Time Complexity of above approach is O(n2 * log(n)) because merge is O(n2). Time complexity of standard merge sort is less, O(n Log n)."
},
{
"code": null,
"e": 12689,
"s": 12501,
"text": "Approach 2: The idea: We start comparing elements that are far from each other rather than adjacent. Basically we are using shell sorting to merge two sorted arrays with O(1) extra space."
},
{
"code": null,
"e": 12703,
"s": 12689,
"text": "mergeSort(): "
},
{
"code": null,
"e": 12787,
"s": 12703,
"text": "Calculate mid two split the array in two halves(left sub-array and right sub-array)"
},
{
"code": null,
"e": 12866,
"s": 12787,
"text": "Recursively call merge sort on left sub-array and right sub-array to sort them"
},
{
"code": null,
"e": 12930,
"s": 12866,
"text": "Call merge function to merge left sub-array and right sub-array"
},
{
"code": null,
"e": 12939,
"s": 12930,
"text": "merge():"
},
{
"code": null,
"e": 13031,
"s": 12939,
"text": "For every pass, we calculate the gap and compare the elements towards the right of the gap."
},
{
"code": null,
"e": 13134,
"s": 13031,
"text": "Initiate the gap with ceiling value of n/2 where n is the combined length of left and right sub-array."
},
{
"code": null,
"e": 13193,
"s": 13134,
"text": "Every pass, the gap reduces to the ceiling value of gap/2."
},
{
"code": null,
"e": 13229,
"s": 13193,
"text": "Take a pointer i to pass the array."
},
{
"code": null,
"e": 13365,
"s": 13229,
"text": "Swap the ith and (i+gap)th elements if (i+gap)th element is smaller than(or greater than when sorting in decreasing order) ith element."
},
{
"code": null,
"e": 13394,
"s": 13365,
"text": "Stop when (i+gap) reaches n."
},
{
"code": null,
"e": 13427,
"s": 13394,
"text": "Input: 10, 30, 14, 11, 16, 7, 28"
},
{
"code": null,
"e": 13549,
"s": 13427,
"text": "Note: Assume left and right subarrays has been sorted so we are merging sorted subarrays [10, 14, 30] and [7, 11, 16, 28]"
},
{
"code": null,
"e": 13560,
"s": 13549,
"text": "Start with"
},
{
"code": null,
"e": 13592,
"s": 13560,
"text": "gap = ceiling of n/2 = 7/2 = 4"
},
{
"code": null,
"e": 13629,
"s": 13592,
"text": "[This gap is for whole merged array]"
},
{
"code": null,
"e": 13655,
"s": 13629,
"text": "10, 14, 30, 7, 11, 16, 28"
},
{
"code": null,
"e": 13681,
"s": 13655,
"text": "10, 14, 30, 7, 11, 16, 28"
},
{
"code": null,
"e": 13707,
"s": 13681,
"text": "10, 14, 30, 7, 11, 16, 28"
},
{
"code": null,
"e": 13733,
"s": 13707,
"text": "10, 14, 28, 7, 11, 16, 30"
},
{
"code": null,
"e": 13759,
"s": 13733,
"text": "gap = ceiling of 4/2 = 2"
},
{
"code": null,
"e": 13785,
"s": 13759,
"text": "10, 14, 28, 7, 11, 16, 30"
},
{
"code": null,
"e": 13811,
"s": 13785,
"text": "10, 14, 28, 7, 11, 16, 30"
},
{
"code": null,
"e": 13837,
"s": 13811,
"text": "10, 7, 28, 14, 11, 16, 30"
},
{
"code": null,
"e": 13863,
"s": 13837,
"text": "10, 7, 11, 14, 28, 16, 30"
},
{
"code": null,
"e": 13889,
"s": 13863,
"text": "10, 7, 11, 14, 28, 16, 30"
},
{
"code": null,
"e": 13917,
"s": 13891,
"text": "gap = ceiling of 2/2 = 1"
},
{
"code": null,
"e": 13943,
"s": 13917,
"text": "10, 7, 11, 14, 28, 16, 30"
},
{
"code": null,
"e": 13969,
"s": 13943,
"text": "7, 10, 11, 14, 28, 16, 30"
},
{
"code": null,
"e": 13995,
"s": 13969,
"text": "7, 10, 11, 14, 28, 16, 30"
},
{
"code": null,
"e": 14021,
"s": 13995,
"text": "7, 10, 11, 14, 28, 16, 30"
},
{
"code": null,
"e": 14047,
"s": 14021,
"text": "7, 10, 11, 14, 28, 16, 30"
},
{
"code": null,
"e": 14073,
"s": 14047,
"text": "7, 10, 11, 14, 16, 28, 30"
},
{
"code": null,
"e": 14109,
"s": 14075,
"text": "Output: 7, 10, 11, 14, 16, 28, 30"
},
{
"code": null,
"e": 14160,
"s": 14109,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 14164,
"s": 14160,
"text": "C++"
},
{
"code": null,
"e": 14169,
"s": 14164,
"text": "Java"
},
{
"code": null,
"e": 14177,
"s": 14169,
"text": "Python3"
},
{
"code": null,
"e": 14180,
"s": 14177,
"text": "C#"
},
{
"code": null,
"e": 14191,
"s": 14180,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Calculating next gapint nextGap(int gap){ if (gap <= 1) return 0; return (int)ceil(gap / 2.0);} // Function for swappingvoid swap(int nums[], int i, int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp;} // Merging the subarrays using shell sorting// Time Complexity: O(nlog n)// Space Complexity: O(1)void inPlaceMerge(int nums[], int start, int end){ int gap = end - start + 1; for(gap = nextGap(gap); gap > 0; gap = nextGap(gap)) { for(int i = start; i + gap <= end; i++) { int j = i + gap; if (nums[i] > nums[j]) swap(nums, i, j); } }} // merge sort makes log n recursive calls// and each time calls merge()// which takes nlog n steps// Time Complexity: O(n*log n + 2((n/2)*log(n/2)) +// 4((n/4)*log(n/4)) +.....+ 1)// Time Complexity: O(logn*(n*log n))// i.e. O(n*(logn)^2)// Space Complexity: O(1)void mergeSort(int nums[], int s, int e){ if (s == e) return; // Calculating mid to slice the // array in two halves int mid = (s + e) / 2; // Recursive calls to sort left // and right subarrays mergeSort(nums, s, mid); mergeSort(nums, mid + 1, e); inPlaceMerge(nums, s, e);} // Driver Codeint main(){ int nums[] = { 12, 11, 13, 5, 6, 7 }; int nums_size = sizeof(nums) / sizeof(nums[0]); mergeSort(nums, 0, nums_size-1); for(int i = 0; i < nums_size; i++) { cout << nums[i] << \" \"; } return 0;} // This code is contributed by adityapande88",
"e": 15849,
"s": 14191,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class InPlaceMerge { // Calculating next gap private static int nextGap(int gap) { if (gap <= 1) return 0; return (int)Math.ceil(gap / 2.0); } // Function for swapping private static void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } // Merging the subarrays using shell sorting // Time Complexity: O(nlog n) // Space Complexity: O(1) private static void inPlaceMerge(int[] nums, int start, int end) { int gap = end - start + 1; for (gap = nextGap(gap); gap > 0; gap = nextGap(gap)) { for (int i = start; i + gap <= end; i++) { int j = i + gap; if (nums[i] > nums[j]) swap(nums, i, j); } } } // merge sort makes log n recursive calls // and each time calls merge() // which takes nlog n steps // Time Complexity: O(n*log n + 2((n/2)*log(n/2)) + // 4((n/4)*log(n/4)) +.....+ 1) // Time Complexity: O(logn*(n*log n)) // i.e. O(n*(logn)^2) // Space Complexity: O(1) private static void mergeSort(int[] nums, int s, int e) { if (s == e) return; // Calculating mid to slice the // array in two halves int mid = (s + e) / 2; // Recursive calls to sort left // and right subarrays mergeSort(nums, s, mid); mergeSort(nums, mid + 1, e); inPlaceMerge(nums, s, e); } // Driver Code public static void main(String[] args) { int[] nums = new int[] { 12, 11, 13, 5, 6, 7 }; mergeSort(nums, 0, nums.length - 1); System.out.println(Arrays.toString(nums)); }}",
"e": 17686,
"s": 15849,
"text": null
},
{
"code": "# Python3 program for the above approachimport math # Calculating next gapdef nextGap(gap): if gap <= 1: return 0 return int(math.ceil(gap / 2)) # Function for swappingdef swap(nums, i, j): temp = nums[i] nums[i] = nums[j] nums[j] = temp # Merging the subarrays using shell sorting# Time Complexity: O(nlog n)# Space Complexity: O(1)def inPlaceMerge(nums,start, end): gap = end - start + 1 gap = nextGap(gap) while gap > 0: i = start while (i + gap) <= end: j = i + gap if nums[i] > nums[j]: swap(nums, i, j) i += 1 gap = nextGap(gap) # merge sort makes log n recursive calls# and each time calls merge()# which takes nlog n steps# Time Complexity: O(n*log n + 2((n/2)*log(n/2)) +# 4((n/4)*log(n/4)) +.....+ 1)# Time Complexity: O(logn*(n*log n))# i.e. O(n*(logn)^2)# Space Complexity: O(1)def mergeSort(nums, s, e): if s == e: return # Calculating mid to slice the # array in two halves mid = (s + e) // 2 # Recursive calls to sort left # and right subarrays mergeSort(nums, s, mid) mergeSort(nums, mid + 1, e) inPlaceMerge(nums, s, e) # UTILITY FUNCTIONS# Function to print an arraydef printArray(A, size): for i in range(size): print(A[i], end = \" \") print() # Driver Codeif __name__ == '__main__': arr = [ 12, 11, 13, 5, 6, 7 ] arr_size = len(arr) mergeSort(arr, 0, arr_size - 1) printArray(arr, arr_size) # This code is contributed by adityapande88",
"e": 19291,
"s": 17686,
"text": null
},
{
"code": "// C# program for the above approach // Include namespace systemusing System;using System.Linq; using System.Collections; public class InPlaceMerge{ // Calculating next gap private static int nextGap(int gap) { if (gap <= 1) { return 0; } return (int)Math.Ceiling(gap / 2.0); } // Function for swapping private static void swap(int[] nums, int i, int j) { var temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } // Merging the subarrays using shell sorting // Time Complexity: O(nlog n) // Space Complexity: O(1) private static void inPlaceMerge(int[] nums, int start, int end) { var gap = end - start + 1; for (gap = InPlaceMerge.nextGap(gap); gap > 0; gap = InPlaceMerge.nextGap(gap)) { for (int i = start; i + gap <= end; i++) { var j = i + gap; if (nums[i] > nums[j]) { InPlaceMerge.swap(nums, i, j); } } } } // merge sort makes log n recursive calls // and each time calls merge() // which takes nlog n steps // Time Complexity: O(n*log n + 2((n/2)*log(n/2)) + // 4((n/4)*log(n/4)) +.....+ 1) // Time Complexity: O(logn*(n*log n)) // i.e. O(n*(logn)^2) // Space Complexity: O(1) private static void mergeSort(int[] nums, int s, int e) { if (s == e) { return; } // Calculating mid to slice the // array in two halves var mid = (int)((s + e) / 2); // Recursive calls to sort left // and right subarrays InPlaceMerge.mergeSort(nums, s, mid); InPlaceMerge.mergeSort(nums, mid + 1, e); InPlaceMerge.inPlaceMerge(nums, s, e); } // Driver Code public static void Main(String[] args) { int[] nums = new int[] { 12, 11, 13, 5, 6, 7 }; InPlaceMerge.mergeSort(nums, 0, nums.Length - 1); Console.WriteLine(string.Join(\", \", nums)); }} // This code is contributed by mukulsomukesh",
"e": 21156,
"s": 19291,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Calculating next gapfunction nextGap(gap){ if (gap <= 1) return 0; return Math.floor(Math.ceil(gap / 2.0));} // Function for swappingfunction swap(nums,i,j){ let temp = nums[i]; nums[i] = nums[j]; nums[j] = temp;} // Merging the subarrays using shell sorting // Time Complexity: O(nlog n) // Space Complexity: O(1)function inPlaceMerge(nums,start,end){ let gap = end - start + 1; for (gap = nextGap(gap); gap > 0; gap = nextGap(gap)) { for (let i = start; i + gap <= end; i++) { let j = i + gap; if (nums[i] > nums[j]) swap(nums, i, j); } }} // merge sort makes log n recursive calls // and each time calls merge() // which takes nlog n steps // Time Complexity: O(n*log n + 2((n/2)*log(n/2)) + // 4((n/4)*log(n/4)) +.....+ 1) // Time Complexity: O(logn*(n*log n)) // i.e. O(n*(logn)^2) // Space Complexity: O(1)function mergeSort(nums,s,e){ if (s == e) return; // Calculating mid to slice the // array in two halves let mid = Math.floor((s + e) / 2); // Recursive calls to sort left // and right subarrays mergeSort(nums, s, mid); mergeSort(nums, mid + 1, e); inPlaceMerge(nums, s, e);} // Driver Codelet nums=[12, 11, 13, 5, 6, 7 ];mergeSort(nums, 0, nums.length - 1);document.write((nums).join(\" \")); // This code is contributed by avanitrachhadiya2155</script>",
"e": 22716,
"s": 21156,
"text": null
},
{
"code": null,
"e": 22732,
"s": 22716,
"text": "5 6 7 11 12 13 "
},
{
"code": null,
"e": 22765,
"s": 22732,
"text": "Time Complexity: O(log n*nlog n)"
},
{
"code": null,
"e": 22900,
"s": 22765,
"text": "Note: mergeSort method makes log n recursive calls and each time merge is called which takes n log n time to merge 2 sorted sub-arrays"
},
{
"code": null,
"e": 22945,
"s": 22900,
"text": "Approach 3: Here we use the below technique:"
},
{
"code": null,
"e": 23458,
"s": 22945,
"text": "Suppose we have a number A and we want to \nconvert it to a number B and there is also a \nconstraint that we can recover number A any \ntime without using other variable.To achieve \nthis we choose a number N which is greater \nthan both numbers and add B*N in A.\nso A --> A+B*N\n\nTo get number B out of (A+B*N) \nwe divide (A+B*N) by N (A+B*N)/N = B.\n\nTo get number A out of (A+B*N) \nwe take modulo with N (A+B*N)%N = A.\n\n-> In short by taking modulo \nwe get old number back and taking divide \nwe new number."
},
{
"code": null,
"e": 23471,
"s": 23458,
"text": "mergeSort():"
},
{
"code": null,
"e": 23557,
"s": 23471,
"text": "Calculate mid two split the array into two halves(left sub-array and right sub-array)"
},
{
"code": null,
"e": 23636,
"s": 23557,
"text": "Recursively call merge sort on left sub-array and right sub-array to sort them"
},
{
"code": null,
"e": 23700,
"s": 23636,
"text": "Call merge function to merge left sub-array and right sub-array"
},
{
"code": null,
"e": 23709,
"s": 23700,
"text": "merge():"
},
{
"code": null,
"e": 23851,
"s": 23709,
"text": "We first find the maximum element of both sub-array and increment it one to avoid collision of 0 and maximum element during modulo operation."
},
{
"code": null,
"e": 24029,
"s": 23851,
"text": "The idea is to traverse both sub-arrays from starting simultaneously. One starts from l till m and another starts from m+1 till r. So, We will initialize 3 pointers say i, j, k."
},
{
"code": null,
"e": 24112,
"s": 24029,
"text": "i will move from l till m; j will move from m+1 till r; k will move from l till r."
},
{
"code": null,
"e": 24176,
"s": 24112,
"text": "Now update value a[k] by adding min(a[i],a[j])*maximum_element."
},
{
"code": null,
"e": 24243,
"s": 24176,
"text": "Then also update those elements which are left in both sub-arrays."
},
{
"code": null,
"e": 24352,
"s": 24243,
"text": "After updating all the elements divide all the elements by maximum_element so we get the updated array back."
},
{
"code": null,
"e": 24403,
"s": 24352,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 24407,
"s": 24403,
"text": "C++"
},
{
"code": null,
"e": 24412,
"s": 24407,
"text": "Java"
},
{
"code": "// C++ program in-place Merge Sort#include <bits/stdc++.h>using namespace std; // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]// Inplace Implementationvoid mergeInPlace(int a[], int l, int m, int r){ // increment the maximum_element by one to avoid // collision of 0 and maximum element of array in modulo // operation int mx = max(a[m], a[r]) + 1; int i = l, j = m + 1, k = l; while (i <= m && j <= r && k <= r) { // recover back original element to compare int e1 = a[i] % mx; int e2 = a[j] % mx; if (e1 <= e2) { a[k] += (e1 * mx); i++; k++; } else { a[k] += (e2 * mx); j++; k++; } } // process those elements which are left in the array while (i <= m) { int el = a[i] % mx; a[k] += (el * mx); i++; k++; } while (j <= r) { int el = a[j] % mx; a[k] += (el * mx); j++; k++; } // finally update elements by dividing with maximum // element for (int i = l; i <= r; i++) a[i] /= mx;} /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); mergeInPlace(arr, l, m, r); }} // Driver Codeint main(){ int nums[] = { 12, 11, 13, 5, 6, 7 }; int nums_size = sizeof(nums) / sizeof(nums[0]); mergeSort(nums, 0, nums_size - 1); for (int i = 0; i < nums_size; i++) { cout << nums[i] << \" \"; } return 0;} // This code is contributed by soham11806959",
"e": 26261,
"s": 24412,
"text": null
},
{
"code": "// Java program in-place Merge Sortimport java.io.*;import java.util.*; class GFG { // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]// Inplace Implementationprivate static void mergeInPlace(int a[], int l, int m, int r){ // increment the maximum_element by one to avoid // collision of 0 and maximum element of array in modulo // operation int mx = Math.max(a[m], a[r]) + 1; int i = l, j = m + 1, k = l; while (i <= m && j <= r && k <= r) { // recover back original element to compare int e1 = a[i] % mx; int e2 = a[j] % mx; if (e1 <= e2) { a[k] += (e1 * mx); i++; k++; } else { a[k] += (e2 * mx); j++; k++; } } // process those elements which are left in the array while (i <= m) { int el = a[i] % mx; a[k] += (el * mx); i++; k++; } while (j <= r) { int el = a[j] % mx; a[k] += (el * mx); j++; k++; } // finally update elements by dividing with maximum // element for (i = l; i <= r; i++) a[i] /= mx;} /* l is for left index and r is right index of the sub-array of arr to be sorted */private static void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l + r) / 2, but avoids overflow // for large l and r int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); mergeInPlace(arr, l, m, r); }} // Driver Code public static void main(String[] args) { int nums[] = { 12, 11, 13, 5, 6, 7 }; int nums_size = nums.length; mergeSort(nums, 0, nums_size - 1); for (int i = 0; i < nums_size; i++) { System.out.print(nums[i]+\" \"); } }} // This code is contributed by Pushpesh Raj",
"e": 28208,
"s": 26261,
"text": null
},
{
"code": null,
"e": 28224,
"s": 28208,
"text": "5 6 7 11 12 13 "
},
{
"code": null,
"e": 28379,
"s": 28224,
"text": "Time Complexity: O(n log n)Note: Time Complexity of above approach is O(n2) because merge is O(n). Time complexity of standard merge sort is O(n log n)."
},
{
"code": null,
"e": 28456,
"s": 28379,
"text": "Approach 4: Here we use the following technique to perform an in-place merge"
},
{
"code": null,
"e": 29367,
"s": 28456,
"text": "Given 2 adjacent sorted sub-arrays within an array (hereafter\nnamed A and B for convenience), appreciate that we can swap\nsome of the last portion of A with an equal number of elements\nfrom the start of B, such that after the exchange, all of the\nelements in A are less than or equal to any element in B.\n\nAfter this exchange, this leaves with the A containing 2 sorted\nsub-arrays, being the first original portion of A, and the first\noriginal portion of B, and sub-array B now containing 2 sorted\nsub-arrays, being the final original portion of A followed by\nthe final original portion of B\n\nWe can now recursively call the merge operation with the 2\nsub-arrays of A, followed by recursively calling the merge\noperation with the 2 sub-arrays of B\n\nWe stop the recursion when either A or B are empty, or when\neither sub-array is small enough to efficiently merge into\nthe other sub-array using insertion sort. "
},
{
"code": null,
"e": 29469,
"s": 29367,
"text": "The above procedure naturally lends itself to the following implementation of an in-place merge sort."
},
{
"code": null,
"e": 29478,
"s": 29469,
"text": "merge():"
},
{
"code": null,
"e": 29577,
"s": 29478,
"text": "Hereafter, for convenience, we’ll refer to the first sub-array as A, and the second sub-array as B"
},
{
"code": null,
"e": 29686,
"s": 29577,
"text": "If either A or B are empty, or if the first element B is not less than the last element of A then we’re done"
},
{
"code": null,
"e": 29823,
"s": 29686,
"text": "If the length of A is small enough and if it’s length is less than the length of B, then use insertion sort to merge A into B and return"
},
{
"code": null,
"e": 29911,
"s": 29823,
"text": "If the length of B is small enough then use insertion sort to merge B into A and return"
},
{
"code": null,
"e": 30087,
"s": 29911,
"text": "Find the location in A where we can exchange the remaining portion of A with the first-portion of B, such that all the elements in A are less than or equal to any element in B"
},
{
"code": null,
"e": 30124,
"s": 30087,
"text": "Perform the exchange between A and B"
},
{
"code": null,
"e": 30194,
"s": 30124,
"text": "Recursively call merge() on the 2 sorted sub-arrays now residing in A"
},
{
"code": null,
"e": 30264,
"s": 30194,
"text": "Recursively call merge() on the 2 sorted sub-arrays now residing in B"
},
{
"code": null,
"e": 30278,
"s": 30264,
"text": "merge_sort():"
},
{
"code": null,
"e": 30346,
"s": 30278,
"text": "Split the array into two halves(left sub-array and right sub-array)"
},
{
"code": null,
"e": 30427,
"s": 30346,
"text": "Recursively call merge_sort() on left sub-array and right sub-array to sort them"
},
{
"code": null,
"e": 30491,
"s": 30427,
"text": "Call merge function to merge left sub-array and right sub-array"
},
{
"code": null,
"e": 30495,
"s": 30491,
"text": "C++"
},
{
"code": null,
"e": 30497,
"s": 30495,
"text": "C"
},
{
"code": "// Merge In Place in C++ #include <iostream>using namespace std; #define __INSERT_THRESH 5#define __swap(x, y) (t = *(x), *(x) = *(y), *(y) = t) // Both sorted sub-arrays must be adjacent in 'a'// 'an' is the length of the first sorted section in 'a'// 'bn' is the length of the second sorted section in 'a'static void merge(int* a, size_t an, size_t bn){ int *b = a + an, *e = b + bn, *s, t; // Return right now if we're done if (an == 0 || bn == 0 || !(*b < *(b - 1))) return; // Do insertion sort to merge if size of sub-arrays are // small enough if (an < __INSERT_THRESH && an <= bn) { for (int *p = b, *v; p > a; p--) // Insert Sort A into B for (v = p, s = p - 1; v < e && *v < *s; s = v, v++) __swap(s, v); return; } if (bn < __INSERT_THRESH) { for (int *p = b, *v; p < e; p++) // Insert Sort B into A for (s = p, v = p - 1; s > a && *s < *v; s = v, v--) __swap(s, v); return; } // Find the pivot points. Basically this is just // finding the point in 'a' where we can swap in the // first part of 'b' such that after the swap the last // element in 'a' will be less than or equal to the // least element in 'b' int *pa = a, *pb = b; for (s = a; s < b && pb < e; s++) if (*pb < *pa) pb++; else pa++; pa += b - s; // Swap first part of b with last part of a for (int *la = pa, *fb = b; la < b; la++, fb++) __swap(la, fb); // Now merge the two sub-array pairings merge(a, pa - a, pb - b); merge(b, pb - b, e - pb);} // merge_array_inplace #undef __swap#undef __INSERT_THRESH // Merge Sort Implementationvoid merge_sort(int* a, size_t n){ size_t m = (n + 1) / 2; // Sort first and second halves if (m > 1) merge_sort(a, m); if (n - m > 1) merge_sort(a + m, n - m); // Now merge the two sorted sub-arrays together merge(a, m, n - m);} // Function to print an arrayvoid print_array(int a[], size_t n){ if (n > 0) { cout <<\" \"<< a[0]; for (size_t i = 1; i < n; i++) cout <<\" \"<< a[i]; } cout <<\"\\n\";} // Driver program to test sort utilityint main(){ int a[] = { 3, 16, 5, 14, 8, 10, 7, 15, 1, 13, 4, 9, 12, 11, 6, 2 }; size_t n = sizeof(a) / sizeof(a[0]); merge_sort(a, n); print_array(a, n); return 0;} // This code is contributed by shivanisinghss2110",
"e": 33017,
"s": 30497,
"text": null
},
{
"code": "// Merge In Place in C #include <stddef.h>#include <stdio.h> #define __INSERT_THRESH 5#define __swap(x, y) (t = *(x), *(x) = *(y), *(y) = t) // Both sorted sub-arrays must be adjacent in 'a'// 'an' is the length of the first sorted section in 'a'// 'bn' is the length of the second sorted section in 'a'static void merge(int* a, size_t an, size_t bn){ int *b = a + an, *e = b + bn, *s, t; // Return right now if we're done if (an == 0 || bn == 0 || !(*b < *(b - 1))) return; // Do insertion sort to merge if size of sub-arrays are // small enough if (an < __INSERT_THRESH && an <= bn) { for (int *p = b, *v; p > a; p--) // Insert Sort A into B for (v = p, s = p - 1; v < e && *v < *s; s = v, v++) __swap(s, v); return; } if (bn < __INSERT_THRESH) { for (int *p = b, *v; p < e; p++) // Insert Sort B into A for (s = p, v = p - 1; s > a && *s < *v; s = v, v--) __swap(s, v); return; } // Find the pivot points. Basically this is just // finding the point in 'a' where we can swap in the // first part of 'b' such that after the swap the last // element in 'a' will be less than or equal to the // least element in 'b' int *pa = a, *pb = b; for (s = a; s < b && pb < e; s++) if (*pb < *pa) pb++; else pa++; pa += b - s; // Swap first part of b with last part of a for (int *la = pa, *fb = b; la < b; la++, fb++) __swap(la, fb); // Now merge the two sub-array pairings merge(a, pa - a, pb - b); merge(b, pb - b, e - pb);} // merge_array_inplace #undef __swap#undef __INSERT_THRESH // Merge Sort Implementationvoid merge_sort(int* a, size_t n){ size_t m = (n + 1) / 2; // Sort first and second halves if (m > 1) merge_sort(a, m); if (n - m > 1) merge_sort(a + m, n - m); // Now merge the two sorted sub-arrays together merge(a, m, n - m);} // Function to print an arrayvoid print_array(int a[], size_t n){ if (n > 0) { printf(\"%d\", a[0]); for (size_t i = 1; i < n; i++) printf(\" %d\", a[i]); } printf(\"\\n\");} // Driver program to test sort utiliyyint main(){ int a[] = { 3, 16, 5, 14, 8, 10, 7, 15, 1, 13, 4, 9, 12, 11, 6, 2 }; size_t n = sizeof(a) / sizeof(a[0]); merge_sort(a, n); print_array(a, n); return 0;} // Author: Stew Forster ([email protected]) Date: 29// July 2021",
"e": 35577,
"s": 33017,
"text": null
},
{
"code": null,
"e": 35616,
"s": 35577,
"text": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16"
},
{
"code": null,
"e": 35699,
"s": 35616,
"text": "Time Complexity of merge(): Worst Case: O(n^2), Average: O(n log n), Best: O(1)"
},
{
"code": null,
"e": 35830,
"s": 35699,
"text": "Time Complexity of merge_sort() function: Overall: O(log n) for the recursion alone, due to always evenly dividing the array in 2"
},
{
"code": null,
"e": 35939,
"s": 35830,
"text": "Time Complexity of merge_sort() overall: Worst Case: O(n^2 log n), Average: O(n (log n)^2), Best: O(log n)"
},
{
"code": null,
"e": 36064,
"s": 35939,
"text": "The worst-case occurs when every sub-array exchange within merge() results in just _INSERT_THRESH-1 elements being exchanged"
},
{
"code": null,
"e": 36072,
"s": 36064,
"text": "ankthon"
},
{
"code": null,
"e": 36085,
"s": 36072,
"text": "princi singh"
},
{
"code": null,
"e": 36096,
"s": 36085,
"text": "nidhi_biet"
},
{
"code": null,
"e": 36108,
"s": 36096,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36118,
"s": 36108,
"text": "naveenk2k"
},
{
"code": null,
"e": 36132,
"s": 36118,
"text": "ShashwatKhare"
},
{
"code": null,
"e": 36146,
"s": 36132,
"text": "mittulmandhan"
},
{
"code": null,
"e": 36160,
"s": 36146,
"text": "adityapande88"
},
{
"code": null,
"e": 36174,
"s": 36160,
"text": "soham11806959"
},
{
"code": null,
"e": 36190,
"s": 36174,
"text": "simranarora5sos"
},
{
"code": null,
"e": 36201,
"s": 36190,
"text": "iit2018065"
},
{
"code": null,
"e": 36209,
"s": 36201,
"text": "rag2127"
},
{
"code": null,
"e": 36217,
"s": 36209,
"text": "stew675"
},
{
"code": null,
"e": 36238,
"s": 36217,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 36257,
"s": 36238,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 36269,
"s": 36257,
"text": "UtkarshGpta"
},
{
"code": null,
"e": 36281,
"s": 36269,
"text": "kashishsoda"
},
{
"code": null,
"e": 36298,
"s": 36281,
"text": "surinderdawra388"
},
{
"code": null,
"e": 36312,
"s": 36298,
"text": "mukulsomukesh"
},
{
"code": null,
"e": 36328,
"s": 36312,
"text": "pushpeshrajdx01"
},
{
"code": null,
"e": 36337,
"s": 36328,
"text": "sweetyty"
},
{
"code": null,
"e": 36349,
"s": 36337,
"text": "array-merge"
},
{
"code": null,
"e": 36360,
"s": 36349,
"text": "Merge Sort"
},
{
"code": null,
"e": 36368,
"s": 36360,
"text": "Sorting"
},
{
"code": null,
"e": 36376,
"s": 36368,
"text": "Sorting"
},
{
"code": null,
"e": 36387,
"s": 36376,
"text": "Merge Sort"
},
{
"code": null,
"e": 36485,
"s": 36387,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36516,
"s": 36485,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 36552,
"s": 36516,
"text": "Longest Common Prefix using Sorting"
},
{
"code": null,
"e": 36593,
"s": 36552,
"text": "Sort a nearly sorted (or K sorted) array"
},
{
"code": null,
"e": 36625,
"s": 36593,
"text": "Segregate 0s and 1s in an array"
},
{
"code": null,
"e": 36641,
"s": 36625,
"text": "Sorting in Java"
},
{
"code": null,
"e": 36690,
"s": 36641,
"text": "Find whether an array is subset of another array"
},
{
"code": null,
"e": 36722,
"s": 36690,
"text": "Find all triplets with zero sum"
},
{
"code": null,
"e": 36754,
"s": 36722,
"text": "Stability in sorting algorithms"
}
] |
C# | Operators | 09 Jul, 2021
Operators are the foundation of any programming language. Thus the functionality of C# language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In C#, operators Can be categorized based upon their different functionality :
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Conditional Operator
In C#, Operators can also categorized based upon Number of Operands :
Unary Operator: Operator that takes one operand to perform the operation.
Binary Operator: Operator that takes two operands to perform the operation.
Ternary Operator: Operator that takes three operands to perform the operation.
Arithmetic Operators
These are used to perform arithmetic/mathematical operations on operands. The Binary Operators falling in this category are :
Addition: The ‘+’ operator adds two operands. For example, x+y.
Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
Division: The ‘/’ operator divides the first operand by the second. For example, x/y.
Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second. For example, x%y.
Example:
C#
// C# program to demonstrate the working// of Binary Arithmetic Operatorsusing System;namespace Arithmetic{ class GFG { // Main Function static void Main(string[] args) { int result; int x = 10, y = 5; // Addition result = (x + y); Console.WriteLine("Addition Operator: " + result); // Subtraction result = (x - y); Console.WriteLine("Subtraction Operator: " + result); // Multiplication result = (x * y); Console.WriteLine("Multiplication Operator: "+ result); // Division result = (x / y); Console.WriteLine("Division Operator: " + result); // Modulo result = (x % y); Console.WriteLine("Modulo Operator: " + result); } }}
Output:
Addition Operator: 15
Subtraction Operator: 5
Multiplication Operator: 50
Division Operator: 2
Modulo Operator: 0
The ones falling into the category of Unary Operators are:
Increment: The ‘++’ operator is used to increment the value of an integer. When placed before the variable name (also called pre-increment operator), its value is incremented instantly. For example, ++x. And when it is placed after the variable name (also called post-increment operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x++.
Decrement: The ‘–‘ operator is used to decrement the value of an integer. When placed before the variable name (also called pre-decrement operator), its value is decremented instantly. For example, –x.And when it is placed after the variable name (also called post-decrement operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x–.
Example:
C#
// C# program to demonstrate the working// of Unary Arithmetic Operatorsusing System;namespace Arithmetic { class GFG { // Main Function static void Main(string[] args) { int a = 10, res; // post-increment example: // res is assigned 10 only, // a is not updated yet res = a++; //a becomes 11 now Console.WriteLine("a is {0} and res is {1}", a, res); // post-decrement example: // res is assigned 11 only, a is not updated yet res = a--; //a becomes 10 now Console.WriteLine("a is {0} and res is {1}", a, res); // pre-increment example: // res is assigned 11 now since a // is updated here itself res = ++a; // a and res have same values = 11 Console.WriteLine("a is {0} and res is {1}", a, res); // pre-decrement example: // res is assigned 10 only since // a is updated here itself res = --a; // a and res have same values = 10 Console.WriteLine("a is {0} and res is {1}",a, res); } }}
Output:
a is 11 and res is 10
a is 10 and res is 11
a is 11 and res is 11
a is 10 and res is 10
Relational Operators
Relational operators are used for comparison of two values. Let’s see them one by one:
‘=='(Equal To) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 5==5 will return true.
‘!='(Not Equal To) operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false.
‘>'(Greater Than) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
‘<‘(Less Than) operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 6<5 will return false.
‘>='(Greater Than Equal To) operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true.
‘<='(Less Than Equal To) operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true.
Example:
C#
// C# program to demonstrate the working// of Relational Operatorsusing System;namespace Relational { class GFG { // Main Function static void Main(string[] args) { bool result; int x = 5, y = 10; // Equal to Operator result = (x == y); Console.WriteLine("Equal to Operator: " + result); // Greater than Operator result = (x > y); Console.WriteLine("Greater than Operator: " + result); // Less than Operator result = (x < y); Console.WriteLine("Less than Operator: " + result); // Greater than Equal to Operator result = (x >= y); Console.WriteLine("Greater than or Equal to: "+ result); // Less than Equal to Operator result = (x <= y); Console.WriteLine("Lesser than or Equal to: "+ result); // Not Equal To Operator result = (x != y); Console.WriteLine("Not Equal to Operator: " + result); }}}
Output:
Equal to Operator: False
Greater than Operator: False
Less than Operator: True
Greater than or Equal to: False
Lesser than or Equal to: True
Not Equal to Operator: True
Logical Operators
They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below:
Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. For example, a && b returns true when both a and b are true (i.e. non-zero).
Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true.
Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e. when a=0.
Example:
C#
// C# program to demonstrate the working// of Logical Operatorsusing System;namespace Logical { class GFG { // Main Function static void Main(string[] args) { bool a = true,b = false, result; // AND operator result = a && b; Console.WriteLine("AND Operator: " + result); // OR operator result = a || b; Console.WriteLine("OR Operator: " + result); // NOT operator result = !a; Console.WriteLine("NOT Operator: " + result); }}}
Output:
AND Operator: False
OR Operator: True
NOT Operator: False
Bitwise Operators
In C#, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations. Following are the bitwise operators :
& (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
| (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.
^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
<< (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.
>> (right shift) Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.
Example:
C#
// C# program to demonstrate the working// of Bitwise Operatorsusing System;namespace Bitwise { class GFG { // Main Function static void Main(string[] args) { int x = 5, y = 10, result; // Bitwise AND Operator result = x & y; Console.WriteLine("Bitwise AND: " + result); // Bitwise OR Operator result = x | y; Console.WriteLine("Bitwise OR: " + result); // Bitwise XOR Operator result = x ^ y; Console.WriteLine("Bitwise XOR: " + result); // Bitwise AND Operator result = ~x; Console.WriteLine("Bitwise Complement: " + result); // Bitwise LEFT SHIFT Operator result = x << 2; Console.WriteLine("Bitwise Left Shift: " + result); // Bitwise RIGHT SHIFT Operator result = x >> 2; Console.WriteLine("Bitwise Right Shift: " + result); }}}
Output:
Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -6
Bitwise Left Shift: 20
Bitwise Right Shift: 1
Assignment Operators
Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.
Different types of assignment operators are shown below:
“=”(Simple Assignment): This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.Example:
a = 10;
b = 20;
ch = 'y';
“+=”(Add Assignment): This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
“-=”(Subtract Assignment): This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left.Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
“*=”(Multiply Assignment): This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.Example:
(a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
“/=”(Division Assignment): This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:
(a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.
“%=”(Modulus Assignment): This operator is combination of ‘%’ and ‘=’ operators. This operator first modulo the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:
(a %= b) can be written as (a = a % b)
If initially value stored in a is 6. Then (a %= 2) = 0.
“<<=”(Left Shift Assignment) : This operator is combination of ‘<<‘ and ‘=’ operators. This operator first Left shift the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:
(a <<= 2) can be written as (a = a << 2)
If initially value stored in a is 6. Then (a <<= 2) = 24.
“>>=”(Right Shift Assignment) : This operator is combination of ‘>>’ and ‘=’ operators. This operator first Right shift the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:
(a >>= 2) can be written as (a = a >> 2)
If initially value stored in a is 6. Then (a >>= 2) = 1.
“&=”(Bitwise AND Assignment): This operator is combination of ‘&’ and ‘=’ operators. This operator first “Bitwise AND” the current value of the variable on the left by the value on the right and then assigns the result to the variable on the left.Example:
(a &= 2) can be written as (a = a & 2)
If initially value stored in a is 6. Then (a &= 2) = 2.
“^=”(Bitwise Exclusive OR): This operator is combination of ‘^’ and ‘=’ operators. This operator first “Bitwise Exclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:
(a ^= 2) can be written as (a = a ^ 2)
If initially value stored in a is 6. Then (a ^= 2) = 4.
“|=”(Bitwise Inclusive OR) : This operator is combination of ‘|’ and ‘=’ operators. This operator first “Bitwise Inclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example :
(a |= 2) can be written as (a = a | 2)
If initially, value stored in a is 6. Then (a |= 2) = 6.
Example:
C#
// C# program to demonstrate the working// of Assignment Operatorsusing System;namespace Assignment { class GFG { // Main Function static void Main(string[] args) { // initialize variable x // using Simple Assignment // Operator "=" int x = 15; // it means x = x + 10 x += 10; Console.WriteLine("Add Assignment Operator: " + x); // initialize variable x again x = 20; // it means x = x - 5 x -= 5; Console.WriteLine("Subtract Assignment Operator: " + x); // initialize variable x again x = 15; // it means x = x * 5 x *= 5; Console.WriteLine("Multiply Assignment Operator: " + x); // initialize variable x again x = 25; // it means x = x / 5 x /= 5; Console.WriteLine("Division Assignment Operator: " + x); // initialize variable x again x = 25; // it means x = x % 5 x %= 5; Console.WriteLine("Modulo Assignment Operator: " + x); // initialize variable x again x = 8; // it means x = x << 2 x <<= 2; Console.WriteLine("Left Shift Assignment Operator: " + x); // initialize variable x again x = 8; // it means x = x >> 2 x >>= 2; Console.WriteLine("Right Shift Assignment Operator: " + x); // initialize variable x again x = 12; // it means x = x >> 4 x &= 4; Console.WriteLine("Bitwise AND Assignment Operator: " + x); // initialize variable x again x = 12; // it means x = x >> 4 x ^= 4; Console.WriteLine("Bitwise Exclusive OR Assignment Operator: " + x); // initialize variable x again x = 12; // it means x = x >> 4 x |= 4; Console.WriteLine("Bitwise Inclusive OR Assignment Operator: " + x); }}}
Output :
Add Assignment Operator: 25
Subtract Assignment Operator: 15
Multiply Assignment Operator: 75
Division Assignment Operator: 5
Modulo Assignment Operator: 0
Left Shift Assignment Operator: 32
Right Shift Assignment Operator: 2
Bitwise AND Assignment Operator: 4
Bitwise Exclusive OR Assignment Operator: 8
Bitwise Inclusive OR Assignment Operator: 12
Conditional Operator
It is ternary operator which is a shorthand version of if-else statement. It has three operands and hence the name ternary. It will return one of two values depending on the value of a Boolean expression.
Syntax:
condition ? first_expression : second_expression;
Explanation:condition: It must be evaluated to true or false.If the condition is truefirst_expression is evaluated and becomes the result. If the condition is false, second_expression is evaluated and becomes the result.
Example:
C#
// C# program to demonstrate the working// of Conditional Operatorusing System;namespace Conditional { class GFG { // Main Function static void Main(string[] args) { int x = 5, y = 10, result; // To find which value is greater // Using Conditional Operator result = x > y ? x : y; // To display the result Console.WriteLine("Result: " + result); // To find which value is greater // Using Conditional Operator result = x < y ? x : y; // To display the result Console.WriteLine("Result: " + result); }}}
Output :
Result: 10
Result: 5
j24351si1icpepnpnnkpi34er5ms2wzv4bggx00n
sumitgumber28
CSharp Operators
CSharp-Basics
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Arrays of Strings
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
Different ways to sort an array in descending order in C#
C# | Replace() Method
C# | How to insert an element in an Array?
How to sort a list in C# | List.Sort() Method Set -1
C# | Multiple inheritance using interfaces
C# | Namespaces
Dynamic Type in C# | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 346,
"s": 54,
"text": "Operators are the foundation of any programming language. Thus the functionality of C# language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In C#, operators Can be categorized based upon their different functionality :"
},
{
"code": null,
"e": 367,
"s": 346,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 388,
"s": 367,
"text": "Relational Operators"
},
{
"code": null,
"e": 406,
"s": 388,
"text": "Logical Operators"
},
{
"code": null,
"e": 424,
"s": 406,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 445,
"s": 424,
"text": "Assignment Operators"
},
{
"code": null,
"e": 466,
"s": 445,
"text": "Conditional Operator"
},
{
"code": null,
"e": 537,
"s": 466,
"text": "In C#, Operators can also categorized based upon Number of Operands : "
},
{
"code": null,
"e": 611,
"s": 537,
"text": "Unary Operator: Operator that takes one operand to perform the operation."
},
{
"code": null,
"e": 687,
"s": 611,
"text": "Binary Operator: Operator that takes two operands to perform the operation."
},
{
"code": null,
"e": 767,
"s": 687,
"text": "Ternary Operator: Operator that takes three operands to perform the operation. "
},
{
"code": null,
"e": 788,
"s": 767,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 914,
"s": 788,
"text": "These are used to perform arithmetic/mathematical operations on operands. The Binary Operators falling in this category are :"
},
{
"code": null,
"e": 978,
"s": 914,
"text": "Addition: The ‘+’ operator adds two operands. For example, x+y."
},
{
"code": null,
"e": 1050,
"s": 978,
"text": "Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y."
},
{
"code": null,
"e": 1126,
"s": 1050,
"text": "Multiplication: The ‘*’ operator multiplies two operands. For example, x*y."
},
{
"code": null,
"e": 1212,
"s": 1126,
"text": "Division: The ‘/’ operator divides the first operand by the second. For example, x/y."
},
{
"code": null,
"e": 1323,
"s": 1212,
"text": "Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second. For example, x%y."
},
{
"code": null,
"e": 1332,
"s": 1323,
"text": "Example:"
},
{
"code": null,
"e": 1335,
"s": 1332,
"text": "C#"
},
{
"code": "// C# program to demonstrate the working// of Binary Arithmetic Operatorsusing System;namespace Arithmetic{ class GFG { // Main Function static void Main(string[] args) { int result; int x = 10, y = 5; // Addition result = (x + y); Console.WriteLine(\"Addition Operator: \" + result); // Subtraction result = (x - y); Console.WriteLine(\"Subtraction Operator: \" + result); // Multiplication result = (x * y); Console.WriteLine(\"Multiplication Operator: \"+ result); // Division result = (x / y); Console.WriteLine(\"Division Operator: \" + result); // Modulo result = (x % y); Console.WriteLine(\"Modulo Operator: \" + result); } }}",
"e": 2271,
"s": 1335,
"text": null
},
{
"code": null,
"e": 2279,
"s": 2271,
"text": "Output:"
},
{
"code": null,
"e": 2393,
"s": 2279,
"text": "Addition Operator: 15\nSubtraction Operator: 5\nMultiplication Operator: 50\nDivision Operator: 2\nModulo Operator: 0"
},
{
"code": null,
"e": 2452,
"s": 2393,
"text": "The ones falling into the category of Unary Operators are:"
},
{
"code": null,
"e": 2896,
"s": 2452,
"text": "Increment: The ‘++’ operator is used to increment the value of an integer. When placed before the variable name (also called pre-increment operator), its value is incremented instantly. For example, ++x. And when it is placed after the variable name (also called post-increment operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x++."
},
{
"code": null,
"e": 3336,
"s": 2896,
"text": "Decrement: The ‘–‘ operator is used to decrement the value of an integer. When placed before the variable name (also called pre-decrement operator), its value is decremented instantly. For example, –x.And when it is placed after the variable name (also called post-decrement operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x–."
},
{
"code": null,
"e": 3345,
"s": 3336,
"text": "Example:"
},
{
"code": null,
"e": 3348,
"s": 3345,
"text": "C#"
},
{
"code": "// C# program to demonstrate the working// of Unary Arithmetic Operatorsusing System;namespace Arithmetic { class GFG { // Main Function static void Main(string[] args) { int a = 10, res; // post-increment example: // res is assigned 10 only, // a is not updated yet res = a++; //a becomes 11 now Console.WriteLine(\"a is {0} and res is {1}\", a, res); // post-decrement example: // res is assigned 11 only, a is not updated yet res = a--; //a becomes 10 now Console.WriteLine(\"a is {0} and res is {1}\", a, res); // pre-increment example: // res is assigned 11 now since a // is updated here itself res = ++a; // a and res have same values = 11 Console.WriteLine(\"a is {0} and res is {1}\", a, res); // pre-decrement example: // res is assigned 10 only since // a is updated here itself res = --a; // a and res have same values = 10 Console.WriteLine(\"a is {0} and res is {1}\",a, res); } }}",
"e": 4699,
"s": 3348,
"text": null
},
{
"code": null,
"e": 4707,
"s": 4699,
"text": "Output:"
},
{
"code": null,
"e": 4795,
"s": 4707,
"text": "a is 11 and res is 10\na is 10 and res is 11\na is 11 and res is 11\na is 10 and res is 10"
},
{
"code": null,
"e": 4816,
"s": 4795,
"text": "Relational Operators"
},
{
"code": null,
"e": 4903,
"s": 4816,
"text": "Relational operators are used for comparison of two values. Let’s see them one by one:"
},
{
"code": null,
"e": 5071,
"s": 4903,
"text": "‘=='(Equal To) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 5==5 will return true."
},
{
"code": null,
"e": 5302,
"s": 5071,
"text": "‘!='(Not Equal To) operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false."
},
{
"code": null,
"e": 5485,
"s": 5302,
"text": "‘>'(Greater Than) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true."
},
{
"code": null,
"e": 5665,
"s": 5485,
"text": "‘<‘(Less Than) operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 6<5 will return false."
},
{
"code": null,
"e": 5871,
"s": 5665,
"text": "‘>='(Greater Than Equal To) operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true."
},
{
"code": null,
"e": 6078,
"s": 5871,
"text": "‘<='(Less Than Equal To) operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true."
},
{
"code": null,
"e": 6087,
"s": 6078,
"text": "Example:"
},
{
"code": null,
"e": 6090,
"s": 6087,
"text": "C#"
},
{
"code": "// C# program to demonstrate the working// of Relational Operatorsusing System;namespace Relational { class GFG { // Main Function static void Main(string[] args) { bool result; int x = 5, y = 10; // Equal to Operator result = (x == y); Console.WriteLine(\"Equal to Operator: \" + result); // Greater than Operator result = (x > y); Console.WriteLine(\"Greater than Operator: \" + result); // Less than Operator result = (x < y); Console.WriteLine(\"Less than Operator: \" + result); // Greater than Equal to Operator result = (x >= y); Console.WriteLine(\"Greater than or Equal to: \"+ result); // Less than Equal to Operator result = (x <= y); Console.WriteLine(\"Lesser than or Equal to: \"+ result); // Not Equal To Operator result = (x != y); Console.WriteLine(\"Not Equal to Operator: \" + result); }}}",
"e": 7102,
"s": 6090,
"text": null
},
{
"code": null,
"e": 7110,
"s": 7102,
"text": "Output:"
},
{
"code": null,
"e": 7279,
"s": 7110,
"text": "Equal to Operator: False\nGreater than Operator: False\nLess than Operator: True\nGreater than or Equal to: False\nLesser than or Equal to: True\nNot Equal to Operator: True"
},
{
"code": null,
"e": 7297,
"s": 7279,
"text": "Logical Operators"
},
{
"code": null,
"e": 7459,
"s": 7297,
"text": "They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below:"
},
{
"code": null,
"e": 7665,
"s": 7459,
"text": "Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. For example, a && b returns true when both a and b are true (i.e. non-zero)."
},
{
"code": null,
"e": 7934,
"s": 7665,
"text": "Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true."
},
{
"code": null,
"e": 8113,
"s": 7934,
"text": "Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e. when a=0."
},
{
"code": null,
"e": 8122,
"s": 8113,
"text": "Example:"
},
{
"code": null,
"e": 8125,
"s": 8122,
"text": "C#"
},
{
"code": "// C# program to demonstrate the working// of Logical Operatorsusing System;namespace Logical { class GFG { // Main Function static void Main(string[] args) { bool a = true,b = false, result; // AND operator result = a && b; Console.WriteLine(\"AND Operator: \" + result); // OR operator result = a || b; Console.WriteLine(\"OR Operator: \" + result); // NOT operator result = !a; Console.WriteLine(\"NOT Operator: \" + result); }}}",
"e": 8727,
"s": 8125,
"text": null
},
{
"code": null,
"e": 8735,
"s": 8727,
"text": "Output:"
},
{
"code": null,
"e": 8793,
"s": 8735,
"text": "AND Operator: False\nOR Operator: True\nNOT Operator: False"
},
{
"code": null,
"e": 8811,
"s": 8793,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 8952,
"s": 8811,
"text": "In C#, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations. Following are the bitwise operators :"
},
{
"code": null,
"e": 9088,
"s": 8952,
"text": "& (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1."
},
{
"code": null,
"e": 9222,
"s": 9088,
"text": "| (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1."
},
{
"code": null,
"e": 9364,
"s": 9222,
"text": "^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different."
},
{
"code": null,
"e": 9500,
"s": 9364,
"text": "<< (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift."
},
{
"code": null,
"e": 9638,
"s": 9500,
"text": ">> (right shift) Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift."
},
{
"code": null,
"e": 9647,
"s": 9638,
"text": "Example:"
},
{
"code": null,
"e": 9650,
"s": 9647,
"text": "C#"
},
{
"code": "// C# program to demonstrate the working// of Bitwise Operatorsusing System;namespace Bitwise { class GFG { // Main Function static void Main(string[] args) { int x = 5, y = 10, result; // Bitwise AND Operator result = x & y; Console.WriteLine(\"Bitwise AND: \" + result); // Bitwise OR Operator result = x | y; Console.WriteLine(\"Bitwise OR: \" + result); // Bitwise XOR Operator result = x ^ y; Console.WriteLine(\"Bitwise XOR: \" + result); // Bitwise AND Operator result = ~x; Console.WriteLine(\"Bitwise Complement: \" + result); // Bitwise LEFT SHIFT Operator result = x << 2; Console.WriteLine(\"Bitwise Left Shift: \" + result); // Bitwise RIGHT SHIFT Operator result = x >> 2; Console.WriteLine(\"Bitwise Right Shift: \" + result); }}}",
"e": 10695,
"s": 9650,
"text": null
},
{
"code": null,
"e": 10703,
"s": 10695,
"text": "Output:"
},
{
"code": null,
"e": 10818,
"s": 10703,
"text": "Bitwise AND: 0\nBitwise OR: 15\nBitwise XOR: 15\nBitwise Complement: -6\nBitwise Left Shift: 20\nBitwise Right Shift: 1"
},
{
"code": null,
"e": 10839,
"s": 10818,
"text": "Assignment Operators"
},
{
"code": null,
"e": 11165,
"s": 10839,
"text": "Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error."
},
{
"code": null,
"e": 11222,
"s": 11165,
"text": "Different types of assignment operators are shown below:"
},
{
"code": null,
"e": 11380,
"s": 11222,
"text": "“=”(Simple Assignment): This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.Example:"
},
{
"code": null,
"e": 11406,
"s": 11380,
"text": "a = 10;\nb = 20;\nch = 'y';"
},
{
"code": null,
"e": 11641,
"s": 11406,
"text": "“+=”(Add Assignment): This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.Example:"
},
{
"code": null,
"e": 11680,
"s": 11641,
"text": "(a += b) can be written as (a = a + b)"
},
{
"code": null,
"e": 11737,
"s": 11680,
"text": "If initially value stored in a is 5. Then (a += 6) = 11."
},
{
"code": null,
"e": 11984,
"s": 11737,
"text": "“-=”(Subtract Assignment): This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left.Example:"
},
{
"code": null,
"e": 12023,
"s": 11984,
"text": "(a -= b) can be written as (a = a - b)"
},
{
"code": null,
"e": 12079,
"s": 12023,
"text": "If initially value stored in a is 8. Then (a -= 6) = 2."
},
{
"code": null,
"e": 12325,
"s": 12079,
"text": "“*=”(Multiply Assignment): This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.Example:"
},
{
"code": null,
"e": 12364,
"s": 12325,
"text": "(a *= b) can be written as (a = a * b)"
},
{
"code": null,
"e": 12421,
"s": 12364,
"text": "If initially value stored in a is 5. Then (a *= 6) = 30."
},
{
"code": null,
"e": 12664,
"s": 12421,
"text": "“/=”(Division Assignment): This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:"
},
{
"code": null,
"e": 12703,
"s": 12664,
"text": "(a /= b) can be written as (a = a / b)"
},
{
"code": null,
"e": 12759,
"s": 12703,
"text": "If initially value stored in a is 6. Then (a /= 2) = 3."
},
{
"code": null,
"e": 13000,
"s": 12759,
"text": "“%=”(Modulus Assignment): This operator is combination of ‘%’ and ‘=’ operators. This operator first modulo the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:"
},
{
"code": null,
"e": 13039,
"s": 13000,
"text": "(a %= b) can be written as (a = a % b)"
},
{
"code": null,
"e": 13095,
"s": 13039,
"text": "If initially value stored in a is 6. Then (a %= 2) = 0."
},
{
"code": null,
"e": 13346,
"s": 13095,
"text": "“<<=”(Left Shift Assignment) : This operator is combination of ‘<<‘ and ‘=’ operators. This operator first Left shift the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:"
},
{
"code": null,
"e": 13387,
"s": 13346,
"text": "(a <<= 2) can be written as (a = a << 2)"
},
{
"code": null,
"e": 13445,
"s": 13387,
"text": "If initially value stored in a is 6. Then (a <<= 2) = 24."
},
{
"code": null,
"e": 13698,
"s": 13445,
"text": "“>>=”(Right Shift Assignment) : This operator is combination of ‘>>’ and ‘=’ operators. This operator first Right shift the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:"
},
{
"code": null,
"e": 13739,
"s": 13698,
"text": "(a >>= 2) can be written as (a = a >> 2)"
},
{
"code": null,
"e": 13796,
"s": 13739,
"text": "If initially value stored in a is 6. Then (a >>= 2) = 1."
},
{
"code": null,
"e": 14052,
"s": 13796,
"text": "“&=”(Bitwise AND Assignment): This operator is combination of ‘&’ and ‘=’ operators. This operator first “Bitwise AND” the current value of the variable on the left by the value on the right and then assigns the result to the variable on the left.Example:"
},
{
"code": null,
"e": 14091,
"s": 14052,
"text": "(a &= 2) can be written as (a = a & 2)"
},
{
"code": null,
"e": 14147,
"s": 14091,
"text": "If initially value stored in a is 6. Then (a &= 2) = 2."
},
{
"code": null,
"e": 14406,
"s": 14147,
"text": "“^=”(Bitwise Exclusive OR): This operator is combination of ‘^’ and ‘=’ operators. This operator first “Bitwise Exclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:"
},
{
"code": null,
"e": 14445,
"s": 14406,
"text": "(a ^= 2) can be written as (a = a ^ 2)"
},
{
"code": null,
"e": 14501,
"s": 14445,
"text": "If initially value stored in a is 6. Then (a ^= 2) = 4."
},
{
"code": null,
"e": 14762,
"s": 14501,
"text": "“|=”(Bitwise Inclusive OR) : This operator is combination of ‘|’ and ‘=’ operators. This operator first “Bitwise Inclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example :"
},
{
"code": null,
"e": 14801,
"s": 14762,
"text": "(a |= 2) can be written as (a = a | 2)"
},
{
"code": null,
"e": 14858,
"s": 14801,
"text": "If initially, value stored in a is 6. Then (a |= 2) = 6."
},
{
"code": null,
"e": 14867,
"s": 14858,
"text": "Example:"
},
{
"code": null,
"e": 14870,
"s": 14867,
"text": "C#"
},
{
"code": "// C# program to demonstrate the working// of Assignment Operatorsusing System;namespace Assignment { class GFG { // Main Function static void Main(string[] args) { // initialize variable x // using Simple Assignment // Operator \"=\" int x = 15; // it means x = x + 10 x += 10; Console.WriteLine(\"Add Assignment Operator: \" + x); // initialize variable x again x = 20; // it means x = x - 5 x -= 5; Console.WriteLine(\"Subtract Assignment Operator: \" + x); // initialize variable x again x = 15; // it means x = x * 5 x *= 5; Console.WriteLine(\"Multiply Assignment Operator: \" + x); // initialize variable x again x = 25; // it means x = x / 5 x /= 5; Console.WriteLine(\"Division Assignment Operator: \" + x); // initialize variable x again x = 25; // it means x = x % 5 x %= 5; Console.WriteLine(\"Modulo Assignment Operator: \" + x); // initialize variable x again x = 8; // it means x = x << 2 x <<= 2; Console.WriteLine(\"Left Shift Assignment Operator: \" + x); // initialize variable x again x = 8; // it means x = x >> 2 x >>= 2; Console.WriteLine(\"Right Shift Assignment Operator: \" + x); // initialize variable x again x = 12; // it means x = x >> 4 x &= 4; Console.WriteLine(\"Bitwise AND Assignment Operator: \" + x); // initialize variable x again x = 12; // it means x = x >> 4 x ^= 4; Console.WriteLine(\"Bitwise Exclusive OR Assignment Operator: \" + x); // initialize variable x again x = 12; // it means x = x >> 4 x |= 4; Console.WriteLine(\"Bitwise Inclusive OR Assignment Operator: \" + x); }}}",
"e": 17232,
"s": 14870,
"text": null
},
{
"code": null,
"e": 17241,
"s": 17232,
"text": "Output :"
},
{
"code": null,
"e": 17591,
"s": 17241,
"text": "Add Assignment Operator: 25\nSubtract Assignment Operator: 15\nMultiply Assignment Operator: 75\nDivision Assignment Operator: 5\nModulo Assignment Operator: 0\nLeft Shift Assignment Operator: 32\nRight Shift Assignment Operator: 2\nBitwise AND Assignment Operator: 4\nBitwise Exclusive OR Assignment Operator: 8\nBitwise Inclusive OR Assignment Operator: 12"
},
{
"code": null,
"e": 17612,
"s": 17591,
"text": "Conditional Operator"
},
{
"code": null,
"e": 17818,
"s": 17612,
"text": "It is ternary operator which is a shorthand version of if-else statement. It has three operands and hence the name ternary. It will return one of two values depending on the value of a Boolean expression. "
},
{
"code": null,
"e": 17826,
"s": 17818,
"text": "Syntax:"
},
{
"code": null,
"e": 17876,
"s": 17826,
"text": "condition ? first_expression : second_expression;"
},
{
"code": null,
"e": 18098,
"s": 17876,
"text": "Explanation:condition: It must be evaluated to true or false.If the condition is truefirst_expression is evaluated and becomes the result. If the condition is false, second_expression is evaluated and becomes the result. "
},
{
"code": null,
"e": 18107,
"s": 18098,
"text": "Example:"
},
{
"code": null,
"e": 18110,
"s": 18107,
"text": "C#"
},
{
"code": "// C# program to demonstrate the working// of Conditional Operatorusing System;namespace Conditional { class GFG { // Main Function static void Main(string[] args) { int x = 5, y = 10, result; // To find which value is greater // Using Conditional Operator result = x > y ? x : y; // To display the result Console.WriteLine(\"Result: \" + result); // To find which value is greater // Using Conditional Operator result = x < y ? x : y; // To display the result Console.WriteLine(\"Result: \" + result); }}}",
"e": 18807,
"s": 18110,
"text": null
},
{
"code": null,
"e": 18816,
"s": 18807,
"text": "Output :"
},
{
"code": null,
"e": 18837,
"s": 18816,
"text": "Result: 10\nResult: 5"
},
{
"code": null,
"e": 18880,
"s": 18839,
"text": "j24351si1icpepnpnnkpi34er5ms2wzv4bggx00n"
},
{
"code": null,
"e": 18894,
"s": 18880,
"text": "sumitgumber28"
},
{
"code": null,
"e": 18911,
"s": 18894,
"text": "CSharp Operators"
},
{
"code": null,
"e": 18925,
"s": 18911,
"text": "CSharp-Basics"
},
{
"code": null,
"e": 18928,
"s": 18925,
"text": "C#"
},
{
"code": null,
"e": 19026,
"s": 18928,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 19049,
"s": 19026,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 19111,
"s": 19049,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 19139,
"s": 19111,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 19197,
"s": 19139,
"text": "Different ways to sort an array in descending order in C#"
},
{
"code": null,
"e": 19219,
"s": 19197,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 19262,
"s": 19219,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 19315,
"s": 19262,
"text": "How to sort a list in C# | List.Sort() Method Set -1"
},
{
"code": null,
"e": 19358,
"s": 19315,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 19374,
"s": 19358,
"text": "C# | Namespaces"
}
] |
How to load external HTML file using jQuery ? | 22 Apr, 2021
In this article, we will learn how to load an external HTML file into a div element.
The following jQuery functions are used in the example codes.
ready(): The ready event occurs when the DOM (document object model) has been loaded.
load(): The load() method loads data from a server and gets the returned data into the selected element.
Note: We will use the ready() function to ensure that our DOM is completely ready before doing any further tasks. We will load the external HTML using load() function.
Approach:
First, we will create our external HTML file.
Add a div element on the HTML file where we want to load external HTML.
Under the script, use the ready() function to check if DOM ready.
Then select the div element on which we want to load HTML using load().
External files: The following div-1.html and div-2.html files are used as external files.
div-1.html
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>div-1</title></head> <body> <p>This content is from first div.</p></body> </html>
div-2.html
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>div 2</title></head> <body> <p>This is content from second div</p></body> </html>
HTML code: The following code demonstrates the loading of external files into an HTML div.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <!-- Some CSS --> <style> div { border: 2px solid green; width: fit-content; margin: 20px auto; padding: 2px 20px; cursor: pointer; } p { font-size: 14px; } </style></head> <body> <!-- First div --> <div id="div-1"> First Div <p>Click to load first html</p> </div> <!-- Second div --> <div id="div-2"> Second div <p>Click to load first html</p> </div> <!-- Script --> <script> // Check if file is completely ready $(document).ready(function () { // Adding click event on id div-1 // if it clicked then anonymous // function will be called $('#div-1').click(function () { // Load the exertnal html // here this refers to // current selector $(this).load('div-1.html'); }); // Same as above $('#div-2').click(function () { $(this).load('div-2.html'); }); }); </script></body> </html>
Output:
Note: We are using the jQuery click() function, which means the external file will be loaded after we clicked on it. But if you want to load external files just after DOM is ready, just omit the click() event and call the load() function
HTML-Questions
jQuery-Methods
jQuery-Questions
Picked
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Design a web page using HTML and CSS
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to add options to a select element using jQuery?
jQuery | children() with Examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 113,
"s": 28,
"text": "In this article, we will learn how to load an external HTML file into a div element."
},
{
"code": null,
"e": 175,
"s": 113,
"text": "The following jQuery functions are used in the example codes."
},
{
"code": null,
"e": 261,
"s": 175,
"text": "ready(): The ready event occurs when the DOM (document object model) has been loaded."
},
{
"code": null,
"e": 367,
"s": 261,
"text": "load(): The load() method loads data from a server and gets the returned data into the selected element."
},
{
"code": null,
"e": 535,
"s": 367,
"text": "Note: We will use the ready() function to ensure that our DOM is completely ready before doing any further tasks. We will load the external HTML using load() function."
},
{
"code": null,
"e": 547,
"s": 537,
"text": "Approach:"
},
{
"code": null,
"e": 593,
"s": 547,
"text": "First, we will create our external HTML file."
},
{
"code": null,
"e": 665,
"s": 593,
"text": "Add a div element on the HTML file where we want to load external HTML."
},
{
"code": null,
"e": 731,
"s": 665,
"text": "Under the script, use the ready() function to check if DOM ready."
},
{
"code": null,
"e": 803,
"s": 731,
"text": "Then select the div element on which we want to load HTML using load()."
},
{
"code": null,
"e": 893,
"s": 803,
"text": "External files: The following div-1.html and div-2.html files are used as external files."
},
{
"code": null,
"e": 904,
"s": 893,
"text": "div-1.html"
},
{
"code": null,
"e": 909,
"s": 904,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>div-1</title></head> <body> <p>This content is from first div.</p></body> </html>",
"e": 1211,
"s": 909,
"text": null
},
{
"code": null,
"e": 1222,
"s": 1211,
"text": "div-2.html"
},
{
"code": null,
"e": 1227,
"s": 1222,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>div 2</title></head> <body> <p>This is content from second div</p></body> </html>",
"e": 1529,
"s": 1227,
"text": null
},
{
"code": null,
"e": 1620,
"s": 1529,
"text": "HTML code: The following code demonstrates the loading of external files into an HTML div."
},
{
"code": null,
"e": 1625,
"s": 1620,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"> </script> <!-- Some CSS --> <style> div { border: 2px solid green; width: fit-content; margin: 20px auto; padding: 2px 20px; cursor: pointer; } p { font-size: 14px; } </style></head> <body> <!-- First div --> <div id=\"div-1\"> First Div <p>Click to load first html</p> </div> <!-- Second div --> <div id=\"div-2\"> Second div <p>Click to load first html</p> </div> <!-- Script --> <script> // Check if file is completely ready $(document).ready(function () { // Adding click event on id div-1 // if it clicked then anonymous // function will be called $('#div-1').click(function () { // Load the exertnal html // here this refers to // current selector $(this).load('div-1.html'); }); // Same as above $('#div-2').click(function () { $(this).load('div-2.html'); }); }); </script></body> </html>",
"e": 3073,
"s": 1625,
"text": null
},
{
"code": null,
"e": 3082,
"s": 3073,
"text": "Output: "
},
{
"code": null,
"e": 3321,
"s": 3082,
"text": "Note: We are using the jQuery click() function, which means the external file will be loaded after we clicked on it. But if you want to load external files just after DOM is ready, just omit the click() event and call the load() function "
},
{
"code": null,
"e": 3336,
"s": 3321,
"text": "HTML-Questions"
},
{
"code": null,
"e": 3351,
"s": 3336,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 3368,
"s": 3351,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 3375,
"s": 3368,
"text": "Picked"
},
{
"code": null,
"e": 3380,
"s": 3375,
"text": "HTML"
},
{
"code": null,
"e": 3387,
"s": 3380,
"text": "JQuery"
},
{
"code": null,
"e": 3404,
"s": 3387,
"text": "Web Technologies"
},
{
"code": null,
"e": 3409,
"s": 3404,
"text": "HTML"
},
{
"code": null,
"e": 3507,
"s": 3409,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3531,
"s": 3507,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3570,
"s": 3531,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3609,
"s": 3570,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 3629,
"s": 3609,
"text": "Angular File Upload"
},
{
"code": null,
"e": 3666,
"s": 3629,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 3712,
"s": 3666,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 3775,
"s": 3712,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 3804,
"s": 3775,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 3857,
"s": 3804,
"text": "How to add options to a select element using jQuery?"
}
] |
How to rotate a text 360 degrees on hover using HTML and CSS? | 20 May, 2021
The Text can be rotated 360 degrees using basic HTML and CSS, this animation can be used as a heading or subheadings in the website to make it look more attractive. The below sections will guide you on how to create the desired effect.
HTML Code: In this section we will create a basic div element which will have some text inside of it.
HTML
<!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Rotate text 360 degrees</title> </head> <body> <div> <h2>GeeksforGeeks</h2> </div></body></html>
CSS Code: In this section first we will design the text using basic CSS properties and then we will create the animation using @keyframes rule, we will use the transform property to rotate the text 360 degrees at regular intervals.
css
<style> body { margin: 0; padding: 0; font-family: serif; justify-content: center; align-items: center; display: flex; background-color: #65E73C; } div { content: ''; font-size: 2em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } h2:hover{ animation: rotate 1s linear; } // Rotate using @keyframes @keyframes rotate{ 0%{ transform: rotate(0deg); } 50%{ transform: rotate(180deg); } 100%{ transform: rotate(360deg); } } </style>
Final Code: It is the combination of above two code sections.
HTML
<!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Rotate text 360 degrees</title> </head><style> body { margin: 0; padding: 0; font-family: serif; justify-content: center; align-items: center; display: flex; background-color: #65E73C; } div { content: ''; font-size: 2em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } h2:hover{ animation: rotate 1s linear; } @keyframes rotate{ 0%{ transform: rotate(0deg); } 50%{ transform: rotate(180deg); } 100%{ transform: rotate(360deg); } }</style> <body> <div> <h2>GeeksforGeeks</h2> </div></body></html>
Output:
Code_Mech
CSS-Misc
CSS
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 290,
"s": 54,
"text": "The Text can be rotated 360 degrees using basic HTML and CSS, this animation can be used as a heading or subheadings in the website to make it look more attractive. The below sections will guide you on how to create the desired effect."
},
{
"code": null,
"e": 392,
"s": 290,
"text": "HTML Code: In this section we will create a basic div element which will have some text inside of it."
},
{
"code": null,
"e": 397,
"s": 392,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title>Rotate text 360 degrees</title> </head> <body> <div> <h2>GeeksforGeeks</h2> </div></body></html>",
"e": 600,
"s": 397,
"text": null
},
{
"code": null,
"e": 834,
"s": 600,
"text": "CSS Code: In this section first we will design the text using basic CSS properties and then we will create the animation using @keyframes rule, we will use the transform property to rotate the text 360 degrees at regular intervals. "
},
{
"code": null,
"e": 838,
"s": 834,
"text": "css"
},
{
"code": "<style> body { margin: 0; padding: 0; font-family: serif; justify-content: center; align-items: center; display: flex; background-color: #65E73C; } div { content: ''; font-size: 2em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } h2:hover{ animation: rotate 1s linear; } // Rotate using @keyframes @keyframes rotate{ 0%{ transform: rotate(0deg); } 50%{ transform: rotate(180deg); } 100%{ transform: rotate(360deg); } } </style>",
"e": 1641,
"s": 838,
"text": null
},
{
"code": null,
"e": 1703,
"s": 1641,
"text": "Final Code: It is the combination of above two code sections."
},
{
"code": null,
"e": 1708,
"s": 1703,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title>Rotate text 360 degrees</title> </head><style> body { margin: 0; padding: 0; font-family: serif; justify-content: center; align-items: center; display: flex; background-color: #65E73C; } div { content: ''; font-size: 2em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } h2:hover{ animation: rotate 1s linear; } @keyframes rotate{ 0%{ transform: rotate(0deg); } 50%{ transform: rotate(180deg); } 100%{ transform: rotate(360deg); } }</style> <body> <div> <h2>GeeksforGeeks</h2> </div></body></html>",
"e": 2540,
"s": 1708,
"text": null
},
{
"code": null,
"e": 2548,
"s": 2540,
"text": "Output:"
},
{
"code": null,
"e": 2558,
"s": 2548,
"text": "Code_Mech"
},
{
"code": null,
"e": 2567,
"s": 2558,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2571,
"s": 2567,
"text": "CSS"
},
{
"code": null,
"e": 2576,
"s": 2571,
"text": "HTML"
},
{
"code": null,
"e": 2581,
"s": 2576,
"text": "HTML"
}
] |
WheelView in Android | 30 Apr, 2021
In this article, WheelView is added in android. WheelView provides a very impressive UI that allows the developer to create a Wheel and add items according to his need. Some important tags provided by WheelView are wheelArcBackgroundColor, wheelAnchorAngle, wheelStartAngle, wheelMode, wheelCenterIcon, and many more. It can be used where the user wants to select items from a list of items. Suppose in the banking app, the user has the option to select its bank account to check balance, payment history, etc in that case this can be used.
Advantages:
It can be customized according to the requirements.
It provides animation with the view which improves the User Interface.
It provides an inbuilt layout that its alternatives like Custom Dialog which can be used instead of wheel view does not provide.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Add dependency and JitPack Repository
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation ‘com.github.psuzn:WheelView:1.0.1’
Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.
allprojects {
repositories {
...
maven { url “https://jitpack.io” }
}
}
After adding this dependency sync your project and now we will move towards its implementation.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<androidx.constraintlayout.widget.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <me.sujanpoudel.wheelview.WheelView android:id="@+id/wheel_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" app:wheelDividerStrokeWidth="16dp" app:wheelArcBackgroundColor="#F7F8FB" app:wheelSelectedArcBackgroundColor="@color/colorPrimary" app:wheelCenterIcon="@drawable/ic_baseline_add_24" app:wheelCenterIconPadding="16dp" app:wheelCenterIconTint="@android:color/white" app:wheelAnchorAngle="270" app:wheelStartAngle="315" app:wheelTextSize="16sp" app:wheelSelectedTextColor="#FFF" app:wheelTextColor="#000000" app:wheelAnimationDuration="800" app:wheelMode="ANIMATE_TO_ANCHOR" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Working with the MainActivityfile
Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail.
Java
Kotlin
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import java.util.Arrays;import me.sujanpoudel.wheelview.WheelView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // create a string array of tiles String[] titles={"Bubble Sort", "Quick Sort", "Merge Sort", "Radix Sort"}; // get the reference of the wheelView WheelView wheelView =(WheelView)findViewById(R.id.wheel_view); // convert tiles array to list and pass it to setTitles wheelView.setTitles(Arrays.asList(titles)); }}
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport me.sujanpoudel.wheelview.WheelView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val wheelView = findViewById<WheelView>(R.id.wheel_view) wheelView.titles = listOf("Bubble Sort", "Quick Sort", "Merge Sort", "Radix Sort") }}
Output:
onlyklohan
android
Android-View
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 593,
"s": 52,
"text": "In this article, WheelView is added in android. WheelView provides a very impressive UI that allows the developer to create a Wheel and add items according to his need. Some important tags provided by WheelView are wheelArcBackgroundColor, wheelAnchorAngle, wheelStartAngle, wheelMode, wheelCenterIcon, and many more. It can be used where the user wants to select items from a list of items. Suppose in the banking app, the user has the option to select its bank account to check balance, payment history, etc in that case this can be used."
},
{
"code": null,
"e": 607,
"s": 593,
"text": "Advantages: "
},
{
"code": null,
"e": 659,
"s": 607,
"text": "It can be customized according to the requirements."
},
{
"code": null,
"e": 730,
"s": 659,
"text": "It provides animation with the view which improves the User Interface."
},
{
"code": null,
"e": 859,
"s": 730,
"text": "It provides an inbuilt layout that its alternatives like Custom Dialog which can be used instead of wheel view does not provide."
},
{
"code": null,
"e": 888,
"s": 859,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 999,
"s": 888,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio."
},
{
"code": null,
"e": 1045,
"s": 999,
"text": "Step 2: Add dependency and JitPack Repository"
},
{
"code": null,
"e": 1164,
"s": 1045,
"text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 1214,
"s": 1164,
"text": "implementation ‘com.github.psuzn:WheelView:1.0.1’"
},
{
"code": null,
"e": 1356,
"s": 1214,
"text": "Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section."
},
{
"code": null,
"e": 1370,
"s": 1356,
"text": "allprojects {"
},
{
"code": null,
"e": 1386,
"s": 1370,
"text": " repositories {"
},
{
"code": null,
"e": 1393,
"s": 1386,
"text": " ..."
},
{
"code": null,
"e": 1431,
"s": 1393,
"text": " maven { url “https://jitpack.io” }"
},
{
"code": null,
"e": 1438,
"s": 1431,
"text": " }"
},
{
"code": null,
"e": 1440,
"s": 1438,
"text": "}"
},
{
"code": null,
"e": 1538,
"s": 1440,
"text": "After adding this dependency sync your project and now we will move towards its implementation. "
},
{
"code": null,
"e": 1586,
"s": 1538,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1729,
"s": 1586,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 1733,
"s": 1729,
"text": "XML"
},
{
"code": "<androidx.constraintlayout.widget.ConstraintLayout xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <me.sujanpoudel.wheelview.WheelView android:id=\"@+id/wheel_view\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"16dp\" app:wheelDividerStrokeWidth=\"16dp\" app:wheelArcBackgroundColor=\"#F7F8FB\" app:wheelSelectedArcBackgroundColor=\"@color/colorPrimary\" app:wheelCenterIcon=\"@drawable/ic_baseline_add_24\" app:wheelCenterIconPadding=\"16dp\" app:wheelCenterIconTint=\"@android:color/white\" app:wheelAnchorAngle=\"270\" app:wheelStartAngle=\"315\" app:wheelTextSize=\"16sp\" app:wheelSelectedTextColor=\"#FFF\" app:wheelTextColor=\"#000000\" app:wheelAnimationDuration=\"800\" app:wheelMode=\"ANIMATE_TO_ANCHOR\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 2805,
"s": 1733,
"text": null
},
{
"code": null,
"e": 2847,
"s": 2805,
"text": "Step 4: Working with the MainActivityfile"
},
{
"code": null,
"e": 3027,
"s": 2847,
"text": "Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 3032,
"s": 3027,
"text": "Java"
},
{
"code": null,
"e": 3039,
"s": 3032,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import java.util.Arrays;import me.sujanpoudel.wheelview.WheelView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // create a string array of tiles String[] titles={\"Bubble Sort\", \"Quick Sort\", \"Merge Sort\", \"Radix Sort\"}; // get the reference of the wheelView WheelView wheelView =(WheelView)findViewById(R.id.wheel_view); // convert tiles array to list and pass it to setTitles wheelView.setTitles(Arrays.asList(titles)); }}",
"e": 3763,
"s": 3039,
"text": null
},
{
"code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport me.sujanpoudel.wheelview.WheelView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val wheelView = findViewById<WheelView>(R.id.wheel_view) wheelView.titles = listOf(\"Bubble Sort\", \"Quick Sort\", \"Merge Sort\", \"Radix Sort\") }}",
"e": 4224,
"s": 3763,
"text": null
},
{
"code": null,
"e": 4233,
"s": 4224,
"text": "Output: "
},
{
"code": null,
"e": 4244,
"s": 4233,
"text": "onlyklohan"
},
{
"code": null,
"e": 4252,
"s": 4244,
"text": "android"
},
{
"code": null,
"e": 4265,
"s": 4252,
"text": "Android-View"
},
{
"code": null,
"e": 4273,
"s": 4265,
"text": "Android"
},
{
"code": null,
"e": 4280,
"s": 4273,
"text": "Kotlin"
},
{
"code": null,
"e": 4288,
"s": 4280,
"text": "Android"
}
] |
JavaScript | encodeURI(), decodeURI() and its components functions | 14 Feb, 2019
Encoding and Decoding URI and URI components is a usual task in web development while making a GET request to API with query params. Many times construct a URL string with query params and in order to understand it, the response server needs to decode this URL. Browsers automatically encode the URL i.e. it converts some special characters to other reserved characters and then makes the request. For eg: Space character ” ” is either converted to + or %20.
Example:
Open www.google.com and write a search query “geeks for geeks”.
After search results appear, observe the browser’s URL bar. The browser URL will consists %20 or + sign in place of space.
The URL will be display be like: https://www.google.com/search?q=geeks%20for%20geeks or https://www.google.com/search?q=geeks+for+geeks
Note: Browser converted the spaces into + or %20 sign automatically.
There are many other special characters and to convert each them by hardcode will be tedious. JavaScript provide following functions to perform this task:
encodeURI()
The encodeURI() function is used to encode complete URI. This function encode the special character except (, / ? : @ & = + $ #) characters.
Syntax:
encodeURI( complete_uri_string )
Parameters: This function accepts single parameter complete_uri_string which is used to hold the URL to be encoded.
Return Value: This function returns the encoded URI.
Example:
<script>const url = "https://www.google.com/search?q=geeks for geeks";const encodedURL = encodeURI(url);document.write(encodedURL)</script>
Output:
https://www.google.com/search?q=geeks%20for%20geeks
encodeURIComponent()
The encodeURIComponent() function is used to encode some parts or components of URI. This function encodes the special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #
Syntax:
encodeURIComponent( uri_string_component )
Parameters:: This function accepts single parameter uri_string_component which is used to hold the string which need to be encoded.
Return Value: This function returns the encoded string.
Example:
<script>const component = "geeks for geeks"const encodedComponent = encodeURIComponent(component);document.write(encodedComponent)</script>
Output:
geeks%20for%20geeks
decodeURI()
The decodeURI() function is used to decode URI generated by encodeURI().
Syntax:
decodeURI( complete_encoded_uri_string )
Parameters: This function accepts single parameter complete_encoded_uri_string which holds the encoded string.
Return Value: This function returns the decoded string (original string).
Example:
<script>const url = "https://www.google.com/search?q=geeks%20for%20geeks";const decodedURL = decodeURI(url);document.write(decodedURL)</script>
Output:
https://www.google.com/search?q=geeks for geeks
decodeURIComponent()
The decodeURIComponent() function is used to decode some parts or components of URI generated by encodeURIComponent().
Syntax:
decodeURIComponent( encoded_uri_string_component )
Parameters: This function accepts single parameter encoded_uri_string_component which holds the encoded string.
Return Value: This function returns the decoded component of URI string.
Example:
<script>const component = "geeks%20for%20geeks"const decodedComponent = decodeURIComponent(component);document.write(decodedComponent) </script>
Output:
geeks for geeks
Applications:
To convert space separated query params provided to API correctly.
In web scraping to decode URL’s query params to extract human-readable strings.
javascript-basics
javascript-functions
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n14 Feb, 2019"
},
{
"code": null,
"e": 512,
"s": 53,
"text": "Encoding and Decoding URI and URI components is a usual task in web development while making a GET request to API with query params. Many times construct a URL string with query params and in order to understand it, the response server needs to decode this URL. Browsers automatically encode the URL i.e. it converts some special characters to other reserved characters and then makes the request. For eg: Space character ” ” is either converted to + or %20."
},
{
"code": null,
"e": 521,
"s": 512,
"text": "Example:"
},
{
"code": null,
"e": 585,
"s": 521,
"text": "Open www.google.com and write a search query “geeks for geeks”."
},
{
"code": null,
"e": 708,
"s": 585,
"text": "After search results appear, observe the browser’s URL bar. The browser URL will consists %20 or + sign in place of space."
},
{
"code": null,
"e": 844,
"s": 708,
"text": "The URL will be display be like: https://www.google.com/search?q=geeks%20for%20geeks or https://www.google.com/search?q=geeks+for+geeks"
},
{
"code": null,
"e": 913,
"s": 844,
"text": "Note: Browser converted the spaces into + or %20 sign automatically."
},
{
"code": null,
"e": 1068,
"s": 913,
"text": "There are many other special characters and to convert each them by hardcode will be tedious. JavaScript provide following functions to perform this task:"
},
{
"code": null,
"e": 1080,
"s": 1068,
"text": "encodeURI()"
},
{
"code": null,
"e": 1221,
"s": 1080,
"text": "The encodeURI() function is used to encode complete URI. This function encode the special character except (, / ? : @ & = + $ #) characters."
},
{
"code": null,
"e": 1229,
"s": 1221,
"text": "Syntax:"
},
{
"code": null,
"e": 1262,
"s": 1229,
"text": "encodeURI( complete_uri_string )"
},
{
"code": null,
"e": 1378,
"s": 1262,
"text": "Parameters: This function accepts single parameter complete_uri_string which is used to hold the URL to be encoded."
},
{
"code": null,
"e": 1431,
"s": 1378,
"text": "Return Value: This function returns the encoded URI."
},
{
"code": null,
"e": 1440,
"s": 1431,
"text": "Example:"
},
{
"code": "<script>const url = \"https://www.google.com/search?q=geeks for geeks\";const encodedURL = encodeURI(url);document.write(encodedURL)</script>",
"e": 1580,
"s": 1440,
"text": null
},
{
"code": null,
"e": 1588,
"s": 1580,
"text": "Output:"
},
{
"code": null,
"e": 1640,
"s": 1588,
"text": "https://www.google.com/search?q=geeks%20for%20geeks"
},
{
"code": null,
"e": 1661,
"s": 1640,
"text": "encodeURIComponent()"
},
{
"code": null,
"e": 1862,
"s": 1661,
"text": "The encodeURIComponent() function is used to encode some parts or components of URI. This function encodes the special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #"
},
{
"code": null,
"e": 1870,
"s": 1862,
"text": "Syntax:"
},
{
"code": null,
"e": 1913,
"s": 1870,
"text": "encodeURIComponent( uri_string_component )"
},
{
"code": null,
"e": 2045,
"s": 1913,
"text": "Parameters:: This function accepts single parameter uri_string_component which is used to hold the string which need to be encoded."
},
{
"code": null,
"e": 2101,
"s": 2045,
"text": "Return Value: This function returns the encoded string."
},
{
"code": null,
"e": 2110,
"s": 2101,
"text": "Example:"
},
{
"code": "<script>const component = \"geeks for geeks\"const encodedComponent = encodeURIComponent(component);document.write(encodedComponent)</script>",
"e": 2250,
"s": 2110,
"text": null
},
{
"code": null,
"e": 2258,
"s": 2250,
"text": "Output:"
},
{
"code": null,
"e": 2278,
"s": 2258,
"text": "geeks%20for%20geeks"
},
{
"code": null,
"e": 2290,
"s": 2278,
"text": "decodeURI()"
},
{
"code": null,
"e": 2363,
"s": 2290,
"text": "The decodeURI() function is used to decode URI generated by encodeURI()."
},
{
"code": null,
"e": 2371,
"s": 2363,
"text": "Syntax:"
},
{
"code": null,
"e": 2412,
"s": 2371,
"text": "decodeURI( complete_encoded_uri_string )"
},
{
"code": null,
"e": 2523,
"s": 2412,
"text": "Parameters: This function accepts single parameter complete_encoded_uri_string which holds the encoded string."
},
{
"code": null,
"e": 2597,
"s": 2523,
"text": "Return Value: This function returns the decoded string (original string)."
},
{
"code": null,
"e": 2606,
"s": 2597,
"text": "Example:"
},
{
"code": "<script>const url = \"https://www.google.com/search?q=geeks%20for%20geeks\";const decodedURL = decodeURI(url);document.write(decodedURL)</script>",
"e": 2750,
"s": 2606,
"text": null
},
{
"code": null,
"e": 2758,
"s": 2750,
"text": "Output:"
},
{
"code": null,
"e": 2806,
"s": 2758,
"text": "https://www.google.com/search?q=geeks for geeks"
},
{
"code": null,
"e": 2827,
"s": 2806,
"text": "decodeURIComponent()"
},
{
"code": null,
"e": 2946,
"s": 2827,
"text": "The decodeURIComponent() function is used to decode some parts or components of URI generated by encodeURIComponent()."
},
{
"code": null,
"e": 2954,
"s": 2946,
"text": "Syntax:"
},
{
"code": null,
"e": 3005,
"s": 2954,
"text": "decodeURIComponent( encoded_uri_string_component )"
},
{
"code": null,
"e": 3117,
"s": 3005,
"text": "Parameters: This function accepts single parameter encoded_uri_string_component which holds the encoded string."
},
{
"code": null,
"e": 3190,
"s": 3117,
"text": "Return Value: This function returns the decoded component of URI string."
},
{
"code": null,
"e": 3199,
"s": 3190,
"text": "Example:"
},
{
"code": "<script>const component = \"geeks%20for%20geeks\"const decodedComponent = decodeURIComponent(component);document.write(decodedComponent) </script>",
"e": 3363,
"s": 3199,
"text": null
},
{
"code": null,
"e": 3371,
"s": 3363,
"text": "Output:"
},
{
"code": null,
"e": 3387,
"s": 3371,
"text": "geeks for geeks"
},
{
"code": null,
"e": 3401,
"s": 3387,
"text": "Applications:"
},
{
"code": null,
"e": 3468,
"s": 3401,
"text": "To convert space separated query params provided to API correctly."
},
{
"code": null,
"e": 3548,
"s": 3468,
"text": "In web scraping to decode URL’s query params to extract human-readable strings."
},
{
"code": null,
"e": 3566,
"s": 3548,
"text": "javascript-basics"
},
{
"code": null,
"e": 3587,
"s": 3566,
"text": "javascript-functions"
},
{
"code": null,
"e": 3598,
"s": 3587,
"text": "JavaScript"
},
{
"code": null,
"e": 3617,
"s": 3598,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3634,
"s": 3617,
"text": "Web Technologies"
}
] |
Python | Add comma between numbers | 01 Jul, 2019
Sometimes, while working with currencies, we need to put commas between numbers to represent a currency, hence given a string, we can have a problem to insert commas into them. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using str.format()The string format function can be used by supplying the valid formatter to perform the formatting. The string formatter is called with the value as argument to perform this particular task.
# Python3 code to demonstrate working of# Adding comma between numbers# Using str.format() # initializing numbertest_num = 1234567 # printing original number print("The original number is : " + str(test_num)) # Using str.format()# Adding comma between numbersres = ('{:, }'.format(test_num)) # printing result print("The number after inserting commas : " + str(res))
The original number is : 1234567
The number after inserting commas : 1, 234, 567
Method #2 : Using format()This task can also be performed without taking the help of format library of strings but the normal format library that can use the “d” notation of numbers and simply insert the commas where required.
# Python3 code to demonstrate working of# Adding comma between numbers# Using format() # initializing numbertest_num = 1234567 # printing original number print("The original number is : " + str(test_num)) # Using format()# Adding comma between numbersres = (format (test_num, ', d')) # printing result print("The number after inserting commas : " + str(res))
The original number is : 1234567
The number after inserting commas : 1, 234, 567
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jul, 2019"
},
{
"code": null,
"e": 293,
"s": 52,
"text": "Sometimes, while working with currencies, we need to put commas between numbers to represent a currency, hence given a string, we can have a problem to insert commas into them. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 513,
"s": 293,
"text": "Method #1 : Using str.format()The string format function can be used by supplying the valid formatter to perform the formatting. The string formatter is called with the value as argument to perform this particular task."
},
{
"code": "# Python3 code to demonstrate working of# Adding comma between numbers# Using str.format() # initializing numbertest_num = 1234567 # printing original number print(\"The original number is : \" + str(test_num)) # Using str.format()# Adding comma between numbersres = ('{:, }'.format(test_num)) # printing result print(\"The number after inserting commas : \" + str(res))",
"e": 884,
"s": 513,
"text": null
},
{
"code": null,
"e": 966,
"s": 884,
"text": "The original number is : 1234567\nThe number after inserting commas : 1, 234, 567\n"
},
{
"code": null,
"e": 1195,
"s": 968,
"text": "Method #2 : Using format()This task can also be performed without taking the help of format library of strings but the normal format library that can use the “d” notation of numbers and simply insert the commas where required."
},
{
"code": "# Python3 code to demonstrate working of# Adding comma between numbers# Using format() # initializing numbertest_num = 1234567 # printing original number print(\"The original number is : \" + str(test_num)) # Using format()# Adding comma between numbersres = (format (test_num, ', d')) # printing result print(\"The number after inserting commas : \" + str(res))",
"e": 1558,
"s": 1195,
"text": null
},
{
"code": null,
"e": 1640,
"s": 1558,
"text": "The original number is : 1234567\nThe number after inserting commas : 1, 234, 567\n"
},
{
"code": null,
"e": 1663,
"s": 1640,
"text": "Python string-programs"
},
{
"code": null,
"e": 1670,
"s": 1663,
"text": "Python"
},
{
"code": null,
"e": 1686,
"s": 1670,
"text": "Python Programs"
},
{
"code": null,
"e": 1784,
"s": 1686,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1802,
"s": 1784,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1844,
"s": 1802,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1866,
"s": 1844,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1901,
"s": 1866,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1927,
"s": 1901,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1970,
"s": 1927,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1992,
"s": 1970,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2031,
"s": 1992,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2069,
"s": 2031,
"text": "Python | Convert a list to dictionary"
}
] |
Java toRadians() method with Example | 11 Aug, 2021
The java.lang.Math.toRadians() is used to convert an angle measured in degrees to an approximately equivalent angle measured in radians. Note: The conversion from degrees to radian is generally inexact.
Syntax:
public static double toRadians(double deg)
Parameter:
deg : This parameter is an angle in degrees which
we want to convert in radians.
Return :
This method returns the measurement of the angle
deg in radians.
Example: To show working of java.lang.Math.toRadians() method.
Java
// Java program to demonstrate working// of java.lang.Math.toRadians() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { // converting PI from degree to radian double deg = 180.0; System.out.println(Math.toRadians(deg)); // converting PI/2 from degree to radian deg = 90.0; System.out.println(Math.toRadians(deg)); // converting PI/4 from degree to radian deg = 45.0; System.out.println(Math.toRadians(deg)); }}
Output:
3.141592653589793
1.5707963267948966
0.7853981633974483
sagar0719kumar
Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 257,
"s": 53,
"text": "The java.lang.Math.toRadians() is used to convert an angle measured in degrees to an approximately equivalent angle measured in radians. Note: The conversion from degrees to radian is generally inexact. "
},
{
"code": null,
"e": 267,
"s": 257,
"text": "Syntax: "
},
{
"code": null,
"e": 478,
"s": 267,
"text": "public static double toRadians(double deg)\n\nParameter:\ndeg : This parameter is an angle in degrees which\nwe want to convert in radians.\nReturn :\nThis method returns the measurement of the angle \ndeg in radians."
},
{
"code": null,
"e": 542,
"s": 478,
"text": "Example: To show working of java.lang.Math.toRadians() method. "
},
{
"code": null,
"e": 547,
"s": 542,
"text": "Java"
},
{
"code": "// Java program to demonstrate working// of java.lang.Math.toRadians() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { // converting PI from degree to radian double deg = 180.0; System.out.println(Math.toRadians(deg)); // converting PI/2 from degree to radian deg = 90.0; System.out.println(Math.toRadians(deg)); // converting PI/4 from degree to radian deg = 45.0; System.out.println(Math.toRadians(deg)); }}",
"e": 1084,
"s": 547,
"text": null
},
{
"code": null,
"e": 1093,
"s": 1084,
"text": "Output: "
},
{
"code": null,
"e": 1149,
"s": 1093,
"text": "3.141592653589793\n1.5707963267948966\n0.7853981633974483"
},
{
"code": null,
"e": 1164,
"s": 1149,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 1182,
"s": 1164,
"text": "Java-lang package"
},
{
"code": null,
"e": 1192,
"s": 1182,
"text": "java-math"
},
{
"code": null,
"e": 1197,
"s": 1192,
"text": "Java"
},
{
"code": null,
"e": 1202,
"s": 1197,
"text": "Java"
}
] |
Complement of a number with any base b | 07 Jul, 2021
One’s Complement of an Integer
1’s and 2’s complement of a Binary Number
In this post, a general method of finding complement with any arbitrary base is discussed.Steps to find (b-1)’s complement: To find (b-1)’s complement,
Subtract each digit of the number from the largest number in the number system with base .
For example, if the number is a three-digit number in base 9, then subtract the number from 888 as 8 is the largest number in base 9 number system.
The obtained result is the (b-1)’s (8’s complement) complement.
Steps to find b’s complement: To find b’s complement, just add 1 to the calculated (b-1)’s complement.Now, this holds true for any base in the number system that exists. It can be tested with familiar bases that is the 1’s and 2’s complement.Example:
Let the number be 10111 base 2 (b=2)
Then, 1's complement will be 01000 (b-1)
2's complement will be 01001 (b)
Taking a number with Octal base:
Let the number be -456.
Then 7's complement will be 321
and 8's complement will be 322
Below is the implementation of above idea:
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to find complement of a// number with any base b#include<iostream>#include<cmath> using namespace std; // Function to find (b-1)'s complementint prevComplement(int n, int b){ int maxDigit, maxNum = 0, digits = 0, num = n; // Calculate number of digits // in the given number while(n!=0) { digits++; n = n/10; } // Largest digit in the number // system with base b maxDigit = b-1; // Largest number in the number // system with base b while(digits--) { maxNum = maxNum*10 + maxDigit; } // return Complement return maxNum - num;} // Function to find b's complementint complement(int n, int b){ // b's complement = (b-1)'s complement + 1 return prevComplement(n,b) + 1;} // Driver codeint main(){ cout << prevComplement(25, 7)<<endl; cout << complement(25, 7); return 0;}
// Java program to find complement// of a number with any base bclass GFG{ // Function to find (b-1)'s complementstatic int prevComplement(int n, int b){ int maxDigit, maxNum = 0, digits = 0, num = n; // Calculate number of digits // in the given number while(n != 0) { digits++; n = n / 10; } // Largest digit in the number // system with base b maxDigit = b - 1; // Largest number in the number // system with base b while((digits--) > 0) { maxNum = maxNum * 10 + maxDigit; } // return Complement return maxNum - num;} // Function to find b's complementstatic int complement(int n, int b){ // b's complement = (b-1)'s // complement + 1 return prevComplement(n, b) + 1;} // Driver codepublic static void main(String args[]){ System.out.println(prevComplement(25, 7)); System.out.println(complement(25, 7));}} // This code is contributed// by Kirti_Mangal
# Python 3 program to find# complement of a number# with any base b # Function to find# (b-1)'s complementdef prevComplement(n, b) : maxNum, digits, num = 0, 0, n # Calculate number of digits # in the given number while n > 1 : digits += 1 n = n // 10 # Largest digit in the number # system with base b maxDigit = b - 1 # Largest number in the number # system with base b while digits : maxNum = maxNum * 10 + maxDigit digits -= 1 # return Complement return maxNum - num # Function to find b's complementdef complement(n, b) : # b's complement = (b-1)'s # complement + 1 return prevComplement(n, b) + 1 # Driver codeif __name__ == "__main__" : # Function calling print(prevComplement(25, 7)) print(complement(25, 7)) # This code is contributed# by ANKITRAI1
// C# program to find complement// of a number with any base bclass GFG{ // Function to find (b-1)'s complementstatic int prevComplement(int n, int b){ int maxDigit, maxNum = 0, digits = 0, num = n; // Calculate number of digits // in the given number while(n != 0) { digits++; n = n / 10; } // Largest digit in the number // system with base b maxDigit = b - 1; // Largest number in the number // system with base b while((digits--) > 0) { maxNum = maxNum * 10 + maxDigit; } // return Complement return maxNum - num;} // Function to find b's complementstatic int complement(int n, int b){ // b's complement = (b-1)'s // complement + 1 return prevComplement(n, b) + 1;} // Driver codepublic static void Main(){ System.Console.WriteLine(prevComplement(25, 7)); System.Console.WriteLine(complement(25, 7));}} // This code is contributed// by mits
<?php// PHP program to find complement// of a number with any base b // Function to find (b-1)'s complementfunction prevComplement($n, $b){ $maxNum = 0; $digits = 0; $num = $n; // Calculate number of digits // in the given number while((int)$n != 0) { $digits++; $n = $n / 10; } // Largest digit in the number // system with base b $maxDigit = $b - 1; // Largest number in the number // system with base b while($digits--) { $maxNum = $maxNum * 10 + $maxDigit; } // return Complement return $maxNum - $num;} // Function to find b's complementfunction complement($n, $b){ // b's complement = (b-1)'s // complement + 1 return prevComplement($n, $b) + 1;} // Driver codeecho prevComplement(25, 7), "\n"; echo(complement(25, 7)); // This code is contributed// by Smitha?>
<script> // Javascript program to find complement// of a number with any base b // Function to find (b-1)'s complement function prevComplement(n , b) { var maxDigit, maxNum = 0, digits = 0, num = n; // Calculate number of digits // in the given number while (n != 0) { digits++; n = parseInt(n / 10); } // Largest digit in the number // system with base b maxDigit = b - 1; // Largest number in the number // system with base b while ((digits--) > 0) { maxNum = maxNum * 10 + maxDigit; } // return Complement return maxNum - num; } // Function to find b's complement function complement(n , b) { // b's complement = (b-1)'s // complement + 1 return prevComplement(n, b) + 1; } // Driver code document.write(prevComplement(25, 7)+"<br/>"); document.write(complement(25, 7)); // This code is contributed by todaysgaurav </script>
41
42
Kirti_Mangal
Mithun Kumar
ankthon
Smitha Dinesh Semwal
todaysgaurav
ruhelaa48
base-conversion
complement
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 85,
"s": 54,
"text": "One’s Complement of an Integer"
},
{
"code": null,
"e": 127,
"s": 85,
"text": "1’s and 2’s complement of a Binary Number"
},
{
"code": null,
"e": 281,
"s": 127,
"text": "In this post, a general method of finding complement with any arbitrary base is discussed.Steps to find (b-1)’s complement: To find (b-1)’s complement, "
},
{
"code": null,
"e": 372,
"s": 281,
"text": "Subtract each digit of the number from the largest number in the number system with base ."
},
{
"code": null,
"e": 520,
"s": 372,
"text": "For example, if the number is a three-digit number in base 9, then subtract the number from 888 as 8 is the largest number in base 9 number system."
},
{
"code": null,
"e": 584,
"s": 520,
"text": "The obtained result is the (b-1)’s (8’s complement) complement."
},
{
"code": null,
"e": 837,
"s": 584,
"text": "Steps to find b’s complement: To find b’s complement, just add 1 to the calculated (b-1)’s complement.Now, this holds true for any base in the number system that exists. It can be tested with familiar bases that is the 1’s and 2’s complement.Example: "
},
{
"code": null,
"e": 1069,
"s": 837,
"text": "Let the number be 10111 base 2 (b=2)\nThen, 1's complement will be 01000 (b-1)\n2's complement will be 01001 (b)\n\nTaking a number with Octal base:\nLet the number be -456.\nThen 7's complement will be 321\nand 8's complement will be 322"
},
{
"code": null,
"e": 1116,
"s": 1071,
"text": "Below is the implementation of above idea: "
},
{
"code": null,
"e": 1120,
"s": 1116,
"text": "C++"
},
{
"code": null,
"e": 1125,
"s": 1120,
"text": "Java"
},
{
"code": null,
"e": 1134,
"s": 1125,
"text": "Python 3"
},
{
"code": null,
"e": 1137,
"s": 1134,
"text": "C#"
},
{
"code": null,
"e": 1141,
"s": 1137,
"text": "PHP"
},
{
"code": null,
"e": 1152,
"s": 1141,
"text": "Javascript"
},
{
"code": "// CPP program to find complement of a// number with any base b#include<iostream>#include<cmath> using namespace std; // Function to find (b-1)'s complementint prevComplement(int n, int b){ int maxDigit, maxNum = 0, digits = 0, num = n; // Calculate number of digits // in the given number while(n!=0) { digits++; n = n/10; } // Largest digit in the number // system with base b maxDigit = b-1; // Largest number in the number // system with base b while(digits--) { maxNum = maxNum*10 + maxDigit; } // return Complement return maxNum - num;} // Function to find b's complementint complement(int n, int b){ // b's complement = (b-1)'s complement + 1 return prevComplement(n,b) + 1;} // Driver codeint main(){ cout << prevComplement(25, 7)<<endl; cout << complement(25, 7); return 0;}",
"e": 2052,
"s": 1152,
"text": null
},
{
"code": "// Java program to find complement// of a number with any base bclass GFG{ // Function to find (b-1)'s complementstatic int prevComplement(int n, int b){ int maxDigit, maxNum = 0, digits = 0, num = n; // Calculate number of digits // in the given number while(n != 0) { digits++; n = n / 10; } // Largest digit in the number // system with base b maxDigit = b - 1; // Largest number in the number // system with base b while((digits--) > 0) { maxNum = maxNum * 10 + maxDigit; } // return Complement return maxNum - num;} // Function to find b's complementstatic int complement(int n, int b){ // b's complement = (b-1)'s // complement + 1 return prevComplement(n, b) + 1;} // Driver codepublic static void main(String args[]){ System.out.println(prevComplement(25, 7)); System.out.println(complement(25, 7));}} // This code is contributed// by Kirti_Mangal",
"e": 3024,
"s": 2052,
"text": null
},
{
"code": "# Python 3 program to find# complement of a number# with any base b # Function to find# (b-1)'s complementdef prevComplement(n, b) : maxNum, digits, num = 0, 0, n # Calculate number of digits # in the given number while n > 1 : digits += 1 n = n // 10 # Largest digit in the number # system with base b maxDigit = b - 1 # Largest number in the number # system with base b while digits : maxNum = maxNum * 10 + maxDigit digits -= 1 # return Complement return maxNum - num # Function to find b's complementdef complement(n, b) : # b's complement = (b-1)'s # complement + 1 return prevComplement(n, b) + 1 # Driver codeif __name__ == \"__main__\" : # Function calling print(prevComplement(25, 7)) print(complement(25, 7)) # This code is contributed# by ANKITRAI1",
"e": 3882,
"s": 3024,
"text": null
},
{
"code": "// C# program to find complement// of a number with any base bclass GFG{ // Function to find (b-1)'s complementstatic int prevComplement(int n, int b){ int maxDigit, maxNum = 0, digits = 0, num = n; // Calculate number of digits // in the given number while(n != 0) { digits++; n = n / 10; } // Largest digit in the number // system with base b maxDigit = b - 1; // Largest number in the number // system with base b while((digits--) > 0) { maxNum = maxNum * 10 + maxDigit; } // return Complement return maxNum - num;} // Function to find b's complementstatic int complement(int n, int b){ // b's complement = (b-1)'s // complement + 1 return prevComplement(n, b) + 1;} // Driver codepublic static void Main(){ System.Console.WriteLine(prevComplement(25, 7)); System.Console.WriteLine(complement(25, 7));}} // This code is contributed// by mits",
"e": 4843,
"s": 3882,
"text": null
},
{
"code": "<?php// PHP program to find complement// of a number with any base b // Function to find (b-1)'s complementfunction prevComplement($n, $b){ $maxNum = 0; $digits = 0; $num = $n; // Calculate number of digits // in the given number while((int)$n != 0) { $digits++; $n = $n / 10; } // Largest digit in the number // system with base b $maxDigit = $b - 1; // Largest number in the number // system with base b while($digits--) { $maxNum = $maxNum * 10 + $maxDigit; } // return Complement return $maxNum - $num;} // Function to find b's complementfunction complement($n, $b){ // b's complement = (b-1)'s // complement + 1 return prevComplement($n, $b) + 1;} // Driver codeecho prevComplement(25, 7), \"\\n\"; echo(complement(25, 7)); // This code is contributed// by Smitha?>",
"e": 5736,
"s": 4843,
"text": null
},
{
"code": "<script> // Javascript program to find complement// of a number with any base b // Function to find (b-1)'s complement function prevComplement(n , b) { var maxDigit, maxNum = 0, digits = 0, num = n; // Calculate number of digits // in the given number while (n != 0) { digits++; n = parseInt(n / 10); } // Largest digit in the number // system with base b maxDigit = b - 1; // Largest number in the number // system with base b while ((digits--) > 0) { maxNum = maxNum * 10 + maxDigit; } // return Complement return maxNum - num; } // Function to find b's complement function complement(n , b) { // b's complement = (b-1)'s // complement + 1 return prevComplement(n, b) + 1; } // Driver code document.write(prevComplement(25, 7)+\"<br/>\"); document.write(complement(25, 7)); // This code is contributed by todaysgaurav </script>",
"e": 6767,
"s": 5736,
"text": null
},
{
"code": null,
"e": 6773,
"s": 6767,
"text": "41\n42"
},
{
"code": null,
"e": 6788,
"s": 6775,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 6801,
"s": 6788,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 6809,
"s": 6801,
"text": "ankthon"
},
{
"code": null,
"e": 6830,
"s": 6809,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 6843,
"s": 6830,
"text": "todaysgaurav"
},
{
"code": null,
"e": 6853,
"s": 6843,
"text": "ruhelaa48"
},
{
"code": null,
"e": 6869,
"s": 6853,
"text": "base-conversion"
},
{
"code": null,
"e": 6880,
"s": 6869,
"text": "complement"
},
{
"code": null,
"e": 6893,
"s": 6880,
"text": "Mathematical"
},
{
"code": null,
"e": 6912,
"s": 6893,
"text": "School Programming"
},
{
"code": null,
"e": 6925,
"s": 6912,
"text": "Mathematical"
}
] |
Validate an IP address using Python without using RegEx | 13 Apr, 2022
Given an IP address as input, the task is to write a Python program to check whether the given IP Address is Valid or not without using RegEx.
What is an IP (Internet Protocol) Address? Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. An IP address (version 4) consists of four numbers (each between 0 and 255) separated by periods. The format of an IP address is a 32-bit numeric address written as four decimal numbers (called octets) separated by periods; each number can be written as 0 to 255 (E.g. – 0.0.0.0 to 255.255.255.255).
Examples:
Input: 192.168.0.1Output: Valid IP address
Input: 110.234.52.124Output: Valid IP address
Input: 666.1.2.2Output: Invalid IP address
Method #1: Checking the number of periods using count() method and then the range of numbers between each period.
Python3
# Python program to verify IP without using RegEx # explicit function to verify IPdef isValidIP(s): # check number of periods if s.count('.') != 3: return 'Invalid Ip address' l = list(map(str, s.split('.'))) # check range of each number between periods for ele in l: if int(ele) < 0 or int(ele) > 255 or (ele[0]=='0' and len(ele)!=1): return 'Invalid Ip address' return 'Valid Ip address' # Driver Codeprint(isValidIP('666.1.2.2'))
Invalid Ip address
Method #2: Using a variable to check the number of periods and using a set to check if the range of numbers between periods is between 0 and 255(inclusive).
Python3
# Python program to verify IP without using RegEx # explicit function to verify IPdef isValidIP(s): # initialize counter counter = 0 # check if period is present for i in range(0, len(s)): if(s[i] == '.'): counter = counter+1 if(counter != 3): return 0 # check the range of numbers between periods st = set() for i in range(0, 256): st.add(str(i)) counter = 0 temp = "" for i in range(0, len(s)): if(s[i] != '.'): temp = temp+s[i] else: if(temp in st): counter = counter+1 temp = "" if(temp in st): counter = counter+1 # verifying all conditions if(counter == 4): return 'Valid Ip address' else: return 'Invalid Ip address' # Driver Codeprint(isValidIP('110.234.52.124'))
Valid Ip address
simmytarika5
chinmayi
niharikajune23
Python Regex-programs
python-regex
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 Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Apr, 2022"
},
{
"code": null,
"e": 196,
"s": 53,
"text": "Given an IP address as input, the task is to write a Python program to check whether the given IP Address is Valid or not without using RegEx."
},
{
"code": null,
"e": 669,
"s": 196,
"text": "What is an IP (Internet Protocol) Address? Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. An IP address (version 4) consists of four numbers (each between 0 and 255) separated by periods. The format of an IP address is a 32-bit numeric address written as four decimal numbers (called octets) separated by periods; each number can be written as 0 to 255 (E.g. – 0.0.0.0 to 255.255.255.255)."
},
{
"code": null,
"e": 680,
"s": 669,
"text": "Examples: "
},
{
"code": null,
"e": 724,
"s": 680,
"text": "Input: 192.168.0.1Output: Valid IP address"
},
{
"code": null,
"e": 770,
"s": 724,
"text": "Input: 110.234.52.124Output: Valid IP address"
},
{
"code": null,
"e": 813,
"s": 770,
"text": "Input: 666.1.2.2Output: Invalid IP address"
},
{
"code": null,
"e": 927,
"s": 813,
"text": "Method #1: Checking the number of periods using count() method and then the range of numbers between each period."
},
{
"code": null,
"e": 935,
"s": 927,
"text": "Python3"
},
{
"code": "# Python program to verify IP without using RegEx # explicit function to verify IPdef isValidIP(s): # check number of periods if s.count('.') != 3: return 'Invalid Ip address' l = list(map(str, s.split('.'))) # check range of each number between periods for ele in l: if int(ele) < 0 or int(ele) > 255 or (ele[0]=='0' and len(ele)!=1): return 'Invalid Ip address' return 'Valid Ip address' # Driver Codeprint(isValidIP('666.1.2.2'))",
"e": 1416,
"s": 935,
"text": null
},
{
"code": null,
"e": 1436,
"s": 1416,
"text": "Invalid Ip address\n"
},
{
"code": null,
"e": 1593,
"s": 1436,
"text": "Method #2: Using a variable to check the number of periods and using a set to check if the range of numbers between periods is between 0 and 255(inclusive)."
},
{
"code": null,
"e": 1601,
"s": 1593,
"text": "Python3"
},
{
"code": "# Python program to verify IP without using RegEx # explicit function to verify IPdef isValidIP(s): # initialize counter counter = 0 # check if period is present for i in range(0, len(s)): if(s[i] == '.'): counter = counter+1 if(counter != 3): return 0 # check the range of numbers between periods st = set() for i in range(0, 256): st.add(str(i)) counter = 0 temp = \"\" for i in range(0, len(s)): if(s[i] != '.'): temp = temp+s[i] else: if(temp in st): counter = counter+1 temp = \"\" if(temp in st): counter = counter+1 # verifying all conditions if(counter == 4): return 'Valid Ip address' else: return 'Invalid Ip address' # Driver Codeprint(isValidIP('110.234.52.124'))",
"e": 2438,
"s": 1601,
"text": null
},
{
"code": null,
"e": 2456,
"s": 2438,
"text": "Valid Ip address\n"
},
{
"code": null,
"e": 2469,
"s": 2456,
"text": "simmytarika5"
},
{
"code": null,
"e": 2478,
"s": 2469,
"text": "chinmayi"
},
{
"code": null,
"e": 2493,
"s": 2478,
"text": "niharikajune23"
},
{
"code": null,
"e": 2515,
"s": 2493,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 2528,
"s": 2515,
"text": "python-regex"
},
{
"code": null,
"e": 2535,
"s": 2528,
"text": "Python"
},
{
"code": null,
"e": 2551,
"s": 2535,
"text": "Python Programs"
},
{
"code": null,
"e": 2649,
"s": 2551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2681,
"s": 2649,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2708,
"s": 2681,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2729,
"s": 2708,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2752,
"s": 2729,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2783,
"s": 2752,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2805,
"s": 2783,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2844,
"s": 2805,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2882,
"s": 2844,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2919,
"s": 2882,
"text": "Python Program for Fibonacci numbers"
}
] |
Program to print modified Binary triangle pattern | 12 Nov, 2021
Given an integer N, the task is to print the modified binary tree pattern.
In Modified Binary Triangle Pattern, the first and last element of a Nth row are 1 and the middle (N – 2) elements are 0.
Examples:
Input: N = 6 Output: 1 11 101 1001 10001 100001Input: N = 3 Output: 1 11 101
Approach: From the above examples, it can be observed that, for each row N:
1st and Nth element is a 1
and elements 2 to (N-1) are 0
Therefore an algorithm can be developed to print such pattern as:
Run a loop from 1 to N using a loop variable i, which denotes the row number of the triangle pattern.
For each row i, run a loop from 1 to i, using a loop variable j, which denotes the number in each row.
In each iteration of j, check if j is 1 or i. If either of it true, print 1.
If none of the case is true for j, then print 0
Increment the value of j by 1 after each iteration
When the j loop has completed successfully, we have printed a row of the pattern. Therefore change the output to the next line by printing a next line.
Increment the value of i and repeat the whole process till N rows has been printed successfully.
Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ implementation to print the// modified binary triangle pattern #include <bits/stdc++.h>using namespace std; // Function to print the modified// binary patternvoid modifiedBinaryPattern(int n){ // Loop to traverse the rows for (int i = 1; i <= n; i++) { // Loop to traverse the // numbers in each row for (int j = 1; j <= i; j++) { // Check if j is 1 or i // In either case print 1 if (j == 1 || j == i) cout << 1; // Else print 0 else cout << 0; } // Change the cursor to next // line after each row cout << endl; }} // Driver Codeint main(){ int n = 7; // Function Call modifiedBinaryPattern(n);}
// Java implementation to print the// modified binary triangle patternimport java.io.*; class GFG{ // Function to print the modified// binary patternstatic void modifiedBinaryPattern(int n){ // Loop to traverse the rows for(int i = 1; i <= n; i++) { // Loop to traverse the // numbers in each row for(int j = 1; j <= i; j++) { // Check if j is 1 or i // In either case print 1 if (j == 1 || j == i) System.out.print(1); // Else print 0 else System.out.print(0); } // Change the cursor to next // line after each row System.out.println(); }} // Driver Codepublic static void main (String[] args){ int n = 7; // Function call modifiedBinaryPattern(n);}} // This code is contributed by shubhamsingh10
# python3 implementation to print the# modified binary triangle pattern # Function to print the modified# binary patterndef modifiedBinaryPattern(n): # Loop to traverse the rows for i in range(1, n + 1, 1): # Loop to traverse the # numbers in each row for j in range(1, i + 1, 1): # Check if j is 1 or i # In either case print 1 if (j == 1 or j == i): print(1, end = "") # Else print 0 else: print(0, end = "") # Change the cursor to next # line after each row print('\n', end = "") # Driver Codeif __name__ == '__main__': n = 7 # Function Call modifiedBinaryPattern(n) # This code is contributed by Samarth
// C# implementation to print the// modified binary triangle patternusing System;class GFG{ // Function to print the modified// binary patternstatic void modifiedBinaryPattern(int n){ // Loop to traverse the rows for(int i = 1; i <= n; i++) { // Loop to traverse the // numbers in each row for(int j = 1; j <= i; j++) { // Check if j is 1 or i // In either case print 1 if (j == 1 || j == i) Console.Write(1); // Else print 0 else Console.Write(0); } // Change the cursor to next // line after each row Console.WriteLine(); }} // Driver Codepublic static void Main(){ int n = 7; // Function call modifiedBinaryPattern(n);}} // This code is contributed by Nidhi_Biet
<script> // Javascript implementation to print the// modified binary triangle pattern // Function to print the modified// binary patternfunction modifiedBinaryPattern(n){ // Loop to traverse the rows for(let i = 1; i <= n; i++) { // Loop to traverse the // numbers in each row for(let j = 1; j <= i; j++) { // Check if j is 1 or i // In either case print 1 if (j == 1 || j == i) document.write(1); // Else print 0 else document.write(0); } // Change the cursor to next // line after each row document.write("<br/>"); }} // Driver code let n = 7; // Function call modifiedBinaryPattern(n); // This code is contributed by susmitakundugoaldanga.</script>
1
11
101
1001
10001
100001
1000001
Time Complexity: O(n2)
Auxiliary Space: O(1)
ipg2016107
SHUBHAMSINGH10
nidhi_biet
susmitakundugoaldanga
subham348
binary-string
pattern-printing
Mathematical
School Programming
Write From Home
Mathematical
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 128,
"s": 52,
"text": "Given an integer N, the task is to print the modified binary tree pattern. "
},
{
"code": null,
"e": 250,
"s": 128,
"text": "In Modified Binary Triangle Pattern, the first and last element of a Nth row are 1 and the middle (N – 2) elements are 0."
},
{
"code": null,
"e": 262,
"s": 250,
"text": "Examples: "
},
{
"code": null,
"e": 341,
"s": 262,
"text": "Input: N = 6 Output: 1 11 101 1001 10001 100001Input: N = 3 Output: 1 11 101 "
},
{
"code": null,
"e": 421,
"s": 343,
"text": "Approach: From the above examples, it can be observed that, for each row N: "
},
{
"code": null,
"e": 448,
"s": 421,
"text": "1st and Nth element is a 1"
},
{
"code": null,
"e": 478,
"s": 448,
"text": "and elements 2 to (N-1) are 0"
},
{
"code": null,
"e": 546,
"s": 478,
"text": "Therefore an algorithm can be developed to print such pattern as: "
},
{
"code": null,
"e": 648,
"s": 546,
"text": "Run a loop from 1 to N using a loop variable i, which denotes the row number of the triangle pattern."
},
{
"code": null,
"e": 751,
"s": 648,
"text": "For each row i, run a loop from 1 to i, using a loop variable j, which denotes the number in each row."
},
{
"code": null,
"e": 828,
"s": 751,
"text": "In each iteration of j, check if j is 1 or i. If either of it true, print 1."
},
{
"code": null,
"e": 876,
"s": 828,
"text": "If none of the case is true for j, then print 0"
},
{
"code": null,
"e": 927,
"s": 876,
"text": "Increment the value of j by 1 after each iteration"
},
{
"code": null,
"e": 1079,
"s": 927,
"text": "When the j loop has completed successfully, we have printed a row of the pattern. Therefore change the output to the next line by printing a next line."
},
{
"code": null,
"e": 1176,
"s": 1079,
"text": "Increment the value of i and repeat the whole process till N rows has been printed successfully."
},
{
"code": null,
"e": 1228,
"s": 1176,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1232,
"s": 1228,
"text": "C++"
},
{
"code": null,
"e": 1237,
"s": 1232,
"text": "Java"
},
{
"code": null,
"e": 1246,
"s": 1237,
"text": "Python 3"
},
{
"code": null,
"e": 1249,
"s": 1246,
"text": "C#"
},
{
"code": null,
"e": 1260,
"s": 1249,
"text": "Javascript"
},
{
"code": "// C++ implementation to print the// modified binary triangle pattern #include <bits/stdc++.h>using namespace std; // Function to print the modified// binary patternvoid modifiedBinaryPattern(int n){ // Loop to traverse the rows for (int i = 1; i <= n; i++) { // Loop to traverse the // numbers in each row for (int j = 1; j <= i; j++) { // Check if j is 1 or i // In either case print 1 if (j == 1 || j == i) cout << 1; // Else print 0 else cout << 0; } // Change the cursor to next // line after each row cout << endl; }} // Driver Codeint main(){ int n = 7; // Function Call modifiedBinaryPattern(n);}",
"e": 2023,
"s": 1260,
"text": null
},
{
"code": "// Java implementation to print the// modified binary triangle patternimport java.io.*; class GFG{ // Function to print the modified// binary patternstatic void modifiedBinaryPattern(int n){ // Loop to traverse the rows for(int i = 1; i <= n; i++) { // Loop to traverse the // numbers in each row for(int j = 1; j <= i; j++) { // Check if j is 1 or i // In either case print 1 if (j == 1 || j == i) System.out.print(1); // Else print 0 else System.out.print(0); } // Change the cursor to next // line after each row System.out.println(); }} // Driver Codepublic static void main (String[] args){ int n = 7; // Function call modifiedBinaryPattern(n);}} // This code is contributed by shubhamsingh10",
"e": 2915,
"s": 2023,
"text": null
},
{
"code": "# python3 implementation to print the# modified binary triangle pattern # Function to print the modified# binary patterndef modifiedBinaryPattern(n): # Loop to traverse the rows for i in range(1, n + 1, 1): # Loop to traverse the # numbers in each row for j in range(1, i + 1, 1): # Check if j is 1 or i # In either case print 1 if (j == 1 or j == i): print(1, end = \"\") # Else print 0 else: print(0, end = \"\") # Change the cursor to next # line after each row print('\\n', end = \"\") # Driver Codeif __name__ == '__main__': n = 7 # Function Call modifiedBinaryPattern(n) # This code is contributed by Samarth",
"e": 3696,
"s": 2915,
"text": null
},
{
"code": "// C# implementation to print the// modified binary triangle patternusing System;class GFG{ // Function to print the modified// binary patternstatic void modifiedBinaryPattern(int n){ // Loop to traverse the rows for(int i = 1; i <= n; i++) { // Loop to traverse the // numbers in each row for(int j = 1; j <= i; j++) { // Check if j is 1 or i // In either case print 1 if (j == 1 || j == i) Console.Write(1); // Else print 0 else Console.Write(0); } // Change the cursor to next // line after each row Console.WriteLine(); }} // Driver Codepublic static void Main(){ int n = 7; // Function call modifiedBinaryPattern(n);}} // This code is contributed by Nidhi_Biet",
"e": 4574,
"s": 3696,
"text": null
},
{
"code": "<script> // Javascript implementation to print the// modified binary triangle pattern // Function to print the modified// binary patternfunction modifiedBinaryPattern(n){ // Loop to traverse the rows for(let i = 1; i <= n; i++) { // Loop to traverse the // numbers in each row for(let j = 1; j <= i; j++) { // Check if j is 1 or i // In either case print 1 if (j == 1 || j == i) document.write(1); // Else print 0 else document.write(0); } // Change the cursor to next // line after each row document.write(\"<br/>\"); }} // Driver code let n = 7; // Function call modifiedBinaryPattern(n); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 5440,
"s": 4574,
"text": null
},
{
"code": null,
"e": 5475,
"s": 5440,
"text": "1\n11\n101\n1001\n10001\n100001\n1000001"
},
{
"code": null,
"e": 5500,
"s": 5477,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 5522,
"s": 5500,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5533,
"s": 5522,
"text": "ipg2016107"
},
{
"code": null,
"e": 5548,
"s": 5533,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 5559,
"s": 5548,
"text": "nidhi_biet"
},
{
"code": null,
"e": 5581,
"s": 5559,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 5591,
"s": 5581,
"text": "subham348"
},
{
"code": null,
"e": 5605,
"s": 5591,
"text": "binary-string"
},
{
"code": null,
"e": 5622,
"s": 5605,
"text": "pattern-printing"
},
{
"code": null,
"e": 5635,
"s": 5622,
"text": "Mathematical"
},
{
"code": null,
"e": 5654,
"s": 5635,
"text": "School Programming"
},
{
"code": null,
"e": 5670,
"s": 5654,
"text": "Write From Home"
},
{
"code": null,
"e": 5683,
"s": 5670,
"text": "Mathematical"
},
{
"code": null,
"e": 5700,
"s": 5683,
"text": "pattern-printing"
}
] |
Click button by text using Python and Selenium | 03 Mar, 2021
Selenium is a tool that provides APIs to automate a web application to aid in its testing. In this article, we discuss the use of Selenium Python API bindings to access the Selenium WebDrivers to click a button by text present in the button. In the following example, we take the help of Chrome. The method used is the find_element_by_link_text() which scrapes the element using the text present. In case there is no such element with the given text attribute, NoSuchElementException is returned.
Make sure you have Selenium installed using
pip3 install Selenium
And also download the WebDriver for your web browser :
Chrome : https://chromedriver.chromium.org/downloads
Firefox : https://github.com/mozilla/geckodriver/releases
Safari : https://webkit.org/blog/6900/webdriver-support-in-safari-10/
Once Selenium is installed along with the desired WebDriver, we create a file script.py and using our code editor write the python script below which opens up the geeksforgeeks website using the Selenium WebDriver and clicks the Sign In button using the link text.
Syntax:
driver.find_element_by_link_text("sample text")
Steps by step Approach:
Import required modules.
Create webdriver object.
Assign URL.
Use maximize_window() method to maximize the browser window. And then wait 10 seconds using sleep() method.
Use find_element_by_link_text() method to click button by text.
Below is the implementation.
Python3
# import modulefrom selenium import webdriverimport time # Create the webdriver object. Here the # chromedriver is present in the driver # folder of the root directory.driver = webdriver.Chrome(r"./driver/chromedriver") # get https://www.geeksforgeeks.org/driver.get("https://www.geeksforgeeks.org/") # Maximize the window and let code stall # for 10s to properly maximise the window.driver.maximize_window()time.sleep(10) # Obtain button by link text and click.button = driver.find_element_by_link_text("Sign In")button.click()
Output:
First, the WebDriver opens up the window with geeksforgeeks, maximizes it, and waits for 10 seconds. Then it clicks the Sign In button and opens up the sign-up panel.
Picked
Python Selenium-Exercises
Python-selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 549,
"s": 52,
"text": "Selenium is a tool that provides APIs to automate a web application to aid in its testing. In this article, we discuss the use of Selenium Python API bindings to access the Selenium WebDrivers to click a button by text present in the button. In the following example, we take the help of Chrome. The method used is the find_element_by_link_text() which scrapes the element using the text present. In case there is no such element with the given text attribute, NoSuchElementException is returned."
},
{
"code": null,
"e": 593,
"s": 549,
"text": "Make sure you have Selenium installed using"
},
{
"code": null,
"e": 615,
"s": 593,
"text": "pip3 install Selenium"
},
{
"code": null,
"e": 670,
"s": 615,
"text": "And also download the WebDriver for your web browser :"
},
{
"code": null,
"e": 851,
"s": 670,
"text": "Chrome : https://chromedriver.chromium.org/downloads\nFirefox : https://github.com/mozilla/geckodriver/releases\nSafari : https://webkit.org/blog/6900/webdriver-support-in-safari-10/"
},
{
"code": null,
"e": 1116,
"s": 851,
"text": "Once Selenium is installed along with the desired WebDriver, we create a file script.py and using our code editor write the python script below which opens up the geeksforgeeks website using the Selenium WebDriver and clicks the Sign In button using the link text."
},
{
"code": null,
"e": 1124,
"s": 1116,
"text": "Syntax:"
},
{
"code": null,
"e": 1172,
"s": 1124,
"text": "driver.find_element_by_link_text(\"sample text\")"
},
{
"code": null,
"e": 1196,
"s": 1172,
"text": "Steps by step Approach:"
},
{
"code": null,
"e": 1221,
"s": 1196,
"text": "Import required modules."
},
{
"code": null,
"e": 1246,
"s": 1221,
"text": "Create webdriver object."
},
{
"code": null,
"e": 1258,
"s": 1246,
"text": "Assign URL."
},
{
"code": null,
"e": 1366,
"s": 1258,
"text": "Use maximize_window() method to maximize the browser window. And then wait 10 seconds using sleep() method."
},
{
"code": null,
"e": 1430,
"s": 1366,
"text": "Use find_element_by_link_text() method to click button by text."
},
{
"code": null,
"e": 1459,
"s": 1430,
"text": "Below is the implementation."
},
{
"code": null,
"e": 1467,
"s": 1459,
"text": "Python3"
},
{
"code": "# import modulefrom selenium import webdriverimport time # Create the webdriver object. Here the # chromedriver is present in the driver # folder of the root directory.driver = webdriver.Chrome(r\"./driver/chromedriver\") # get https://www.geeksforgeeks.org/driver.get(\"https://www.geeksforgeeks.org/\") # Maximize the window and let code stall # for 10s to properly maximise the window.driver.maximize_window()time.sleep(10) # Obtain button by link text and click.button = driver.find_element_by_link_text(\"Sign In\")button.click()",
"e": 2000,
"s": 1467,
"text": null
},
{
"code": null,
"e": 2008,
"s": 2000,
"text": "Output:"
},
{
"code": null,
"e": 2175,
"s": 2008,
"text": "First, the WebDriver opens up the window with geeksforgeeks, maximizes it, and waits for 10 seconds. Then it clicks the Sign In button and opens up the sign-up panel."
},
{
"code": null,
"e": 2182,
"s": 2175,
"text": "Picked"
},
{
"code": null,
"e": 2208,
"s": 2182,
"text": "Python Selenium-Exercises"
},
{
"code": null,
"e": 2224,
"s": 2208,
"text": "Python-selenium"
},
{
"code": null,
"e": 2231,
"s": 2224,
"text": "Python"
}
] |
Tailwind CSS Container | 23 Mar, 2022
In Tailwind CSS, a container is used to fix the max-width of an element to match the min-width of the breakpoint. It comes very handy when content has to be displayed in a responsive manner to every breakpoint.
Breakpoints in tailwind CSS are as follows.
Tailwind CSS does not center itself automatically and also does not contain any pre-defined padding. The following are some utility classes that make the container class stand out.
mx-auto: To center the container, we use mx-auto utility class. It adjust the margin of the container automatically so that the container appears to be in center.
Syntax:
<element class="mx-auto">...</element>
Example:
HTML
<!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> <style> .container { background-color: rgb(2, 201, 118); color: white; } h2 { text-align: center; } </style></head> <body> <h2 style="color:green"> GeeksforGeeks </h2><br /> <div class="container mx-auto"> This is mx-auto class </div></body> </html>
Output:
mx-auto class
px-{size}: To add padding the container, we use px-{size} utility class. It adds horizontal padding to the container which is equal to the size mentioned.
Syntax:
<element class="px-20">...</element>
Example:
HTML
<!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> <style> .container { background-color: rgb(2, 201, 118); color: white; } h2 { text-align: center; } </style></head> <body> <h2 style="color:green"> GeeksforGeeks </h2> <br /> <div class="container mx-auto px-20"> This is px-20 class </div></body> </html>
Output:
px-size class
Picked
Tailwind CSS
Tailwind-Layout
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 263,
"s": 52,
"text": "In Tailwind CSS, a container is used to fix the max-width of an element to match the min-width of the breakpoint. It comes very handy when content has to be displayed in a responsive manner to every breakpoint."
},
{
"code": null,
"e": 307,
"s": 263,
"text": "Breakpoints in tailwind CSS are as follows."
},
{
"code": null,
"e": 488,
"s": 307,
"text": "Tailwind CSS does not center itself automatically and also does not contain any pre-defined padding. The following are some utility classes that make the container class stand out."
},
{
"code": null,
"e": 652,
"s": 488,
"text": "mx-auto: To center the container, we use mx-auto utility class. It adjust the margin of the container automatically so that the container appears to be in center. "
},
{
"code": null,
"e": 662,
"s": 654,
"text": "Syntax:"
},
{
"code": null,
"e": 701,
"s": 662,
"text": "<element class=\"mx-auto\">...</element>"
},
{
"code": null,
"e": 710,
"s": 701,
"text": "Example:"
},
{
"code": null,
"e": 715,
"s": 710,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> <style> .container { background-color: rgb(2, 201, 118); color: white; } h2 { text-align: center; } </style></head> <body> <h2 style=\"color:green\"> GeeksforGeeks </h2><br /> <div class=\"container mx-auto\"> This is mx-auto class </div></body> </html>",
"e": 1198,
"s": 715,
"text": null
},
{
"code": null,
"e": 1206,
"s": 1198,
"text": "Output:"
},
{
"code": null,
"e": 1220,
"s": 1206,
"text": "mx-auto class"
},
{
"code": null,
"e": 1375,
"s": 1220,
"text": "px-{size}: To add padding the container, we use px-{size} utility class. It adds horizontal padding to the container which is equal to the size mentioned."
},
{
"code": null,
"e": 1383,
"s": 1375,
"text": "Syntax:"
},
{
"code": null,
"e": 1420,
"s": 1383,
"text": "<element class=\"px-20\">...</element>"
},
{
"code": null,
"e": 1429,
"s": 1420,
"text": "Example:"
},
{
"code": null,
"e": 1434,
"s": 1429,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> <style> .container { background-color: rgb(2, 201, 118); color: white; } h2 { text-align: center; } </style></head> <body> <h2 style=\"color:green\"> GeeksforGeeks </h2> <br /> <div class=\"container mx-auto px-20\"> This is px-20 class </div></body> </html>",
"e": 1925,
"s": 1434,
"text": null
},
{
"code": null,
"e": 1933,
"s": 1925,
"text": "Output:"
},
{
"code": null,
"e": 1947,
"s": 1933,
"text": "px-size class"
},
{
"code": null,
"e": 1954,
"s": 1947,
"text": "Picked"
},
{
"code": null,
"e": 1967,
"s": 1954,
"text": "Tailwind CSS"
},
{
"code": null,
"e": 1983,
"s": 1967,
"text": "Tailwind-Layout"
},
{
"code": null,
"e": 1987,
"s": 1983,
"text": "CSS"
},
{
"code": null,
"e": 2004,
"s": 1987,
"text": "Web Technologies"
}
] |
Sum of product of all pairs of array elements | 14 Aug, 2021
Given an array A[] of integers find sum of product of all pairs of array elements i. e., we need to find of product after execution of following pseudo code
product = 0
for i = 1:n
for j = i+1:n
product = product + A[i]*A[j]
Examples:
Input : A[] = {1, 3, 4}
Output : 19
Possible Pairs : (1,3), (1,4), (3,4)
Sum of Product : 1*3 + 1*4 + 3*4 = 19
For each index i we loop through j=i+1 to j=n and add A[i]*A[j] each time. Below is implementation for the same.
C++
Java
Python3
C#
PHP
Javascript
// A naive C++ program to find sum of product#include <iostream>using namespace std; // Returns sum of pair productsint findProductSum(int A[], int n){ int product = 0; for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) product = product + A[i]*A[j]; return product;} // Driver codeint main(){ int A[] = {1, 3, 4}; int n = sizeof(A)/sizeof(A[0]); cout << "sum of product of all pairs " "of array elements : " << findProductSum(A, n); return 0;}
/*package whatever //do not write package name here */// A naive Java program to find sum of productimport java.io.*;class test{ // Returns sum of pair products int findProductSum(int A[], int n) { int product = 0; for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) product = product + A[i]*A[j]; return product; }}class GFG { // Driver code public static void main (String[] args) { int A[] = {1, 3, 4}; int n = A.length; test t = new test(); System.out.print("sum of product of all pairs of array elements : "); System.out.println(t.findProductSum(A, n)); }}
# A naive python3 program to find sum of product # Returns sum of pair productsdef findProductSum(A,n): product = 0 for i in range (n): for j in range ( i+1,n): product = product + A[i]*A[j] return product # Driver codeif __name__=="__main__": A = [1, 3, 4] n = len (A) print("sum of product of all pairs " "of array elements : " ,findProductSum(A, n))
// A naive C# program to find sum of productusing System; class GFG{ // Returns sum of pair productsstatic int findProductSum(int[] A, int n){ int product = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) product = product + A[i] * A[j]; return product;} // Driver codepublic static void Main(){ int[] A = {1, 3, 4}; int n = A.Length; Console.WriteLine("sum of product of all " + "pairs of array elements : "); Console.WriteLine(findProductSum(A, n));}} // This code is contributed// by Akanksha Rai
<?php// A naive PHP program to find// sum of product // Returns sum of pair productsfunction findProductSum($A, $n){ $product = 0; for ($i = 0; $i < $n; $i++) for ($j = $i + 1; $j < $n; $j++) $product = $product + $A[$i] * $A[$j]; return $product;} // Driver code $A = array (1, 3, 4); $n = sizeof($A); echo "sum of product of all pairs ", "of array elements : " ,findProductSum($A, $n); // This code is contributed by aj_36?>
<script> // A naive Javascript program to find sum of product // Returns sum of pair productsfunction findProductSum(A, n){ let product = 0; for (let i= 0; i < n; i++) for (let j = i+1; j < n; j++) product = product + A[i]*A[j]; return product;} // Driver code let A = [1, 3, 4]; let n = A.length; document.write("sum of product of all pairs " + "of array elements : " + findProductSum(A, n)); // This code is contributed by Mayank Tyagi </script>
Output:
sum of product of all pairs of array elements : 19
Time Complexity : O(n2) Space Complexity : O(1)
We know that
(a + b + c)2 = a2 + b2 + c2 + 2*(a*b + b*c + c*a)
Let required sum be P
Let E = (a1 + a2 + a3 + a4 ... + an)^2
=> E = a12 + a22 + ... + an2 + 2*(a1*a2 + a1*a3 + ....)
=> E = a12 + a22 + ... + an2 + 2*(P)
=> P = ( E - (a12 + a22 + .... + an2) ) / 2
C++
Java
Python3
C#
PHP
Javascript
// Efficient C++ program to find sum pair products// in an array.#include <iostream>using namespace std; // required functionint findProductSum(int A[], int n){ // calculating array sum (a1 + a2 ... + an) int array_sum = 0; for (int i = 0; i < n; i++) array_sum = array_sum + A[i]; // calculating square of array sum // (a1 + a2 + ... + an)^2 int array_sum_square = array_sum * array_sum; // calculating a1^2 + a2^2 + ... + an^2 int individual_square_sum = 0; for (int i = 0; i < n; i++) individual_square_sum += A[i]*A[i]; // required sum is (array_sum_square - // individual_square_sum) / 2 return (array_sum_square - individual_square_sum)/2;} // Driver codeint main(){ int A[] = {1, 3, 4}; int n = sizeof(A)/sizeof(A[0]); cout << "sum of product of all pairs of array " "elements : " << findProductSum(A, n); return 0;}
// Efficient Java program to find sum pair products// in an array.class GFG{ // required functionstatic int findProductSum(int A[], int n){ // calculating array sum (a1 + a2 ... + an) int array_sum = 0; for (int i = 0; i < n; i++) array_sum = array_sum + A[i]; // calculating square of array sum // (a1 + a2 + ... + an)^2 int array_sum_square = array_sum * array_sum; // calculating a1^2 + a2^2 + ... + an^2 int individual_square_sum = 0; for (int i = 0; i < n; i++) individual_square_sum += A[i] * A[i]; // required sum is (array_sum_square - // individual_square_sum) / 2 return (array_sum_square - individual_square_sum) / 2;} // Driver codepublic static void main(String[] args){ int A[] = {1, 3, 4}; int n = A.length; System.out.println("sum of product of all pairs of array " +"elements : " + findProductSum(A, n)); }} // This code is contributed by 29AjayKumar
# Efficient python 3 program to find sum# pair products in an array. # required functiondef findProductSum(A, n): # calculating array sum (a1 + a2 ... + an) array_sum = 0 for i in range(0, n, 1): array_sum = array_sum + A[i] # calculating square of array sum # (a1 + a2 + ... + an)^2 array_sum_square = array_sum * array_sum # calculating a1^2 + a2^2 + ... + an^2 individual_square_sum = 0 for i in range(0, n, 1): individual_square_sum += A[i] * A[i] # required sum is (array_sum_square - # individual_square_sum) / 2 return (array_sum_square - individual_square_sum) / 2 # Driver codeif __name__ == '__main__': A = [1, 3, 4] n = len(A) print("sum of product of all pairs of", "array elements :", int(findProductSum(A, n))) # This code is contributed by# Sahil_Shelangia
// Efficient C# program to find sum pair// products in an array.using System; class GFG{ // required functionstatic int findProductSum(int[] A, int n){ // calculating array sum (a1 + a2 ... + an) int array_sum = 0; for (int i = 0; i < n; i++) array_sum = array_sum + A[i]; // calculating square of array sum // (a1 + a2 + ... + an)^2 int array_sum_square = array_sum * array_sum; // calculating a1^2 + a2^2 + ... + an^2 int individual_square_sum = 0; for (int i = 0; i < n; i++) individual_square_sum += A[i] * A[i]; // required sum is (array_sum_square - // individual_square_sum) / 2 return (array_sum_square - individual_square_sum) / 2;} // Driver codepublic static void Main(){ int[] A = {1, 3, 4}; int n = A.Length; Console.WriteLine("sum of product of all " + "pairs of array elements : " + findProductSum(A, n));}} // This code is contributed by Akanksha Rai
<?php// Efficient PHP program to find sum// pair products in an array. // required functionfunction findProductSum(&$A, $n){ // calculating array sum (a1 + a2 ... + an) $array_sum = 0; for ($i = 0; $i < $n; $i++) $array_sum = $array_sum + $A[$i]; // calculating square of array sum // (a1 + a2 + ... + an)^2 $array_sum_square = $array_sum * $array_sum; // calculating a1^2 + a2^2 + ... + an^2 $individual_square_sum = 0; for ($i = 0; $i < $n; $i++) $individual_square_sum += $A[$i] * $A[$i]; // required sum is (array_sum_square - // individual_square_sum) / 2 return ($array_sum_square - $individual_square_sum) / 2;} // Driver code$A = array(1, 3, 4);$n = sizeof($A);echo("sum of product of all pairs " . "of array elements : ");echo (findProductSum($A, $n)); // This code is contributed// by Shivi_Aggarwal?>
<script> // Efficient Javascript program to find sum pair // products in an array. // required function function findProductSum(A, n) { // calculating array sum (a1 + a2 ... + an) let array_sum = 0; for (let i = 0; i < n; i++) array_sum = array_sum + A[i]; // calculating square of array sum // (a1 + a2 + ... + an)^2 let array_sum_square = array_sum * array_sum; // calculating a1^2 + a2^2 + ... + an^2 let individual_square_sum = 0; for (let i = 0; i < n; i++) individual_square_sum += A[i] * A[i]; // required sum is (array_sum_square - // individual_square_sum) / 2 return (array_sum_square - individual_square_sum) / 2; } let A = [1, 3, 4]; let n = A.length; document.write("sum of product of all " + "pairs of array elements : " + findProductSum(A, n)); // This code is contributed by rameshtravel07.</script>
Output:
sum of product of all pairs of array elements : 19
Time Complexity : O(n) Space Complexity : O(1)This article is contributed by Pratik Chhajer. 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
ukasp
29AjayKumar
sahilshelangia
Akanksha_Rai
princiraj1992
Shivi_Aggarwal
mayanktyagi1709
rameshtravel07
saurabh1990aror
surindertarika1234
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": "\n14 Aug, 2021"
},
{
"code": null,
"e": 210,
"s": 52,
"text": "Given an array A[] of integers find sum of product of all pairs of array elements i. e., we need to find of product after execution of following pseudo code "
},
{
"code": null,
"e": 290,
"s": 210,
"text": "product = 0\nfor i = 1:n\n for j = i+1:n\n product = product + A[i]*A[j]"
},
{
"code": null,
"e": 301,
"s": 290,
"text": "Examples: "
},
{
"code": null,
"e": 412,
"s": 301,
"text": "Input : A[] = {1, 3, 4}\nOutput : 19\nPossible Pairs : (1,3), (1,4), (3,4)\nSum of Product : 1*3 + 1*4 + 3*4 = 19"
},
{
"code": null,
"e": 531,
"s": 416,
"text": "For each index i we loop through j=i+1 to j=n and add A[i]*A[j] each time. Below is implementation for the same. "
},
{
"code": null,
"e": 535,
"s": 531,
"text": "C++"
},
{
"code": null,
"e": 540,
"s": 535,
"text": "Java"
},
{
"code": null,
"e": 548,
"s": 540,
"text": "Python3"
},
{
"code": null,
"e": 551,
"s": 548,
"text": "C#"
},
{
"code": null,
"e": 555,
"s": 551,
"text": "PHP"
},
{
"code": null,
"e": 566,
"s": 555,
"text": "Javascript"
},
{
"code": "// A naive C++ program to find sum of product#include <iostream>using namespace std; // Returns sum of pair productsint findProductSum(int A[], int n){ int product = 0; for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) product = product + A[i]*A[j]; return product;} // Driver codeint main(){ int A[] = {1, 3, 4}; int n = sizeof(A)/sizeof(A[0]); cout << \"sum of product of all pairs \" \"of array elements : \" << findProductSum(A, n); return 0;}",
"e": 1062,
"s": 566,
"text": null
},
{
"code": "/*package whatever //do not write package name here */// A naive Java program to find sum of productimport java.io.*;class test{ // Returns sum of pair products int findProductSum(int A[], int n) { int product = 0; for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) product = product + A[i]*A[j]; return product; }}class GFG { // Driver code public static void main (String[] args) { int A[] = {1, 3, 4}; int n = A.length; test t = new test(); System.out.print(\"sum of product of all pairs of array elements : \"); System.out.println(t.findProductSum(A, n)); }}",
"e": 1692,
"s": 1062,
"text": null
},
{
"code": "# A naive python3 program to find sum of product # Returns sum of pair productsdef findProductSum(A,n): product = 0 for i in range (n): for j in range ( i+1,n): product = product + A[i]*A[j] return product # Driver codeif __name__==\"__main__\": A = [1, 3, 4] n = len (A) print(\"sum of product of all pairs \" \"of array elements : \" ,findProductSum(A, n))",
"e": 2090,
"s": 1692,
"text": null
},
{
"code": "// A naive C# program to find sum of productusing System; class GFG{ // Returns sum of pair productsstatic int findProductSum(int[] A, int n){ int product = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) product = product + A[i] * A[j]; return product;} // Driver codepublic static void Main(){ int[] A = {1, 3, 4}; int n = A.Length; Console.WriteLine(\"sum of product of all \" + \"pairs of array elements : \"); Console.WriteLine(findProductSum(A, n));}} // This code is contributed// by Akanksha Rai",
"e": 2669,
"s": 2090,
"text": null
},
{
"code": "<?php// A naive PHP program to find// sum of product // Returns sum of pair productsfunction findProductSum($A, $n){ $product = 0; for ($i = 0; $i < $n; $i++) for ($j = $i + 1; $j < $n; $j++) $product = $product + $A[$i] * $A[$j]; return $product;} // Driver code $A = array (1, 3, 4); $n = sizeof($A); echo \"sum of product of all pairs \", \"of array elements : \" ,findProductSum($A, $n); // This code is contributed by aj_36?>",
"e": 3153,
"s": 2669,
"text": null
},
{
"code": "<script> // A naive Javascript program to find sum of product // Returns sum of pair productsfunction findProductSum(A, n){ let product = 0; for (let i= 0; i < n; i++) for (let j = i+1; j < n; j++) product = product + A[i]*A[j]; return product;} // Driver code let A = [1, 3, 4]; let n = A.length; document.write(\"sum of product of all pairs \" + \"of array elements : \" + findProductSum(A, n)); // This code is contributed by Mayank Tyagi </script>",
"e": 3653,
"s": 3153,
"text": null
},
{
"code": null,
"e": 3662,
"s": 3653,
"text": "Output: "
},
{
"code": null,
"e": 3713,
"s": 3662,
"text": "sum of product of all pairs of array elements : 19"
},
{
"code": null,
"e": 3762,
"s": 3713,
"text": "Time Complexity : O(n2) Space Complexity : O(1) "
},
{
"code": null,
"e": 4024,
"s": 3762,
"text": "We know that\n(a + b + c)2 = a2 + b2 + c2 + 2*(a*b + b*c + c*a)\nLet required sum be P\nLet E = (a1 + a2 + a3 + a4 ... + an)^2 \n=> E = a12 + a22 + ... + an2 + 2*(a1*a2 + a1*a3 + ....)\n=> E = a12 + a22 + ... + an2 + 2*(P)\n=> P = ( E - (a12 + a22 + .... + an2) ) / 2"
},
{
"code": null,
"e": 4030,
"s": 4026,
"text": "C++"
},
{
"code": null,
"e": 4035,
"s": 4030,
"text": "Java"
},
{
"code": null,
"e": 4043,
"s": 4035,
"text": "Python3"
},
{
"code": null,
"e": 4046,
"s": 4043,
"text": "C#"
},
{
"code": null,
"e": 4050,
"s": 4046,
"text": "PHP"
},
{
"code": null,
"e": 4061,
"s": 4050,
"text": "Javascript"
},
{
"code": "// Efficient C++ program to find sum pair products// in an array.#include <iostream>using namespace std; // required functionint findProductSum(int A[], int n){ // calculating array sum (a1 + a2 ... + an) int array_sum = 0; for (int i = 0; i < n; i++) array_sum = array_sum + A[i]; // calculating square of array sum // (a1 + a2 + ... + an)^2 int array_sum_square = array_sum * array_sum; // calculating a1^2 + a2^2 + ... + an^2 int individual_square_sum = 0; for (int i = 0; i < n; i++) individual_square_sum += A[i]*A[i]; // required sum is (array_sum_square - // individual_square_sum) / 2 return (array_sum_square - individual_square_sum)/2;} // Driver codeint main(){ int A[] = {1, 3, 4}; int n = sizeof(A)/sizeof(A[0]); cout << \"sum of product of all pairs of array \" \"elements : \" << findProductSum(A, n); return 0;}",
"e": 4962,
"s": 4061,
"text": null
},
{
"code": "// Efficient Java program to find sum pair products// in an array.class GFG{ // required functionstatic int findProductSum(int A[], int n){ // calculating array sum (a1 + a2 ... + an) int array_sum = 0; for (int i = 0; i < n; i++) array_sum = array_sum + A[i]; // calculating square of array sum // (a1 + a2 + ... + an)^2 int array_sum_square = array_sum * array_sum; // calculating a1^2 + a2^2 + ... + an^2 int individual_square_sum = 0; for (int i = 0; i < n; i++) individual_square_sum += A[i] * A[i]; // required sum is (array_sum_square - // individual_square_sum) / 2 return (array_sum_square - individual_square_sum) / 2;} // Driver codepublic static void main(String[] args){ int A[] = {1, 3, 4}; int n = A.length; System.out.println(\"sum of product of all pairs of array \" +\"elements : \" + findProductSum(A, n)); }} // This code is contributed by 29AjayKumar",
"e": 5906,
"s": 4962,
"text": null
},
{
"code": "# Efficient python 3 program to find sum# pair products in an array. # required functiondef findProductSum(A, n): # calculating array sum (a1 + a2 ... + an) array_sum = 0 for i in range(0, n, 1): array_sum = array_sum + A[i] # calculating square of array sum # (a1 + a2 + ... + an)^2 array_sum_square = array_sum * array_sum # calculating a1^2 + a2^2 + ... + an^2 individual_square_sum = 0 for i in range(0, n, 1): individual_square_sum += A[i] * A[i] # required sum is (array_sum_square - # individual_square_sum) / 2 return (array_sum_square - individual_square_sum) / 2 # Driver codeif __name__ == '__main__': A = [1, 3, 4] n = len(A) print(\"sum of product of all pairs of\", \"array elements :\", int(findProductSum(A, n))) # This code is contributed by# Sahil_Shelangia",
"e": 6769,
"s": 5906,
"text": null
},
{
"code": "// Efficient C# program to find sum pair// products in an array.using System; class GFG{ // required functionstatic int findProductSum(int[] A, int n){ // calculating array sum (a1 + a2 ... + an) int array_sum = 0; for (int i = 0; i < n; i++) array_sum = array_sum + A[i]; // calculating square of array sum // (a1 + a2 + ... + an)^2 int array_sum_square = array_sum * array_sum; // calculating a1^2 + a2^2 + ... + an^2 int individual_square_sum = 0; for (int i = 0; i < n; i++) individual_square_sum += A[i] * A[i]; // required sum is (array_sum_square - // individual_square_sum) / 2 return (array_sum_square - individual_square_sum) / 2;} // Driver codepublic static void Main(){ int[] A = {1, 3, 4}; int n = A.Length; Console.WriteLine(\"sum of product of all \" + \"pairs of array elements : \" + findProductSum(A, n));}} // This code is contributed by Akanksha Rai",
"e": 7752,
"s": 6769,
"text": null
},
{
"code": "<?php// Efficient PHP program to find sum// pair products in an array. // required functionfunction findProductSum(&$A, $n){ // calculating array sum (a1 + a2 ... + an) $array_sum = 0; for ($i = 0; $i < $n; $i++) $array_sum = $array_sum + $A[$i]; // calculating square of array sum // (a1 + a2 + ... + an)^2 $array_sum_square = $array_sum * $array_sum; // calculating a1^2 + a2^2 + ... + an^2 $individual_square_sum = 0; for ($i = 0; $i < $n; $i++) $individual_square_sum += $A[$i] * $A[$i]; // required sum is (array_sum_square - // individual_square_sum) / 2 return ($array_sum_square - $individual_square_sum) / 2;} // Driver code$A = array(1, 3, 4);$n = sizeof($A);echo(\"sum of product of all pairs \" . \"of array elements : \");echo (findProductSum($A, $n)); // This code is contributed// by Shivi_Aggarwal?>",
"e": 8640,
"s": 7752,
"text": null
},
{
"code": "<script> // Efficient Javascript program to find sum pair // products in an array. // required function function findProductSum(A, n) { // calculating array sum (a1 + a2 ... + an) let array_sum = 0; for (let i = 0; i < n; i++) array_sum = array_sum + A[i]; // calculating square of array sum // (a1 + a2 + ... + an)^2 let array_sum_square = array_sum * array_sum; // calculating a1^2 + a2^2 + ... + an^2 let individual_square_sum = 0; for (let i = 0; i < n; i++) individual_square_sum += A[i] * A[i]; // required sum is (array_sum_square - // individual_square_sum) / 2 return (array_sum_square - individual_square_sum) / 2; } let A = [1, 3, 4]; let n = A.length; document.write(\"sum of product of all \" + \"pairs of array elements : \" + findProductSum(A, n)); // This code is contributed by rameshtravel07.</script>",
"e": 9653,
"s": 8640,
"text": null
},
{
"code": null,
"e": 9662,
"s": 9653,
"text": "Output: "
},
{
"code": null,
"e": 9713,
"s": 9662,
"text": "sum of product of all pairs of array elements : 19"
},
{
"code": null,
"e": 10181,
"s": 9713,
"text": "Time Complexity : O(n) Space Complexity : O(1)This article is contributed by Pratik Chhajer. 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": 10187,
"s": 10181,
"text": "jit_t"
},
{
"code": null,
"e": 10193,
"s": 10187,
"text": "ukasp"
},
{
"code": null,
"e": 10205,
"s": 10193,
"text": "29AjayKumar"
},
{
"code": null,
"e": 10220,
"s": 10205,
"text": "sahilshelangia"
},
{
"code": null,
"e": 10233,
"s": 10220,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 10247,
"s": 10233,
"text": "princiraj1992"
},
{
"code": null,
"e": 10262,
"s": 10247,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 10278,
"s": 10262,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 10293,
"s": 10278,
"text": "rameshtravel07"
},
{
"code": null,
"e": 10309,
"s": 10293,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 10328,
"s": 10309,
"text": "surindertarika1234"
},
{
"code": null,
"e": 10335,
"s": 10328,
"text": "Arrays"
},
{
"code": null,
"e": 10342,
"s": 10335,
"text": "Arrays"
}
] |
Finding power of prime number p in n! | 23 Jun, 2022
Given a number ‘n’ and a prime number ‘p’. We need to find out the power of ‘p’ in the prime factorization of n!Examples:
Input : n = 4, p = 2
Output : 3
Power of 2 in the prime factorization
of 2 in 4! = 24 is 3
Input : n = 24, p = 2
Output : 22
Naive approach The naive approach is to find the power of p in each number from 1 to n and add them. Because we know that during multiplication power is added.
C++
Java
Python3
C#
PHP
Javascript
Kotlin
// C++ implementation of finding// power of p in n!#include <bits/stdc++.h> using namespace std; // Returns power of p in n!int PowerOFPINnfactorial(int n, int p){ // initializing answer int ans = 0; // initializing int temp = p; // loop until temp<=n while (temp <= n) { // add number of numbers divisible by temp ans += n / temp; // each time multiply temp by p temp = temp * p; } return ans;} // Driver functionint main(){ cout << PowerOFPINnfactorial(4, 2) << endl; return 0;}
// Java implementation of naive approach public class GFG{ // Method to calculate the power of prime number p in n! static int PowerOFPINnfactorial(int n, int p) { // initializing answer int ans = 0; // finding power of p from 1 to n for (int i = 1; i <= n; i++) { // variable to note the power of p in i int count = 0, temp = i; // loop until temp is equal to i while (temp % p == 0) { count++; temp = temp / p; } // adding count to i ans += count; } return ans; } // Driver Method public static void main(String[] args) { System.out.println(PowerOFPINnfactorial(4, 2)); }}
# Python3 implementation of# finding power of p in n! # Returns power of p in n!def PowerOFPINnfactorial(n, p): # initializing answer ans = 0; # initializing temp = p; # loop until temp<=n while (temp <= n): # add number of numbers # divisible by n ans += n / temp; # each time multiply # temp by p temp = temp * p; return ans; # Driver Codeprint(PowerOFPINnfactorial(4, 2)); # This code is contributed by# mits
// C# implementation of naive approachusing System; public class GFG{ // Method to calculate power // of prime number p in n! static int PowerOFPINnfactorial(int n, int p) { // initializing answer int ans = 0; // finding power of p from 1 to n for (int i = 1; i <= n; i++) { // variable to note the power of p in i int count = 0, temp = i; // loop until temp is equal to i while (temp % p == 0) { count++; temp = temp / p; } // adding count to i ans += count; } return ans; } // Driver Code public static void Main(String []args) { Console.WriteLine(PowerOFPINnfactorial(4, 2)); }} // This code is contributed by vt_m.
<?php// PHP implementation of// finding power of p in n! // Returns power of p in n!function PowerOFPINnfactorial($n, $p){ // initializing answer $ans = 0; // initializing $temp = $p; // loop until temp<=n while ($temp <= $n) { // add number of numbers // divisible by n $ans += $n / $temp; // each time multiply // temp by p $temp = $temp * $p; } return $ans;} // Driver Codeecho PowerOFPINnfactorial(4, 2) . "\n"; // This code is contributed by// Akanksha Rai(Abby_akku)?>
<script> // Javascript implementation of// finding power of p in n! // Returns power of p in n!function PowerOFPINnfactorial(n, p){ // initializing answer let ans = 0; // initializing let temp = p; // loop until temp<=n while (temp <= n) { // add number of numbers // divisible by n ans += n / temp; // each time multiply // temp by p temp = temp * p; } return ans;} // Driver Codedocument.write(PowerOFPINnfactorial(4, 2)); // This code is contributed by _saurabh_jaiswal </script>
//function to find the power of p in n! in Kotlinfun PowerOFPINnfactorial(n: Int, p: Int){ // initializing answer var ans = 0; // initializing var temp = p; // loop until temp<=n while(temp<=n) { // add number of numbers divisible by temp ans+=n/temp; // each time multiply temp by p temp*=p; } println(ans)} //Driver Codefun main(args: Array<String>){ val n = 4 val p = 2 PowerOFPINnfactorial(n,p)}
Output:
3
Time Complexity: O(logpn) Auxiliary Space: O(1)
Efficient Approach Before discussing efficient approach lets discuss a question given a two numbers n, m how many numbers are there from 1 to n that are divisible by m the answer is floor(n/m). Now coming back to our original question to find the power of p in n! what we do is count the number of numbers from 1 to n that are divisible by p then by then by till > n and add them. This will be our required answer.
Powerofp(n!) = floor(n/p) + floor(n/p^2) + floor(n/p^3)........
Below is the implementation of the above steps.
C++
Java
Python3
C#
PHP
Javascript
Kotlin
// C++ implementation of finding power of p in n!#include <bits/stdc++.h> using namespace std; // Returns power of p in n!int PowerOFPINnfactorial(int n, int p){ // initializing answer int ans = 0; // initializing int temp = p; // loop until temp<=n while (temp <= n) { // add number of numbers divisible by temp ans += n / temp; // each time multiply temp by p temp = temp * p; } return ans;} // Driver functionint main(){ cout << PowerOFPINnfactorial(4, 2) << endl; return 0;}
// Java implementation of finding power of p in n! public class GFG{ // Method to calculate the power of prime number p in n! static int PowerOFPINnfactorial(int n, int p) { // initializing answer int ans = 0; // initializing int temp = p; // loop until temp<=n while (temp <= n) { // add number of numbers divisible by n ans += n / temp; // each time multiply temp by p temp = temp * p; } return ans; } // Driver Method public static void main(String[] args) { System.out.println(PowerOFPINnfactorial(4, 2)); }}
# Python3 implementation of# finding power of p in n! # Returns power of p in n!def PowerOFPINnfactorial(n, p): # initializing answer ans = 0 # initializing temp = p # loop until temp<=n while (temp <= n) : # add number of numbers # divisible by n ans += n / temp # each time multiply # temp by p temp = temp * p return int(ans) # Driver Codeprint(PowerOFPINnfactorial(4, 2)) # This code is contributed# by Smitha
// C# implementation of finding// power of p in n!using System; public class GFG{ // Method to calculate power // of prime number p in n! static int PowerOFPINnfactorial(int n, int p) { // initializing answer int ans = 0; // initializing int temp = p; // loop until temp <= n while (temp <= n) { // add number of numbers divisible by n ans += n / temp; // each time multiply temp by p temp = temp * p; } return ans; } // Driver Code public static void Main(String []args) { Console.WriteLine(PowerOFPINnfactorial(4, 2)); }} // This code is contributed by vt_m.
<?php// PHP implementation of// finding power of p in n! // Returns power of p in n!function PowerOFPINnfactorial($n, $p){ // initializing answer $ans = 0; // initializing $temp = $p; // loop until temp<=n while ($temp <= $n) { // add number of numbers divisible by n $ans += $n / $temp; // each time multiply temp by p $temp = $temp * $p; } return $ans;} // Driver functionecho PowerOFPINnfactorial(4, 2) . "\n"; // This code is contributed// by Akanksha Rai(Abby_akku)?>
<script> // Javascript implementation of// finding power of p in n! // Returns power of p in n!function PowerOFPINnfactorial(n, p){ // initializing answer let ans = 0; // initializing let temp = p; // loop until temp<=n while (temp <= n) { // add number of numbers divisible by n ans += n / temp; // each time multiply temp by p temp = temp * p; } return ans;} // Driver functiondocument.write(PowerOFPINnfactorial(4, 2)); // This code is contributed by _saurabh_jaiswal </script>
//function to find the power of p in n! in Kotlinfun PowerOFPINnfactorial(n: Int, p: Int){ // initializing answer var ans = 0; // initializing var temp = p; // loop until temp<=n while(temp<=n) { // add number of numbers divisible by temp ans+=n/temp; // each time multiply temp by p temp*=p; } println(ans)} //Driver Codefun main(args: Array<String>){ val n = 4 val p = 2 PowerOFPINnfactorial(n,p)}
Output:
3
Time Complexity :O((n))Auxiliary Space: O(1)This article is contributed by Aarti_Rathi and Ayush Jha. 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.
vt_m
Smitha Dinesh Semwal
Akanksha_Rai
Mithun Kumar
nidhi_biet
_saurabh_jaiswal
zargon
codewithshinchan
factorial
Prime Number
Mathematical
Mathematical
Prime Number
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
C++ Data Types
Write a program to print all permutations of a given string
Merge two sorted arrays
Coin Change | DP-7
Operators in C / C++
Find minimum number of coins that make a given value
Modulo 10^9+7 (1000000007)
Minimum number of jumps to reach end | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 178,
"s": 54,
"text": "Given a number ‘n’ and a prime number ‘p’. We need to find out the power of ‘p’ in the prime factorization of n!Examples: "
},
{
"code": null,
"e": 324,
"s": 178,
"text": "Input : n = 4, p = 2\nOutput : 3\n Power of 2 in the prime factorization\n of 2 in 4! = 24 is 3\n\nInput : n = 24, p = 2\nOutput : 22"
},
{
"code": null,
"e": 487,
"s": 326,
"text": "Naive approach The naive approach is to find the power of p in each number from 1 to n and add them. Because we know that during multiplication power is added. "
},
{
"code": null,
"e": 491,
"s": 487,
"text": "C++"
},
{
"code": null,
"e": 496,
"s": 491,
"text": "Java"
},
{
"code": null,
"e": 504,
"s": 496,
"text": "Python3"
},
{
"code": null,
"e": 507,
"s": 504,
"text": "C#"
},
{
"code": null,
"e": 511,
"s": 507,
"text": "PHP"
},
{
"code": null,
"e": 522,
"s": 511,
"text": "Javascript"
},
{
"code": null,
"e": 529,
"s": 522,
"text": "Kotlin"
},
{
"code": "// C++ implementation of finding// power of p in n!#include <bits/stdc++.h> using namespace std; // Returns power of p in n!int PowerOFPINnfactorial(int n, int p){ // initializing answer int ans = 0; // initializing int temp = p; // loop until temp<=n while (temp <= n) { // add number of numbers divisible by temp ans += n / temp; // each time multiply temp by p temp = temp * p; } return ans;} // Driver functionint main(){ cout << PowerOFPINnfactorial(4, 2) << endl; return 0;}",
"e": 1072,
"s": 529,
"text": null
},
{
"code": "// Java implementation of naive approach public class GFG{ // Method to calculate the power of prime number p in n! static int PowerOFPINnfactorial(int n, int p) { // initializing answer int ans = 0; // finding power of p from 1 to n for (int i = 1; i <= n; i++) { // variable to note the power of p in i int count = 0, temp = i; // loop until temp is equal to i while (temp % p == 0) { count++; temp = temp / p; } // adding count to i ans += count; } return ans; } // Driver Method public static void main(String[] args) { System.out.println(PowerOFPINnfactorial(4, 2)); }}",
"e": 1856,
"s": 1072,
"text": null
},
{
"code": "# Python3 implementation of# finding power of p in n! # Returns power of p in n!def PowerOFPINnfactorial(n, p): # initializing answer ans = 0; # initializing temp = p; # loop until temp<=n while (temp <= n): # add number of numbers # divisible by n ans += n / temp; # each time multiply # temp by p temp = temp * p; return ans; # Driver Codeprint(PowerOFPINnfactorial(4, 2)); # This code is contributed by# mits",
"e": 2345,
"s": 1856,
"text": null
},
{
"code": "// C# implementation of naive approachusing System; public class GFG{ // Method to calculate power // of prime number p in n! static int PowerOFPINnfactorial(int n, int p) { // initializing answer int ans = 0; // finding power of p from 1 to n for (int i = 1; i <= n; i++) { // variable to note the power of p in i int count = 0, temp = i; // loop until temp is equal to i while (temp % p == 0) { count++; temp = temp / p; } // adding count to i ans += count; } return ans; } // Driver Code public static void Main(String []args) { Console.WriteLine(PowerOFPINnfactorial(4, 2)); }} // This code is contributed by vt_m.",
"e": 3172,
"s": 2345,
"text": null
},
{
"code": "<?php// PHP implementation of// finding power of p in n! // Returns power of p in n!function PowerOFPINnfactorial($n, $p){ // initializing answer $ans = 0; // initializing $temp = $p; // loop until temp<=n while ($temp <= $n) { // add number of numbers // divisible by n $ans += $n / $temp; // each time multiply // temp by p $temp = $temp * $p; } return $ans;} // Driver Codeecho PowerOFPINnfactorial(4, 2) . \"\\n\"; // This code is contributed by// Akanksha Rai(Abby_akku)?>",
"e": 3727,
"s": 3172,
"text": null
},
{
"code": "<script> // Javascript implementation of// finding power of p in n! // Returns power of p in n!function PowerOFPINnfactorial(n, p){ // initializing answer let ans = 0; // initializing let temp = p; // loop until temp<=n while (temp <= n) { // add number of numbers // divisible by n ans += n / temp; // each time multiply // temp by p temp = temp * p; } return ans;} // Driver Codedocument.write(PowerOFPINnfactorial(4, 2)); // This code is contributed by _saurabh_jaiswal </script>",
"e": 4290,
"s": 3727,
"text": null
},
{
"code": "//function to find the power of p in n! in Kotlinfun PowerOFPINnfactorial(n: Int, p: Int){ // initializing answer var ans = 0; // initializing var temp = p; // loop until temp<=n while(temp<=n) { // add number of numbers divisible by temp ans+=n/temp; // each time multiply temp by p temp*=p; } println(ans)} //Driver Codefun main(args: Array<String>){ val n = 4 val p = 2 PowerOFPINnfactorial(n,p)}",
"e": 4766,
"s": 4290,
"text": null
},
{
"code": null,
"e": 4775,
"s": 4766,
"text": "Output: "
},
{
"code": null,
"e": 4777,
"s": 4775,
"text": "3"
},
{
"code": null,
"e": 4825,
"s": 4777,
"text": "Time Complexity: O(logpn) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5241,
"s": 4825,
"text": "Efficient Approach Before discussing efficient approach lets discuss a question given a two numbers n, m how many numbers are there from 1 to n that are divisible by m the answer is floor(n/m). Now coming back to our original question to find the power of p in n! what we do is count the number of numbers from 1 to n that are divisible by p then by then by till > n and add them. This will be our required answer. "
},
{
"code": null,
"e": 5309,
"s": 5241,
"text": " Powerofp(n!) = floor(n/p) + floor(n/p^2) + floor(n/p^3)........ "
},
{
"code": null,
"e": 5358,
"s": 5309,
"text": "Below is the implementation of the above steps. "
},
{
"code": null,
"e": 5362,
"s": 5358,
"text": "C++"
},
{
"code": null,
"e": 5367,
"s": 5362,
"text": "Java"
},
{
"code": null,
"e": 5375,
"s": 5367,
"text": "Python3"
},
{
"code": null,
"e": 5378,
"s": 5375,
"text": "C#"
},
{
"code": null,
"e": 5382,
"s": 5378,
"text": "PHP"
},
{
"code": null,
"e": 5393,
"s": 5382,
"text": "Javascript"
},
{
"code": null,
"e": 5400,
"s": 5393,
"text": "Kotlin"
},
{
"code": "// C++ implementation of finding power of p in n!#include <bits/stdc++.h> using namespace std; // Returns power of p in n!int PowerOFPINnfactorial(int n, int p){ // initializing answer int ans = 0; // initializing int temp = p; // loop until temp<=n while (temp <= n) { // add number of numbers divisible by temp ans += n / temp; // each time multiply temp by p temp = temp * p; } return ans;} // Driver functionint main(){ cout << PowerOFPINnfactorial(4, 2) << endl; return 0;}",
"e": 5941,
"s": 5400,
"text": null
},
{
"code": "// Java implementation of finding power of p in n! public class GFG{ // Method to calculate the power of prime number p in n! static int PowerOFPINnfactorial(int n, int p) { // initializing answer int ans = 0; // initializing int temp = p; // loop until temp<=n while (temp <= n) { // add number of numbers divisible by n ans += n / temp; // each time multiply temp by p temp = temp * p; } return ans; } // Driver Method public static void main(String[] args) { System.out.println(PowerOFPINnfactorial(4, 2)); }}",
"e": 6614,
"s": 5941,
"text": null
},
{
"code": "# Python3 implementation of# finding power of p in n! # Returns power of p in n!def PowerOFPINnfactorial(n, p): # initializing answer ans = 0 # initializing temp = p # loop until temp<=n while (temp <= n) : # add number of numbers # divisible by n ans += n / temp # each time multiply # temp by p temp = temp * p return int(ans) # Driver Codeprint(PowerOFPINnfactorial(4, 2)) # This code is contributed# by Smitha",
"e": 7101,
"s": 6614,
"text": null
},
{
"code": "// C# implementation of finding// power of p in n!using System; public class GFG{ // Method to calculate power // of prime number p in n! static int PowerOFPINnfactorial(int n, int p) { // initializing answer int ans = 0; // initializing int temp = p; // loop until temp <= n while (temp <= n) { // add number of numbers divisible by n ans += n / temp; // each time multiply temp by p temp = temp * p; } return ans; } // Driver Code public static void Main(String []args) { Console.WriteLine(PowerOFPINnfactorial(4, 2)); }} // This code is contributed by vt_m.",
"e": 7822,
"s": 7101,
"text": null
},
{
"code": "<?php// PHP implementation of// finding power of p in n! // Returns power of p in n!function PowerOFPINnfactorial($n, $p){ // initializing answer $ans = 0; // initializing $temp = $p; // loop until temp<=n while ($temp <= $n) { // add number of numbers divisible by n $ans += $n / $temp; // each time multiply temp by p $temp = $temp * $p; } return $ans;} // Driver functionecho PowerOFPINnfactorial(4, 2) . \"\\n\"; // This code is contributed// by Akanksha Rai(Abby_akku)?>",
"e": 8354,
"s": 7822,
"text": null
},
{
"code": "<script> // Javascript implementation of// finding power of p in n! // Returns power of p in n!function PowerOFPINnfactorial(n, p){ // initializing answer let ans = 0; // initializing let temp = p; // loop until temp<=n while (temp <= n) { // add number of numbers divisible by n ans += n / temp; // each time multiply temp by p temp = temp * p; } return ans;} // Driver functiondocument.write(PowerOFPINnfactorial(4, 2)); // This code is contributed by _saurabh_jaiswal </script>",
"e": 8894,
"s": 8354,
"text": null
},
{
"code": "//function to find the power of p in n! in Kotlinfun PowerOFPINnfactorial(n: Int, p: Int){ // initializing answer var ans = 0; // initializing var temp = p; // loop until temp<=n while(temp<=n) { // add number of numbers divisible by temp ans+=n/temp; // each time multiply temp by p temp*=p; } println(ans)} //Driver Codefun main(args: Array<String>){ val n = 4 val p = 2 PowerOFPINnfactorial(n,p)}",
"e": 9370,
"s": 8894,
"text": null
},
{
"code": null,
"e": 9379,
"s": 9370,
"text": "Output: "
},
{
"code": null,
"e": 9381,
"s": 9379,
"text": "3"
},
{
"code": null,
"e": 9859,
"s": 9381,
"text": "Time Complexity :O((n))Auxiliary Space: O(1)This article is contributed by Aarti_Rathi and Ayush Jha. 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": 9864,
"s": 9859,
"text": "vt_m"
},
{
"code": null,
"e": 9885,
"s": 9864,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 9898,
"s": 9885,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9911,
"s": 9898,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 9922,
"s": 9911,
"text": "nidhi_biet"
},
{
"code": null,
"e": 9939,
"s": 9922,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 9946,
"s": 9939,
"text": "zargon"
},
{
"code": null,
"e": 9963,
"s": 9946,
"text": "codewithshinchan"
},
{
"code": null,
"e": 9973,
"s": 9963,
"text": "factorial"
},
{
"code": null,
"e": 9986,
"s": 9973,
"text": "Prime Number"
},
{
"code": null,
"e": 9999,
"s": 9986,
"text": "Mathematical"
},
{
"code": null,
"e": 10012,
"s": 9999,
"text": "Mathematical"
},
{
"code": null,
"e": 10025,
"s": 10012,
"text": "Prime Number"
},
{
"code": null,
"e": 10035,
"s": 10025,
"text": "factorial"
},
{
"code": null,
"e": 10133,
"s": 10035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10163,
"s": 10133,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 10206,
"s": 10163,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10221,
"s": 10206,
"text": "C++ Data Types"
},
{
"code": null,
"e": 10281,
"s": 10221,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10305,
"s": 10281,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 10324,
"s": 10305,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 10345,
"s": 10324,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 10398,
"s": 10345,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 10425,
"s": 10398,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Difference Between insert(), insertOne(), and insertMany() in Pymongo | 19 Jan, 2022
MongoDB is a NoSql Database that can be used to store data required by different applications. Python can be used to access MongoDB databases. Python requires a driver to access the databases. PyMongo enables interacting with MongoDB database from Python applications. The pymongo package acts as a native Python driver for MongoDB. Pymongo provides commands that can be used in Python applications to perform required action on the MongoDB. MongoDB offers three methods to insert records or documents into the database which are as follows:
insert() : Used to insert a document or documents into a collection. If the collection does not exist, then insert() will create the collection and then insert the specified documents.
Syntax db.collection.insert(<document or array of documents>, { writeConcern: <document>, ordered: <boolean> } )Parameter
<document>: The document or record that is to be stored in the database
writeConcern: Optional.
ordered: Optional. Can be set to true or false.
Example:
Python3
# importing Mongoclient from pymongofrom pymongo import MongoClient myclient = MongoClient("mongodb://localhost:27017/") # database db = myclient["GFG"] # Created or Switched to collection # names: Collegecollection = db["College"] mylist = [ { "_id": 1, "name": "Vishwash", "Roll No": "1001", "Branch":"CSE"}, { "_id": 2, "name": "Vishesh", "Roll No": "1002", "Branch":"IT"}, { "_id": 3, "name": "Shivam", "Roll No": "1003", "Branch":"ME"}, { "_id": 4, "name": "Yash", "Roll No": "1004", "Branch":"ECE"},] # Inserting the entire list in the collectioncollection.insert(mylist)
Output:
insertOne() : Used to insert a single document or record into the database. If the collection does not exist, then insertOne() method creates the collection first and then inserts the specified document.
Syntax db.collection.insertOne(<document>, { writeConcern: <document> } )Parameter
<document> The document or record that is to be stored in the database
writeConcern: Optional.
Return Value: It returns the _id of the document inserted into the database.
Note: The Pymongo command for insertOne() is insert_one() Example:
Python3
# importing Mongoclient from pymongofrom pymongo import MongoClient # Making Connectionmyclient = MongoClient("mongodb://localhost:27017/") # databasedb = myclient["GFG"] # Created or Switched to collection# names: GeeksForGeekscollection = db["Student"] # Creating Dictionary of records to be# insertedrecord = { "_id": 5, "name": "Raju", "Roll No": "1005", "Branch": "CSE"} # Inserting the record1 in the collection# by using collection.insert_one()rec_id1 = collection.insert_one(record)
Output:
insertMany()
Syntax db.collection.insertMany([ <document 1>, <document 2>, ... ], { writeConcern: <document>, ordered: <boolean> } )Parameter
<documents> The document or record that is to be stored in the database
writeConcern: Optional.
ordered: Optional. Can be set to true or false.
Return Value: It returns the _ids of the documents inserted into the database.
Note: The Pymongo command for insertMany() is insert_many() Example:
Python3
# importing Mongoclient from pymongofrom pymongo import MongoClient myclient = MongoClient("mongodb://localhost:27017/") # database db = myclient["GFG"] # Created or Switched to collection # names: GeeksForGeekscollection = db["College"] mylist = [ { "_id": 6, "name": "Deepanshu", "Roll No": "1006", "Branch":"CSE"}, { "_id": 7, "name": "Anshul", "Roll No": "1007", "Branch":"IT"}] # Inserting the entire list in the collectioncollection.insert_many(mylist)
Output:
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }
clintra
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 571,
"s": 28,
"text": "MongoDB is a NoSql Database that can be used to store data required by different applications. Python can be used to access MongoDB databases. Python requires a driver to access the databases. PyMongo enables interacting with MongoDB database from Python applications. The pymongo package acts as a native Python driver for MongoDB. Pymongo provides commands that can be used in Python applications to perform required action on the MongoDB. MongoDB offers three methods to insert records or documents into the database which are as follows: "
},
{
"code": null,
"e": 756,
"s": 571,
"text": "insert() : Used to insert a document or documents into a collection. If the collection does not exist, then insert() will create the collection and then insert the specified documents."
},
{
"code": null,
"e": 879,
"s": 756,
"text": "Syntax db.collection.insert(<document or array of documents>, { writeConcern: <document>, ordered: <boolean> } )Parameter "
},
{
"code": null,
"e": 951,
"s": 879,
"text": "<document>: The document or record that is to be stored in the database"
},
{
"code": null,
"e": 975,
"s": 951,
"text": "writeConcern: Optional."
},
{
"code": null,
"e": 1024,
"s": 975,
"text": "ordered: Optional. Can be set to true or false. "
},
{
"code": null,
"e": 1034,
"s": 1024,
"text": "Example: "
},
{
"code": null,
"e": 1042,
"s": 1034,
"text": "Python3"
},
{
"code": "# importing Mongoclient from pymongofrom pymongo import MongoClient myclient = MongoClient(\"mongodb://localhost:27017/\") # database db = myclient[\"GFG\"] # Created or Switched to collection # names: Collegecollection = db[\"College\"] mylist = [ { \"_id\": 1, \"name\": \"Vishwash\", \"Roll No\": \"1001\", \"Branch\":\"CSE\"}, { \"_id\": 2, \"name\": \"Vishesh\", \"Roll No\": \"1002\", \"Branch\":\"IT\"}, { \"_id\": 3, \"name\": \"Shivam\", \"Roll No\": \"1003\", \"Branch\":\"ME\"}, { \"_id\": 4, \"name\": \"Yash\", \"Roll No\": \"1004\", \"Branch\":\"ECE\"},] # Inserting the entire list in the collectioncollection.insert(mylist)",
"e": 1639,
"s": 1042,
"text": null
},
{
"code": null,
"e": 1647,
"s": 1639,
"text": "Output:"
},
{
"code": null,
"e": 1851,
"s": 1647,
"text": "insertOne() : Used to insert a single document or record into the database. If the collection does not exist, then insertOne() method creates the collection first and then inserts the specified document."
},
{
"code": null,
"e": 1936,
"s": 1851,
"text": "Syntax db.collection.insertOne(<document>, { writeConcern: <document> } )Parameter "
},
{
"code": null,
"e": 2007,
"s": 1936,
"text": "<document> The document or record that is to be stored in the database"
},
{
"code": null,
"e": 2031,
"s": 2007,
"text": "writeConcern: Optional."
},
{
"code": null,
"e": 2110,
"s": 2031,
"text": "Return Value: It returns the _id of the document inserted into the database. "
},
{
"code": null,
"e": 2178,
"s": 2110,
"text": "Note: The Pymongo command for insertOne() is insert_one() Example: "
},
{
"code": null,
"e": 2186,
"s": 2178,
"text": "Python3"
},
{
"code": "# importing Mongoclient from pymongofrom pymongo import MongoClient # Making Connectionmyclient = MongoClient(\"mongodb://localhost:27017/\") # databasedb = myclient[\"GFG\"] # Created or Switched to collection# names: GeeksForGeekscollection = db[\"Student\"] # Creating Dictionary of records to be# insertedrecord = { \"_id\": 5, \"name\": \"Raju\", \"Roll No\": \"1005\", \"Branch\": \"CSE\"} # Inserting the record1 in the collection# by using collection.insert_one()rec_id1 = collection.insert_one(record)",
"e": 2706,
"s": 2186,
"text": null
},
{
"code": null,
"e": 2715,
"s": 2706,
"text": "Output: "
},
{
"code": null,
"e": 2728,
"s": 2715,
"text": "insertMany()"
},
{
"code": null,
"e": 2859,
"s": 2728,
"text": "Syntax db.collection.insertMany([ <document 1>, <document 2>, ... ], { writeConcern: <document>, ordered: <boolean> } )Parameter "
},
{
"code": null,
"e": 2931,
"s": 2859,
"text": "<documents> The document or record that is to be stored in the database"
},
{
"code": null,
"e": 2955,
"s": 2931,
"text": "writeConcern: Optional."
},
{
"code": null,
"e": 3003,
"s": 2955,
"text": "ordered: Optional. Can be set to true or false."
},
{
"code": null,
"e": 3084,
"s": 3003,
"text": "Return Value: It returns the _ids of the documents inserted into the database. "
},
{
"code": null,
"e": 3153,
"s": 3084,
"text": "Note: The Pymongo command for insertMany() is insert_many() Example:"
},
{
"code": null,
"e": 3161,
"s": 3153,
"text": "Python3"
},
{
"code": "# importing Mongoclient from pymongofrom pymongo import MongoClient myclient = MongoClient(\"mongodb://localhost:27017/\") # database db = myclient[\"GFG\"] # Created or Switched to collection # names: GeeksForGeekscollection = db[\"College\"] mylist = [ { \"_id\": 6, \"name\": \"Deepanshu\", \"Roll No\": \"1006\", \"Branch\":\"CSE\"}, { \"_id\": 7, \"name\": \"Anshul\", \"Roll No\": \"1007\", \"Branch\":\"IT\"}] # Inserting the entire list in the collectioncollection.insert_many(mylist)",
"e": 3634,
"s": 3161,
"text": null
},
{
"code": null,
"e": 3642,
"s": 3634,
"text": "Output:"
},
{
"code": null,
"e": 3982,
"s": 3642,
"text": ".math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } "
},
{
"code": null,
"e": 3990,
"s": 3982,
"text": "clintra"
},
{
"code": null,
"e": 4005,
"s": 3990,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 4012,
"s": 4005,
"text": "Python"
}
] |
Insertion Sort Visualization using Matplotlib in Python | 28 Jul, 2020
Prerequisites: Insertion Sort, Using Matplotlib for Animations
Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. For this we will use matplotlib, to plot bar graphs to represent the elements of the array,
Approach:
We will generate an array with random elements.The algorithm will be called on that array and yield statement will be used instead of a return statement for visualization purposes.We will yield the current states of the array after comparing and swapping. Hence the algorithm will return a generator object.Matplotlib animation will be used to visualize the comparing and swapping of the array.The array will be stored in a matplotlib bar container object (‘rects’), where the size of each bar will be equal to the corresponding value of the element in the array.The inbuilt FuncAnimation method of matplotlib animation will pass the container and generator objects to the function used to create animation. Each frame of the animation corresponds to a single iteration of the generator.The animation function is repeatedly called will set the height of the rectangle equal to the value of the elements.
We will generate an array with random elements.
The algorithm will be called on that array and yield statement will be used instead of a return statement for visualization purposes.
We will yield the current states of the array after comparing and swapping. Hence the algorithm will return a generator object.
Matplotlib animation will be used to visualize the comparing and swapping of the array.
The array will be stored in a matplotlib bar container object (‘rects’), where the size of each bar will be equal to the corresponding value of the element in the array.
The inbuilt FuncAnimation method of matplotlib animation will pass the container and generator objects to the function used to create animation. Each frame of the animation corresponds to a single iteration of the generator.
The animation function is repeatedly called will set the height of the rectangle equal to the value of the elements.
Python3
# import all the modulesimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationimport matplotlib as mpimport numpy as npimport random # set the style of the graphplt.style.use('fivethirtyeight') # input the size of the array (list here)# and shuffle the elements to create# a random listn = int(input("enter array size\n"))a = [i for i in range(1, n+1)]random.shuffle(a) # insertion sort def insertionsort(a): for j in range(1, len(a)): key = a[j] i = j-1 while(i >= 0 and a[i] > key): a[i+1] = a[i] i -= 1 # yield the current position # of elements in a yield a a[i+1] = key yield a # generator object returned by the functiongenerator = insertionsort(a) # to set the colors of the bars.data_normalizer = mp.colors.Normalize()color_map = mp.colors.LinearSegmentedColormap( "my_map", { "red": [(0, 1.0, 1.0), (1.0, .5, .5)], "green": [(0, 0.5, 0.5), (1.0, 0, 0)], "blue": [(0, 0.50, 0.5), (1.0, 0, 0)] }) fig, ax = plt.subplots() # the bar containerrects = ax.bar(range(len(a)), a, align="edge", color=color_map(data_normalizer(range(n)))) # setting the view limit of x and y axesax.set_xlim(0, len(a))ax.set_ylim(0, int(1.1*len(a))) # the text to be shown on the upper left# indicating the number of iterations# transform indicates the position with# relevance to the axes coordinates.text = ax.text(0.01, 0.95, "", transform=ax.transAxes)iteration = [0] # function to be called repeatedly to animate def animate(A, rects, iteration): # setting the size of each bar equal # to the value of the elements for rect, val in zip(rects, A): rect.set_height(val) iteration[0] += 1 text.set_text("iterations : {}".format(iteration[0])) anim = FuncAnimation(fig, func=animate, fargs=(rects, iteration), frames=generator, interval=50, repeat=False) plt.show()
Output:
Insertion Sort
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": "\n28 Jul, 2020"
},
{
"code": null,
"e": 91,
"s": 28,
"text": "Prerequisites: Insertion Sort, Using Matplotlib for Animations"
},
{
"code": null,
"e": 344,
"s": 91,
"text": "Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. For this we will use matplotlib, to plot bar graphs to represent the elements of the array, "
},
{
"code": null,
"e": 354,
"s": 344,
"text": "Approach:"
},
{
"code": null,
"e": 1258,
"s": 354,
"text": "We will generate an array with random elements.The algorithm will be called on that array and yield statement will be used instead of a return statement for visualization purposes.We will yield the current states of the array after comparing and swapping. Hence the algorithm will return a generator object.Matplotlib animation will be used to visualize the comparing and swapping of the array.The array will be stored in a matplotlib bar container object (‘rects’), where the size of each bar will be equal to the corresponding value of the element in the array.The inbuilt FuncAnimation method of matplotlib animation will pass the container and generator objects to the function used to create animation. Each frame of the animation corresponds to a single iteration of the generator.The animation function is repeatedly called will set the height of the rectangle equal to the value of the elements."
},
{
"code": null,
"e": 1306,
"s": 1258,
"text": "We will generate an array with random elements."
},
{
"code": null,
"e": 1440,
"s": 1306,
"text": "The algorithm will be called on that array and yield statement will be used instead of a return statement for visualization purposes."
},
{
"code": null,
"e": 1568,
"s": 1440,
"text": "We will yield the current states of the array after comparing and swapping. Hence the algorithm will return a generator object."
},
{
"code": null,
"e": 1656,
"s": 1568,
"text": "Matplotlib animation will be used to visualize the comparing and swapping of the array."
},
{
"code": null,
"e": 1826,
"s": 1656,
"text": "The array will be stored in a matplotlib bar container object (‘rects’), where the size of each bar will be equal to the corresponding value of the element in the array."
},
{
"code": null,
"e": 2051,
"s": 1826,
"text": "The inbuilt FuncAnimation method of matplotlib animation will pass the container and generator objects to the function used to create animation. Each frame of the animation corresponds to a single iteration of the generator."
},
{
"code": null,
"e": 2168,
"s": 2051,
"text": "The animation function is repeatedly called will set the height of the rectangle equal to the value of the elements."
},
{
"code": null,
"e": 2176,
"s": 2168,
"text": "Python3"
},
{
"code": "# import all the modulesimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimationimport matplotlib as mpimport numpy as npimport random # set the style of the graphplt.style.use('fivethirtyeight') # input the size of the array (list here)# and shuffle the elements to create# a random listn = int(input(\"enter array size\\n\"))a = [i for i in range(1, n+1)]random.shuffle(a) # insertion sort def insertionsort(a): for j in range(1, len(a)): key = a[j] i = j-1 while(i >= 0 and a[i] > key): a[i+1] = a[i] i -= 1 # yield the current position # of elements in a yield a a[i+1] = key yield a # generator object returned by the functiongenerator = insertionsort(a) # to set the colors of the bars.data_normalizer = mp.colors.Normalize()color_map = mp.colors.LinearSegmentedColormap( \"my_map\", { \"red\": [(0, 1.0, 1.0), (1.0, .5, .5)], \"green\": [(0, 0.5, 0.5), (1.0, 0, 0)], \"blue\": [(0, 0.50, 0.5), (1.0, 0, 0)] }) fig, ax = plt.subplots() # the bar containerrects = ax.bar(range(len(a)), a, align=\"edge\", color=color_map(data_normalizer(range(n)))) # setting the view limit of x and y axesax.set_xlim(0, len(a))ax.set_ylim(0, int(1.1*len(a))) # the text to be shown on the upper left# indicating the number of iterations# transform indicates the position with# relevance to the axes coordinates.text = ax.text(0.01, 0.95, \"\", transform=ax.transAxes)iteration = [0] # function to be called repeatedly to animate def animate(A, rects, iteration): # setting the size of each bar equal # to the value of the elements for rect, val in zip(rects, A): rect.set_height(val) iteration[0] += 1 text.set_text(\"iterations : {}\".format(iteration[0])) anim = FuncAnimation(fig, func=animate, fargs=(rects, iteration), frames=generator, interval=50, repeat=False) plt.show()",
"e": 4228,
"s": 2176,
"text": null
},
{
"code": null,
"e": 4236,
"s": 4228,
"text": "Output:"
},
{
"code": null,
"e": 4251,
"s": 4236,
"text": "Insertion Sort"
},
{
"code": null,
"e": 4269,
"s": 4251,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 4276,
"s": 4269,
"text": "Python"
}
] |
JCL - Conditional Processing | The Job Entry System uses two approaches to perform conditional processing in a JCL. When a job completes, a return code is set based on the status of execution. The return code can be a number between 0 (successful execution) to 4095 (non-zero shows error condition). The most common conventional values are:
0 = Normal - all OK
0 = Normal - all OK
4 = Warning - minor errors or problems.
4 = Warning - minor errors or problems.
8 = Error - significant errors or problems.
8 = Error - significant errors or problems.
12 = Severe error - major errors or problems, the results should not be trusted.
12 = Severe error - major errors or problems, the results should not be trusted.
16 = Terminal error - very serious problems, do not use the results.
16 = Terminal error - very serious problems, do not use the results.
A job step execution can be controlled based on the return code of the previous step(s) using the COND parameter and IF-THEN-ELSE construct, which has been explained in this tutorial.
A COND parameter can be coded in the JOB or EXEC statement of JCL. It is a test on the return code of the preceding job steps. If the test is evaluated to be true, the current job step execution is bypassed. Bypassing is just omission of the job step and not an abnormal termination. There can be at most eight conditions combined in a single test.
Following is the basic syntax of a JCL COND Parameter:
COND=(rc,logical-operator)
or
COND=(rc,logical-operator,stepname)
or
COND=EVEN
or
COND=ONLY
Here is the description of parameters used:
rc : This is the return code
rc : This is the return code
logical-operator : This can be GT (Greater Than), GE (Greater than or Equal to), EQ (Equal to), LT (Lesser Than), LE (Lesser than or Equal to) or NE (Not Equal to).
logical-operator : This can be GT (Greater Than), GE (Greater than or Equal to), EQ (Equal to), LT (Lesser Than), LE (Lesser than or Equal to) or NE (Not Equal to).
stepname : This is the job step whose return code is used in the test.
stepname : This is the job step whose return code is used in the test.
Last two conditions (a) COND=EVEN and (b) COND=ONLY, have been explained below in this tutorial.
The COND can be coded either inside JOB statement or EXEC statement, and in both the cases, it behaves differently as explained below:
When COND is coded in JOB statement, the condition is tested for every job step. When the condition is true at any particular job step, it is bypassed along with the job steps following it. Following is an example:
//CNDSAMP JOB CLASS=6,NOTIFY=&SYSUID,COND=(5,LE)
//*
//STEP10 EXEC PGM=FIRSTP
//* STEP10 executes without any test being performed.
//STEP20 EXEC PGM=SECONDP
//* STEP20 is bypassed, if RC of STEP10 is 5 or above.
//* Say STEP10 ends with RC4 and hence test is false.
//* So STEP20 executes and lets say it ends with RC16.
//STEP30 EXEC PGM=SORT
//* STEP30 is bypassed since 5 <= 16.
When COND is coded in EXEC statement of a job step and found to be true, only that job step is bypassed, and execution is continued from next job step.
//CNDSAMP JOB CLASS=6,NOTIFY=&SYSUID
//*
//STP01 EXEC PGM=SORT
//* Assuming STP01 ends with RC0.
//STP02 EXEC PGM=MYCOBB,COND=(0,EQ,STP01)
//* In STP02, condition evaluates to TRUE and step bypassed.
//STP03 EXEC PGM=IEBGENER,COND=((10,LT,STP01),(10,GT,STP02))
//* In STP03, first condition fails and hence STP03 executes.
//* Since STP02 is bypassed, the condition (10,GT,STP02) in
//* STP03 is not tested.
When COND=EVEN is coded, the current job step is executed, even if any of the previous steps abnormally terminate. If any other RC condition is coded along with COND=EVEN, then the job step executes if none of the RC condition is true.
//CNDSAMP JOB CLASS=6,NOTIFY=&SYSUID
//*
//STP01 EXEC PGM=SORT
//* Assuming STP01 ends with RC0.
//STP02 EXEC PGM=MYCOBB,COND=(0,EQ,STP01)
//* In STP02, condition evaluates to TRUE and step bypassed.
//STP03 EXEC PGM=IEBGENER,COND=((10,LT,STP01),EVEN)
//* In STP03, condition (10,LT,STP01) evaluates to true,
//* hence the step is bypassed.
When COND=ONLY is coded, the current job step is executed, only when any of the previous steps abnormally terminate. If any other RC condition is coded along with COND=ONLY, then the job step executes if none of the RC condition is true and any of the previous job steps fail abnormally.
//CNDSAMP JOB CLASS=6,NOTIFY=&SYSUID
//*
//STP01 EXEC PGM=SORT
//* Assuming STP01 ends with RC0.
//STP02 EXEC PGM=MYCOBB,COND=(4,EQ,STP01)
//* In STP02, condition evaluates to FALSE, step is executed
//* and assume the step abends.
//STP03 EXEC PGM=IEBGENER,COND=((0,EQ,STP01),ONLY)
//* In STP03, though the STP02 abends, the condition
//* (0,EQ,STP01) is met. Hence STP03 is bypassed.
Another approach to control the job processing is by using IF-THEN-ELSE constructs. This gives more flexibility and user-friendly way of conditional processing.
Following is the basic syntax of a JCL IF-THEN-ELSE Construct:
//name IF condition THEN
list of statements //* action to be taken when condition is true
//name ELSE
list of statements //* action to be taken when condition is false
//name ENDIF
Following is the description of the used terms in the above IF-THEN-ELSE Construct:
name : This is optional and a name can have 1 to 8 alphanumeric characters starting with alphabet, #,$ or @.
name : This is optional and a name can have 1 to 8 alphanumeric characters starting with alphabet, #,$ or @.
Condition : A condition will have a format: KEYWORD OPERATOR VALUE, where KEYWORDS can be RC (Return Code), ABENDCC (System or user completion code), ABEND, RUN (step started execution). An OPERATOR can be logical operator (AND (&), OR (|)) or relational operator (<, <=, >, >=, <>).
Condition : A condition will have a format: KEYWORD OPERATOR VALUE, where KEYWORDS can be RC (Return Code), ABENDCC (System or user completion code), ABEND, RUN (step started execution). An OPERATOR can be logical operator (AND (&), OR (|)) or relational operator (<, <=, >, >=, <>).
Following is a simple example showing the usage of IF-THEN-ELSE:
//CNDSAMP JOB CLASS=6,NOTIFY=&SYSUID
//*
//PRC1 PROC
//PST1 EXEC PGM=SORT
//PST2 EXEC PGM=IEBGENER
// PEND
//STP01 EXEC PGM=SORT
//IF1 IF STP01.RC = 0 THEN
//STP02 EXEC PGM=MYCOBB1,PARM=123
// ENDIF
//IF2 IF STP01.RUN THEN
//STP03a EXEC PGM=IEBGENER
//STP03b EXEC PGM=SORT
// ENDIF
//IF3 IF STP03b.!ABEND THEN
//STP04 EXEC PGM=MYCOBB1,PARM=456
// ELSE
// ENDIF
//IF4 IF (STP01.RC = 0 & STP02.RC <= 4) THEN
//STP05 EXEC PROC=PRC1
// ENDIF
//IF5 IF STP05.PRC1.PST1.ABEND THEN
//STP06 EXEC PGM=MYABD
// ELSE
//STP07 EXEC PGM=SORT
// ENDIF
Let's try to look into the above program to understand it in little more detail:
The return code of STP01 is tested in IF1. If it is 0, then STP02 is executed. Else, the processing goes to the next IF statement (IF2).
The return code of STP01 is tested in IF1. If it is 0, then STP02 is executed. Else, the processing goes to the next IF statement (IF2).
In IF2, If STP01 has started execution, then STP03a and STP03b are executed.
In IF2, If STP01 has started execution, then STP03a and STP03b are executed.
In IF3, If STP03b does not ABEND, then STP04 is executed. In ELSE, there are no statements. It is called a NULL ELSE statement.
In IF3, If STP03b does not ABEND, then STP04 is executed. In ELSE, there are no statements. It is called a NULL ELSE statement.
In IF4, if STP01.RC = 0 and STP02.RC <=4 are TRUE, then STP05 is executed.
In IF4, if STP01.RC = 0 and STP02.RC <=4 are TRUE, then STP05 is executed.
In IF5, if the proc-step PST1 in PROC PRC1 in jobstep STP05 ABEND, then STP06 is executed. Else STP07 is executed.
In IF5, if the proc-step PST1 in PROC PRC1 in jobstep STP05 ABEND, then STP06 is executed. Else STP07 is executed.
If IF4 evaluates to false, then STP05 is not executed. In that case, IF5 are not tested and the steps STP06, STP07 are not executed.
If IF4 evaluates to false, then STP05 is not executed. In that case, IF5 are not tested and the steps STP06, STP07 are not executed.
The IF-THEN-ELSE will not be executed in the case of abnormal termination of the job such as user cancelling the job, job time expiry or a dataset is backward referenced to a step that is bypassed.
You can set checkpoint dataset inside your JCL program using SYSCKEOV, which is a DD statement.
A CHKPT is the parameter coded for multi-volume QSAM datasets in a DD statement. When a CHKPT is coded as CHKPT=EOV, a checkpoint is written to the dataset specified in the SYSCKEOV statement at the end of each volume of the input/output multi-volume dataset.
//CHKSAMP JOB CLASS=6,NOTIFY=&SYSUID
//*
//STP01 EXEC PGM=MYCOBB
//SYSCKEOV DD DSNAME=SAMPLE.CHK,DISP=MOD
//IN1 DD DSN=SAMPLE.IN,DISP=SHR
//OUT1 DD DSN=SAMPLE.OUT,DISP=(,CATLG,CATLG)
// CHKPT=EOV,LRECL=80,RECFM=FB
In the above example, a checkpoint is written in dataset SAMPLE.CHK at the end of each volume of the output dataset SAMPLE.OUT.
You can restart processing ether using automated way using the RD parameter or manual using the RESTART parameter.
RD parameter is coded in the JOB or EXEC statement and it helps in automated JOB/STEP restart and can hold one of the four values: R, RNC, NR or NC.
RD=R allows automated restarts and considers the checkpoint coded in the CHKPT parameter of the DD statement.
RD=R allows automated restarts and considers the checkpoint coded in the CHKPT parameter of the DD statement.
RD=RNC allows automated restarts, but overrides (ignores) the CHKPT parameter.
RD=RNC allows automated restarts, but overrides (ignores) the CHKPT parameter.
RD=NR specifies that the job/step cannot be automatically restarted. But when it is manually restarted using the RESTART parameter, CHKPT parameter (if any) will be considered.
RD=NR specifies that the job/step cannot be automatically restarted. But when it is manually restarted using the RESTART parameter, CHKPT parameter (if any) will be considered.
RD=NC disallows automated restart and checkpoint processing.
RD=NC disallows automated restart and checkpoint processing.
If there is a requirement to do automated restart for specific abend codes only, then it can be specified in the SCHEDxx member of the IBM system parmlib library.
RESTART parameter is coded in the JOB or EXEC statement and it helps in manual restart of the JOB/STEP after the job failure. RESTART can be accompanied with a checkid, which is the checkpoint written in the dataset coded in the SYSCKEOV DD statement. When a checkid is coded, the SYSCHK DD statement should be coded to reference the checkpoint dataset after the JOBLIB statement (if any), else after the JOB statement.
//CHKSAMP JOB CLASS=6,NOTIFY=&SYSUID,RESTART=(STP01,chk5)
//*
//SYSCHK DD DSN=SAMPLE.CHK,DISP=OLD
//STP01 EXEC PGM=MYCOBB
//*SYSCKEOV DD DSNAME=SAMPLE.CHK,DISP=MOD
//IN1 DD DSN=SAMPLE.IN,DISP=SHR
//OUT1 DD DSN=SAMPLE.OUT,DISP=(,CATLG,CATLG)
// CHKPT=EOV,LRECL=80,RECFM=FB
In the above example, chk5 is the checkid, i.e., STP01 is restarted at checkpoint5. Please note that a SYSCHK statement is added and SYSCKEOV statement is commented out in the previous program explained in Setting Checkpoint section.
12 Lectures
2 hours
Nishant Malik
73 Lectures
4.5 hours
Topictrick Education
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2174,
"s": 1864,
"text": "The Job Entry System uses two approaches to perform conditional processing in a JCL. When a job completes, a return code is set based on the status of execution. The return code can be a number between 0 (successful execution) to 4095 (non-zero shows error condition). The most common conventional values are:"
},
{
"code": null,
"e": 2194,
"s": 2174,
"text": "0 = Normal - all OK"
},
{
"code": null,
"e": 2214,
"s": 2194,
"text": "0 = Normal - all OK"
},
{
"code": null,
"e": 2254,
"s": 2214,
"text": "4 = Warning - minor errors or problems."
},
{
"code": null,
"e": 2294,
"s": 2254,
"text": "4 = Warning - minor errors or problems."
},
{
"code": null,
"e": 2338,
"s": 2294,
"text": "8 = Error - significant errors or problems."
},
{
"code": null,
"e": 2382,
"s": 2338,
"text": "8 = Error - significant errors or problems."
},
{
"code": null,
"e": 2463,
"s": 2382,
"text": "12 = Severe error - major errors or problems, the results should not be trusted."
},
{
"code": null,
"e": 2544,
"s": 2463,
"text": "12 = Severe error - major errors or problems, the results should not be trusted."
},
{
"code": null,
"e": 2613,
"s": 2544,
"text": "16 = Terminal error - very serious problems, do not use the results."
},
{
"code": null,
"e": 2682,
"s": 2613,
"text": "16 = Terminal error - very serious problems, do not use the results."
},
{
"code": null,
"e": 2867,
"s": 2682,
"text": "A job step execution can be controlled based on the return code of the previous step(s) using the COND parameter and IF-THEN-ELSE construct, which has been explained in this tutorial."
},
{
"code": null,
"e": 3216,
"s": 2867,
"text": "A COND parameter can be coded in the JOB or EXEC statement of JCL. It is a test on the return code of the preceding job steps. If the test is evaluated to be true, the current job step execution is bypassed. Bypassing is just omission of the job step and not an abnormal termination. There can be at most eight conditions combined in a single test."
},
{
"code": null,
"e": 3271,
"s": 3216,
"text": "Following is the basic syntax of a JCL COND Parameter:"
},
{
"code": null,
"e": 3364,
"s": 3271,
"text": "COND=(rc,logical-operator)\nor\nCOND=(rc,logical-operator,stepname)\nor\nCOND=EVEN\nor \nCOND=ONLY"
},
{
"code": null,
"e": 3408,
"s": 3364,
"text": "Here is the description of parameters used:"
},
{
"code": null,
"e": 3437,
"s": 3408,
"text": "rc : This is the return code"
},
{
"code": null,
"e": 3466,
"s": 3437,
"text": "rc : This is the return code"
},
{
"code": null,
"e": 3631,
"s": 3466,
"text": "logical-operator : This can be GT (Greater Than), GE (Greater than or Equal to), EQ (Equal to), LT (Lesser Than), LE (Lesser than or Equal to) or NE (Not Equal to)."
},
{
"code": null,
"e": 3796,
"s": 3631,
"text": "logical-operator : This can be GT (Greater Than), GE (Greater than or Equal to), EQ (Equal to), LT (Lesser Than), LE (Lesser than or Equal to) or NE (Not Equal to)."
},
{
"code": null,
"e": 3867,
"s": 3796,
"text": "stepname : This is the job step whose return code is used in the test."
},
{
"code": null,
"e": 3938,
"s": 3867,
"text": "stepname : This is the job step whose return code is used in the test."
},
{
"code": null,
"e": 4035,
"s": 3938,
"text": "Last two conditions (a) COND=EVEN and (b) COND=ONLY, have been explained below in this tutorial."
},
{
"code": null,
"e": 4170,
"s": 4035,
"text": "The COND can be coded either inside JOB statement or EXEC statement, and in both the cases, it behaves differently as explained below:"
},
{
"code": null,
"e": 4385,
"s": 4170,
"text": "When COND is coded in JOB statement, the condition is tested for every job step. When the condition is true at any particular job step, it is bypassed along with the job steps following it. Following is an example:"
},
{
"code": null,
"e": 4776,
"s": 4385,
"text": "//CNDSAMP JOB CLASS=6,NOTIFY=&SYSUID,COND=(5,LE)\n//*\n//STEP10 EXEC PGM=FIRSTP \n//* STEP10 executes without any test being performed.\n\n//STEP20 EXEC PGM=SECONDP \n//* STEP20 is bypassed, if RC of STEP10 is 5 or above. \n//* Say STEP10 ends with RC4 and hence test is false. \n//* So STEP20 executes and lets say it ends with RC16.\n\n//STEP30 EXEC PGM=SORT\n//* STEP30 is bypassed since 5 <= 16.\n"
},
{
"code": null,
"e": 4928,
"s": 4776,
"text": "When COND is coded in EXEC statement of a job step and found to be true, only that job step is bypassed, and execution is continued from next job step."
},
{
"code": null,
"e": 5341,
"s": 4928,
"text": "//CNDSAMP JOB CLASS=6,NOTIFY=&SYSUID\n//*\n//STP01 EXEC PGM=SORT\n//* Assuming STP01 ends with RC0.\n\n//STP02 EXEC PGM=MYCOBB,COND=(0,EQ,STP01)\n//* In STP02, condition evaluates to TRUE and step bypassed.\n\n//STP03 EXEC PGM=IEBGENER,COND=((10,LT,STP01),(10,GT,STP02))\n//* In STP03, first condition fails and hence STP03 executes. \n//* Since STP02 is bypassed, the condition (10,GT,STP02) in \n//* STP03 is not tested.\n"
},
{
"code": null,
"e": 5577,
"s": 5341,
"text": "When COND=EVEN is coded, the current job step is executed, even if any of the previous steps abnormally terminate. If any other RC condition is coded along with COND=EVEN, then the job step executes if none of the RC condition is true."
},
{
"code": null,
"e": 5921,
"s": 5577,
"text": "//CNDSAMP JOB CLASS=6,NOTIFY=&SYSUID\n//*\n//STP01 EXEC PGM=SORT\n//* Assuming STP01 ends with RC0.\n\n//STP02 EXEC PGM=MYCOBB,COND=(0,EQ,STP01)\n//* In STP02, condition evaluates to TRUE and step bypassed.\n\n//STP03 EXEC PGM=IEBGENER,COND=((10,LT,STP01),EVEN)\n//* In STP03, condition (10,LT,STP01) evaluates to true,\n//* hence the step is bypassed.\n"
},
{
"code": null,
"e": 6209,
"s": 5921,
"text": "When COND=ONLY is coded, the current job step is executed, only when any of the previous steps abnormally terminate. If any other RC condition is coded along with COND=ONLY, then the job step executes if none of the RC condition is true and any of the previous job steps fail abnormally."
},
{
"code": null,
"e": 6600,
"s": 6209,
"text": "//CNDSAMP JOB CLASS=6,NOTIFY=&SYSUID\n//*\n//STP01 EXEC PGM=SORT\n//* Assuming STP01 ends with RC0.\n\n//STP02 EXEC PGM=MYCOBB,COND=(4,EQ,STP01)\n//* In STP02, condition evaluates to FALSE, step is executed \n//* and assume the step abends.\n\n//STP03 EXEC PGM=IEBGENER,COND=((0,EQ,STP01),ONLY)\n//* In STP03, though the STP02 abends, the condition \n//* (0,EQ,STP01) is met. Hence STP03 is bypassed.\n"
},
{
"code": null,
"e": 6761,
"s": 6600,
"text": "Another approach to control the job processing is by using IF-THEN-ELSE constructs. This gives more flexibility and user-friendly way of conditional processing."
},
{
"code": null,
"e": 6824,
"s": 6761,
"text": "Following is the basic syntax of a JCL IF-THEN-ELSE Construct:"
},
{
"code": null,
"e": 7006,
"s": 6824,
"text": "//name IF condition THEN\nlist of statements //* action to be taken when condition is true\n//name ELSE \nlist of statements //* action to be taken when condition is false\n//name ENDIF"
},
{
"code": null,
"e": 7090,
"s": 7006,
"text": "Following is the description of the used terms in the above IF-THEN-ELSE Construct:"
},
{
"code": null,
"e": 7199,
"s": 7090,
"text": "name : This is optional and a name can have 1 to 8 alphanumeric characters starting with alphabet, #,$ or @."
},
{
"code": null,
"e": 7308,
"s": 7199,
"text": "name : This is optional and a name can have 1 to 8 alphanumeric characters starting with alphabet, #,$ or @."
},
{
"code": null,
"e": 7592,
"s": 7308,
"text": "Condition : A condition will have a format: KEYWORD OPERATOR VALUE, where KEYWORDS can be RC (Return Code), ABENDCC (System or user completion code), ABEND, RUN (step started execution). An OPERATOR can be logical operator (AND (&), OR (|)) or relational operator (<, <=, >, >=, <>)."
},
{
"code": null,
"e": 7876,
"s": 7592,
"text": "Condition : A condition will have a format: KEYWORD OPERATOR VALUE, where KEYWORDS can be RC (Return Code), ABENDCC (System or user completion code), ABEND, RUN (step started execution). An OPERATOR can be logical operator (AND (&), OR (|)) or relational operator (<, <=, >, >=, <>)."
},
{
"code": null,
"e": 7941,
"s": 7876,
"text": "Following is a simple example showing the usage of IF-THEN-ELSE:"
},
{
"code": null,
"e": 8576,
"s": 7941,
"text": "//CNDSAMP JOB CLASS=6,NOTIFY=&SYSUID\n//*\n//PRC1 PROC\n//PST1\t EXEC PGM=SORT\n//PST2\t EXEC PGM=IEBGENER\n// PEND\n//STP01 EXEC PGM=SORT \n//IF1 IF STP01.RC = 0 THEN\n//STP02 EXEC PGM=MYCOBB1,PARM=123\n// ENDIF\n//IF2 IF STP01.RUN THEN\n//STP03a EXEC PGM=IEBGENER\n//STP03b EXEC PGM=SORT\n// ENDIF\n//IF3 IF STP03b.!ABEND THEN\n//STP04 EXEC PGM=MYCOBB1,PARM=456\n// ELSE\n// ENDIF\n//IF4 IF (STP01.RC = 0 & STP02.RC <= 4) THEN\n//STP05 EXEC PROC=PRC1\n// ENDIF\n//IF5 IF STP05.PRC1.PST1.ABEND THEN\n//STP06 EXEC PGM=MYABD\n// ELSE\n//STP07 EXEC PGM=SORT\n// ENDIF"
},
{
"code": null,
"e": 8657,
"s": 8576,
"text": "Let's try to look into the above program to understand it in little more detail:"
},
{
"code": null,
"e": 8794,
"s": 8657,
"text": "The return code of STP01 is tested in IF1. If it is 0, then STP02 is executed. Else, the processing goes to the next IF statement (IF2)."
},
{
"code": null,
"e": 8931,
"s": 8794,
"text": "The return code of STP01 is tested in IF1. If it is 0, then STP02 is executed. Else, the processing goes to the next IF statement (IF2)."
},
{
"code": null,
"e": 9008,
"s": 8931,
"text": "In IF2, If STP01 has started execution, then STP03a and STP03b are executed."
},
{
"code": null,
"e": 9085,
"s": 9008,
"text": "In IF2, If STP01 has started execution, then STP03a and STP03b are executed."
},
{
"code": null,
"e": 9213,
"s": 9085,
"text": "In IF3, If STP03b does not ABEND, then STP04 is executed. In ELSE, there are no statements. It is called a NULL ELSE statement."
},
{
"code": null,
"e": 9341,
"s": 9213,
"text": "In IF3, If STP03b does not ABEND, then STP04 is executed. In ELSE, there are no statements. It is called a NULL ELSE statement."
},
{
"code": null,
"e": 9416,
"s": 9341,
"text": "In IF4, if STP01.RC = 0 and STP02.RC <=4 are TRUE, then STP05 is executed."
},
{
"code": null,
"e": 9491,
"s": 9416,
"text": "In IF4, if STP01.RC = 0 and STP02.RC <=4 are TRUE, then STP05 is executed."
},
{
"code": null,
"e": 9606,
"s": 9491,
"text": "In IF5, if the proc-step PST1 in PROC PRC1 in jobstep STP05 ABEND, then STP06 is executed. Else STP07 is executed."
},
{
"code": null,
"e": 9721,
"s": 9606,
"text": "In IF5, if the proc-step PST1 in PROC PRC1 in jobstep STP05 ABEND, then STP06 is executed. Else STP07 is executed."
},
{
"code": null,
"e": 9854,
"s": 9721,
"text": "If IF4 evaluates to false, then STP05 is not executed. In that case, IF5 are not tested and the steps STP06, STP07 are not executed."
},
{
"code": null,
"e": 9987,
"s": 9854,
"text": "If IF4 evaluates to false, then STP05 is not executed. In that case, IF5 are not tested and the steps STP06, STP07 are not executed."
},
{
"code": null,
"e": 10185,
"s": 9987,
"text": "The IF-THEN-ELSE will not be executed in the case of abnormal termination of the job such as user cancelling the job, job time expiry or a dataset is backward referenced to a step that is bypassed."
},
{
"code": null,
"e": 10281,
"s": 10185,
"text": "You can set checkpoint dataset inside your JCL program using SYSCKEOV, which is a DD statement."
},
{
"code": null,
"e": 10541,
"s": 10281,
"text": "A CHKPT is the parameter coded for multi-volume QSAM datasets in a DD statement. When a CHKPT is coded as CHKPT=EOV, a checkpoint is written to the dataset specified in the SYSCKEOV statement at the end of each volume of the input/output multi-volume dataset."
},
{
"code": null,
"e": 10781,
"s": 10541,
"text": "//CHKSAMP JOB CLASS=6,NOTIFY=&SYSUID\n//*\n//STP01 EXEC PGM=MYCOBB\n//SYSCKEOV DD DSNAME=SAMPLE.CHK,DISP=MOD\n//IN1 DD DSN=SAMPLE.IN,DISP=SHR\n//OUT1 DD DSN=SAMPLE.OUT,DISP=(,CATLG,CATLG)\n// CHKPT=EOV,LRECL=80,RECFM=FB\t"
},
{
"code": null,
"e": 10909,
"s": 10781,
"text": "In the above example, a checkpoint is written in dataset SAMPLE.CHK at the end of each volume of the output dataset SAMPLE.OUT."
},
{
"code": null,
"e": 11026,
"s": 10909,
"text": "You can restart processing ether using automated way using the RD parameter or manual using the RESTART parameter."
},
{
"code": null,
"e": 11175,
"s": 11026,
"text": "RD parameter is coded in the JOB or EXEC statement and it helps in automated JOB/STEP restart and can hold one of the four values: R, RNC, NR or NC."
},
{
"code": null,
"e": 11285,
"s": 11175,
"text": "RD=R allows automated restarts and considers the checkpoint coded in the CHKPT parameter of the DD statement."
},
{
"code": null,
"e": 11395,
"s": 11285,
"text": "RD=R allows automated restarts and considers the checkpoint coded in the CHKPT parameter of the DD statement."
},
{
"code": null,
"e": 11474,
"s": 11395,
"text": "RD=RNC allows automated restarts, but overrides (ignores) the CHKPT parameter."
},
{
"code": null,
"e": 11553,
"s": 11474,
"text": "RD=RNC allows automated restarts, but overrides (ignores) the CHKPT parameter."
},
{
"code": null,
"e": 11730,
"s": 11553,
"text": "RD=NR specifies that the job/step cannot be automatically restarted. But when it is manually restarted using the RESTART parameter, CHKPT parameter (if any) will be considered."
},
{
"code": null,
"e": 11907,
"s": 11730,
"text": "RD=NR specifies that the job/step cannot be automatically restarted. But when it is manually restarted using the RESTART parameter, CHKPT parameter (if any) will be considered."
},
{
"code": null,
"e": 11968,
"s": 11907,
"text": "RD=NC disallows automated restart and checkpoint processing."
},
{
"code": null,
"e": 12029,
"s": 11968,
"text": "RD=NC disallows automated restart and checkpoint processing."
},
{
"code": null,
"e": 12193,
"s": 12029,
"text": "If there is a requirement to do automated restart for specific abend codes only, then it can be specified in the SCHEDxx member of the IBM system parmlib library."
},
{
"code": null,
"e": 12613,
"s": 12193,
"text": "RESTART parameter is coded in the JOB or EXEC statement and it helps in manual restart of the JOB/STEP after the job failure. RESTART can be accompanied with a checkid, which is the checkpoint written in the dataset coded in the SYSCKEOV DD statement. When a checkid is coded, the SYSCHK DD statement should be coded to reference the checkpoint dataset after the JOBLIB statement (if any), else after the JOB statement."
},
{
"code": null,
"e": 12913,
"s": 12613,
"text": "//CHKSAMP JOB CLASS=6,NOTIFY=&SYSUID,RESTART=(STP01,chk5)\n//*\n//SYSCHK DD DSN=SAMPLE.CHK,DISP=OLD\n//STP01 EXEC PGM=MYCOBB\n//*SYSCKEOV\tDD DSNAME=SAMPLE.CHK,DISP=MOD\n//IN1 DD DSN=SAMPLE.IN,DISP=SHR\n//OUT1 DD DSN=SAMPLE.OUT,DISP=(,CATLG,CATLG)\n// CHKPT=EOV,LRECL=80,RECFM=FB\t"
},
{
"code": null,
"e": 13147,
"s": 12913,
"text": "In the above example, chk5 is the checkid, i.e., STP01 is restarted at checkpoint5. Please note that a SYSCHK statement is added and SYSCKEOV statement is commented out in the previous program explained in Setting Checkpoint section."
},
{
"code": null,
"e": 13180,
"s": 13147,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13195,
"s": 13180,
"text": " Nishant Malik"
},
{
"code": null,
"e": 13230,
"s": 13195,
"text": "\n 73 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13252,
"s": 13230,
"text": " Topictrick Education"
},
{
"code": null,
"e": 13259,
"s": 13252,
"text": " Print"
},
{
"code": null,
"e": 13270,
"s": 13259,
"text": " Add Notes"
}
] |
Node.js request.socket Property - GeeksforGeeks | 01 Sep, 2020
The request.socket (Added in v0.3.0) property is an inbuilt property of the ‘http’ module which references to the underlying socket and most users don’t get access to this property. Particularly, the socket doesn’t emit ‘readable‘ events but, the socket could be accessed via request.connection. This property guarantees to being an instance of the <net.Socket> class, a subclass of <stream.Duplex>.
In order to get a response and a proper result, we need to import ‘http’ module.
const http = require('http');
Syntax:
request.socket
Parameters: This property does not accept any parameters.
Return Value: It returns the request data in the form of an object which contains a huge amount of data related to socket.
<stream.Duplex>: <stream.Duplex> or duplex stream is a stream that implements both a readable and a writable.
The below examples illustrate the use of request.socket property in Node.js.
Example 1: Filename: index.js
// Node.js program to demonstrate the // req.socket property // Using require to access http module const http = require('http'); // Requesting from google serverconst req = http.get({ host: 'www.geeksforgeeks.org' }); // Ending the requestreq.end(); req.once('response', (res) => { // Printing socket after getting response console.log(req.socket); // Printing address and port after // getting response console.log(`IP address of geeksforgeeks is ${req.socket.localAddress}.`); console.log(`Its Port is ${req.socket.localPort}.`);});
Output:
>> <ref *1> Socket{ connecting: false,
_hadError: false,
_parent: null,
_host: ‘www.geeeksforgeeks.org’... [Symbol(kBytesWritten)]: 0 }
>> IP address is 192.168.43.207
>> Its port is 56933.
Example 2: Filename: index.js
// Node.js program to demonstrate the // req.socket property // Using require to access http module const { get } = require('http'); // Setting host server urlconst options = { host: 'www.geeksforgeeks.org' }; // Requesting from geeksforgeeks serverconst req = get(options);req.end(); req.once('response', (res) => { // Printing the requestrelated data console.log("Status:", res.statusCode, res.statusMessage); console.log("Host:", req.socket._host); console.log("Method:", req.socket.parser.outgoing.method); console.log("Parser Header:", req.socket.parser.outgoing._header); console.log("Writable:", req.socket.writable); console.log("Readable:", req.socket.readable); console.log("Http Header:", req.socket._httpMessage._header); if (req.socket._httpMessage._header === req.socket.parser.outgoing._header) { console.log("Both headers are exactly same...") } else { console.log("Headers are not same...") } // Printing address and port after // getting response console.log(`IP address of geeksforgeeks is ${req.socket.localAddress}.`); console.log(`Its port is ${req.socket.localPort}.`);});
Run index.js file using the following command:
node index.js
Output:
>> Status: 301 Moved Permanently
>> Host: www.geeksforgeeks.org
>> Method: GET
>> Parser Header: GET / HTTP/1.1
Host: www.geeksforgeeks.org
Connection: close
>> Writable: true
>> Readable: true
>> Http Header: GET / HTTP/1.1
Host: www.geeksforgeeks.org
Connection: close
>> Both headers are exactly same...
>> IP address is 192.168.43.207
>> Its port is 57425.
Reference: https://nodejs.org/api/http.html#http_request_socket
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Difference between npm i and npm ci in Node.js
Mongoose Populate() Method
Roadmap to Become a Web Developer in 2022
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25002,
"s": 24974,
"text": "\n01 Sep, 2020"
},
{
"code": null,
"e": 25402,
"s": 25002,
"text": "The request.socket (Added in v0.3.0) property is an inbuilt property of the ‘http’ module which references to the underlying socket and most users don’t get access to this property. Particularly, the socket doesn’t emit ‘readable‘ events but, the socket could be accessed via request.connection. This property guarantees to being an instance of the <net.Socket> class, a subclass of <stream.Duplex>."
},
{
"code": null,
"e": 25483,
"s": 25402,
"text": "In order to get a response and a proper result, we need to import ‘http’ module."
},
{
"code": null,
"e": 25514,
"s": 25483,
"text": "const http = require('http'); "
},
{
"code": null,
"e": 25522,
"s": 25514,
"text": "Syntax:"
},
{
"code": null,
"e": 25538,
"s": 25522,
"text": "request.socket\n"
},
{
"code": null,
"e": 25596,
"s": 25538,
"text": "Parameters: This property does not accept any parameters."
},
{
"code": null,
"e": 25719,
"s": 25596,
"text": "Return Value: It returns the request data in the form of an object which contains a huge amount of data related to socket."
},
{
"code": null,
"e": 25830,
"s": 25719,
"text": "<stream.Duplex>: <stream.Duplex> or duplex stream is a stream that implements both a readable and a writable."
},
{
"code": null,
"e": 25907,
"s": 25830,
"text": "The below examples illustrate the use of request.socket property in Node.js."
},
{
"code": null,
"e": 25938,
"s": 25907,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // req.socket property // Using require to access http module const http = require('http'); // Requesting from google serverconst req = http.get({ host: 'www.geeksforgeeks.org' }); // Ending the requestreq.end(); req.once('response', (res) => { // Printing socket after getting response console.log(req.socket); // Printing address and port after // getting response console.log(`IP address of geeksforgeeks is ${req.socket.localAddress}.`); console.log(`Its Port is ${req.socket.localPort}.`);});",
"e": 26527,
"s": 25938,
"text": null
},
{
"code": null,
"e": 26535,
"s": 26527,
"text": "Output:"
},
{
"code": null,
"e": 26574,
"s": 26535,
"text": ">> <ref *1> Socket{ connecting: false,"
},
{
"code": null,
"e": 26596,
"s": 26574,
"text": " _hadError: false,"
},
{
"code": null,
"e": 26615,
"s": 26596,
"text": " _parent: null,"
},
{
"code": null,
"e": 26683,
"s": 26615,
"text": " _host: ‘www.geeeksforgeeks.org’... [Symbol(kBytesWritten)]: 0 }"
},
{
"code": null,
"e": 26715,
"s": 26683,
"text": ">> IP address is 192.168.43.207"
},
{
"code": null,
"e": 26737,
"s": 26715,
"text": ">> Its port is 56933."
},
{
"code": null,
"e": 26767,
"s": 26737,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // req.socket property // Using require to access http module const { get } = require('http'); // Setting host server urlconst options = { host: 'www.geeksforgeeks.org' }; // Requesting from geeksforgeeks serverconst req = get(options);req.end(); req.once('response', (res) => { // Printing the requestrelated data console.log(\"Status:\", res.statusCode, res.statusMessage); console.log(\"Host:\", req.socket._host); console.log(\"Method:\", req.socket.parser.outgoing.method); console.log(\"Parser Header:\", req.socket.parser.outgoing._header); console.log(\"Writable:\", req.socket.writable); console.log(\"Readable:\", req.socket.readable); console.log(\"Http Header:\", req.socket._httpMessage._header); if (req.socket._httpMessage._header === req.socket.parser.outgoing._header) { console.log(\"Both headers are exactly same...\") } else { console.log(\"Headers are not same...\") } // Printing address and port after // getting response console.log(`IP address of geeksforgeeks is ${req.socket.localAddress}.`); console.log(`Its port is ${req.socket.localPort}.`);});",
"e": 28025,
"s": 26767,
"text": null
},
{
"code": null,
"e": 28072,
"s": 28025,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 28087,
"s": 28072,
"text": "node index.js\n"
},
{
"code": null,
"e": 28095,
"s": 28087,
"text": "Output:"
},
{
"code": null,
"e": 28128,
"s": 28095,
"text": ">> Status: 301 Moved Permanently"
},
{
"code": null,
"e": 28159,
"s": 28128,
"text": ">> Host: www.geeksforgeeks.org"
},
{
"code": null,
"e": 28174,
"s": 28159,
"text": ">> Method: GET"
},
{
"code": null,
"e": 28207,
"s": 28174,
"text": ">> Parser Header: GET / HTTP/1.1"
},
{
"code": null,
"e": 28239,
"s": 28207,
"text": " Host: www.geeksforgeeks.org"
},
{
"code": null,
"e": 28261,
"s": 28239,
"text": " Connection: close"
},
{
"code": null,
"e": 28279,
"s": 28261,
"text": ">> Writable: true"
},
{
"code": null,
"e": 28297,
"s": 28279,
"text": ">> Readable: true"
},
{
"code": null,
"e": 28328,
"s": 28297,
"text": ">> Http Header: GET / HTTP/1.1"
},
{
"code": null,
"e": 28360,
"s": 28328,
"text": " Host: www.geeksforgeeks.org"
},
{
"code": null,
"e": 28382,
"s": 28360,
"text": " Connection: close"
},
{
"code": null,
"e": 28418,
"s": 28382,
"text": ">> Both headers are exactly same..."
},
{
"code": null,
"e": 28450,
"s": 28418,
"text": ">> IP address is 192.168.43.207"
},
{
"code": null,
"e": 28472,
"s": 28450,
"text": ">> Its port is 57425."
},
{
"code": null,
"e": 28536,
"s": 28472,
"text": "Reference: https://nodejs.org/api/http.html#http_request_socket"
},
{
"code": null,
"e": 28549,
"s": 28536,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 28557,
"s": 28549,
"text": "Node.js"
},
{
"code": null,
"e": 28574,
"s": 28557,
"text": "Web Technologies"
},
{
"code": null,
"e": 28672,
"s": 28574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28681,
"s": 28672,
"text": "Comments"
},
{
"code": null,
"e": 28694,
"s": 28681,
"text": "Old Comments"
},
{
"code": null,
"e": 28731,
"s": 28694,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 28763,
"s": 28731,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 28794,
"s": 28763,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 28841,
"s": 28794,
"text": "Difference between npm i and npm ci in Node.js"
},
{
"code": null,
"e": 28868,
"s": 28841,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 28910,
"s": 28868,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28960,
"s": 28910,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29022,
"s": 28960,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29065,
"s": 29022,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to create the Azure Storage context using PowerShell? | Storage context is helpful when you are working with the Storage accounts in the PowerShell session. It is like authenticating for Azure storage. Generally, we use the Azure storage account key and the connection string to create the Azure storage context.
To create a new storage context, we need to use the New-AzStorageContext command but to use this command we need a storage account key or the connection string.
We will use here Storage account key. We have the resource group “Az204” and the Storage account name “az204storage05june” which are stored in a variable.
$rg = "az204"
$storageaccount = "az204storage05june"
To get the storage account key,
$key = (Get-AzStorageAccountKey -ResourceGroupName $rg -
Name $storageaccount)[0].Value
To generate the storage context,
$context = New-AzStorageContext -StorageAccountName $storageaccount -
StorageAccountKey $key
You can use this storage context in the various storage commands to deal with the storage operations. | [
{
"code": null,
"e": 1319,
"s": 1062,
"text": "Storage context is helpful when you are working with the Storage accounts in the PowerShell session. It is like authenticating for Azure storage. Generally, we use the Azure storage account key and the connection string to create the Azure storage context."
},
{
"code": null,
"e": 1480,
"s": 1319,
"text": "To create a new storage context, we need to use the New-AzStorageContext command but to use this command we need a storage account key or the connection string."
},
{
"code": null,
"e": 1635,
"s": 1480,
"text": "We will use here Storage account key. We have the resource group “Az204” and the Storage account name “az204storage05june” which are stored in a variable."
},
{
"code": null,
"e": 1688,
"s": 1635,
"text": "$rg = \"az204\"\n$storageaccount = \"az204storage05june\""
},
{
"code": null,
"e": 1720,
"s": 1688,
"text": "To get the storage account key,"
},
{
"code": null,
"e": 1808,
"s": 1720,
"text": "$key = (Get-AzStorageAccountKey -ResourceGroupName $rg -\nName $storageaccount)[0].Value"
},
{
"code": null,
"e": 1841,
"s": 1808,
"text": "To generate the storage context,"
},
{
"code": null,
"e": 1934,
"s": 1841,
"text": "$context = New-AzStorageContext -StorageAccountName $storageaccount -\nStorageAccountKey $key"
},
{
"code": null,
"e": 2036,
"s": 1934,
"text": "You can use this storage context in the various storage commands to deal with the storage operations."
}
] |
AWK - Output Redirection | So far, we displayed data on standard output stream. We can also redirect data to a file. A redirection appears after the print or printf statement. Redirections in AWK are written just like redirection in shell commands, except that they are written inside the AWK program. This chapter explains redirection with suitable examples.
The syntax of the redirection operator is −
print DATA > output-file
It writes the data into the output-file. If the output-file does not exist, then it creates one. When this type of redirection is used, the output-file is erased before the first output is written to it. Subsequent write operations to the same output-file do not erase the output-file, but append to it. For instance, the following example writes Hello, World !!! to the file.
Let us create a file with some text data.
[jerry]$ echo "Old data" > /tmp/message.txt
[jerry]$ cat /tmp/message.txt
On executing this code, you get the following result −
Old data
Now let us redirect some contents into it using AWK's redirection operator.
[jerry]$ awk 'BEGIN { print "Hello, World !!!" > "/tmp/message.txt" }'
[jerry]$ cat /tmp/message.txt
On executing this code, you get the following result −
Hello, World !!!
The syntax of append operator is as follows −
print DATA >> output-file
It appends the data into the output-file. If the output-file does not exist, then it creates one. When this type of redirection is used, new contents are appended at the end of file. For instance, the following example appends Hello, World !!! to the file.
Let us create a file with some text data.
[jerry]$ echo "Old data" > /tmp/message.txt
[jerry]$ cat /tmp/message.txt
On executing this code, you get the following result −
Old data
Now let us append some contents to it using AWK's append operator.
[jerry]$ awk 'BEGIN { print "Hello, World !!!" >> "/tmp/message.txt" }'
[jerry]$ cat /tmp/message.txt
On executing this code, you get the following result −
Old data
Hello, World !!!
It is possible to send output to another program through a pipe instead of using a file. This redirection opens a pipe to command, and writes the values of items through this pipe to another process to execute the command. The redirection argument command is actually an AWK expression. Here is the syntax of pipe −
print items | command
Let us use tr command to convert lowercase letters to uppercase.
[jerry]$ awk 'BEGIN { print "hello, world !!!" | "tr [a-z] [A-Z]" }'
On executing this code, you get the following result −
HELLO, WORLD !!!
AWK can communicate to an external process using |&, which is two-way communication. For instance, the following example uses tr command to convert lowercase letters to uppercase. Our command.awk file contains −
BEGIN {
cmd = "tr [a-z] [A-Z]"
print "hello, world !!!" |& cmd
close(cmd, "to")
cmd |& getline out
print out;
close(cmd);
}
On executing this code, you get the following result −
HELLO, WORLD !!!
Does the script look cryptic? Let us demystify it.
The first statement, cmd = "tr [a-z] [A-Z]", is the command to which we establish the two-way communication from AWK.
The first statement, cmd = "tr [a-z] [A-Z]", is the command to which we establish the two-way communication from AWK.
The next statement, i.e., the print command provides input to the tr command. Here &| indicates two-way communication.
The next statement, i.e., the print command provides input to the tr command. Here &| indicates two-way communication.
The third statement, i.e., close(cmd, "to"), closes the to process after competing its execution.
The third statement, i.e., close(cmd, "to"), closes the to process after competing its execution.
The next statement cmd |& getline out stores the output into out variable with the aid of getline function.
The next statement cmd |& getline out stores the output into out variable with the aid of getline function.
The next print statement prints the output and finally the close function closes the command.
The next print statement prints the output and finally the close function closes the command.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2190,
"s": 1857,
"text": "So far, we displayed data on standard output stream. We can also redirect data to a file. A redirection appears after the print or printf statement. Redirections in AWK are written just like redirection in shell commands, except that they are written inside the AWK program. This chapter explains redirection with suitable examples."
},
{
"code": null,
"e": 2234,
"s": 2190,
"text": "The syntax of the redirection operator is −"
},
{
"code": null,
"e": 2260,
"s": 2234,
"text": "print DATA > output-file\n"
},
{
"code": null,
"e": 2637,
"s": 2260,
"text": "It writes the data into the output-file. If the output-file does not exist, then it creates one. When this type of redirection is used, the output-file is erased before the first output is written to it. Subsequent write operations to the same output-file do not erase the output-file, but append to it. For instance, the following example writes Hello, World !!! to the file."
},
{
"code": null,
"e": 2679,
"s": 2637,
"text": "Let us create a file with some text data."
},
{
"code": null,
"e": 2753,
"s": 2679,
"text": "[jerry]$ echo \"Old data\" > /tmp/message.txt\n[jerry]$ cat /tmp/message.txt"
},
{
"code": null,
"e": 2808,
"s": 2753,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 2818,
"s": 2808,
"text": "Old data\n"
},
{
"code": null,
"e": 2894,
"s": 2818,
"text": "Now let us redirect some contents into it using AWK's redirection operator."
},
{
"code": null,
"e": 2995,
"s": 2894,
"text": "[jerry]$ awk 'BEGIN { print \"Hello, World !!!\" > \"/tmp/message.txt\" }'\n[jerry]$ cat /tmp/message.txt"
},
{
"code": null,
"e": 3050,
"s": 2995,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 3068,
"s": 3050,
"text": "Hello, World !!!\n"
},
{
"code": null,
"e": 3114,
"s": 3068,
"text": "The syntax of append operator is as follows −"
},
{
"code": null,
"e": 3141,
"s": 3114,
"text": "print DATA >> output-file\n"
},
{
"code": null,
"e": 3398,
"s": 3141,
"text": "It appends the data into the output-file. If the output-file does not exist, then it creates one. When this type of redirection is used, new contents are appended at the end of file. For instance, the following example appends Hello, World !!! to the file."
},
{
"code": null,
"e": 3440,
"s": 3398,
"text": "Let us create a file with some text data."
},
{
"code": null,
"e": 3515,
"s": 3440,
"text": "[jerry]$ echo \"Old data\" > /tmp/message.txt \n[jerry]$ cat /tmp/message.txt"
},
{
"code": null,
"e": 3570,
"s": 3515,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 3580,
"s": 3570,
"text": "Old data\n"
},
{
"code": null,
"e": 3647,
"s": 3580,
"text": "Now let us append some contents to it using AWK's append operator."
},
{
"code": null,
"e": 3749,
"s": 3647,
"text": "[jerry]$ awk 'BEGIN { print \"Hello, World !!!\" >> \"/tmp/message.txt\" }'\n[jerry]$ cat /tmp/message.txt"
},
{
"code": null,
"e": 3804,
"s": 3749,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 3831,
"s": 3804,
"text": "Old data\nHello, World !!!\n"
},
{
"code": null,
"e": 4147,
"s": 3831,
"text": "It is possible to send output to another program through a pipe instead of using a file. This redirection opens a pipe to command, and writes the values of items through this pipe to another process to execute the command. The redirection argument command is actually an AWK expression. Here is the syntax of pipe −"
},
{
"code": null,
"e": 4170,
"s": 4147,
"text": "print items | command\n"
},
{
"code": null,
"e": 4235,
"s": 4170,
"text": "Let us use tr command to convert lowercase letters to uppercase."
},
{
"code": null,
"e": 4304,
"s": 4235,
"text": "[jerry]$ awk 'BEGIN { print \"hello, world !!!\" | \"tr [a-z] [A-Z]\" }'"
},
{
"code": null,
"e": 4359,
"s": 4304,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 4377,
"s": 4359,
"text": "HELLO, WORLD !!!\n"
},
{
"code": null,
"e": 4589,
"s": 4377,
"text": "AWK can communicate to an external process using |&, which is two-way communication. For instance, the following example uses tr command to convert lowercase letters to uppercase. Our command.awk file contains −"
},
{
"code": null,
"e": 4735,
"s": 4589,
"text": "BEGIN {\n cmd = \"tr [a-z] [A-Z]\"\n print \"hello, world !!!\" |& cmd\n close(cmd, \"to\")\n \n cmd |& getline out\n print out;\n close(cmd);\n}"
},
{
"code": null,
"e": 4790,
"s": 4735,
"text": "On executing this code, you get the following result −"
},
{
"code": null,
"e": 4808,
"s": 4790,
"text": "HELLO, WORLD !!!\n"
},
{
"code": null,
"e": 4859,
"s": 4808,
"text": "Does the script look cryptic? Let us demystify it."
},
{
"code": null,
"e": 4977,
"s": 4859,
"text": "The first statement, cmd = \"tr [a-z] [A-Z]\", is the command to which we establish the two-way communication from AWK."
},
{
"code": null,
"e": 5095,
"s": 4977,
"text": "The first statement, cmd = \"tr [a-z] [A-Z]\", is the command to which we establish the two-way communication from AWK."
},
{
"code": null,
"e": 5214,
"s": 5095,
"text": "The next statement, i.e., the print command provides input to the tr command. Here &| indicates two-way communication."
},
{
"code": null,
"e": 5333,
"s": 5214,
"text": "The next statement, i.e., the print command provides input to the tr command. Here &| indicates two-way communication."
},
{
"code": null,
"e": 5431,
"s": 5333,
"text": "The third statement, i.e., close(cmd, \"to\"), closes the to process after competing its execution."
},
{
"code": null,
"e": 5529,
"s": 5431,
"text": "The third statement, i.e., close(cmd, \"to\"), closes the to process after competing its execution."
},
{
"code": null,
"e": 5637,
"s": 5529,
"text": "The next statement cmd |& getline out stores the output into out variable with the aid of getline function."
},
{
"code": null,
"e": 5745,
"s": 5637,
"text": "The next statement cmd |& getline out stores the output into out variable with the aid of getline function."
},
{
"code": null,
"e": 5839,
"s": 5745,
"text": "The next print statement prints the output and finally the close function closes the command."
},
{
"code": null,
"e": 5933,
"s": 5839,
"text": "The next print statement prints the output and finally the close function closes the command."
},
{
"code": null,
"e": 5940,
"s": 5933,
"text": " Print"
},
{
"code": null,
"e": 5951,
"s": 5940,
"text": " Add Notes"
}
] |
Check if all substrings of length K of a Binary String has equal count of 0s and 1s - GeeksforGeeks | 17 May, 2021
Given a binary string S of length N and an even integer K, the task is to check if all substrings of length K contains an equal number of 0s and 1s. If found to be true, print “Yes”. Otherwise, print “No”.
Examples:
Input: S = “101010”, K = 2Output: YesExplanation:Since all the substrings of length 2 has equal number of 0s and 1s, the answer is Yes.
Input: S = “101011”, K = 4Output: NoExplanation:Since substring “1011” has unequal count of 0s and 1s, the answer is No..
Naive Approach: The simplest approach to solve the problem is to generate all substrings of length K and check it if it contains an equal count of 1s and 0s or not.
Time Complexity: O(N2) Auxiliary Space: O(1)
Efficient Approach: The main observation for optimizing the above approach is, for the string S to have an equal count of 0 and 1 in substrings of length K, S[i] must be equal to S[i + k]. Follow the steps below to solve the problem:
Traverse the string and for every ith character, check if S[i] = S[j] where (i == (j % k))
If found to be false at any instant, then print “No”.
Otherwise, check the first substring of length K and if it contains an equal count of 1s and 0s or not. If found to be true, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; // Function to check if the substring// of length K has equal 0 and 1int check(string& s, int k){ int n = s.size(); // Traverse the string for (int i = 0; i < k; i++) { for (int j = i; j < n; j += k) { // Check if every K-th character // is the same or not if (s[i] != s[j]) return false; } } int c = 0; // Traverse substring of length K for (int i = 0; i < k; i++) { // If current character is 0 if (s[i] == '0') // Increment count c++; // Otherwise else // Decrement count c--; } // Check for equal 0s and 1s if (c == 0) return true; else return false;} // Driver codeint main(){ string s = "101010"; int k = 2; if (check(s, k)) cout << "Yes" << endl; else cout << "No" << endl; return 0;}
// Java program for// the above approachimport java.util.*;class GFG{ // Function to check if the substring// of length K has equal 0 and 1static boolean check(String s, int k){ int n = s.length(); // Traverse the String for (int i = 0; i < k; i++) { for (int j = i; j < n; j += k) { // Check if every K-th character // is the same or not if (s.charAt(i) != s.charAt(j)) return false; } } int c = 0; // Traverse subString of length K for (int i = 0; i < k; i++) { // If current character is 0 if (s.charAt(i) == '0') // Increment count c++; // Otherwise else // Decrement count c--; } // Check for equal 0s and 1s if (c == 0) return true; else return false;} // Driver codepublic static void main(String[] args){ String s = "101010"; int k = 2; if (check(s, k)) System.out.print("Yes" + "\n"); else System.out.print("No" + "\n");}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function to check if the substring# of length K has equal 0 and 1def check(s, k): n = len(s) # Traverse the string for i in range(k): for j in range(i, n, k): # Check if every K-th character # is the same or not if (s[i] != s[j]): return False c = 0 # Traverse substring of length K for i in range(k): # If current character is 0 if (s[i] == '0'): # Increment count c += 1 # Otherwise else: # Decrement count c -= 1 # Check for equal 0s and 1s if (c == 0): return True else: return False # Driver codes = "101010"k = 2 if (check(s, k) != 0): print("Yes")else: print("No") # This code is contributed by sanjoy_62
// C# program for// the above approachusing System;class GFG{ // Function to check if the substring// of length K has equal 0 and 1static bool check(String s, int k){ int n = s.Length; // Traverse the String for (int i = 0; i < k; i++) { for (int j = i; j < n; j += k) { // Check if every K-th character // is the same or not if (s[i] != s[j]) return false; } } int c = 0; // Traverse subString of length K for (int i = 0; i < k; i++) { // If current character is 0 if (s[i] == '0') // Increment count c++; // Otherwise else // Decrement count c--; } // Check for equal 0s and 1s if (c == 0) return true; else return false;} // Driver codepublic static void Main(String[] args){ String s = "101010"; int k = 2; if (check(s, k)) Console.Write("Yes" + "\n"); else Console.Write("No" + "\n");}} // This code is contributed by Rajput-Ji
<script>// javascript program for the// above approach // Function to check if the substring// of length K has equal 0 and 1function check(s, k){ let n = s.length; // Traverse the String for (let i = 0; i < k; i++) { for (let j = i; j < n; j += k) { // Check if every K-th character // is the same or not if (s[i] != s[j]) return false; } } let c = 0; // Traverse subString of length K for (let i = 0; i < k; i++) { // If current character is 0 if (s[i]== '0') // Increment count c++; // Otherwise else // Decrement count c--; } // Check for equal 0s and 1s if (c == 0) return true; else return false;} // Driver Code let s = "101010"; let k = 2; if (check(s, k)) document.write("Yes" + "<br/>"); else document.write("No"); // This code is contributed by target_2.</script>
Yes
Time Complexity: O(N)Auxiliary Space: O(1)
29AjayKumar
Rajput-Ji
sanjoy_62
target_2
frequency-counting
substring
Greedy
Pattern Searching
Searching
Strings
Searching
Strings
Greedy
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program for First Fit algorithm in Memory Management
Program for Best Fit algorithm in Memory Management
Optimal Page Replacement Algorithm
Program for Worst Fit algorithm in Memory Management
Max Flow Problem Introduction
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching | [
{
"code": null,
"e": 25294,
"s": 25266,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 25500,
"s": 25294,
"text": "Given a binary string S of length N and an even integer K, the task is to check if all substrings of length K contains an equal number of 0s and 1s. If found to be true, print “Yes”. Otherwise, print “No”."
},
{
"code": null,
"e": 25510,
"s": 25500,
"text": "Examples:"
},
{
"code": null,
"e": 25646,
"s": 25510,
"text": "Input: S = “101010”, K = 2Output: YesExplanation:Since all the substrings of length 2 has equal number of 0s and 1s, the answer is Yes."
},
{
"code": null,
"e": 25768,
"s": 25646,
"text": "Input: S = “101011”, K = 4Output: NoExplanation:Since substring “1011” has unequal count of 0s and 1s, the answer is No.."
},
{
"code": null,
"e": 25934,
"s": 25768,
"text": "Naive Approach: The simplest approach to solve the problem is to generate all substrings of length K and check it if it contains an equal count of 1s and 0s or not. "
},
{
"code": null,
"e": 25979,
"s": 25934,
"text": "Time Complexity: O(N2) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26213,
"s": 25979,
"text": "Efficient Approach: The main observation for optimizing the above approach is, for the string S to have an equal count of 0 and 1 in substrings of length K, S[i] must be equal to S[i + k]. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26304,
"s": 26213,
"text": "Traverse the string and for every ith character, check if S[i] = S[j] where (i == (j % k))"
},
{
"code": null,
"e": 26358,
"s": 26304,
"text": "If found to be false at any instant, then print “No”."
},
{
"code": null,
"e": 26524,
"s": 26358,
"text": "Otherwise, check the first substring of length K and if it contains an equal count of 1s and 0s or not. If found to be true, then print “Yes”. Otherwise, print “No”."
},
{
"code": null,
"e": 26575,
"s": 26524,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26579,
"s": 26575,
"text": "C++"
},
{
"code": null,
"e": 26584,
"s": 26579,
"text": "Java"
},
{
"code": null,
"e": 26592,
"s": 26584,
"text": "Python3"
},
{
"code": null,
"e": 26595,
"s": 26592,
"text": "C#"
},
{
"code": null,
"e": 26606,
"s": 26595,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; // Function to check if the substring// of length K has equal 0 and 1int check(string& s, int k){ int n = s.size(); // Traverse the string for (int i = 0; i < k; i++) { for (int j = i; j < n; j += k) { // Check if every K-th character // is the same or not if (s[i] != s[j]) return false; } } int c = 0; // Traverse substring of length K for (int i = 0; i < k; i++) { // If current character is 0 if (s[i] == '0') // Increment count c++; // Otherwise else // Decrement count c--; } // Check for equal 0s and 1s if (c == 0) return true; else return false;} // Driver codeint main(){ string s = \"101010\"; int k = 2; if (check(s, k)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}",
"e": 27595,
"s": 26606,
"text": null
},
{
"code": "// Java program for// the above approachimport java.util.*;class GFG{ // Function to check if the substring// of length K has equal 0 and 1static boolean check(String s, int k){ int n = s.length(); // Traverse the String for (int i = 0; i < k; i++) { for (int j = i; j < n; j += k) { // Check if every K-th character // is the same or not if (s.charAt(i) != s.charAt(j)) return false; } } int c = 0; // Traverse subString of length K for (int i = 0; i < k; i++) { // If current character is 0 if (s.charAt(i) == '0') // Increment count c++; // Otherwise else // Decrement count c--; } // Check for equal 0s and 1s if (c == 0) return true; else return false;} // Driver codepublic static void main(String[] args){ String s = \"101010\"; int k = 2; if (check(s, k)) System.out.print(\"Yes\" + \"\\n\"); else System.out.print(\"No\" + \"\\n\");}} // This code is contributed by 29AjayKumar",
"e": 28569,
"s": 27595,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to check if the substring# of length K has equal 0 and 1def check(s, k): n = len(s) # Traverse the string for i in range(k): for j in range(i, n, k): # Check if every K-th character # is the same or not if (s[i] != s[j]): return False c = 0 # Traverse substring of length K for i in range(k): # If current character is 0 if (s[i] == '0'): # Increment count c += 1 # Otherwise else: # Decrement count c -= 1 # Check for equal 0s and 1s if (c == 0): return True else: return False # Driver codes = \"101010\"k = 2 if (check(s, k) != 0): print(\"Yes\")else: print(\"No\") # This code is contributed by sanjoy_62",
"e": 29461,
"s": 28569,
"text": null
},
{
"code": "// C# program for// the above approachusing System;class GFG{ // Function to check if the substring// of length K has equal 0 and 1static bool check(String s, int k){ int n = s.Length; // Traverse the String for (int i = 0; i < k; i++) { for (int j = i; j < n; j += k) { // Check if every K-th character // is the same or not if (s[i] != s[j]) return false; } } int c = 0; // Traverse subString of length K for (int i = 0; i < k; i++) { // If current character is 0 if (s[i] == '0') // Increment count c++; // Otherwise else // Decrement count c--; } // Check for equal 0s and 1s if (c == 0) return true; else return false;} // Driver codepublic static void Main(String[] args){ String s = \"101010\"; int k = 2; if (check(s, k)) Console.Write(\"Yes\" + \"\\n\"); else Console.Write(\"No\" + \"\\n\");}} // This code is contributed by Rajput-Ji",
"e": 30393,
"s": 29461,
"text": null
},
{
"code": "<script>// javascript program for the// above approach // Function to check if the substring// of length K has equal 0 and 1function check(s, k){ let n = s.length; // Traverse the String for (let i = 0; i < k; i++) { for (let j = i; j < n; j += k) { // Check if every K-th character // is the same or not if (s[i] != s[j]) return false; } } let c = 0; // Traverse subString of length K for (let i = 0; i < k; i++) { // If current character is 0 if (s[i]== '0') // Increment count c++; // Otherwise else // Decrement count c--; } // Check for equal 0s and 1s if (c == 0) return true; else return false;} // Driver Code let s = \"101010\"; let k = 2; if (check(s, k)) document.write(\"Yes\" + \"<br/>\"); else document.write(\"No\"); // This code is contributed by target_2.</script>",
"e": 31278,
"s": 30393,
"text": null
},
{
"code": null,
"e": 31282,
"s": 31278,
"text": "Yes"
},
{
"code": null,
"e": 31328,
"s": 31284,
"text": "Time Complexity: O(N)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 31340,
"s": 31328,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31350,
"s": 31340,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31360,
"s": 31350,
"text": "sanjoy_62"
},
{
"code": null,
"e": 31369,
"s": 31360,
"text": "target_2"
},
{
"code": null,
"e": 31388,
"s": 31369,
"text": "frequency-counting"
},
{
"code": null,
"e": 31398,
"s": 31388,
"text": "substring"
},
{
"code": null,
"e": 31405,
"s": 31398,
"text": "Greedy"
},
{
"code": null,
"e": 31423,
"s": 31405,
"text": "Pattern Searching"
},
{
"code": null,
"e": 31433,
"s": 31423,
"text": "Searching"
},
{
"code": null,
"e": 31441,
"s": 31433,
"text": "Strings"
},
{
"code": null,
"e": 31451,
"s": 31441,
"text": "Searching"
},
{
"code": null,
"e": 31459,
"s": 31451,
"text": "Strings"
},
{
"code": null,
"e": 31466,
"s": 31459,
"text": "Greedy"
},
{
"code": null,
"e": 31484,
"s": 31466,
"text": "Pattern Searching"
},
{
"code": null,
"e": 31582,
"s": 31484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31591,
"s": 31582,
"text": "Comments"
},
{
"code": null,
"e": 31604,
"s": 31591,
"text": "Old Comments"
},
{
"code": null,
"e": 31657,
"s": 31604,
"text": "Program for First Fit algorithm in Memory Management"
},
{
"code": null,
"e": 31709,
"s": 31657,
"text": "Program for Best Fit algorithm in Memory Management"
},
{
"code": null,
"e": 31744,
"s": 31709,
"text": "Optimal Page Replacement Algorithm"
},
{
"code": null,
"e": 31797,
"s": 31744,
"text": "Program for Worst Fit algorithm in Memory Management"
},
{
"code": null,
"e": 31827,
"s": 31797,
"text": "Max Flow Problem Introduction"
},
{
"code": null,
"e": 31863,
"s": 31827,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 31906,
"s": 31863,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 31944,
"s": 31906,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 31986,
"s": 31944,
"text": "Check if a string is substring of another"
}
] |
How to get a list of MySQL views? | To get a list of MySQL views, we can use the SELECT command with LIKE operator. Let us see the syntax first.
mysql> SELECT TABLE_SCHEMA, TABLE_NAME
-> FROM information_schema.tables
-> WHERE TABLE_TYPE LIKE 'VIEW';
The following is the output that displays the total number of views.
+--------------+-----------------------------------------------+
| TABLE_SCHEMA | TABLE_NAME |
+--------------+-----------------------------------------------+
| sys | version |
| sys | innodb_buffer_stats_by_schema |
| sys | x$innodb_buffer_stats_by_schema |
| sys | innodb_buffer_stats_by_table |
| sys | x$innodb_buffer_stats_by_table |
| sys | schema_object_overview |
| sys | schema_auto_increment_columns |
| sys | x$schema_flattened_keys |
| sys | schema_redundant_indexes |
| sys | ps_check_lost_instrumentation |
| sys | latest_file_io |
| sys | x$latest_file_io |
| sys | io_by_thread_by_latency |
| sys | x$io_by_thread_by_latency |
| sys | io_global_by_file_by_bytes |
| sys | x$io_global_by_file_by_bytes |
| sys | io_global_by_file_by_latency |
| sys | x$io_global_by_file_by_latency |
| sys | io_global_by_wait_by_bytes |
| sys | x$io_global_by_wait_by_bytes |
| sys | io_global_by_wait_by_latency |
| sys | x$io_global_by_wait_by_latency |
| sys | innodb_lock_waits |
| sys | x$innodb_lock_waits |
| sys | memory_by_user_by_current_bytes |
| sys | x$memory_by_user_by_current_bytes |
| sys | memory_by_host_by_current_bytes |
| sys | x$memory_by_host_by_current_bytes |
| sys | memory_by_thread_by_current_bytes |
| sys | x$memory_by_thread_by_current_bytes |
| sys | memory_global_by_current_bytes |
| sys | x$memory_global_by_current_bytes |
| sys | memory_global_total |
| sys | x$memory_global_total |
| sys | schema_index_statistics |
| sys | x$schema_index_statistics |
| sys | x$ps_schema_table_statistics_io |
| sys | schema_table_statistics |
| sys | x$schema_table_statistics |
| sys | schema_table_statistics_with_buffer |
| sys | x$schema_table_statistics_with_buffer |
| sys | schema_tables_with_full_table_scans |
| sys | x$schema_tables_with_full_table_scans |
| sys | schema_unused_indexes |
| sys | schema_table_lock_waits |
| sys | x$schema_table_lock_waits |
| sys | statement_analysis |
| sys | x$statement_analysis |
| sys | statements_with_errors_or_warnings |
| sys | x$statements_with_errors_or_warnings |
| sys | statements_with_full_table_scans |
| sys | x$statements_with_full_table_scans |
| sys | x$ps_digest_avg_latency_distribution |
| sys | x$ps_digest_95th_percentile_by_avg_us |
| sys | statements_with_runtimes_in_95th_percentile |
| sys | x$statements_with_runtimes_in_95th_percentile |
| sys | statements_with_sorting |
| sys | x$statements_with_sorting |
| sys | statements_with_temp_tables |
| sys | x$statements_with_temp_tables |
| sys | user_summary_by_file_io_type |
| sys | x$user_summary_by_file_io_type |
| sys | user_summary_by_file_io |
| sys | x$user_summary_by_file_io |
| sys | user_summary_by_statement_type |
| sys | x$user_summary_by_statement_type |
| sys | user_summary_by_statement_latency |
| sys | x$user_summary_by_statement_latency |
| sys | user_summary_by_stages |
| sys | x$user_summary_by_stages |
| sys | user_summary |
| sys | x$user_summary |
| sys | host_summary_by_file_io_type |
| sys | x$host_summary_by_file_io_type |
| sys | host_summary_by_file_io |
| sys | x$host_summary_by_file_io |
| sys | host_summary_by_statement_type |
| sys | x$host_summary_by_statement_type |
| sys | host_summary_by_statement_latency |
| sys | x$host_summary_by_statement_latency |
| sys | host_summary_by_stages |
| sys | x$host_summary_by_stages |
| sys | host_summary |
| sys | x$host_summary |
| sys | wait_classes_global_by_avg_latency |
| sys | x$wait_classes_global_by_avg_latency |
| sys | wait_classes_global_by_latency |
| sys | x$wait_classes_global_by_latency |
| sys | waits_by_user_by_latency |
| sys | x$waits_by_user_by_latency |
| sys | waits_by_host_by_latency |
| sys | x$waits_by_host_by_latency |
| sys | waits_global_by_latency |
| sys | x$waits_global_by_latency |
| sys | metrics |
| sys | processlist |
| sys | x$processlist |
| sys | session |
| sys | x$session |
| sys | session_ssl_status |
+--------------+-----------------------------------------------+
100 rows in set (0.01 sec) | [
{
"code": null,
"e": 1171,
"s": 1062,
"text": "To get a list of MySQL views, we can use the SELECT command with LIKE operator. Let us see the syntax first."
},
{
"code": null,
"e": 1283,
"s": 1171,
"text": "mysql> SELECT TABLE_SCHEMA, TABLE_NAME\n -> FROM information_schema.tables\n -> WHERE TABLE_TYPE LIKE 'VIEW';"
},
{
"code": null,
"e": 1352,
"s": 1283,
"text": "The following is the output that displays the total number of views."
},
{
"code": null,
"e": 8140,
"s": 1352,
"text": "+--------------+-----------------------------------------------+\n| TABLE_SCHEMA | TABLE_NAME |\n+--------------+-----------------------------------------------+\n| sys | version |\n| sys | innodb_buffer_stats_by_schema |\n| sys | x$innodb_buffer_stats_by_schema |\n| sys | innodb_buffer_stats_by_table |\n| sys | x$innodb_buffer_stats_by_table |\n| sys | schema_object_overview |\n| sys | schema_auto_increment_columns |\n| sys | x$schema_flattened_keys |\n| sys | schema_redundant_indexes |\n| sys | ps_check_lost_instrumentation |\n| sys | latest_file_io |\n| sys | x$latest_file_io |\n| sys | io_by_thread_by_latency |\n| sys | x$io_by_thread_by_latency |\n| sys | io_global_by_file_by_bytes |\n| sys | x$io_global_by_file_by_bytes |\n| sys | io_global_by_file_by_latency |\n| sys | x$io_global_by_file_by_latency |\n| sys | io_global_by_wait_by_bytes |\n| sys | x$io_global_by_wait_by_bytes |\n| sys | io_global_by_wait_by_latency |\n| sys | x$io_global_by_wait_by_latency |\n| sys | innodb_lock_waits |\n| sys | x$innodb_lock_waits |\n| sys | memory_by_user_by_current_bytes |\n| sys | x$memory_by_user_by_current_bytes |\n| sys | memory_by_host_by_current_bytes |\n| sys | x$memory_by_host_by_current_bytes |\n| sys | memory_by_thread_by_current_bytes |\n| sys | x$memory_by_thread_by_current_bytes |\n| sys | memory_global_by_current_bytes |\n| sys | x$memory_global_by_current_bytes |\n| sys | memory_global_total |\n| sys | x$memory_global_total |\n| sys | schema_index_statistics |\n| sys | x$schema_index_statistics |\n| sys | x$ps_schema_table_statistics_io |\n| sys | schema_table_statistics |\n| sys | x$schema_table_statistics |\n| sys | schema_table_statistics_with_buffer |\n| sys | x$schema_table_statistics_with_buffer |\n| sys | schema_tables_with_full_table_scans |\n| sys | x$schema_tables_with_full_table_scans |\n| sys | schema_unused_indexes |\n| sys | schema_table_lock_waits |\n| sys | x$schema_table_lock_waits |\n| sys | statement_analysis |\n| sys | x$statement_analysis |\n| sys | statements_with_errors_or_warnings |\n| sys | x$statements_with_errors_or_warnings |\n| sys | statements_with_full_table_scans |\n| sys | x$statements_with_full_table_scans |\n| sys | x$ps_digest_avg_latency_distribution |\n| sys | x$ps_digest_95th_percentile_by_avg_us |\n| sys | statements_with_runtimes_in_95th_percentile |\n| sys | x$statements_with_runtimes_in_95th_percentile |\n| sys | statements_with_sorting |\n| sys | x$statements_with_sorting |\n| sys | statements_with_temp_tables |\n| sys | x$statements_with_temp_tables |\n| sys | user_summary_by_file_io_type |\n| sys | x$user_summary_by_file_io_type |\n| sys | user_summary_by_file_io |\n| sys | x$user_summary_by_file_io |\n| sys | user_summary_by_statement_type |\n| sys | x$user_summary_by_statement_type |\n| sys | user_summary_by_statement_latency |\n| sys | x$user_summary_by_statement_latency |\n| sys | user_summary_by_stages |\n| sys | x$user_summary_by_stages |\n| sys | user_summary |\n| sys | x$user_summary |\n| sys | host_summary_by_file_io_type |\n| sys | x$host_summary_by_file_io_type |\n| sys | host_summary_by_file_io |\n| sys | x$host_summary_by_file_io |\n| sys | host_summary_by_statement_type |\n| sys | x$host_summary_by_statement_type |\n| sys | host_summary_by_statement_latency |\n| sys | x$host_summary_by_statement_latency |\n| sys | host_summary_by_stages |\n| sys | x$host_summary_by_stages |\n| sys | host_summary |\n| sys | x$host_summary |\n| sys | wait_classes_global_by_avg_latency |\n| sys | x$wait_classes_global_by_avg_latency |\n| sys | wait_classes_global_by_latency |\n| sys | x$wait_classes_global_by_latency |\n| sys | waits_by_user_by_latency |\n| sys | x$waits_by_user_by_latency |\n| sys | waits_by_host_by_latency |\n| sys | x$waits_by_host_by_latency |\n| sys | waits_global_by_latency |\n| sys | x$waits_global_by_latency |\n| sys | metrics |\n| sys | processlist |\n| sys | x$processlist |\n| sys | session |\n| sys | x$session |\n| sys | session_ssl_status |\n+--------------+-----------------------------------------------+\n100 rows in set (0.01 sec)\n"
}
] |
How to Update Data to SQLite Database in Android? - GeeksforGeeks | 25 Feb, 2021
We have seen How to Create and Add Data to SQLite Database in Android as well as How to Read Data from SQLite Database in Android. We have performed different SQL queries for reading and writing our data to SQLite database. In this article, we will take a look at updating data to SQLite database in Android.
We will be building a simple application in which we were already adding as well as reading the data. Now we will simply update our data in a new activity and we can get to see the updated data. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Creating a new activity for updating our course
As we want to update our course, so for this process we will be creating a new activity where we will be able to update our courses in the SQLite database. To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as UpdateCourseActivity and create new Activity. Make sure to select the empty activity.
Step 2: Working with the activity_update_course.xml file
Navigate to the app > res > Layout > activity_update_course.xml and add the below code to it.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".UpdateCourseActivity"> <!--Edit text to enter course name--> <EditText android:id="@+id/idEdtCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter course Name" /> <!--edit text to enter course duration--> <EditText android:id="@+id/idEdtCourseDuration" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Duration" /> <!--edit text to display course tracks--> <EditText android:id="@+id/idEdtCourseTracks" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Tracks" /> <!--edit text for course description--> <EditText android:id="@+id/idEdtCourseDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Description" /> <!--button for updating our course--> <Button android:id="@+id/idBtnUpdateCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Update Course" android:textAllCaps="false" /> </LinearLayout>
Step 3: Updating our DBHandler class
Navigate to the app > java > your app’s package name > DBHandler and add the below code to it. In this, we simply have to create a new method to update our course.
Java
// below is the method for updating our coursespublic void updateCourse(String originalCourseName, String courseName, String courseDescription, String courseTracks, String courseDuration) { // calling a method to get writable database. SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, courseName); values.put(DURATION_COL, courseDuration); values.put(DESCRIPTION_COL, courseDescription); values.put(TRACKS_COL, courseTracks); // on below line we are calling a update method to update our database and passing our values. // and we are comparing it with name of our course which is stored in original name variable. db.update(TABLE_NAME, values, "name=?", new String[]{originalCourseName}); db.close();}
Below is the updated code for the DBHandler.java file after adding the above code snippet.
Java
import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; public class DBHandler extends SQLiteOpenHelper { // creating a constant variables for our database. // below variable is for our database name. private static final String DB_NAME = "coursedb"; // below int is our database version private static final int DB_VERSION = 1; // below variable is for our table name. private static final String TABLE_NAME = "mycourses"; // below variable is for our id column. private static final String ID_COL = "id"; // below variable is for our course name column private static final String NAME_COL = "name"; // below variable id for our course duration column. private static final String DURATION_COL = "duration"; // below variable for our course description column. private static final String DESCRIPTION_COL = "description"; // below variable is for our course tracks column. private static final String TRACKS_COL = "tracks"; // creating a constructor for our database handler. public DBHandler(Context context) { super(context, DB_NAME, null, DB_VERSION); } // below method is for creating a database by running a sqlite query @Override public void onCreate(SQLiteDatabase db) { // on below line we are creating // an sqlite query and we are // setting our column names // along with their data types. String query = "CREATE TABLE " + TABLE_NAME + " (" + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME_COL + " TEXT," + DURATION_COL + " TEXT," + DESCRIPTION_COL + " TEXT," + TRACKS_COL + " TEXT)"; // at last we are calling a exec sql // method to execute above sql query db.execSQL(query); } // this method is use to add new course to our sqlite database. public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) { // on below line we are creating a variable for // our sqlite database and calling writable method // as we are writing data in our database. SQLiteDatabase db = this.getWritableDatabase(); // on below line we are creating a // variable for content values. ContentValues values = new ContentValues(); // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, courseName); values.put(DURATION_COL, courseDuration); values.put(DESCRIPTION_COL, courseDescription); values.put(TRACKS_COL, courseTracks); // after adding all values we are passing // content values to our table. db.insert(TABLE_NAME, null, values); // at last we are closing our // database after adding database. db.close(); } // we have created a new method for reading all the courses. public ArrayList<CourseModal> readCourses() { // on below line we are creating a // database for reading our database. SQLiteDatabase db = this.getReadableDatabase(); // on below line we are creating a cursor with query to read data from database. Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null); // on below line we are creating a new array list. ArrayList<CourseModal> courseModalArrayList = new ArrayList<>(); // moving our cursor to first position. if (cursorCourses.moveToFirst()) { do { // on below line we are adding the data from cursor to our array list. courseModalArrayList.add(new CourseModal(cursorCourses.getString(1), cursorCourses.getString(4), cursorCourses.getString(2), cursorCourses.getString(3))); } while (cursorCourses.moveToNext()); // moving our cursor to next. } // at last closing our cursor // and returning our array list. cursorCourses.close(); return courseModalArrayList; } // below is the method for updating our courses public void updateCourse(String originalCourseName, String courseName, String courseDescription, String courseTracks, String courseDuration) { // calling a method to get writable database. SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, courseName); values.put(DURATION_COL, courseDuration); values.put(DESCRIPTION_COL, courseDescription); values.put(TRACKS_COL, courseTracks); // on below line we are calling a update method to update our database and passing our values. // and we are comparing it with name of our course which is stored in original name variable. db.update(TABLE_NAME, values, "name=?", new String[]{originalCourseName}); db.close(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // this method is called to check if the table exists already. db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); }}
Step 4: Updating our CourseRVAdapter.java class
As we will be opening a new activity to update our course. We have to add on click listener for the items of our RecycleView. For adding onClickListener() to our recycler view items navigate to the app > java > your app’s package name > CourseRVAdapter class and simply add an onClickListener() for our RecyclerView item. Add the below code to your adapter class.
Java
// below line is to add on click listener for our recycler view item.holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are calling an intent. Intent i = new Intent(context, UpdateCourseActivity.class); // below we are passing all our values. i.putExtra("name", modal.getCourseName()); i.putExtra("description", modal.getCourseDescription()); i.putExtra("duration", modal.getCourseDuration()); i.putExtra("tracks", modal.getCourseTracks()); // starting our activity. context.startActivity(i); }});
Below is the updated code for the CourseRVAdapter.java file after adding the above code snippet.
Java
import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> { // variable for our array list and context private ArrayList<CourseModal> courseModalArrayList; private Context context; // constructor public CourseRVAdapter(ArrayList<CourseModal> courseModalArrayList, Context context) { this.courseModalArrayList = courseModalArrayList; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // on below line we are inflating our layout // file for our recycler view items. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // on below line we are setting data // to our views of recycler view item. CourseModal modal = courseModalArrayList.get(position); holder.courseNameTV.setText(modal.getCourseName()); holder.courseDescTV.setText(modal.getCourseDescription()); holder.courseDurationTV.setText(modal.getCourseDuration()); holder.courseTracksTV.setText(modal.getCourseTracks()); // below line is to add on click listener for our recycler view item. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are calling an intent. Intent i = new Intent(context, UpdateCourseActivity.class); // below we are passing all our values. i.putExtra("name", modal.getCourseName()); i.putExtra("description", modal.getCourseDescription()); i.putExtra("duration", modal.getCourseDuration()); i.putExtra("tracks", modal.getCourseTracks()); // starting our activity. context.startActivity(i); } }); } @Override public int getItemCount() { // returning the size of our array list return courseModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our text views. private TextView courseNameTV, courseDescTV, courseDurationTV, courseTracksTV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our text views courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); courseTracksTV = itemView.findViewById(R.id.idTVCourseTracks); } }}
Step 5: Working with the UpdateCourseActivity.java file
Navigate to the app > java > your app’s package name > UpdateCourseActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class UpdateCourseActivity extends AppCompatActivity { // variables for our edit text, button, strings and dbhandler class. private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt; private Button updateCourseBtn; private DBHandler dbHandler; String courseName, courseDesc, courseDuration, courseTracks; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_course); // initializing all our variables. courseNameEdt = findViewById(R.id.idEdtCourseName); courseTracksEdt = findViewById(R.id.idEdtCourseTracks); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); updateCourseBtn = findViewById(R.id.idBtnUpdateCourse); // on below line we are initialing our dbhandler class. dbHandler = new DBHandler(UpdateCourseActivity.this); // on below lines we are getting data which // we passed in our adapter class. courseName = getIntent().getStringExtra("name"); courseDesc = getIntent().getStringExtra("description"); courseDuration = getIntent().getStringExtra("duration"); courseTracks = getIntent().getStringExtra("tracks"); // setting data to edit text // of our update activity. courseNameEdt.setText(courseName); courseDescriptionEdt.setText(courseDesc); courseTracksEdt.setText(courseTracks); courseDurationEdt.setText(courseDuration); // adding on click listener to our update course button. updateCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside this method we are calling an update course // method and passing all our edit text values. dbHandler.updateCourse(courseName, courseNameEdt.getText().toString(), courseDescriptionEdt.getText().toString(), courseTracksEdt.getText().toString(), courseDurationEdt.getText().toString()); // displaying a toast message that our course has been updated. Toast.makeText(UpdateCourseActivity.this, "Course Updated..", Toast.LENGTH_SHORT).show(); // launching our main activity. Intent i = new Intent(UpdateCourseActivity.this, MainActivity.class); startActivity(i); } }); }}
Now run your app and see the output of the app. Make sure to add data to the SQLite database before updating it.
Below is the complete project file structure after performing the update operation:
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
GridView in Android with Example
How to Post Data to API using Retrofit in Android?
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 | [
{
"code": null,
"e": 25142,
"s": 25114,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 25452,
"s": 25142,
"text": "We have seen How to Create and Add Data to SQLite Database in Android as well as How to Read Data from SQLite Database in Android. We have performed different SQL queries for reading and writing our data to SQLite database. In this article, we will take a look at updating data to SQLite database in Android. "
},
{
"code": null,
"e": 25814,
"s": 25452,
"text": "We will be building a simple application in which we were already adding as well as reading the data. Now we will simply update our data in a new activity and we can get to see the updated data. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25870,
"s": 25814,
"text": "Step 1: Creating a new activity for updating our course"
},
{
"code": null,
"e": 26281,
"s": 25870,
"text": "As we want to update our course, so for this process we will be creating a new activity where we will be able to update our courses in the SQLite database. To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as UpdateCourseActivity and create new Activity. Make sure to select the empty activity. "
},
{
"code": null,
"e": 26338,
"s": 26281,
"text": "Step 2: Working with the activity_update_course.xml file"
},
{
"code": null,
"e": 26433,
"s": 26338,
"text": "Navigate to the app > res > Layout > activity_update_course.xml and add the below code to it. "
},
{
"code": null,
"e": 26437,
"s": 26433,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".UpdateCourseActivity\"> <!--Edit text to enter course name--> <EditText android:id=\"@+id/idEdtCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter course Name\" /> <!--edit text to enter course duration--> <EditText android:id=\"@+id/idEdtCourseDuration\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Duration\" /> <!--edit text to display course tracks--> <EditText android:id=\"@+id/idEdtCourseTracks\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Tracks\" /> <!--edit text for course description--> <EditText android:id=\"@+id/idEdtCourseDescription\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Description\" /> <!--button for updating our course--> <Button android:id=\"@+id/idBtnUpdateCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:text=\"Update Course\" android:textAllCaps=\"false\" /> </LinearLayout>",
"e": 28160,
"s": 26437,
"text": null
},
{
"code": null,
"e": 28197,
"s": 28160,
"text": "Step 3: Updating our DBHandler class"
},
{
"code": null,
"e": 28362,
"s": 28197,
"text": "Navigate to the app > java > your app’s package name > DBHandler and add the below code to it. In this, we simply have to create a new method to update our course. "
},
{
"code": null,
"e": 28367,
"s": 28362,
"text": "Java"
},
{
"code": "// below is the method for updating our coursespublic void updateCourse(String originalCourseName, String courseName, String courseDescription, String courseTracks, String courseDuration) { // calling a method to get writable database. SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, courseName); values.put(DURATION_COL, courseDuration); values.put(DESCRIPTION_COL, courseDescription); values.put(TRACKS_COL, courseTracks); // on below line we are calling a update method to update our database and passing our values. // and we are comparing it with name of our course which is stored in original name variable. db.update(TABLE_NAME, values, \"name=?\", new String[]{originalCourseName}); db.close();}",
"e": 29364,
"s": 28367,
"text": null
},
{
"code": null,
"e": 29455,
"s": 29364,
"text": "Below is the updated code for the DBHandler.java file after adding the above code snippet."
},
{
"code": null,
"e": 29460,
"s": 29455,
"text": "Java"
},
{
"code": "import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; public class DBHandler extends SQLiteOpenHelper { // creating a constant variables for our database. // below variable is for our database name. private static final String DB_NAME = \"coursedb\"; // below int is our database version private static final int DB_VERSION = 1; // below variable is for our table name. private static final String TABLE_NAME = \"mycourses\"; // below variable is for our id column. private static final String ID_COL = \"id\"; // below variable is for our course name column private static final String NAME_COL = \"name\"; // below variable id for our course duration column. private static final String DURATION_COL = \"duration\"; // below variable for our course description column. private static final String DESCRIPTION_COL = \"description\"; // below variable is for our course tracks column. private static final String TRACKS_COL = \"tracks\"; // creating a constructor for our database handler. public DBHandler(Context context) { super(context, DB_NAME, null, DB_VERSION); } // below method is for creating a database by running a sqlite query @Override public void onCreate(SQLiteDatabase db) { // on below line we are creating // an sqlite query and we are // setting our column names // along with their data types. String query = \"CREATE TABLE \" + TABLE_NAME + \" (\" + ID_COL + \" INTEGER PRIMARY KEY AUTOINCREMENT, \" + NAME_COL + \" TEXT,\" + DURATION_COL + \" TEXT,\" + DESCRIPTION_COL + \" TEXT,\" + TRACKS_COL + \" TEXT)\"; // at last we are calling a exec sql // method to execute above sql query db.execSQL(query); } // this method is use to add new course to our sqlite database. public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) { // on below line we are creating a variable for // our sqlite database and calling writable method // as we are writing data in our database. SQLiteDatabase db = this.getWritableDatabase(); // on below line we are creating a // variable for content values. ContentValues values = new ContentValues(); // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, courseName); values.put(DURATION_COL, courseDuration); values.put(DESCRIPTION_COL, courseDescription); values.put(TRACKS_COL, courseTracks); // after adding all values we are passing // content values to our table. db.insert(TABLE_NAME, null, values); // at last we are closing our // database after adding database. db.close(); } // we have created a new method for reading all the courses. public ArrayList<CourseModal> readCourses() { // on below line we are creating a // database for reading our database. SQLiteDatabase db = this.getReadableDatabase(); // on below line we are creating a cursor with query to read data from database. Cursor cursorCourses = db.rawQuery(\"SELECT * FROM \" + TABLE_NAME, null); // on below line we are creating a new array list. ArrayList<CourseModal> courseModalArrayList = new ArrayList<>(); // moving our cursor to first position. if (cursorCourses.moveToFirst()) { do { // on below line we are adding the data from cursor to our array list. courseModalArrayList.add(new CourseModal(cursorCourses.getString(1), cursorCourses.getString(4), cursorCourses.getString(2), cursorCourses.getString(3))); } while (cursorCourses.moveToNext()); // moving our cursor to next. } // at last closing our cursor // and returning our array list. cursorCourses.close(); return courseModalArrayList; } // below is the method for updating our courses public void updateCourse(String originalCourseName, String courseName, String courseDescription, String courseTracks, String courseDuration) { // calling a method to get writable database. SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); // on below line we are passing all values // along with its key and value pair. values.put(NAME_COL, courseName); values.put(DURATION_COL, courseDuration); values.put(DESCRIPTION_COL, courseDescription); values.put(TRACKS_COL, courseTracks); // on below line we are calling a update method to update our database and passing our values. // and we are comparing it with name of our course which is stored in original name variable. db.update(TABLE_NAME, values, \"name=?\", new String[]{originalCourseName}); db.close(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // this method is called to check if the table exists already. db.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_NAME); onCreate(db); }}",
"e": 35000,
"s": 29460,
"text": null
},
{
"code": null,
"e": 35049,
"s": 35000,
"text": "Step 4: Updating our CourseRVAdapter.java class"
},
{
"code": null,
"e": 35414,
"s": 35049,
"text": "As we will be opening a new activity to update our course. We have to add on click listener for the items of our RecycleView. For adding onClickListener() to our recycler view items navigate to the app > java > your app’s package name > CourseRVAdapter class and simply add an onClickListener() for our RecyclerView item. Add the below code to your adapter class. "
},
{
"code": null,
"e": 35419,
"s": 35414,
"text": "Java"
},
{
"code": "// below line is to add on click listener for our recycler view item.holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are calling an intent. Intent i = new Intent(context, UpdateCourseActivity.class); // below we are passing all our values. i.putExtra(\"name\", modal.getCourseName()); i.putExtra(\"description\", modal.getCourseDescription()); i.putExtra(\"duration\", modal.getCourseDuration()); i.putExtra(\"tracks\", modal.getCourseTracks()); // starting our activity. context.startActivity(i); }});",
"e": 36174,
"s": 35419,
"text": null
},
{
"code": null,
"e": 36271,
"s": 36174,
"text": "Below is the updated code for the CourseRVAdapter.java file after adding the above code snippet."
},
{
"code": null,
"e": 36276,
"s": 36271,
"text": "Java"
},
{
"code": "import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> { // variable for our array list and context private ArrayList<CourseModal> courseModalArrayList; private Context context; // constructor public CourseRVAdapter(ArrayList<CourseModal> courseModalArrayList, Context context) { this.courseModalArrayList = courseModalArrayList; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // on below line we are inflating our layout // file for our recycler view items. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // on below line we are setting data // to our views of recycler view item. CourseModal modal = courseModalArrayList.get(position); holder.courseNameTV.setText(modal.getCourseName()); holder.courseDescTV.setText(modal.getCourseDescription()); holder.courseDurationTV.setText(modal.getCourseDuration()); holder.courseTracksTV.setText(modal.getCourseTracks()); // below line is to add on click listener for our recycler view item. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are calling an intent. Intent i = new Intent(context, UpdateCourseActivity.class); // below we are passing all our values. i.putExtra(\"name\", modal.getCourseName()); i.putExtra(\"description\", modal.getCourseDescription()); i.putExtra(\"duration\", modal.getCourseDuration()); i.putExtra(\"tracks\", modal.getCourseTracks()); // starting our activity. context.startActivity(i); } }); } @Override public int getItemCount() { // returning the size of our array list return courseModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our text views. private TextView courseNameTV, courseDescTV, courseDurationTV, courseTracksTV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our text views courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); courseTracksTV = itemView.findViewById(R.id.idTVCourseTracks); } }}",
"e": 39422,
"s": 36276,
"text": null
},
{
"code": null,
"e": 39479,
"s": 39422,
"text": "Step 5: Working with the UpdateCourseActivity.java file "
},
{
"code": null,
"e": 39669,
"s": 39479,
"text": "Navigate to the app > java > your app’s package name > UpdateCourseActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 39674,
"s": 39669,
"text": "Java"
},
{
"code": "import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class UpdateCourseActivity extends AppCompatActivity { // variables for our edit text, button, strings and dbhandler class. private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt; private Button updateCourseBtn; private DBHandler dbHandler; String courseName, courseDesc, courseDuration, courseTracks; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_course); // initializing all our variables. courseNameEdt = findViewById(R.id.idEdtCourseName); courseTracksEdt = findViewById(R.id.idEdtCourseTracks); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); updateCourseBtn = findViewById(R.id.idBtnUpdateCourse); // on below line we are initialing our dbhandler class. dbHandler = new DBHandler(UpdateCourseActivity.this); // on below lines we are getting data which // we passed in our adapter class. courseName = getIntent().getStringExtra(\"name\"); courseDesc = getIntent().getStringExtra(\"description\"); courseDuration = getIntent().getStringExtra(\"duration\"); courseTracks = getIntent().getStringExtra(\"tracks\"); // setting data to edit text // of our update activity. courseNameEdt.setText(courseName); courseDescriptionEdt.setText(courseDesc); courseTracksEdt.setText(courseTracks); courseDurationEdt.setText(courseDuration); // adding on click listener to our update course button. updateCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside this method we are calling an update course // method and passing all our edit text values. dbHandler.updateCourse(courseName, courseNameEdt.getText().toString(), courseDescriptionEdt.getText().toString(), courseTracksEdt.getText().toString(), courseDurationEdt.getText().toString()); // displaying a toast message that our course has been updated. Toast.makeText(UpdateCourseActivity.this, \"Course Updated..\", Toast.LENGTH_SHORT).show(); // launching our main activity. Intent i = new Intent(UpdateCourseActivity.this, MainActivity.class); startActivity(i); } }); }}",
"e": 42515,
"s": 39674,
"text": null
},
{
"code": null,
"e": 42629,
"s": 42515,
"text": "Now run your app and see the output of the app. Make sure to add data to the SQLite database before updating it. "
},
{
"code": null,
"e": 42713,
"s": 42629,
"text": "Below is the complete project file structure after performing the update operation:"
},
{
"code": null,
"e": 42737,
"s": 42713,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 42745,
"s": 42737,
"text": "Android"
},
{
"code": null,
"e": 42750,
"s": 42745,
"text": "Java"
},
{
"code": null,
"e": 42769,
"s": 42750,
"text": "Technical Scripter"
},
{
"code": null,
"e": 42774,
"s": 42769,
"text": "Java"
},
{
"code": null,
"e": 42782,
"s": 42774,
"text": "Android"
},
{
"code": null,
"e": 42880,
"s": 42782,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42919,
"s": 42880,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 42961,
"s": 42919,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 42999,
"s": 42961,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 43032,
"s": 42999,
"text": "GridView in Android with Example"
},
{
"code": null,
"e": 43083,
"s": 43032,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 43098,
"s": 43083,
"text": "Arrays in Java"
},
{
"code": null,
"e": 43142,
"s": 43098,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 43164,
"s": 43142,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 43200,
"s": 43164,
"text": "Arrays.sort() in Java with examples"
}
] |
Numbers in C++ | Normally, when we work with Numbers, we use primitive data types such as int, short, long, float and double, etc. The number data types, their possible values and number ranges have been explained while discussing C++ Data Types.
You have already defined numbers in various examples given in previous chapters. Here is another consolidated example to define various types of numbers in C++ −
#include <iostream>
using namespace std;
int main () {
// number definition:
short s;
int i;
long l;
float f;
double d;
// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// number printing;
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4
In addition to the various functions you can create, C++ also includes some useful functions you can use. These functions are available in standard C and C++ libraries and called built-in functions. These are functions that can be included in your program and then use.
C++ has a rich set of mathematical operations, which can be performed on various numbers. Following table lists down some useful built-in mathematical functions available in C++.
To utilize these functions you need to include the math header file <cmath>.
double cos(double);
This function takes an angle (as a double) and returns the cosine.
double sin(double);
This function takes an angle (as a double) and returns the sine.
double tan(double);
This function takes an angle (as a double) and returns the tangent.
double log(double);
This function takes a number and returns the natural log of that number.
double pow(double, double);
The first is a number you wish to raise and the second is the power you wish to raise it t
double hypot(double, double);
If you pass this function the length of two sides of a right triangle, it will return you the length of the hypotenuse.
double sqrt(double);
You pass this function a number and it gives you the square root.
int abs(int);
This function returns the absolute value of an integer that is passed to it.
double fabs(double);
This function returns the absolute value of any decimal number passed to it.
double floor(double);
Finds the integer which is less than or equal to the argument passed to it.
Following is a simple example to show few of the mathematical operations −
#include <iostream>
#include <cmath>
using namespace std;
int main () {
// number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// mathematical operations;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow( d, 2) :" << pow(d, 2) << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
sign(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
There are many cases where you will wish to generate a random number. There are actually two functions you will need to know about random number generation. The first is rand(), this function will only return a pseudo random number. The way to fix this is to first call the srand() function.
Following is a simple example to generate few random numbers. This example makes use of time() function to get the number of seconds on your system time, to randomly seed the rand() function −
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main () {
int i,j;
// set the seed
srand( (unsigned)time( NULL ) );
/* generate 10 random numbers. */
for( i = 0; i < 10; i++ ) {
// generate actual random number
j = rand();
cout <<" Random Number : " << j << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Random Number : 1748144778
Random Number : 630873888
Random Number : 2134540646
Random Number : 219404170
Random Number : 902129458
Random Number : 920445370
Random Number : 1319072661
Random Number : 257938873
Random Number : 1256201101
Random Number : 580322989
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2548,
"s": 2318,
"text": "Normally, when we work with Numbers, we use primitive data types such as int, short, long, float and double, etc. The number data types, their possible values and number ranges have been explained while discussing C++ Data Types."
},
{
"code": null,
"e": 2710,
"s": 2548,
"text": "You have already defined numbers in various examples given in previous chapters. Here is another consolidated example to define various types of numbers in C++ −"
},
{
"code": null,
"e": 3207,
"s": 2710,
"text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // number definition:\n short s;\n int i;\n long l;\n float f;\n double d;\n \n // number assignments;\n s = 10; \n i = 1000; \n l = 1000000; \n f = 230.47; \n d = 30949.374;\n \n // number printing;\n cout << \"short s :\" << s << endl;\n cout << \"int i :\" << i << endl;\n cout << \"long l :\" << l << endl;\n cout << \"float f :\" << f << endl;\n cout << \"double d :\" << d << endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 3288,
"s": 3207,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3370,
"s": 3288,
"text": "short s :10\nint i :1000\nlong l :1000000\nfloat f :230.47\ndouble d :30949.4\n"
},
{
"code": null,
"e": 3640,
"s": 3370,
"text": "In addition to the various functions you can create, C++ also includes some useful functions you can use. These functions are available in standard C and C++ libraries and called built-in functions. These are functions that can be included in your program and then use."
},
{
"code": null,
"e": 3819,
"s": 3640,
"text": "C++ has a rich set of mathematical operations, which can be performed on various numbers. Following table lists down some useful built-in mathematical functions available in C++."
},
{
"code": null,
"e": 3896,
"s": 3819,
"text": "To utilize these functions you need to include the math header file <cmath>."
},
{
"code": null,
"e": 3916,
"s": 3896,
"text": "double cos(double);"
},
{
"code": null,
"e": 3983,
"s": 3916,
"text": "This function takes an angle (as a double) and returns the cosine."
},
{
"code": null,
"e": 4003,
"s": 3983,
"text": "double sin(double);"
},
{
"code": null,
"e": 4068,
"s": 4003,
"text": "This function takes an angle (as a double) and returns the sine."
},
{
"code": null,
"e": 4088,
"s": 4068,
"text": "double tan(double);"
},
{
"code": null,
"e": 4156,
"s": 4088,
"text": "This function takes an angle (as a double) and returns the tangent."
},
{
"code": null,
"e": 4176,
"s": 4156,
"text": "double log(double);"
},
{
"code": null,
"e": 4249,
"s": 4176,
"text": "This function takes a number and returns the natural log of that number."
},
{
"code": null,
"e": 4277,
"s": 4249,
"text": "double pow(double, double);"
},
{
"code": null,
"e": 4368,
"s": 4277,
"text": "The first is a number you wish to raise and the second is the power you wish to raise it t"
},
{
"code": null,
"e": 4398,
"s": 4368,
"text": "double hypot(double, double);"
},
{
"code": null,
"e": 4518,
"s": 4398,
"text": "If you pass this function the length of two sides of a right triangle, it will return you the length of the hypotenuse."
},
{
"code": null,
"e": 4539,
"s": 4518,
"text": "double sqrt(double);"
},
{
"code": null,
"e": 4605,
"s": 4539,
"text": "You pass this function a number and it gives you the square root."
},
{
"code": null,
"e": 4619,
"s": 4605,
"text": "int abs(int);"
},
{
"code": null,
"e": 4696,
"s": 4619,
"text": "This function returns the absolute value of an integer that is passed to it."
},
{
"code": null,
"e": 4717,
"s": 4696,
"text": "double fabs(double);"
},
{
"code": null,
"e": 4794,
"s": 4717,
"text": "This function returns the absolute value of any decimal number passed to it."
},
{
"code": null,
"e": 4816,
"s": 4794,
"text": "double floor(double);"
},
{
"code": null,
"e": 4892,
"s": 4816,
"text": "Finds the integer which is less than or equal to the argument passed to it."
},
{
"code": null,
"e": 4967,
"s": 4892,
"text": "Following is a simple example to show few of the mathematical operations −"
},
{
"code": null,
"e": 5440,
"s": 4967,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\n \nint main () {\n // number definition:\n short s = 10;\n int i = -1000;\n long l = 100000;\n float f = 230.47;\n double d = 200.374;\n\n // mathematical operations;\n cout << \"sin(d) :\" << sin(d) << endl;\n cout << \"abs(i) :\" << abs(i) << endl;\n cout << \"floor(d) :\" << floor(d) << endl;\n cout << \"sqrt(f) :\" << sqrt(f) << endl;\n cout << \"pow( d, 2) :\" << pow(d, 2) << endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 5521,
"s": 5440,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5622,
"s": 5521,
"text": "sign(d) :-0.634939\nabs(i) :1000\nfloor(d) :200\nsqrt(f) :15.1812\npow( d, 2 ) :40149.7\n"
},
{
"code": null,
"e": 5914,
"s": 5622,
"text": "There are many cases where you will wish to generate a random number. There are actually two functions you will need to know about random number generation. The first is rand(), this function will only return a pseudo random number. The way to fix this is to first call the srand() function."
},
{
"code": null,
"e": 6107,
"s": 5914,
"text": "Following is a simple example to generate few random numbers. This example makes use of time() function to get the number of seconds on your system time, to randomly seed the rand() function −"
},
{
"code": null,
"e": 6465,
"s": 6107,
"text": "#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nusing namespace std;\n \nint main () {\n int i,j;\n \n // set the seed\n srand( (unsigned)time( NULL ) );\n\n /* generate 10 random numbers. */\n for( i = 0; i < 10; i++ ) {\n // generate actual random number\n j = rand();\n cout <<\" Random Number : \" << j << endl;\n }\n\n return 0;\n}"
},
{
"code": null,
"e": 6546,
"s": 6465,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6811,
"s": 6546,
"text": "Random Number : 1748144778\nRandom Number : 630873888\nRandom Number : 2134540646\nRandom Number : 219404170\nRandom Number : 902129458\nRandom Number : 920445370\nRandom Number : 1319072661\nRandom Number : 257938873\nRandom Number : 1256201101\nRandom Number : 580322989\n"
},
{
"code": null,
"e": 6848,
"s": 6811,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 6867,
"s": 6848,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6899,
"s": 6867,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 6922,
"s": 6899,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6958,
"s": 6922,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 6975,
"s": 6958,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7010,
"s": 6975,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7027,
"s": 7010,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7062,
"s": 7027,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7079,
"s": 7062,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7114,
"s": 7079,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7131,
"s": 7114,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7138,
"s": 7131,
"text": " Print"
},
{
"code": null,
"e": 7149,
"s": 7138,
"text": " Add Notes"
}
] |
How to Mount a Directory Inside a Docker Container | by Mahbub Zaman | Towards Data Science | It works on my machine, let’s ship your machine then! That’s Docker in a nutshell. It allows us to run an application from a Docker image on any computer by using containerization technology. A Docker container is a package of a Base OS (alpine, ubuntu, etc.) and other necessary software dependencies, which you can define inside a docker image. Now you can use that image to create a container to run your application on different machines or even on the cloud platforms (AWS, GCP, Azure, etc.) without worrying about environment management (development, testing, and production).
Docker is one of the popular tools for DevOps for its portability, security, and performance. From this post, you’ll learn some basic concepts and commands of Docker that will teach you how to mount a directory inside a Docker container. I use Docker almost every day for local development — for example, you can see how I dockerized a Ruby on Rails application for a personal project, here.
First, you will need to install Docker. For demonstration purposes, we will use the pre-built official image of Ruby and macOS.
Docker Image: It’s a template containing instructions to create containers.
Docker Container: A Container is the running instance of an image.
The docker run command is used to run a container from an image. Here we are using the ruby image to create the container, but you can use your own image. If the ruby image does not exist on the host machine, Docker will pull that from Docker Hub. Once downloaded on your local machine, Docker uses the same image for consecutive container creation. To mount a volume, just run this line in your terminal
docker run -v /host/directory:/container/directory
Now you’re going to mount the scripts folder inside the scripts folder of the container. This is the best practice because you don’t have to worry about environment management on different machines.
docker run -it --rm -v $HOME/Desktop/scripts:/scripts --name scripts ruby bash
The flags -i -t (often written as -it) is used to access the container in an interactive mode. The --rm flag (optional) removes the container when you exit or stop it to free system resources (CPU, memory). If you don’t use that after you stop or exit the container, it has to be manually removed if you want to free disk space. The -v flag is used to mount a host folder, and it consists of two fields separated by a colon. The first part is the path in the host machine. The second part is the path in the container.
-v /host/directory:/container/directory
The--name flag (optional) is used to give the container a specific name. If you don’t want to provide one, Docker will randomly assign a name, so you may want to choose one specifically if you want to keep track of your containers more easily. The ruby command is used to load the image. If you want to use the 2.5 version of Ruby specifically, use the ruby:2.5 command.
docker run -it --rm -v $HOME/Desktop/scripts:/scripts --name scripts ruby:2.5 bash
Last but not least, the bash command is used to get a bash shell inside the container.
To run Python code, use the python image.
docker run -it --rm -v $HOME/Desktop/scripts:/scripts --name scripts python bash
As I explained above, if you want to free system resources and disk space, you need to stop and remove containers. You can run docker ps command on the host machine to see a list of your running containers. To stop a container, use the docker stop command with either the container id or container name. You can use the -a flag to see all the stopped or exited containers.
docker stop d61f09eb42ad# ordocker stop scripts
To manually remove a container, use one of the following commands.
docker rm d61f09eb42ad# ordocker rm scripts
In the case that you want to remove an image to free the disk space, for example, the Ruby image you just created, use the docker rmi command. But first, let’s try to understand what is going on under the hood. For that, we will use the docker images and docker system df commands to display information regarding disk space usage by the Docker daemon. The docker images command lists all the images you have in your machine.
The docker system df command tells me that I can only claim 65% of the disk space because I’m still running the scripts container, and that container is using the ruby image. If you add the remaining two images, you’ll get the 65% reclaimable disk space.
933MB (python) + 643MB (java) = 1.576GB (65%)
Alright, by running the docker system df command after stopping the container tells us that we can now claim 100% of disk space.
Be aware if you try to remove an image that's being used by a container, you’ll get the following error.
Error response from daemon: conflict: unable to delete 121862ceb25f (cannot be forced) — image is being used by running container d61f09eb42ad
Finally, we can use the docker rmi command with the image id to remove an image.
docker rmi 121862ceb25f# remove multiple images by putting a space between themdocker rmi efdecc2e377a d23bdf5b1b1b
Now you know how to mount a directory inside a docker container. Docker helps me immensely to create local development environments easily on multiple machines without any extra effort and time. It’s a skill you want to keep in your bag for both personal and industrial purposes. I hope this will help you to get started with the magical world of Docker. | [
{
"code": null,
"e": 754,
"s": 171,
"text": "It works on my machine, let’s ship your machine then! That’s Docker in a nutshell. It allows us to run an application from a Docker image on any computer by using containerization technology. A Docker container is a package of a Base OS (alpine, ubuntu, etc.) and other necessary software dependencies, which you can define inside a docker image. Now you can use that image to create a container to run your application on different machines or even on the cloud platforms (AWS, GCP, Azure, etc.) without worrying about environment management (development, testing, and production)."
},
{
"code": null,
"e": 1146,
"s": 754,
"text": "Docker is one of the popular tools for DevOps for its portability, security, and performance. From this post, you’ll learn some basic concepts and commands of Docker that will teach you how to mount a directory inside a Docker container. I use Docker almost every day for local development — for example, you can see how I dockerized a Ruby on Rails application for a personal project, here."
},
{
"code": null,
"e": 1274,
"s": 1146,
"text": "First, you will need to install Docker. For demonstration purposes, we will use the pre-built official image of Ruby and macOS."
},
{
"code": null,
"e": 1350,
"s": 1274,
"text": "Docker Image: It’s a template containing instructions to create containers."
},
{
"code": null,
"e": 1417,
"s": 1350,
"text": "Docker Container: A Container is the running instance of an image."
},
{
"code": null,
"e": 1822,
"s": 1417,
"text": "The docker run command is used to run a container from an image. Here we are using the ruby image to create the container, but you can use your own image. If the ruby image does not exist on the host machine, Docker will pull that from Docker Hub. Once downloaded on your local machine, Docker uses the same image for consecutive container creation. To mount a volume, just run this line in your terminal"
},
{
"code": null,
"e": 1873,
"s": 1822,
"text": "docker run -v /host/directory:/container/directory"
},
{
"code": null,
"e": 2072,
"s": 1873,
"text": "Now you’re going to mount the scripts folder inside the scripts folder of the container. This is the best practice because you don’t have to worry about environment management on different machines."
},
{
"code": null,
"e": 2151,
"s": 2072,
"text": "docker run -it --rm -v $HOME/Desktop/scripts:/scripts --name scripts ruby bash"
},
{
"code": null,
"e": 2670,
"s": 2151,
"text": "The flags -i -t (often written as -it) is used to access the container in an interactive mode. The --rm flag (optional) removes the container when you exit or stop it to free system resources (CPU, memory). If you don’t use that after you stop or exit the container, it has to be manually removed if you want to free disk space. The -v flag is used to mount a host folder, and it consists of two fields separated by a colon. The first part is the path in the host machine. The second part is the path in the container."
},
{
"code": null,
"e": 2710,
"s": 2670,
"text": "-v /host/directory:/container/directory"
},
{
"code": null,
"e": 3081,
"s": 2710,
"text": "The--name flag (optional) is used to give the container a specific name. If you don’t want to provide one, Docker will randomly assign a name, so you may want to choose one specifically if you want to keep track of your containers more easily. The ruby command is used to load the image. If you want to use the 2.5 version of Ruby specifically, use the ruby:2.5 command."
},
{
"code": null,
"e": 3164,
"s": 3081,
"text": "docker run -it --rm -v $HOME/Desktop/scripts:/scripts --name scripts ruby:2.5 bash"
},
{
"code": null,
"e": 3251,
"s": 3164,
"text": "Last but not least, the bash command is used to get a bash shell inside the container."
},
{
"code": null,
"e": 3293,
"s": 3251,
"text": "To run Python code, use the python image."
},
{
"code": null,
"e": 3374,
"s": 3293,
"text": "docker run -it --rm -v $HOME/Desktop/scripts:/scripts --name scripts python bash"
},
{
"code": null,
"e": 3747,
"s": 3374,
"text": "As I explained above, if you want to free system resources and disk space, you need to stop and remove containers. You can run docker ps command on the host machine to see a list of your running containers. To stop a container, use the docker stop command with either the container id or container name. You can use the -a flag to see all the stopped or exited containers."
},
{
"code": null,
"e": 3795,
"s": 3747,
"text": "docker stop d61f09eb42ad# ordocker stop scripts"
},
{
"code": null,
"e": 3862,
"s": 3795,
"text": "To manually remove a container, use one of the following commands."
},
{
"code": null,
"e": 3906,
"s": 3862,
"text": "docker rm d61f09eb42ad# ordocker rm scripts"
},
{
"code": null,
"e": 4332,
"s": 3906,
"text": "In the case that you want to remove an image to free the disk space, for example, the Ruby image you just created, use the docker rmi command. But first, let’s try to understand what is going on under the hood. For that, we will use the docker images and docker system df commands to display information regarding disk space usage by the Docker daemon. The docker images command lists all the images you have in your machine."
},
{
"code": null,
"e": 4587,
"s": 4332,
"text": "The docker system df command tells me that I can only claim 65% of the disk space because I’m still running the scripts container, and that container is using the ruby image. If you add the remaining two images, you’ll get the 65% reclaimable disk space."
},
{
"code": null,
"e": 4633,
"s": 4587,
"text": "933MB (python) + 643MB (java) = 1.576GB (65%)"
},
{
"code": null,
"e": 4762,
"s": 4633,
"text": "Alright, by running the docker system df command after stopping the container tells us that we can now claim 100% of disk space."
},
{
"code": null,
"e": 4867,
"s": 4762,
"text": "Be aware if you try to remove an image that's being used by a container, you’ll get the following error."
},
{
"code": null,
"e": 5010,
"s": 4867,
"text": "Error response from daemon: conflict: unable to delete 121862ceb25f (cannot be forced) — image is being used by running container d61f09eb42ad"
},
{
"code": null,
"e": 5091,
"s": 5010,
"text": "Finally, we can use the docker rmi command with the image id to remove an image."
},
{
"code": null,
"e": 5207,
"s": 5091,
"text": "docker rmi 121862ceb25f# remove multiple images by putting a space between themdocker rmi efdecc2e377a d23bdf5b1b1b"
}
] |
Apache Pig - MAX() | The Pig Latin MAX() function is used to calculate the highest value for a column (numeric values or chararrays) in a single-column bag. While calculating the maximum value, the Max() function ignores the NULL values.
Note −
To get the global maximum value, we need to perform a Group All operation, and calculate the maximum value using the MAX() function.
To get the global maximum value, we need to perform a Group All operation, and calculate the maximum value using the MAX() function.
To get the maximum value of a group, we need to group it using the Group By operator and proceed with the maximum function.
To get the maximum value of a group, we need to group it using the Group By operator and proceed with the maximum function.
Given below is the syntax of the Max() function.
grunt> Max(expression)
Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below.
student_details.txt
001,Rajiv,Reddy,21,9848022337,Hyderabad,89
002,siddarth,Battacharya,22,9848022338,Kolkata,78
003,Rajesh,Khanna,22,9848022339,Delhi,90
004,Preethi,Agarwal,21,9848022330,Pune,93
005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar,75
006,Archana,Mishra,23,9848022335,Chennai,87
007,Komal,Nayak,24,9848022334,trivendram,83
008,Bharathi,Nambiayar,24,9848022333,Chennai,72
And we have loaded this file into Pig with the relation name student_details as shown below.
grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',')
as (id:int, firstname:chararray, lastname:chararray, age:int, phone:chararray, city:chararray, gpa:int);
We can use the built-in function MAX() (case-sensitive) to calculate the maximum value from a set of given numerical values. Let us group the relation student_details using the Group All operator, and store the result in the relation named student_group_all as shown below.
grunt> student_group_all = Group student_details All;
This will produce a relation as shown below.
grunt> Dump student_group_all;
(all,{(8,Bharathi,Nambiayar,24,9848022333,Chennai,72),
(7,Komal,Nayak,24,9848022 334,trivendram,83),
(6,Archana,Mishra,23,9848022335,Chennai,87),
(5,Trupthi,Mohan thy,23,9848022336,Bhuwaneshwar,75),
(4,Preethi,Agarwal,21,9848022330,Pune,93),
(3,Rajesh,Khanna,22,9848022339,Delhi,90),
(2,siddarth,Battacharya,22,9848022338,Ko lkata,78),
(1,Rajiv,Reddy,21,9848022337,Hyderabad,89)})
Let us now calculate the global maximum of GPA, i.e., maximum among the GPA values of all the students using the MAX() function as shown below.
grunt> student_gpa_max = foreach student_group_all Generate
(student_details.firstname, student_details.gpa), MAX(student_details.gpa);
Verify the relation student_gpa_max using the DUMP operator as shown below.
grunt> Dump student_gpa_max;
It will produce the following output, displaying the contents of the relation student_gpa_max.
(({(Bharathi),(Komal),(Archana),(Trupthi),(Preethi),(Rajesh),(siddarth),(Rajiv) } ,
{ (72) , (83) , (87) , (75) , (93) , (90) , (78) , (89) }) ,93)
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": 2901,
"s": 2684,
"text": "The Pig Latin MAX() function is used to calculate the highest value for a column (numeric values or chararrays) in a single-column bag. While calculating the maximum value, the Max() function ignores the NULL values."
},
{
"code": null,
"e": 2908,
"s": 2901,
"text": "Note −"
},
{
"code": null,
"e": 3041,
"s": 2908,
"text": "To get the global maximum value, we need to perform a Group All operation, and calculate the maximum value using the MAX() function."
},
{
"code": null,
"e": 3174,
"s": 3041,
"text": "To get the global maximum value, we need to perform a Group All operation, and calculate the maximum value using the MAX() function."
},
{
"code": null,
"e": 3298,
"s": 3174,
"text": "To get the maximum value of a group, we need to group it using the Group By operator and proceed with the maximum function."
},
{
"code": null,
"e": 3422,
"s": 3298,
"text": "To get the maximum value of a group, we need to group it using the Group By operator and proceed with the maximum function."
},
{
"code": null,
"e": 3471,
"s": 3422,
"text": "Given below is the syntax of the Max() function."
},
{
"code": null,
"e": 3495,
"s": 3471,
"text": "grunt> Max(expression)\n"
},
{
"code": null,
"e": 3597,
"s": 3495,
"text": "Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below."
},
{
"code": null,
"e": 3617,
"s": 3597,
"text": "student_details.txt"
},
{
"code": null,
"e": 3989,
"s": 3617,
"text": "001,Rajiv,Reddy,21,9848022337,Hyderabad,89 \n002,siddarth,Battacharya,22,9848022338,Kolkata,78 \n003,Rajesh,Khanna,22,9848022339,Delhi,90 \n004,Preethi,Agarwal,21,9848022330,Pune,93 \n005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar,75 \n006,Archana,Mishra,23,9848022335,Chennai,87 \n007,Komal,Nayak,24,9848022334,trivendram,83 \n008,Bharathi,Nambiayar,24,9848022333,Chennai,72 \n"
},
{
"code": null,
"e": 4082,
"s": 3989,
"text": "And we have loaded this file into Pig with the relation name student_details as shown below."
},
{
"code": null,
"e": 4295,
"s": 4082,
"text": "grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',')\n as (id:int, firstname:chararray, lastname:chararray, age:int, phone:chararray, city:chararray, gpa:int);"
},
{
"code": null,
"e": 4569,
"s": 4295,
"text": "We can use the built-in function MAX() (case-sensitive) to calculate the maximum value from a set of given numerical values. Let us group the relation student_details using the Group All operator, and store the result in the relation named student_group_all as shown below."
},
{
"code": null,
"e": 4623,
"s": 4569,
"text": "grunt> student_group_all = Group student_details All;"
},
{
"code": null,
"e": 4668,
"s": 4623,
"text": "This will produce a relation as shown below."
},
{
"code": null,
"e": 5084,
"s": 4668,
"text": "grunt> Dump student_group_all;\n \n(all,{(8,Bharathi,Nambiayar,24,9848022333,Chennai,72),\n(7,Komal,Nayak,24,9848022 334,trivendram,83),\n(6,Archana,Mishra,23,9848022335,Chennai,87),\n(5,Trupthi,Mohan thy,23,9848022336,Bhuwaneshwar,75),\n(4,Preethi,Agarwal,21,9848022330,Pune,93),\n(3,Rajesh,Khanna,22,9848022339,Delhi,90),\n(2,siddarth,Battacharya,22,9848022338,Ko lkata,78),\n(1,Rajiv,Reddy,21,9848022337,Hyderabad,89)})\n"
},
{
"code": null,
"e": 5228,
"s": 5084,
"text": "Let us now calculate the global maximum of GPA, i.e., maximum among the GPA values of all the students using the MAX() function as shown below."
},
{
"code": null,
"e": 5368,
"s": 5228,
"text": "grunt> student_gpa_max = foreach student_group_all Generate\n (student_details.firstname, student_details.gpa), MAX(student_details.gpa);"
},
{
"code": null,
"e": 5444,
"s": 5368,
"text": "Verify the relation student_gpa_max using the DUMP operator as shown below."
},
{
"code": null,
"e": 5473,
"s": 5444,
"text": "grunt> Dump student_gpa_max;"
},
{
"code": null,
"e": 5568,
"s": 5473,
"text": "It will produce the following output, displaying the contents of the relation student_gpa_max."
},
{
"code": null,
"e": 5760,
"s": 5568,
"text": "(({(Bharathi),(Komal),(Archana),(Trupthi),(Preethi),(Rajesh),(siddarth),(Rajiv) } , \n { (72) , (83) , (87) , (75) , (93) , (90) , (78) , (89) }) ,93)\n"
},
{
"code": null,
"e": 5795,
"s": 5760,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5814,
"s": 5795,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5849,
"s": 5814,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5870,
"s": 5849,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5903,
"s": 5870,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5916,
"s": 5903,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5951,
"s": 5916,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5969,
"s": 5951,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6002,
"s": 5969,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6020,
"s": 6002,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6053,
"s": 6020,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6071,
"s": 6053,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6078,
"s": 6071,
"text": " Print"
},
{
"code": null,
"e": 6089,
"s": 6078,
"text": " Add Notes"
}
] |
Online JSON Editor | Editable JSON Code
12345678910111213141516{ "Company": { "Employee": { "FirstName": "Tanmay", "LastName": "Patil", "ContactNo": "1234567890", "Email": "[email protected]", "Address": { "City": "Bangalore", "State": "Karnataka", "Zip": "560212" } } }}X
Privacy Policy
Cookies Policy
Terms of Use | [
{
"code": null,
"e": 19,
"s": 0,
"text": "Editable JSON Code"
},
{
"code": null,
"e": 385,
"s": 19,
"text": "12345678910111213141516{ \"Company\": { \"Employee\": { \"FirstName\": \"Tanmay\", \"LastName\": \"Patil\", \"ContactNo\": \"1234567890\", \"Email\": \"[email protected]\", \"Address\": { \"City\": \"Bangalore\", \"State\": \"Karnataka\", \"Zip\": \"560212\" } } }}X"
},
{
"code": null,
"e": 400,
"s": 385,
"text": "Privacy Policy"
},
{
"code": null,
"e": 415,
"s": 400,
"text": "Cookies Policy"
}
] |
Non-negative Integers without Consecutive Ones in C++ | Suppose we have a positive integer n. We have to find the non-negative integers less than or equal to n. The constraint is that the binary representation will not contain consecutive ones. So if the input is 7, then the answer will be 5, as binary representation of 5 is 101.
To solve this, we will follow these steps −
Define a function convert(), this will take n,
ret := empty string
while n is non-zero, do −ret := ret + (n mod 2)n := right shift n, 1 time
ret := ret + (n mod 2)
n := right shift n, 1 time
return ret
From the main method, do the following −
bits := call the function convert(num)
n := size of bits
Define an array ones of size n, Define an array zeroes of size n
ones[0] := 1, zeroes[0] := 1
for initialize i := 1, when i < n, update (increase i by 1), do −zeroes[i] := zeroes[i - 1] + ones[i - 1]ones[i] := zeroes[i - 1]
zeroes[i] := zeroes[i - 1] + ones[i - 1]
ones[i] := zeroes[i - 1]
ret := ones[n - 1] + zeroes[n - 1]
for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −if bits[i] is same as '0' and bits[i + 1] is same as '0', then −ret := ret - ones[i]otherwise when bits[i] is same as '1' and bits[i + 1] is same as '1', then −Come out from the loop
if bits[i] is same as '0' and bits[i + 1] is same as '0', then −ret := ret - ones[i]
ret := ret - ones[i]
otherwise when bits[i] is same as '1' and bits[i + 1] is same as '1', then −Come out from the loop
Come out from the loop
return ret
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string convert(int n){
string ret = "";
while(n){
ret += (n % 2) + '0';
n >>= 1;
}
return ret;
}
int findIntegers(int num) {
string bits = convert(num);
int n = bits.size();
vector <int> ones(n);
vector <int> zeroes(n);
ones[0] = zeroes[0] = 1;
for(int i = 1; i < n; i++){
zeroes[i] = zeroes[i - 1] + ones[i - 1];
ones[i] = zeroes[i - 1];
}
int ret = ones[n - 1] + zeroes[n - 1];
for(int i = n - 2; i >= 0; i--){
if(bits[i] == '0' && bits[i + 1] == '0') ret -= ones[i];
else if(bits[i] == '1' && bits[i + 1]== '1') break;
}
return ret;
}
};
main(){
Solution ob;
cout << (ob.findIntegers(7));
}
7
5 | [
{
"code": null,
"e": 1338,
"s": 1062,
"text": "Suppose we have a positive integer n. We have to find the non-negative integers less than or equal to n. The constraint is that the binary representation will not contain consecutive ones. So if the input is 7, then the answer will be 5, as binary representation of 5 is 101."
},
{
"code": null,
"e": 1382,
"s": 1338,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1429,
"s": 1382,
"text": "Define a function convert(), this will take n,"
},
{
"code": null,
"e": 1449,
"s": 1429,
"text": "ret := empty string"
},
{
"code": null,
"e": 1523,
"s": 1449,
"text": "while n is non-zero, do −ret := ret + (n mod 2)n := right shift n, 1 time"
},
{
"code": null,
"e": 1546,
"s": 1523,
"text": "ret := ret + (n mod 2)"
},
{
"code": null,
"e": 1573,
"s": 1546,
"text": "n := right shift n, 1 time"
},
{
"code": null,
"e": 1584,
"s": 1573,
"text": "return ret"
},
{
"code": null,
"e": 1625,
"s": 1584,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 1664,
"s": 1625,
"text": "bits := call the function convert(num)"
},
{
"code": null,
"e": 1682,
"s": 1664,
"text": "n := size of bits"
},
{
"code": null,
"e": 1747,
"s": 1682,
"text": "Define an array ones of size n, Define an array zeroes of size n"
},
{
"code": null,
"e": 1776,
"s": 1747,
"text": "ones[0] := 1, zeroes[0] := 1"
},
{
"code": null,
"e": 1906,
"s": 1776,
"text": "for initialize i := 1, when i < n, update (increase i by 1), do −zeroes[i] := zeroes[i - 1] + ones[i - 1]ones[i] := zeroes[i - 1]"
},
{
"code": null,
"e": 1947,
"s": 1906,
"text": "zeroes[i] := zeroes[i - 1] + ones[i - 1]"
},
{
"code": null,
"e": 1972,
"s": 1947,
"text": "ones[i] := zeroes[i - 1]"
},
{
"code": null,
"e": 2007,
"s": 1972,
"text": "ret := ones[n - 1] + zeroes[n - 1]"
},
{
"code": null,
"e": 2260,
"s": 2007,
"text": "for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −if bits[i] is same as '0' and bits[i + 1] is same as '0', then −ret := ret - ones[i]otherwise when bits[i] is same as '1' and bits[i + 1] is same as '1', then −Come out from the loop"
},
{
"code": null,
"e": 2345,
"s": 2260,
"text": "if bits[i] is same as '0' and bits[i + 1] is same as '0', then −ret := ret - ones[i]"
},
{
"code": null,
"e": 2366,
"s": 2345,
"text": "ret := ret - ones[i]"
},
{
"code": null,
"e": 2465,
"s": 2366,
"text": "otherwise when bits[i] is same as '1' and bits[i + 1] is same as '1', then −Come out from the loop"
},
{
"code": null,
"e": 2488,
"s": 2465,
"text": "Come out from the loop"
},
{
"code": null,
"e": 2499,
"s": 2488,
"text": "return ret"
},
{
"code": null,
"e": 2569,
"s": 2499,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2580,
"s": 2569,
"text": " Live Demo"
},
{
"code": null,
"e": 3407,
"s": 2580,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n string convert(int n){\n string ret = \"\";\n while(n){\n ret += (n % 2) + '0';\n n >>= 1;\n }\n return ret;\n }\n int findIntegers(int num) {\n string bits = convert(num);\n int n = bits.size();\n vector <int> ones(n);\n vector <int> zeroes(n);\n ones[0] = zeroes[0] = 1;\n for(int i = 1; i < n; i++){\n zeroes[i] = zeroes[i - 1] + ones[i - 1];\n ones[i] = zeroes[i - 1];\n }\n int ret = ones[n - 1] + zeroes[n - 1];\n for(int i = n - 2; i >= 0; i--){\n if(bits[i] == '0' && bits[i + 1] == '0') ret -= ones[i];\n else if(bits[i] == '1' && bits[i + 1]== '1') break;\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.findIntegers(7));\n}"
},
{
"code": null,
"e": 3409,
"s": 3407,
"text": "7"
},
{
"code": null,
"e": 3411,
"s": 3409,
"text": "5"
}
] |
An end-to-end machine learning project with Python Pandas, Keras, Flask, Docker and Heroku | by Ryan Lamb | Towards Data Science | At the time of the Rugby World Cup in 2019 I did a small data science project to try and predict rugby match results, which I wrote about here. I’ve expanded this into an example end-to-end machine learning project to demonstrate how to deploy a machine learning model as an interactive web app.
To provide a high-level overview of the key steps needed in going from raw data to a live deployed machine learning app.
Once you’ve gone through this — pick a topic that you’re interested in, find some data, get your hands dirty and aim to build your own machine learning app, from data preparation to deployment.
Data wrangling with Pandas & data storage with SQLiteMachine learning (Neural Network) with KerasWeb app with Flask (and a bit of CSS & HTML)App deployment with Docker and Heroku
Data wrangling with Pandas & data storage with SQLite
Machine learning (Neural Network) with Keras
Web app with Flask (and a bit of CSS & HTML)
App deployment with Docker and Heroku
The code for this is available on GitHub here and the live app can be viewed here. (Note that this code isn’t necessarily production level, but meant to show what can be done as a starting point. The live app uses a snapshot of data at a specific point in time).
Data scientists spend about 45% of their time simply getting data ready for model development
Data wrangling includes cleaning, structuring and enriching your data to get it ready for your machine learning model. For example, dealing with blank data or inconsistent formats.
Unless you’re using an already clean dataset (which seldom happens in the real world), you’d need to perform Exploratory Data Analysis (EDA) to better understand the data profile.
Pandas-profiling is an excellent module for EDA. It generates profile reports of DataFrames including quantile and descriptive statistics, correlations, missing values and histograms.
For this project, I needed data from ESPN Scrum. You can find detailed cleaning steps in the data_prep.py file, for example defining the Match Date format with the to_datetime() method. I also enriched the data with the World Rugby Rankings and a measure of skill using Microsoft’s TrueSkill rating system.
If you’re looking for datasets to get started, UC Irvine’s Machine Learning repository and Kaggle are good sources to explore. Alternatively you can get data from scraping using BeautifulSoup.
I stored my DataFrames as tables in a SQLite database. This is a lightweight database and the mostly widely deployed in the world. Plain csv files can of course be used, but this provides an opportunity to learn about SQLite. The code below connects to the match_results database and writes the latest_stats DataFrame to it as a table.
conn = sqlite3.connect('match_results.db')latest_stats.to_sql('latest_stats', conn, if_exists='replace')
Now we’ve got the data - time to test and train the machine learning model.
Mean Squared Error (MSE) was used as a loss function to minimize. Hyperparameter tuning was performed (Jason Brownlee has a tutorial here), and I experimented with both wide (one layer with a lot of neurons) and deep (more layers but fewer neurons per layer) networks until the MSE didn’t improve significantly.
You want the model to be able to perform well with unseen data. If you overfit your model, you may have a low error on your training data but a high error on your test (unseen) data. When this happens, the model has learned the training data almost too well and cannot generalize to new data. There are various techniques to avoid overfitting.
Below you can see the MSE decreasing rapidly up until ~25 epochs and then remaining relatively stable for both training and testing data.
The final model had a first layer of 15 neurons and a second layer of 8 neurons, both with the Rectified Linear Activation Unit (ReLU).
It was compiled with the Adam optimization algorithm, which is an efficient gradient descent algorithm.
model = Sequential()model.add(Dense(15, input_dim=5, kernel_initializer='normal', activation='relu'))model.add(Dense(8, kernel_initializer='normal', activation='relu'))model.add(Dense(2, kernel_initializer='normal'))model.compile(loss='mse', optimizer='adam')
The save() function is used to save the final Keras model. This saves the model architecture and weights, and will allow us to load the model later on in the app to make predictions on new data.
Flask is a web framework that can be used for developing web applications relatively quickly. You can find a walk through for quick development here.
The code below in the app.py file essentially sets up the home page and serves the index.html to the user:
WTForms is used for the form so that the user can select their two rugby teams. When the button is clicked, the inputs are sent to the saved ML model via the model_predict function. The resulting model predictions are then sent as input variables to the prediction.html template.
@app.route("/", methods=['GET', 'POST'])def home(): form = TeamForm(request.form) # Get team names and send to model if request.method == 'POST' and form.validate(): team1 = request.form['team1'] team2 = request.form['team2'] return render_template('prediction.html', win_prob=model_predict(team1,team2)[0], score=model_predict(team1, team2)[1]) # Send template information to index.html return render_template('index.html', form=form)
The prediction.html template does three key things:
Gets the win probability and score sent from the output of the model to display to the end user (via the win_prob and score variables)Provides a button for the user to return to the home pageReferences the main.css file to provide some styling
Gets the win probability and score sent from the output of the model to display to the end user (via the win_prob and score variables)
Provides a button for the user to return to the home page
References the main.css file to provide some styling
<!DOCTYPE html><head> <title>Prediction</title> <link rel="stylesheet" href="/static/css/main.css"></head><body> <div class="container"> <h1> <center>Predictions</center> </h1> {% block content %} <div class="flash">{{win_prob}}</div> <div class="flash">{{score}}</div> <form action="/button" method = "POST"> <p><input type = "submit" value = "Return" /></p> </form> {% endblock %} </div></body></html>
And that’s it! In summary, you have:
Two templates, index.html and prediction.html for the home page and prediction results page
CSS files to provide styling
Your saved model file to make predictions
The app.py Flask code to define your pages and their functionality and to run your app
Now to deploy your app and share it with the world.
I won’t go into much detail about Docker but the key thing to know is that it allows you to package your application in a self-sufficient container that can be used across systems i.e. it creates a portable container that makes it easier to deploy your app. You can dig into the details in the official Docker documentation here.
Download Docker Desktop here.
Create a Dockerfile in your app directory. This contains the instructions for building your Docker image. Best practices for Dockerfiles can be viewed here and here. Below you’ll see I’ve included instructions to run the requirements.txt file that contains the app dependencies.
FROM python:3.7.3-stretchRUN mkdir /appWORKDIR /app#Copy all filesCOPY . .# Install dependenciesRUN pip install --upgrade pipRUN pip install -r requirements.txt# RunCMD ["python","./main.py"]
Open a terminal and go to the directory containing your Dockerfile and app. Use the build command to build your image: docker build -t rugby_prediction . This builds the Docker image from the Dockerfile.
You can run the app locally using the runcommand which creates a container: docker run --name rugby -p 5000:5000 -d rugby_prediction. Here, the -p publishes the container’s port to the host and -d makes the container run in the background. Once this is running, you should be able to view your app running in your browser (in Docker Desktop, click on the open in browser button).
If you experience any errors when running your app, you can use the docker logs command to view the logs and debug.
I used Heroku for hosting because they have a good free tier for non-commercial apps.
Once you’ve created a Heroku account, create a new app and select Container Registry as the deployment method
Download the Heroku CLI and log in to your Heroku account:heroku login
Sign in to the Container Registry: heroku container:login
Go to your app working directory and push the Docker image: heroku container:push web --app [YOUR APP NAME]
Deploy your app: heroku container:release web --app [YOUR APP NAME]
Done! You are ready to share your live machine learning web app.
Hope this has been helpful to get you started. Feel free to post links to your own ML apps in the comments - would be great to see them.
If you’d like to collaborate on rugby (or sport) analytics, drop me a message on LinkedIn! | [
{
"code": null,
"e": 467,
"s": 171,
"text": "At the time of the Rugby World Cup in 2019 I did a small data science project to try and predict rugby match results, which I wrote about here. I’ve expanded this into an example end-to-end machine learning project to demonstrate how to deploy a machine learning model as an interactive web app."
},
{
"code": null,
"e": 588,
"s": 467,
"text": "To provide a high-level overview of the key steps needed in going from raw data to a live deployed machine learning app."
},
{
"code": null,
"e": 782,
"s": 588,
"text": "Once you’ve gone through this — pick a topic that you’re interested in, find some data, get your hands dirty and aim to build your own machine learning app, from data preparation to deployment."
},
{
"code": null,
"e": 961,
"s": 782,
"text": "Data wrangling with Pandas & data storage with SQLiteMachine learning (Neural Network) with KerasWeb app with Flask (and a bit of CSS & HTML)App deployment with Docker and Heroku"
},
{
"code": null,
"e": 1015,
"s": 961,
"text": "Data wrangling with Pandas & data storage with SQLite"
},
{
"code": null,
"e": 1060,
"s": 1015,
"text": "Machine learning (Neural Network) with Keras"
},
{
"code": null,
"e": 1105,
"s": 1060,
"text": "Web app with Flask (and a bit of CSS & HTML)"
},
{
"code": null,
"e": 1143,
"s": 1105,
"text": "App deployment with Docker and Heroku"
},
{
"code": null,
"e": 1406,
"s": 1143,
"text": "The code for this is available on GitHub here and the live app can be viewed here. (Note that this code isn’t necessarily production level, but meant to show what can be done as a starting point. The live app uses a snapshot of data at a specific point in time)."
},
{
"code": null,
"e": 1500,
"s": 1406,
"text": "Data scientists spend about 45% of their time simply getting data ready for model development"
},
{
"code": null,
"e": 1681,
"s": 1500,
"text": "Data wrangling includes cleaning, structuring and enriching your data to get it ready for your machine learning model. For example, dealing with blank data or inconsistent formats."
},
{
"code": null,
"e": 1861,
"s": 1681,
"text": "Unless you’re using an already clean dataset (which seldom happens in the real world), you’d need to perform Exploratory Data Analysis (EDA) to better understand the data profile."
},
{
"code": null,
"e": 2045,
"s": 1861,
"text": "Pandas-profiling is an excellent module for EDA. It generates profile reports of DataFrames including quantile and descriptive statistics, correlations, missing values and histograms."
},
{
"code": null,
"e": 2352,
"s": 2045,
"text": "For this project, I needed data from ESPN Scrum. You can find detailed cleaning steps in the data_prep.py file, for example defining the Match Date format with the to_datetime() method. I also enriched the data with the World Rugby Rankings and a measure of skill using Microsoft’s TrueSkill rating system."
},
{
"code": null,
"e": 2545,
"s": 2352,
"text": "If you’re looking for datasets to get started, UC Irvine’s Machine Learning repository and Kaggle are good sources to explore. Alternatively you can get data from scraping using BeautifulSoup."
},
{
"code": null,
"e": 2881,
"s": 2545,
"text": "I stored my DataFrames as tables in a SQLite database. This is a lightweight database and the mostly widely deployed in the world. Plain csv files can of course be used, but this provides an opportunity to learn about SQLite. The code below connects to the match_results database and writes the latest_stats DataFrame to it as a table."
},
{
"code": null,
"e": 2986,
"s": 2881,
"text": "conn = sqlite3.connect('match_results.db')latest_stats.to_sql('latest_stats', conn, if_exists='replace')"
},
{
"code": null,
"e": 3062,
"s": 2986,
"text": "Now we’ve got the data - time to test and train the machine learning model."
},
{
"code": null,
"e": 3374,
"s": 3062,
"text": "Mean Squared Error (MSE) was used as a loss function to minimize. Hyperparameter tuning was performed (Jason Brownlee has a tutorial here), and I experimented with both wide (one layer with a lot of neurons) and deep (more layers but fewer neurons per layer) networks until the MSE didn’t improve significantly."
},
{
"code": null,
"e": 3718,
"s": 3374,
"text": "You want the model to be able to perform well with unseen data. If you overfit your model, you may have a low error on your training data but a high error on your test (unseen) data. When this happens, the model has learned the training data almost too well and cannot generalize to new data. There are various techniques to avoid overfitting."
},
{
"code": null,
"e": 3856,
"s": 3718,
"text": "Below you can see the MSE decreasing rapidly up until ~25 epochs and then remaining relatively stable for both training and testing data."
},
{
"code": null,
"e": 3992,
"s": 3856,
"text": "The final model had a first layer of 15 neurons and a second layer of 8 neurons, both with the Rectified Linear Activation Unit (ReLU)."
},
{
"code": null,
"e": 4096,
"s": 3992,
"text": "It was compiled with the Adam optimization algorithm, which is an efficient gradient descent algorithm."
},
{
"code": null,
"e": 4356,
"s": 4096,
"text": "model = Sequential()model.add(Dense(15, input_dim=5, kernel_initializer='normal', activation='relu'))model.add(Dense(8, kernel_initializer='normal', activation='relu'))model.add(Dense(2, kernel_initializer='normal'))model.compile(loss='mse', optimizer='adam')"
},
{
"code": null,
"e": 4551,
"s": 4356,
"text": "The save() function is used to save the final Keras model. This saves the model architecture and weights, and will allow us to load the model later on in the app to make predictions on new data."
},
{
"code": null,
"e": 4701,
"s": 4551,
"text": "Flask is a web framework that can be used for developing web applications relatively quickly. You can find a walk through for quick development here."
},
{
"code": null,
"e": 4808,
"s": 4701,
"text": "The code below in the app.py file essentially sets up the home page and serves the index.html to the user:"
},
{
"code": null,
"e": 5088,
"s": 4808,
"text": "WTForms is used for the form so that the user can select their two rugby teams. When the button is clicked, the inputs are sent to the saved ML model via the model_predict function. The resulting model predictions are then sent as input variables to the prediction.html template."
},
{
"code": null,
"e": 5590,
"s": 5088,
"text": "@app.route(\"/\", methods=['GET', 'POST'])def home(): form = TeamForm(request.form) # Get team names and send to model if request.method == 'POST' and form.validate(): team1 = request.form['team1'] team2 = request.form['team2'] return render_template('prediction.html', win_prob=model_predict(team1,team2)[0], score=model_predict(team1, team2)[1]) # Send template information to index.html return render_template('index.html', form=form)"
},
{
"code": null,
"e": 5642,
"s": 5590,
"text": "The prediction.html template does three key things:"
},
{
"code": null,
"e": 5886,
"s": 5642,
"text": "Gets the win probability and score sent from the output of the model to display to the end user (via the win_prob and score variables)Provides a button for the user to return to the home pageReferences the main.css file to provide some styling"
},
{
"code": null,
"e": 6021,
"s": 5886,
"text": "Gets the win probability and score sent from the output of the model to display to the end user (via the win_prob and score variables)"
},
{
"code": null,
"e": 6079,
"s": 6021,
"text": "Provides a button for the user to return to the home page"
},
{
"code": null,
"e": 6132,
"s": 6079,
"text": "References the main.css file to provide some styling"
},
{
"code": null,
"e": 6572,
"s": 6132,
"text": "<!DOCTYPE html><head> <title>Prediction</title> <link rel=\"stylesheet\" href=\"/static/css/main.css\"></head><body> <div class=\"container\"> <h1> <center>Predictions</center> </h1> {% block content %} <div class=\"flash\">{{win_prob}}</div> <div class=\"flash\">{{score}}</div> <form action=\"/button\" method = \"POST\"> <p><input type = \"submit\" value = \"Return\" /></p> </form> {% endblock %} </div></body></html>"
},
{
"code": null,
"e": 6609,
"s": 6572,
"text": "And that’s it! In summary, you have:"
},
{
"code": null,
"e": 6701,
"s": 6609,
"text": "Two templates, index.html and prediction.html for the home page and prediction results page"
},
{
"code": null,
"e": 6730,
"s": 6701,
"text": "CSS files to provide styling"
},
{
"code": null,
"e": 6772,
"s": 6730,
"text": "Your saved model file to make predictions"
},
{
"code": null,
"e": 6859,
"s": 6772,
"text": "The app.py Flask code to define your pages and their functionality and to run your app"
},
{
"code": null,
"e": 6911,
"s": 6859,
"text": "Now to deploy your app and share it with the world."
},
{
"code": null,
"e": 7241,
"s": 6911,
"text": "I won’t go into much detail about Docker but the key thing to know is that it allows you to package your application in a self-sufficient container that can be used across systems i.e. it creates a portable container that makes it easier to deploy your app. You can dig into the details in the official Docker documentation here."
},
{
"code": null,
"e": 7271,
"s": 7241,
"text": "Download Docker Desktop here."
},
{
"code": null,
"e": 7550,
"s": 7271,
"text": "Create a Dockerfile in your app directory. This contains the instructions for building your Docker image. Best practices for Dockerfiles can be viewed here and here. Below you’ll see I’ve included instructions to run the requirements.txt file that contains the app dependencies."
},
{
"code": null,
"e": 7742,
"s": 7550,
"text": "FROM python:3.7.3-stretchRUN mkdir /appWORKDIR /app#Copy all filesCOPY . .# Install dependenciesRUN pip install --upgrade pipRUN pip install -r requirements.txt# RunCMD [\"python\",\"./main.py\"]"
},
{
"code": null,
"e": 7946,
"s": 7742,
"text": "Open a terminal and go to the directory containing your Dockerfile and app. Use the build command to build your image: docker build -t rugby_prediction . This builds the Docker image from the Dockerfile."
},
{
"code": null,
"e": 8326,
"s": 7946,
"text": "You can run the app locally using the runcommand which creates a container: docker run --name rugby -p 5000:5000 -d rugby_prediction. Here, the -p publishes the container’s port to the host and -d makes the container run in the background. Once this is running, you should be able to view your app running in your browser (in Docker Desktop, click on the open in browser button)."
},
{
"code": null,
"e": 8442,
"s": 8326,
"text": "If you experience any errors when running your app, you can use the docker logs command to view the logs and debug."
},
{
"code": null,
"e": 8528,
"s": 8442,
"text": "I used Heroku for hosting because they have a good free tier for non-commercial apps."
},
{
"code": null,
"e": 8638,
"s": 8528,
"text": "Once you’ve created a Heroku account, create a new app and select Container Registry as the deployment method"
},
{
"code": null,
"e": 8709,
"s": 8638,
"text": "Download the Heroku CLI and log in to your Heroku account:heroku login"
},
{
"code": null,
"e": 8767,
"s": 8709,
"text": "Sign in to the Container Registry: heroku container:login"
},
{
"code": null,
"e": 8875,
"s": 8767,
"text": "Go to your app working directory and push the Docker image: heroku container:push web --app [YOUR APP NAME]"
},
{
"code": null,
"e": 8943,
"s": 8875,
"text": "Deploy your app: heroku container:release web --app [YOUR APP NAME]"
},
{
"code": null,
"e": 9008,
"s": 8943,
"text": "Done! You are ready to share your live machine learning web app."
},
{
"code": null,
"e": 9145,
"s": 9008,
"text": "Hope this has been helpful to get you started. Feel free to post links to your own ML apps in the comments - would be great to see them."
}
] |
How to open an activity after receiving a PUSH notification in Android? | This example demonstrate about How to open an activity after receiving a PUSH notification in Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to src/MyFirebaseMessagingService.java
package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.app.PendingIntent ;
import android.content.Context ;
import android.content.Intent ;
import android.support.v4.app.NotificationCompat ;
import com.google.firebase.messaging.FirebaseMessagingService ;
import com.google.firebase.messaging.RemoteMessage ;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
@Override
public void onNewToken (String s) {
super .onNewToken(s) ;
}
@Override
public void onMessageReceived (RemoteMessage remoteMessage) {
super .onMessageReceived(remoteMessage) ;
Intent notificationIntent = new Intent(getApplicationContext() , MainActivity. class ) ;
notificationIntent.putExtra( "NotificationMessage" , "I am from Notification" ) ;
notificationIntent.addCategory(Intent. CATEGORY_LAUNCHER ) ;
notificationIntent.setAction(Intent. ACTION_MAIN ) ;
notificationIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_SINGLE_TOP ) ;
PendingIntent resultIntent = PendingIntent. getActivity (getApplicationContext() , 0 , notificationIntent , 0 ) ;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext() ,
default_notification_channel_id )
.setSmallIcon(R.drawable. ic_launcher_foreground )
.setContentTitle( "Test" )
.setContentText( "Hello! This is my first push notification" )
.setContentIntent(resultIntent) ;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE ) ;
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new
NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel) ;
}
assert mNotificationManager != null;
mNotificationManager.notify(( int ) System. currentTimeMillis () ,
mBuilder.build()) ;
}
}
Click here to download the project code | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "This example demonstrate about How to open an activity after receiving a PUSH notification in Android"
},
{
"code": null,
"e": 1293,
"s": 1164,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1364,
"s": 1293,
"text": "Step 2 − Add the following code to src/MyFirebaseMessagingService.java"
},
{
"code": null,
"e": 3846,
"s": 1364,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.app.PendingIntent ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport android.support.v4.app.NotificationCompat ;\nimport com.google.firebase.messaging.FirebaseMessagingService ;\nimport com.google.firebase.messaging.RemoteMessage ;\npublic class MyFirebaseMessagingService extends FirebaseMessagingService {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n public void onNewToken (String s) {\n super .onNewToken(s) ;\n }\n @Override\n public void onMessageReceived (RemoteMessage remoteMessage) {\n super .onMessageReceived(remoteMessage) ;\n Intent notificationIntent = new Intent(getApplicationContext() , MainActivity. class ) ;\n notificationIntent.putExtra( \"NotificationMessage\" , \"I am from Notification\" ) ;\n notificationIntent.addCategory(Intent. CATEGORY_LAUNCHER ) ;\n notificationIntent.setAction(Intent. ACTION_MAIN ) ;\n notificationIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_SINGLE_TOP ) ;\n PendingIntent resultIntent = PendingIntent. getActivity (getApplicationContext() , 0 , notificationIntent , 0 ) ; \n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext() , \n default_notification_channel_id )\n .setSmallIcon(R.drawable. ic_launcher_foreground )\n .setContentTitle( \"Test\" )\n .setContentText( \"Hello! This is my first push notification\" )\n .setContentIntent(resultIntent) ;\n NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new\n NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () ,\n mBuilder.build()) ;\n }\n}"
},
{
"code": null,
"e": 3888,
"s": 3846,
"text": "Click here to download the project code"
}
] |
html.unescape() in Python - GeeksforGeeks | 22 Apr, 2020
With the help of html.unescape() method, we can convert the ascii string into html script by replacing ascii characters with special characters by using html.escape() method.
Syntax : html.unescape(String)
Return : Return a html script.
Example #1 :In this example we can see that by using html.unescape() method, we are able to convert the ascii string into html script by using this method.
# import htmlimport html s = '<html><head></head><body><h1>This is python</h1></body></html>'temp = html.escape(s)# Using html.unescape() methodgfg = html.unescape(temp) print(gfg)
Output :
Example #2 :
# import htmlimport html s = '<html><head></head><body><h1>GeeksForGeeks</h1></body></html>'temp = html.escape(s)# Using html.unescape() methodgfg = html.unescape(temp) print(gfg)
Output :
Python html-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python | [
{
"code": null,
"e": 24029,
"s": 24001,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 24204,
"s": 24029,
"text": "With the help of html.unescape() method, we can convert the ascii string into html script by replacing ascii characters with special characters by using html.escape() method."
},
{
"code": null,
"e": 24235,
"s": 24204,
"text": "Syntax : html.unescape(String)"
},
{
"code": null,
"e": 24266,
"s": 24235,
"text": "Return : Return a html script."
},
{
"code": null,
"e": 24422,
"s": 24266,
"text": "Example #1 :In this example we can see that by using html.unescape() method, we are able to convert the ascii string into html script by using this method."
},
{
"code": "# import htmlimport html s = '<html><head></head><body><h1>This is python</h1></body></html>'temp = html.escape(s)# Using html.unescape() methodgfg = html.unescape(temp) print(gfg)",
"e": 24605,
"s": 24422,
"text": null
},
{
"code": null,
"e": 24614,
"s": 24605,
"text": "Output :"
},
{
"code": null,
"e": 24627,
"s": 24614,
"text": "Example #2 :"
},
{
"code": "# import htmlimport html s = '<html><head></head><body><h1>GeeksForGeeks</h1></body></html>'temp = html.escape(s)# Using html.unescape() methodgfg = html.unescape(temp) print(gfg)",
"e": 24809,
"s": 24627,
"text": null
},
{
"code": null,
"e": 24818,
"s": 24809,
"text": "Output :"
},
{
"code": null,
"e": 24837,
"s": 24818,
"text": "Python html-module"
},
{
"code": null,
"e": 24844,
"s": 24837,
"text": "Python"
},
{
"code": null,
"e": 24942,
"s": 24844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24951,
"s": 24942,
"text": "Comments"
},
{
"code": null,
"e": 24964,
"s": 24951,
"text": "Old Comments"
},
{
"code": null,
"e": 24982,
"s": 24964,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25004,
"s": 24982,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25036,
"s": 25004,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25078,
"s": 25036,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25104,
"s": 25078,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25148,
"s": 25104,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 25173,
"s": 25148,
"text": "sum() function in Python"
},
{
"code": null,
"e": 25210,
"s": 25173,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 25266,
"s": 25210,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Python 3 - Exceptions Handling | Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them −
Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions available in Python − Standard Exceptions.
Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions available in Python − Standard Exceptions.
Assertions − This would be covered in Assertions in Python 3 tutorial.
Assertions − This would be covered in Assertions in Python 3 tutorial.
Here is a list of Standard Exceptions available in Python. −
Exception
Base class for all exceptions
StopIteration
Raised when the next() method of an iterator does not point to any object.
SystemExit
Raised by the sys.exit() function.
StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError
Base class for all errors that occur for numeric calculation.
OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError
Raised when a floating point calculation fails.
ZeroDivisonError
Raised when division or modulo by zero takes place for all numeric types.
AssertionError
Raised in case of failure of the Assert statement.
AttributeError
Raised in case of failure of attribute reference or assignment.
EOFError
Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
ImportError
Raised when an import statement fails.
KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
LookupError
Base class for all lookup errors.
IndexError
Raised when an index is not found in a sequence.
KeyError
Raised when the specified key is not found in the dictionary.
NameError
Raised when an identifier is not found in the local or global namespace.
UnboundLocalError
Raised when trying to access a local variable in a function or method but no value has been assigned to it.
EnvironmentError
Base class for all exceptions that occur outside the Python environment.
IOError
Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
OSError
Raised for operating system-related errors.
SyntaxError
Raised when there is an error in Python syntax.
IndentationError
Raised when indentation is not specified properly.
SystemError
Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.
SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.
TypeError
Raised when an operation or function is attempted that is invalid for the specified data type.
ValueError
Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
RuntimeError
Raised when a generated error does not fall into any category.
NotImplementedError
Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.
An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program.
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised.
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised.
Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5.
Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5.
Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.
Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.
When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.
The syntax for assert is −
assert Expression[, Arguments]
If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception, using the try-except statement. If they are not handled, they will terminate the program and produce a traceback.
Here is a function that converts a given temperature from degrees Kelvin to degrees Fahrenheit. Since 0° K is as cold as it gets, the function bails out if it sees a negative temperature −
#!/usr/bin/python3
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print (KelvinToFahrenheit(273))
print (int(KelvinToFahrenheit(505.78)))
print (KelvinToFahrenheit(-5))
When the above code is executed, it produces the following result −
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.
If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.
Here is simple syntax of try....except...else blocks −
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points about the above-mentioned syntax −
A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.
A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.
You can also provide a generic except clause, which handles any exception.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.
After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's protection.
The else-block is a good place for code that does not need the try: block's protection.
This example opens a file, writes content in the, file and comes out gracefully because there is no problem at all −
#!/usr/bin/python3
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
This produces the following result −
Written content in the file successfully
This example tries to open a file where you do not have the write permission, so it raises an exception −
#!/usr/bin/python3
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
This produces the following result −
Error: can't find file or read data
You can also use the except statement with no exceptions defined as follows −
try:
You do your operations here
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.
You can also use the same except statement to handle multiple exceptions as follows −
try:
You do your operations here
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
You can use a finally: block along with a try: block. The finally: block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this −
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Note − You can provide except clause(s), or a finally clause, but not both. You cannot use else clause as well along with a finally clause.
#!/usr/bin/python3
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can\'t find file or read data")
fh.close()
If you do not have permission to open the file in writing mode, then this will produce the following result −
Error: can't find file or read data
Same example can be written more cleanly as follows −
#!/usr/bin/python3
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print ("Going to close the file")
fh.close()
except IOError:
print ("Error: can\'t find file or read data")
This produces the following result −
Going to close the file
When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.
An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows −
try:
You do your operations here
......................
except ExceptionType as Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.
Following is an example for a single exception −
#!/usr/bin/python3
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError as Argument:
print ("The argument does not contain numbers\n", Argument)
# Call above function here.
temp_convert("xyz")
This produces the following result −
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows −
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception.
An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows −
def functionName( level ):
if level <1:
raise Exception(level)
# The code below to this would not be executed
# if we raise the exception
return level
Note − In order to catch an exception, an "except" clause must refer to the same exception thrown either as a class object or a simple string. For example, to capture the above exception, we must write the except clause as follows −
try:
Business Logic here...
except Exception as e:
Exception handling here using e.args...
else:
Rest of the code here...
The following example illustrates the use of raising an exception −
#!/usr/bin/python3
def functionName( level ):
if level <1:
raise Exception(level)
# The code below to this would not be executed
# if we raise the exception
return level
try:
l = functionName(-10)
print ("level = ",l)
except Exception as e:
print ("error in level argument",e.args[0])
This will produce the following result
error in level argument -10
Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you have defined the above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2483,
"s": 2340,
"text": "Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them −"
},
{
"code": null,
"e": 2622,
"s": 2483,
"text": "Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions available in Python − Standard Exceptions."
},
{
"code": null,
"e": 2761,
"s": 2622,
"text": "Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions available in Python − Standard Exceptions."
},
{
"code": null,
"e": 2832,
"s": 2761,
"text": "Assertions − This would be covered in Assertions in Python 3 tutorial."
},
{
"code": null,
"e": 2903,
"s": 2832,
"text": "Assertions − This would be covered in Assertions in Python 3 tutorial."
},
{
"code": null,
"e": 2964,
"s": 2903,
"text": "Here is a list of Standard Exceptions available in Python. −"
},
{
"code": null,
"e": 2974,
"s": 2964,
"text": "Exception"
},
{
"code": null,
"e": 3004,
"s": 2974,
"text": "Base class for all exceptions"
},
{
"code": null,
"e": 3018,
"s": 3004,
"text": "StopIteration"
},
{
"code": null,
"e": 3093,
"s": 3018,
"text": "Raised when the next() method of an iterator does not point to any object."
},
{
"code": null,
"e": 3104,
"s": 3093,
"text": "SystemExit"
},
{
"code": null,
"e": 3139,
"s": 3104,
"text": "Raised by the sys.exit() function."
},
{
"code": null,
"e": 3153,
"s": 3139,
"text": "StandardError"
},
{
"code": null,
"e": 3229,
"s": 3153,
"text": "Base class for all built-in exceptions except StopIteration and SystemExit."
},
{
"code": null,
"e": 3245,
"s": 3229,
"text": "ArithmeticError"
},
{
"code": null,
"e": 3307,
"s": 3245,
"text": "Base class for all errors that occur for numeric calculation."
},
{
"code": null,
"e": 3321,
"s": 3307,
"text": "OverflowError"
},
{
"code": null,
"e": 3389,
"s": 3321,
"text": "Raised when a calculation exceeds maximum limit for a numeric type."
},
{
"code": null,
"e": 3408,
"s": 3389,
"text": "FloatingPointError"
},
{
"code": null,
"e": 3456,
"s": 3408,
"text": "Raised when a floating point calculation fails."
},
{
"code": null,
"e": 3473,
"s": 3456,
"text": "ZeroDivisonError"
},
{
"code": null,
"e": 3547,
"s": 3473,
"text": "Raised when division or modulo by zero takes place for all numeric types."
},
{
"code": null,
"e": 3562,
"s": 3547,
"text": "AssertionError"
},
{
"code": null,
"e": 3613,
"s": 3562,
"text": "Raised in case of failure of the Assert statement."
},
{
"code": null,
"e": 3628,
"s": 3613,
"text": "AttributeError"
},
{
"code": null,
"e": 3692,
"s": 3628,
"text": "Raised in case of failure of attribute reference or assignment."
},
{
"code": null,
"e": 3701,
"s": 3692,
"text": "EOFError"
},
{
"code": null,
"e": 3811,
"s": 3701,
"text": "Raised when there is no input from either the raw_input() or input() function and the end of file is reached."
},
{
"code": null,
"e": 3823,
"s": 3811,
"text": "ImportError"
},
{
"code": null,
"e": 3862,
"s": 3823,
"text": "Raised when an import statement fails."
},
{
"code": null,
"e": 3880,
"s": 3862,
"text": "KeyboardInterrupt"
},
{
"code": null,
"e": 3959,
"s": 3880,
"text": "Raised when the user interrupts program execution, usually by pressing Ctrl+c."
},
{
"code": null,
"e": 3971,
"s": 3959,
"text": "LookupError"
},
{
"code": null,
"e": 4005,
"s": 3971,
"text": "Base class for all lookup errors."
},
{
"code": null,
"e": 4016,
"s": 4005,
"text": "IndexError"
},
{
"code": null,
"e": 4065,
"s": 4016,
"text": "Raised when an index is not found in a sequence."
},
{
"code": null,
"e": 4074,
"s": 4065,
"text": "KeyError"
},
{
"code": null,
"e": 4136,
"s": 4074,
"text": "Raised when the specified key is not found in the dictionary."
},
{
"code": null,
"e": 4146,
"s": 4136,
"text": "NameError"
},
{
"code": null,
"e": 4219,
"s": 4146,
"text": "Raised when an identifier is not found in the local or global namespace."
},
{
"code": null,
"e": 4237,
"s": 4219,
"text": "UnboundLocalError"
},
{
"code": null,
"e": 4345,
"s": 4237,
"text": "Raised when trying to access a local variable in a function or method but no value has been assigned to it."
},
{
"code": null,
"e": 4362,
"s": 4345,
"text": "EnvironmentError"
},
{
"code": null,
"e": 4435,
"s": 4362,
"text": "Base class for all exceptions that occur outside the Python environment."
},
{
"code": null,
"e": 4443,
"s": 4435,
"text": "IOError"
},
{
"code": null,
"e": 4588,
"s": 4443,
"text": "Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist."
},
{
"code": null,
"e": 4596,
"s": 4588,
"text": "OSError"
},
{
"code": null,
"e": 4640,
"s": 4596,
"text": "Raised for operating system-related errors."
},
{
"code": null,
"e": 4652,
"s": 4640,
"text": "SyntaxError"
},
{
"code": null,
"e": 4700,
"s": 4652,
"text": "Raised when there is an error in Python syntax."
},
{
"code": null,
"e": 4717,
"s": 4700,
"text": "IndentationError"
},
{
"code": null,
"e": 4768,
"s": 4717,
"text": "Raised when indentation is not specified properly."
},
{
"code": null,
"e": 4780,
"s": 4768,
"text": "SystemError"
},
{
"code": null,
"e": 4908,
"s": 4780,
"text": "Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit."
},
{
"code": null,
"e": 4919,
"s": 4908,
"text": "SystemExit"
},
{
"code": null,
"e": 5052,
"s": 4919,
"text": "Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit."
},
{
"code": null,
"e": 5062,
"s": 5052,
"text": "TypeError"
},
{
"code": null,
"e": 5157,
"s": 5062,
"text": "Raised when an operation or function is attempted that is invalid for the specified data type."
},
{
"code": null,
"e": 5168,
"s": 5157,
"text": "ValueError"
},
{
"code": null,
"e": 5300,
"s": 5168,
"text": "Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified."
},
{
"code": null,
"e": 5313,
"s": 5300,
"text": "RuntimeError"
},
{
"code": null,
"e": 5376,
"s": 5313,
"text": "Raised when a generated error does not fall into any category."
},
{
"code": null,
"e": 5396,
"s": 5376,
"text": "NotImplementedError"
},
{
"code": null,
"e": 5507,
"s": 5396,
"text": "Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented."
},
{
"code": null,
"e": 5623,
"s": 5507,
"text": "An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program."
},
{
"code": null,
"e": 5838,
"s": 5623,
"text": "The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised."
},
{
"code": null,
"e": 6053,
"s": 5838,
"text": "The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised."
},
{
"code": null,
"e": 6162,
"s": 6053,
"text": "Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5."
},
{
"code": null,
"e": 6271,
"s": 6162,
"text": "Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5."
},
{
"code": null,
"e": 6412,
"s": 6271,
"text": "Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output."
},
{
"code": null,
"e": 6553,
"s": 6412,
"text": "Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output."
},
{
"code": null,
"e": 6735,
"s": 6553,
"text": "When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception."
},
{
"code": null,
"e": 6762,
"s": 6735,
"text": "The syntax for assert is −"
},
{
"code": null,
"e": 6794,
"s": 6762,
"text": "assert Expression[, Arguments]\n"
},
{
"code": null,
"e": 7081,
"s": 6794,
"text": "If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception, using the try-except statement. If they are not handled, they will terminate the program and produce a traceback."
},
{
"code": null,
"e": 7270,
"s": 7081,
"text": "Here is a function that converts a given temperature from degrees Kelvin to degrees Fahrenheit. Since 0° K is as cold as it gets, the function bails out if it sees a negative temperature −"
},
{
"code": null,
"e": 7526,
"s": 7270,
"text": "#!/usr/bin/python3\n\ndef KelvinToFahrenheit(Temperature):\n assert (Temperature >= 0),\"Colder than absolute zero!\"\n return ((Temperature-273)*1.8)+32\n\nprint (KelvinToFahrenheit(273))\nprint (int(KelvinToFahrenheit(505.78)))\nprint (KelvinToFahrenheit(-5))"
},
{
"code": null,
"e": 7594,
"s": 7526,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 7848,
"s": 7594,
"text": "32.0\n451\nTraceback (most recent call last):\nFile \"test.py\", line 9, in <module>\nprint KelvinToFahrenheit(-5)\nFile \"test.py\", line 4, in KelvinToFahrenheit\nassert (Temperature >= 0),\"Colder than absolute zero!\"\nAssertionError: Colder than absolute zero!\n"
},
{
"code": null,
"e": 8146,
"s": 7848,
"text": "An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error."
},
{
"code": null,
"e": 8271,
"s": 8146,
"text": "When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits."
},
{
"code": null,
"e": 8541,
"s": 8271,
"text": "If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible."
},
{
"code": null,
"e": 8596,
"s": 8541,
"text": "Here is simple syntax of try....except...else blocks −"
},
{
"code": null,
"e": 8888,
"s": 8596,
"text": "try:\n You do your operations here\n ......................\nexcept ExceptionI:\n If there is ExceptionI, then execute this block.\nexcept ExceptionII:\n If there is ExceptionII, then execute this block.\n ......................\nelse:\n If there is no exception then execute this block. "
},
{
"code": null,
"e": 8953,
"s": 8888,
"text": "Here are few important points about the above-mentioned syntax −"
},
{
"code": null,
"e": 9113,
"s": 8953,
"text": "A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions."
},
{
"code": null,
"e": 9273,
"s": 9113,
"text": "A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions."
},
{
"code": null,
"e": 9348,
"s": 9273,
"text": "You can also provide a generic except clause, which handles any exception."
},
{
"code": null,
"e": 9423,
"s": 9348,
"text": "You can also provide a generic except clause, which handles any exception."
},
{
"code": null,
"e": 9578,
"s": 9423,
"text": "After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception."
},
{
"code": null,
"e": 9733,
"s": 9578,
"text": "After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception."
},
{
"code": null,
"e": 9821,
"s": 9733,
"text": "The else-block is a good place for code that does not need the try: block's protection."
},
{
"code": null,
"e": 9909,
"s": 9821,
"text": "The else-block is a good place for code that does not need the try: block's protection."
},
{
"code": null,
"e": 10026,
"s": 9909,
"text": "This example opens a file, writes content in the, file and comes out gracefully because there is no problem at all −"
},
{
"code": null,
"e": 10282,
"s": 10026,
"text": "#!/usr/bin/python3\n\ntry:\n fh = open(\"testfile\", \"w\")\n fh.write(\"This is my test file for exception handling!!\")\nexcept IOError:\n print (\"Error: can\\'t find file or read data\")\nelse:\n print (\"Written content in the file successfully\")\n fh.close()"
},
{
"code": null,
"e": 10319,
"s": 10282,
"text": "This produces the following result −"
},
{
"code": null,
"e": 10361,
"s": 10319,
"text": "Written content in the file successfully\n"
},
{
"code": null,
"e": 10467,
"s": 10361,
"text": "This example tries to open a file where you do not have the write permission, so it raises an exception −"
},
{
"code": null,
"e": 10709,
"s": 10467,
"text": "#!/usr/bin/python3\n\ntry:\n fh = open(\"testfile\", \"r\")\n fh.write(\"This is my test file for exception handling!!\")\nexcept IOError:\n print (\"Error: can\\'t find file or read data\")\nelse:\n print (\"Written content in the file successfully\")"
},
{
"code": null,
"e": 10746,
"s": 10709,
"text": "This produces the following result −"
},
{
"code": null,
"e": 10783,
"s": 10746,
"text": "Error: can't find file or read data\n"
},
{
"code": null,
"e": 10861,
"s": 10783,
"text": "You can also use the except statement with no exceptions defined as follows −"
},
{
"code": null,
"e": 11072,
"s": 10861,
"text": "try:\n You do your operations here\n ......................\nexcept:\n If there is any exception, then execute this block.\n ......................\nelse:\n If there is no exception then execute this block. "
},
{
"code": null,
"e": 11363,
"s": 11072,
"text": "This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur."
},
{
"code": null,
"e": 11449,
"s": 11363,
"text": "You can also use the same except statement to handle multiple exceptions as follows −"
},
{
"code": null,
"e": 11737,
"s": 11449,
"text": "try:\n You do your operations here\n ......................\nexcept(Exception1[, Exception2[,...ExceptionN]]]):\n If there is any exception from the given exception list, \n then execute this block.\n ......................\nelse:\n If there is no exception then execute this block. "
},
{
"code": null,
"e": 11956,
"s": 11737,
"text": "You can use a finally: block along with a try: block. The finally: block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this −"
},
{
"code": null,
"e": 12134,
"s": 11956,
"text": "try:\n You do your operations here;\n ......................\n Due to any exception, this may be skipped.\nfinally:\n This would always be executed.\n ......................"
},
{
"code": null,
"e": 12274,
"s": 12134,
"text": "Note − You can provide except clause(s), or a finally clause, but not both. You cannot use else clause as well along with a finally clause."
},
{
"code": null,
"e": 12463,
"s": 12274,
"text": "#!/usr/bin/python3\n\ntry:\n fh = open(\"testfile\", \"w\")\n fh.write(\"This is my test file for exception handling!!\")\nfinally:\n print (\"Error: can\\'t find file or read data\")\n fh.close()"
},
{
"code": null,
"e": 12573,
"s": 12463,
"text": "If you do not have permission to open the file in writing mode, then this will produce the following result −"
},
{
"code": null,
"e": 12610,
"s": 12573,
"text": "Error: can't find file or read data\n"
},
{
"code": null,
"e": 12664,
"s": 12610,
"text": "Same example can be written more cleanly as follows −"
},
{
"code": null,
"e": 12926,
"s": 12664,
"text": "#!/usr/bin/python3\n\ntry:\n fh = open(\"testfile\", \"w\")\n try:\n fh.write(\"This is my test file for exception handling!!\")\n finally:\n print (\"Going to close the file\")\n fh.close()\nexcept IOError:\n print (\"Error: can\\'t find file or read data\")"
},
{
"code": null,
"e": 12963,
"s": 12926,
"text": "This produces the following result −"
},
{
"code": null,
"e": 12988,
"s": 12963,
"text": "Going to close the file\n"
},
{
"code": null,
"e": 13284,
"s": 12988,
"text": "When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement."
},
{
"code": null,
"e": 13532,
"s": 13284,
"text": "An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows −"
},
{
"code": null,
"e": 13671,
"s": 13532,
"text": "try:\n You do your operations here\n ......................\nexcept ExceptionType as Argument:\n You can print value of Argument here..."
},
{
"code": null,
"e": 13905,
"s": 13671,
"text": "If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception."
},
{
"code": null,
"e": 14171,
"s": 13905,
"text": "This variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location."
},
{
"code": null,
"e": 14220,
"s": 14171,
"text": "Following is an example for a single exception −"
},
{
"code": null,
"e": 14468,
"s": 14220,
"text": "#!/usr/bin/python3\n\n# Define a function here.\ndef temp_convert(var):\n try:\n return int(var)\n except ValueError as Argument:\n print (\"The argument does not contain numbers\\n\", Argument)\n\n# Call above function here.\ntemp_convert(\"xyz\")"
},
{
"code": null,
"e": 14505,
"s": 14468,
"text": "This produces the following result −"
},
{
"code": null,
"e": 14590,
"s": 14505,
"text": "The argument does not contain numbers\ninvalid literal for int() with base 10: 'xyz'\n"
},
{
"code": null,
"e": 14720,
"s": 14590,
"text": "You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows −"
},
{
"code": null,
"e": 14762,
"s": 14720,
"text": "raise [Exception [, args [, traceback]]]\n"
},
{
"code": null,
"e": 14955,
"s": 14762,
"text": "Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None."
},
{
"code": null,
"e": 15098,
"s": 14955,
"text": "The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception."
},
{
"code": null,
"e": 15332,
"s": 15098,
"text": "An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows −"
},
{
"code": null,
"e": 15507,
"s": 15332,
"text": "def functionName( level ):\n if level <1:\n raise Exception(level)\n # The code below to this would not be executed\n # if we raise the exception\n return level"
},
{
"code": null,
"e": 15740,
"s": 15507,
"text": "Note − In order to catch an exception, an \"except\" clause must refer to the same exception thrown either as a class object or a simple string. For example, to capture the above exception, we must write the except clause as follows −"
},
{
"code": null,
"e": 15871,
"s": 15740,
"text": "try:\n Business Logic here...\nexcept Exception as e:\n Exception handling here using e.args...\nelse:\n Rest of the code here..."
},
{
"code": null,
"e": 15939,
"s": 15871,
"text": "The following example illustrates the use of raising an exception −"
},
{
"code": null,
"e": 16259,
"s": 15939,
"text": "#!/usr/bin/python3\n\ndef functionName( level ):\n if level <1:\n raise Exception(level)\n # The code below to this would not be executed\n # if we raise the exception\n return level\n\ntry:\n l = functionName(-10)\n print (\"level = \",l)\nexcept Exception as e:\n print (\"error in level argument\",e.args[0])"
},
{
"code": null,
"e": 16298,
"s": 16259,
"text": "This will produce the following result"
},
{
"code": null,
"e": 16327,
"s": 16298,
"text": "error in level argument -10\n"
},
{
"code": null,
"e": 16439,
"s": 16327,
"text": "Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions."
},
{
"code": null,
"e": 16641,
"s": 16439,
"text": "Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught."
},
{
"code": null,
"e": 16800,
"s": 16641,
"text": "In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror."
},
{
"code": null,
"e": 16884,
"s": 16800,
"text": "class Networkerror(RuntimeError):\n def __init__(self, arg):\n self.args = arg"
},
{
"code": null,
"e": 16967,
"s": 16884,
"text": "So once you have defined the above class, you can raise the exception as follows −"
},
{
"code": null,
"e": 17049,
"s": 16967,
"text": "try:\n raise Networkerror(\"Bad hostname\")\nexcept Networkerror,e:\n print e.args"
},
{
"code": null,
"e": 17086,
"s": 17049,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 17102,
"s": 17086,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 17135,
"s": 17102,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 17154,
"s": 17135,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 17189,
"s": 17154,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 17211,
"s": 17189,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 17245,
"s": 17211,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 17273,
"s": 17245,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 17308,
"s": 17273,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 17322,
"s": 17308,
"text": " Lets Kode It"
},
{
"code": null,
"e": 17355,
"s": 17322,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 17372,
"s": 17355,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 17379,
"s": 17372,
"text": " Print"
},
{
"code": null,
"e": 17390,
"s": 17379,
"text": " Add Notes"
}
] |
Minimum characters that are to be inserted such that no three consecutive characters are same - GeeksforGeeks | 21 May, 2021
Given a string str and the task is to modify the string such that no three consecutive characters are same. In a single operation, any character can be inserted at any position in the string. Find the minimum number of such operations required.Examples:
Input : str = “aabbbcc” Output: 1 “aabbdbcc” is the modified string.Input: str = “geeksforgeeks” Output: 0
Approach: For every three consecutive characters which are same, a single character has to be inserted in between them to make any three consecutive characters different. But the number of operations needs to be minimized so the character must be inserted after the second character. For example, if the string is “bbbb” then if the character is inserted at the second position i.e. “babbb” then there are still three consecutive same characters and another operation is required to resolve that but if the character was inserted at the third position i.e. “bbabb” then only a single operation is required.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of characters// that are to be inserted in str such that no// three consecutive characters are sameint getCount(string str, int n){ // To store the count of // operations required int cnt = 0; int i = 0; while (i < n - 2) { // A character needs to be // inserted after str[i + 1] if (str[i] == str[i + 1] && str[i] == str[i + 2]) { cnt++; i = i + 2; } // Current three consecutive // characters are not same else i++; } return cnt;} // Driver codeint main(){ string str = "aabbbcc"; int n = str.length(); cout << getCount(str, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the count of characters // that are to be inserted in str such that no // three consecutive characters are same static int getCount(char[] str, int n) { // To store the count of // operations required int cnt = 0; int i = 0; while (i < n - 2) { // A character needs to be // inserted after str[i + 1] if (str[i] == str[i + 1] && str[i] == str[i + 2]) { cnt++; i = i + 2; } // Current three consecutive // characters are not same else { i++; } } return cnt; } // Driver code static public void main(String[] arg) { String str = "aabbbcc"; int n = str.length(); System.out.println(getCount(str.toCharArray(), n)); }} // This code is contributed by PrinciRaj1992
# Python3 implementation of the approach # Function to return the count of characters# that are to be inserted in str1 such that no# three consecutive characters are samedef getCount(str1, n): # To store the count of # operations required cnt = 0; i = 0; while (i < n - 2): # A character needs to be # inserted after str1[i + 1] if (str1[i] == str1[i + 1] and str1[i] == str1[i + 2]): cnt += 1 i = i + 2 # Current three consecutive # characters are not same else: i += 1 return cnt # Driver codestr1 = "aabbbcc"n = len(str1) print(getCount(str1, n)) # This code is contributed by Mohit Kumar
// C# implementation of the above approachusing System; class GFG{ // Function to return the count of characters // that are to be inserted in str such that no // three consecutive characters are same static int getCount(string str, int n) { // To store the count of // operations required int cnt = 0; int i = 0; while (i < n - 2) { // A character needs to be // inserted after str[i + 1] if (str[i] == str[i + 1] && str[i] == str[i + 2]) { cnt++; i = i + 2; } // Current three consecutive // characters are not same else { i++; } } return cnt; } // Driver code static public void Main () { string str = "aabbbcc"; int n = str.Length; Console.WriteLine(getCount(str, n)); }} // This code is contributed by AnkitRai01
<script> // JavaScript implementation of the above approach // Function to return the count of characters // that are to be inserted in str such that no // three consecutive characters are same function getCount(str, n) { // To store the count of // operations required var cnt = 0; var i = 0; while (i < n - 2) { // A character needs to be // inserted after str[i + 1] if (str[i] === str[i + 1] && str[i] === str[i + 2]) { cnt++; i = i + 2; } // Current three consecutive // characters are not same else { i++; } } return cnt; } // Driver code var str = "aabbbcc"; var n = str.length; document.write(getCount(str, n)); </script>
1
princiraj1992
ankthon
mohit kumar 29
rdtank
Constructive Algorithms
Data Structures
Strings
Data Structures
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Tree Data Structure
Static Data Structure vs Dynamic Data Structure
TCS NQT Coding Sheet
Building an undirected graph and finding shortest path using Dictionaries in Python
Program to implement Singly Linked List in C++ using class
Longest Common Subsequence | DP-4
Reverse a string in Java
Write a program to print all permutations of a given string
KMP Algorithm for Pattern Searching
C++ Data Types | [
{
"code": null,
"e": 24637,
"s": 24609,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 24893,
"s": 24637,
"text": "Given a string str and the task is to modify the string such that no three consecutive characters are same. In a single operation, any character can be inserted at any position in the string. Find the minimum number of such operations required.Examples: "
},
{
"code": null,
"e": 25002,
"s": 24893,
"text": "Input : str = “aabbbcc” Output: 1 “aabbdbcc” is the modified string.Input: str = “geeksforgeeks” Output: 0 "
},
{
"code": null,
"e": 25663,
"s": 25004,
"text": "Approach: For every three consecutive characters which are same, a single character has to be inserted in between them to make any three consecutive characters different. But the number of operations needs to be minimized so the character must be inserted after the second character. For example, if the string is “bbbb” then if the character is inserted at the second position i.e. “babbb” then there are still three consecutive same characters and another operation is required to resolve that but if the character was inserted at the third position i.e. “bbabb” then only a single operation is required.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25667,
"s": 25663,
"text": "C++"
},
{
"code": null,
"e": 25672,
"s": 25667,
"text": "Java"
},
{
"code": null,
"e": 25680,
"s": 25672,
"text": "Python3"
},
{
"code": null,
"e": 25683,
"s": 25680,
"text": "C#"
},
{
"code": null,
"e": 25694,
"s": 25683,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of characters// that are to be inserted in str such that no// three consecutive characters are sameint getCount(string str, int n){ // To store the count of // operations required int cnt = 0; int i = 0; while (i < n - 2) { // A character needs to be // inserted after str[i + 1] if (str[i] == str[i + 1] && str[i] == str[i + 2]) { cnt++; i = i + 2; } // Current three consecutive // characters are not same else i++; } return cnt;} // Driver codeint main(){ string str = \"aabbbcc\"; int n = str.length(); cout << getCount(str, n); return 0;}",
"e": 26483,
"s": 25694,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the count of characters // that are to be inserted in str such that no // three consecutive characters are same static int getCount(char[] str, int n) { // To store the count of // operations required int cnt = 0; int i = 0; while (i < n - 2) { // A character needs to be // inserted after str[i + 1] if (str[i] == str[i + 1] && str[i] == str[i + 2]) { cnt++; i = i + 2; } // Current three consecutive // characters are not same else { i++; } } return cnt; } // Driver code static public void main(String[] arg) { String str = \"aabbbcc\"; int n = str.length(); System.out.println(getCount(str.toCharArray(), n)); }} // This code is contributed by PrinciRaj1992",
"e": 27534,
"s": 26483,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the count of characters# that are to be inserted in str1 such that no# three consecutive characters are samedef getCount(str1, n): # To store the count of # operations required cnt = 0; i = 0; while (i < n - 2): # A character needs to be # inserted after str1[i + 1] if (str1[i] == str1[i + 1] and str1[i] == str1[i + 2]): cnt += 1 i = i + 2 # Current three consecutive # characters are not same else: i += 1 return cnt # Driver codestr1 = \"aabbbcc\"n = len(str1) print(getCount(str1, n)) # This code is contributed by Mohit Kumar",
"e": 28235,
"s": 27534,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to return the count of characters // that are to be inserted in str such that no // three consecutive characters are same static int getCount(string str, int n) { // To store the count of // operations required int cnt = 0; int i = 0; while (i < n - 2) { // A character needs to be // inserted after str[i + 1] if (str[i] == str[i + 1] && str[i] == str[i + 2]) { cnt++; i = i + 2; } // Current three consecutive // characters are not same else { i++; } } return cnt; } // Driver code static public void Main () { string str = \"aabbbcc\"; int n = str.Length; Console.WriteLine(getCount(str, n)); }} // This code is contributed by AnkitRai01",
"e": 29253,
"s": 28235,
"text": null
},
{
"code": "<script> // JavaScript implementation of the above approach // Function to return the count of characters // that are to be inserted in str such that no // three consecutive characters are same function getCount(str, n) { // To store the count of // operations required var cnt = 0; var i = 0; while (i < n - 2) { // A character needs to be // inserted after str[i + 1] if (str[i] === str[i + 1] && str[i] === str[i + 2]) { cnt++; i = i + 2; } // Current three consecutive // characters are not same else { i++; } } return cnt; } // Driver code var str = \"aabbbcc\"; var n = str.length; document.write(getCount(str, n)); </script>",
"e": 30094,
"s": 29253,
"text": null
},
{
"code": null,
"e": 30096,
"s": 30094,
"text": "1"
},
{
"code": null,
"e": 30112,
"s": 30098,
"text": "princiraj1992"
},
{
"code": null,
"e": 30120,
"s": 30112,
"text": "ankthon"
},
{
"code": null,
"e": 30135,
"s": 30120,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 30142,
"s": 30135,
"text": "rdtank"
},
{
"code": null,
"e": 30166,
"s": 30142,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 30182,
"s": 30166,
"text": "Data Structures"
},
{
"code": null,
"e": 30190,
"s": 30182,
"text": "Strings"
},
{
"code": null,
"e": 30206,
"s": 30190,
"text": "Data Structures"
},
{
"code": null,
"e": 30214,
"s": 30206,
"text": "Strings"
},
{
"code": null,
"e": 30312,
"s": 30214,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30321,
"s": 30312,
"text": "Comments"
},
{
"code": null,
"e": 30334,
"s": 30321,
"text": "Old Comments"
},
{
"code": null,
"e": 30370,
"s": 30334,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 30418,
"s": 30370,
"text": "Static Data Structure vs Dynamic Data Structure"
},
{
"code": null,
"e": 30439,
"s": 30418,
"text": "TCS NQT Coding Sheet"
},
{
"code": null,
"e": 30523,
"s": 30439,
"text": "Building an undirected graph and finding shortest path using Dictionaries in Python"
},
{
"code": null,
"e": 30582,
"s": 30523,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 30616,
"s": 30582,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 30641,
"s": 30616,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30701,
"s": 30641,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30737,
"s": 30701,
"text": "KMP Algorithm for Pattern Searching"
}
] |
How to plot a smooth 2D color plot for z = f(x, y) in Matplotlib? | To plot a smooth 2D color plot for z = f(x, y) in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Get z data points using f(x, y).
Display the data as an image, i.e., on a 2D regular raster, with z data points.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
def f(x, y):
return np.array([i * i + j * j for j in y for i in x]).reshape(5, 5)
x = y = np.linspace(-1, 1, 5)
z = f(x, y)
plt.imshow(z, interpolation='bilinear')
plt.show() | [
{
"code": null,
"e": 1158,
"s": 1062,
"text": "To plot a smooth 2D color plot for z = f(x, y) in Matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1234,
"s": 1158,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1274,
"s": 1234,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1307,
"s": 1274,
"text": "Get z data points using f(x, y)."
},
{
"code": null,
"e": 1387,
"s": 1307,
"text": "Display the data as an image, i.e., on a 2D regular raster, with z data points."
},
{
"code": null,
"e": 1429,
"s": 1387,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1755,
"s": 1429,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndef f(x, y):\n return np.array([i * i + j * j for j in y for i in x]).reshape(5, 5)\n\nx = y = np.linspace(-1, 1, 5)\nz = f(x, y)\n\nplt.imshow(z, interpolation='bilinear')\n\nplt.show()"
}
] |
How to Update Your Live Django Website | Towards Data Science | I’ve recently built a web app (see it here) using Django and deployed it through DigitalOcean.
There are many wonderful reasons to use DigitalOcean, but updating is not one of them. Because it is a cloud hosting provider and not a PaaS like AWS Elastic Beanstalk, the updating process is 100% your problem.
Plus, if you’ve also deployed with DigitalOcean, you might have realized that there are very few resources on how to run updates. That’s where I come in.
I’ve written about this process in my detailed walkthrough of how I built my website (which you can read below if you’d like to), but I wanted to elaborate on this to help fill in the knowledge gap for beginners like myself.
towardsdatascience.com
If you’re deploying elsewhere than DigitalOcean, updating is much easier, and here are some pages that may be relevant to you:
AWS Elastic Beanstalk (Console / Command Line Interface)
Heroku
Microsoft Azure
Step 1: If Django: Configure your Django settings for local debugging. You need to do this to run your work-in-progress on your localhost.
# in settings.pyDEBUG = TrueALLOWED_HOSTS = []
You could make this slightly easier if you use a custom variable in your settings file to switch between ‘live’ and ‘local’ modes, especially if your database changes too (e.g. if you use PostgreSQL).
In this example, all I do is toggle the live_deploy variable when I want to edit or deploy.
Step 2: Make updates in your project’s code.
Step 3: If Django: Make migrations. Make them locally but do the migration on the server because migration files are part of the source code and shouldn’t be tampered with on the server. Read this StackOverflow post for more info.
# in terminalpython3 manage.py makemigrations
Step 4: If Django: Reconfigure your settings for deploying live.
# in settings.pyDEBUG = FalseALLOWED_HOSTS = ['00.000.0.000','www.yourdomain.com'] # insert your IP or domain
Step 5: Stage your changes, commit them to Git and push them to your remote repository of choice. Extremely important, because the remote is where you’ll get the code from while in DigitalOcean (Step 8).
# in terminalgit commit -m "your commit message"git push origin master
Step 6: Login to your DigitalOcean virtual machine with SSH.
# in terminalssh [email protected]
Step 7: Activate the virtual environment you’re using for your project, because you need to run Django commands.
# in terminalsource venv/bin/activate #replace with your venv
Step 8: From your project directory, pull your updated code from your remote repository.
# in terminalcd /your/project/dirgit pull origin
Step 9: If Django: Run migration and collect static. Do not make migrations — refer to Step 3.
# in terminalpython3 manage.py migratepython3 manage.py collectstatic
Step 10: Restart Gunicorn (your WSGI server) to apply the changes. Typically you won’t need to restart NGINX since no changes are made to the web server — the only time I do is when I renew my SSL certificate.
# in terminalsudo service gunicorn restartsudo service nginx restart #only if you need to
Seems a little drawn-out, but it’s important to stick to all the steps to ensure that your new code is correctly configured for live deployment, makes it onto the virtual machine, and shows up in your website or app.
If you want to automate updates, you can do so with Fabric and Ansible. You can find a pretty complete guide here, so I won’t expand on it.
But if you’re just starting out like me, odds are you won’t need to perform frequent updates, and prefer to keep things as simple as possible.
In that case, these 10 steps will be all you need to run updates reliably every time. | [
{
"code": null,
"e": 266,
"s": 171,
"text": "I’ve recently built a web app (see it here) using Django and deployed it through DigitalOcean."
},
{
"code": null,
"e": 478,
"s": 266,
"text": "There are many wonderful reasons to use DigitalOcean, but updating is not one of them. Because it is a cloud hosting provider and not a PaaS like AWS Elastic Beanstalk, the updating process is 100% your problem."
},
{
"code": null,
"e": 632,
"s": 478,
"text": "Plus, if you’ve also deployed with DigitalOcean, you might have realized that there are very few resources on how to run updates. That’s where I come in."
},
{
"code": null,
"e": 857,
"s": 632,
"text": "I’ve written about this process in my detailed walkthrough of how I built my website (which you can read below if you’d like to), but I wanted to elaborate on this to help fill in the knowledge gap for beginners like myself."
},
{
"code": null,
"e": 880,
"s": 857,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1007,
"s": 880,
"text": "If you’re deploying elsewhere than DigitalOcean, updating is much easier, and here are some pages that may be relevant to you:"
},
{
"code": null,
"e": 1064,
"s": 1007,
"text": "AWS Elastic Beanstalk (Console / Command Line Interface)"
},
{
"code": null,
"e": 1071,
"s": 1064,
"text": "Heroku"
},
{
"code": null,
"e": 1087,
"s": 1071,
"text": "Microsoft Azure"
},
{
"code": null,
"e": 1226,
"s": 1087,
"text": "Step 1: If Django: Configure your Django settings for local debugging. You need to do this to run your work-in-progress on your localhost."
},
{
"code": null,
"e": 1273,
"s": 1226,
"text": "# in settings.pyDEBUG = TrueALLOWED_HOSTS = []"
},
{
"code": null,
"e": 1474,
"s": 1273,
"text": "You could make this slightly easier if you use a custom variable in your settings file to switch between ‘live’ and ‘local’ modes, especially if your database changes too (e.g. if you use PostgreSQL)."
},
{
"code": null,
"e": 1566,
"s": 1474,
"text": "In this example, all I do is toggle the live_deploy variable when I want to edit or deploy."
},
{
"code": null,
"e": 1611,
"s": 1566,
"text": "Step 2: Make updates in your project’s code."
},
{
"code": null,
"e": 1842,
"s": 1611,
"text": "Step 3: If Django: Make migrations. Make them locally but do the migration on the server because migration files are part of the source code and shouldn’t be tampered with on the server. Read this StackOverflow post for more info."
},
{
"code": null,
"e": 1888,
"s": 1842,
"text": "# in terminalpython3 manage.py makemigrations"
},
{
"code": null,
"e": 1953,
"s": 1888,
"text": "Step 4: If Django: Reconfigure your settings for deploying live."
},
{
"code": null,
"e": 2063,
"s": 1953,
"text": "# in settings.pyDEBUG = FalseALLOWED_HOSTS = ['00.000.0.000','www.yourdomain.com'] # insert your IP or domain"
},
{
"code": null,
"e": 2267,
"s": 2063,
"text": "Step 5: Stage your changes, commit them to Git and push them to your remote repository of choice. Extremely important, because the remote is where you’ll get the code from while in DigitalOcean (Step 8)."
},
{
"code": null,
"e": 2338,
"s": 2267,
"text": "# in terminalgit commit -m \"your commit message\"git push origin master"
},
{
"code": null,
"e": 2399,
"s": 2338,
"text": "Step 6: Login to your DigitalOcean virtual machine with SSH."
},
{
"code": null,
"e": 2434,
"s": 2399,
"text": "# in terminalssh [email protected]"
},
{
"code": null,
"e": 2547,
"s": 2434,
"text": "Step 7: Activate the virtual environment you’re using for your project, because you need to run Django commands."
},
{
"code": null,
"e": 2609,
"s": 2547,
"text": "# in terminalsource venv/bin/activate #replace with your venv"
},
{
"code": null,
"e": 2698,
"s": 2609,
"text": "Step 8: From your project directory, pull your updated code from your remote repository."
},
{
"code": null,
"e": 2747,
"s": 2698,
"text": "# in terminalcd /your/project/dirgit pull origin"
},
{
"code": null,
"e": 2842,
"s": 2747,
"text": "Step 9: If Django: Run migration and collect static. Do not make migrations — refer to Step 3."
},
{
"code": null,
"e": 2912,
"s": 2842,
"text": "# in terminalpython3 manage.py migratepython3 manage.py collectstatic"
},
{
"code": null,
"e": 3122,
"s": 2912,
"text": "Step 10: Restart Gunicorn (your WSGI server) to apply the changes. Typically you won’t need to restart NGINX since no changes are made to the web server — the only time I do is when I renew my SSL certificate."
},
{
"code": null,
"e": 3212,
"s": 3122,
"text": "# in terminalsudo service gunicorn restartsudo service nginx restart #only if you need to"
},
{
"code": null,
"e": 3429,
"s": 3212,
"text": "Seems a little drawn-out, but it’s important to stick to all the steps to ensure that your new code is correctly configured for live deployment, makes it onto the virtual machine, and shows up in your website or app."
},
{
"code": null,
"e": 3569,
"s": 3429,
"text": "If you want to automate updates, you can do so with Fabric and Ansible. You can find a pretty complete guide here, so I won’t expand on it."
},
{
"code": null,
"e": 3712,
"s": 3569,
"text": "But if you’re just starting out like me, odds are you won’t need to perform frequent updates, and prefer to keep things as simple as possible."
}
] |
Pandas – Remove special characters from column names | 05 Sep, 2020
Let us see how to remove special characters like #, @, &, etc. from column names in the pandas data frame. Here we will use replace function for removing special character.
Example 1: remove a special character from column names
Python
# import pandasimport pandas as pd # create data frameData = {'Name#': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location': ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut'], 'Pay': [25000, 30000, 35000, 40000, 45000]} df = pd.DataFrame(Data) # print original data frameprint(df) # remove special characterdf.columns = df.columns.str.replace('[#,@,&]', '') # print file after removing special characterprint("\n\n", df)
Output:
Here, we have successfully remove a special character from the column names. Now we will use a list with replace function for removing multiple special characters from our column names.
Example 2: remove multiple special characters from the pandas data frame
Python
# import pandasimport pandas as pd # create data frameData = {'Name#': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location@' : ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut'], 'Pay&' : [25000,30000,35000,40000,45000]} df=pd.DataFrame(Data) # print original data frameprint(df) # remove special characterdf.columns=df.columns.str.replace('[#,@,&]','') # print file after removing special characterprint("\n\n" , df)
Output:
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 227,
"s": 53,
"text": "Let us see how to remove special characters like #, @, &, etc. from column names in the pandas data frame. Here we will use replace function for removing special character."
},
{
"code": null,
"e": 283,
"s": 227,
"text": "Example 1: remove a special character from column names"
},
{
"code": null,
"e": 290,
"s": 283,
"text": "Python"
},
{
"code": "# import pandasimport pandas as pd # create data frameData = {'Name#': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location': ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut'], 'Pay': [25000, 30000, 35000, 40000, 45000]} df = pd.DataFrame(Data) # print original data frameprint(df) # remove special characterdf.columns = df.columns.str.replace('[#,@,&]', '') # print file after removing special characterprint(\"\\n\\n\", df)",
"e": 803,
"s": 290,
"text": null
},
{
"code": null,
"e": 811,
"s": 803,
"text": "Output:"
},
{
"code": null,
"e": 997,
"s": 811,
"text": "Here, we have successfully remove a special character from the column names. Now we will use a list with replace function for removing multiple special characters from our column names."
},
{
"code": null,
"e": 1070,
"s": 997,
"text": "Example 2: remove multiple special characters from the pandas data frame"
},
{
"code": null,
"e": 1077,
"s": 1070,
"text": "Python"
},
{
"code": "# import pandasimport pandas as pd # create data frameData = {'Name#': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location@' : ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut'], 'Pay&' : [25000,30000,35000,40000,45000]} df=pd.DataFrame(Data) # print original data frameprint(df) # remove special characterdf.columns=df.columns.str.replace('[#,@,&]','') # print file after removing special characterprint(\"\\n\\n\" , df)",
"e": 1594,
"s": 1077,
"text": null
},
{
"code": null,
"e": 1602,
"s": 1594,
"text": "Output:"
},
{
"code": null,
"e": 1616,
"s": 1602,
"text": "Python-pandas"
},
{
"code": null,
"e": 1623,
"s": 1616,
"text": "Python"
}
] |
GenericIPAddressField – Django Models | 12 Feb, 2020
GenericIPAddressField is a field which stores an IPv4 or IPv6 address, in string format (e.g. 192.0.2.30 or 2a02:42fe::4). The default form widget for this field is a TextInput. The IPv6 address normalization follows RFC 4291#section-2.2 section 2.2, including using the IPv4 format suggested in paragraph 3 of that section, like ::ffff:192.0.2.0. For example, 2001:0::0:01 would be normalized to 2001::1, and ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. All characters are converted to lowercase.
Syntax:
field_name = models.GenericIPAddressField(**options)
GenericIPAddressField accepts following arguments :
GenericIPAddressField.protocol
Limits valid inputs to the specified protocol. Accepted values are ‘both‘ (default), ‘IPv4‘ or ‘IPv6‘. Matching is case insensitive.
GenericIPAddressField.unpack_ipv4
Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to ‘both’.
Illustration of GenericIPAddressField using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app.
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.GenericIPAddressField()
Add the geeks app to INSTALLED_APPS
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]
Now when we run makemigrations command from the terminal,
Python manage.py makemigrations
A new folder named migrations would be created in geeks directory with a file named 0001_initial.py
# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.GenericIPAddressField()), ], ), ]
Now run,
Python manage.py migrate
Thus, an geeks_field GenericIPAddressField is created when you run migrations on the project. It is a field to store a integer numbers.
GenericIPAddressField is used for storing Pv4 or IPv6 address, in string format, so it is basically a CharField with validation of IP Address. Let’s try to save a IP address “0.0.0.0” in this field.
# importing the model# from geeks appfrom geeks.models import GeeksModel # creating an instance of# IP addressesd = "0.0.0.0" # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()
Now let’s check it in admin server. We have created an instance of GeeksModel.
Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to GenericIPAddressField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an GenericIPAddressField can use.
NaveenArora
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Feb, 2020"
},
{
"code": null,
"e": 521,
"s": 28,
"text": "GenericIPAddressField is a field which stores an IPv4 or IPv6 address, in string format (e.g. 192.0.2.30 or 2a02:42fe::4). The default form widget for this field is a TextInput. The IPv6 address normalization follows RFC 4291#section-2.2 section 2.2, including using the IPv4 format suggested in paragraph 3 of that section, like ::ffff:192.0.2.0. For example, 2001:0::0:01 would be normalized to 2001::1, and ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. All characters are converted to lowercase."
},
{
"code": null,
"e": 529,
"s": 521,
"text": "Syntax:"
},
{
"code": null,
"e": 582,
"s": 529,
"text": "field_name = models.GenericIPAddressField(**options)"
},
{
"code": null,
"e": 634,
"s": 582,
"text": "GenericIPAddressField accepts following arguments :"
},
{
"code": null,
"e": 665,
"s": 634,
"text": "GenericIPAddressField.protocol"
},
{
"code": null,
"e": 798,
"s": 665,
"text": "Limits valid inputs to the specified protocol. Accepted values are ‘both‘ (default), ‘IPv4‘ or ‘IPv6‘. Matching is case insensitive."
},
{
"code": null,
"e": 832,
"s": 798,
"text": "GenericIPAddressField.unpack_ipv4"
},
{
"code": null,
"e": 1026,
"s": 832,
"text": "Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to ‘both’."
},
{
"code": null,
"e": 1148,
"s": 1026,
"text": "Illustration of GenericIPAddressField using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 1235,
"s": 1148,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 1286,
"s": 1235,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 1319,
"s": 1286,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 1378,
"s": 1319,
"text": "Enter the following code into models.py file of geeks app."
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.GenericIPAddressField()",
"e": 1541,
"s": 1378,
"text": null
},
{
"code": null,
"e": 1577,
"s": 1541,
"text": "Add the geeks app to INSTALLED_APPS"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]",
"e": 1815,
"s": 1577,
"text": null
},
{
"code": null,
"e": 1873,
"s": 1815,
"text": "Now when we run makemigrations command from the terminal,"
},
{
"code": null,
"e": 1905,
"s": 1873,
"text": "Python manage.py makemigrations"
},
{
"code": null,
"e": 2005,
"s": 1905,
"text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py"
},
{
"code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.GenericIPAddressField()), ], ), ]",
"e": 2621,
"s": 2005,
"text": null
},
{
"code": null,
"e": 2630,
"s": 2621,
"text": "Now run,"
},
{
"code": null,
"e": 2655,
"s": 2630,
"text": "Python manage.py migrate"
},
{
"code": null,
"e": 2791,
"s": 2655,
"text": "Thus, an geeks_field GenericIPAddressField is created when you run migrations on the project. It is a field to store a integer numbers."
},
{
"code": null,
"e": 2990,
"s": 2791,
"text": "GenericIPAddressField is used for storing Pv4 or IPv6 address, in string format, so it is basically a CharField with validation of IP Address. Let’s try to save a IP address “0.0.0.0” in this field."
},
{
"code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # creating an instance of# IP addressesd = \"0.0.0.0\" # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()",
"e": 3230,
"s": 2990,
"text": null
},
{
"code": null,
"e": 3309,
"s": 3230,
"text": "Now let’s check it in admin server. We have created an instance of GeeksModel."
},
{
"code": null,
"e": 3679,
"s": 3309,
"text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to GenericIPAddressField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an GenericIPAddressField can use."
},
{
"code": null,
"e": 3691,
"s": 3679,
"text": "NaveenArora"
},
{
"code": null,
"e": 3705,
"s": 3691,
"text": "Django-models"
},
{
"code": null,
"e": 3719,
"s": 3705,
"text": "Python Django"
},
{
"code": null,
"e": 3726,
"s": 3719,
"text": "Python"
}
] |
Writing a Windows batch script | 08 Jun, 2022
In Windows, the batch file is a file that stores commands in a serial order. The command line interpreter takes the file as an input and executes in the same order. A batch file is simply a text file saved with the .bat file extension. It can be written using Notepad or any other text editor. A simple batch file will be:
// When echo is turned off, the command prompt doesn't appear in the Command Prompt window.
ECHO OFF
// The following command writes GeeksforGeeks to the console.
ECHO GeeksforGeeks
// The following command suspends the processing of a batch program and displays the prompt.
PAUSE
After saving it with a .bat extension. Double click it to run the file. It prints shows:
In the above script, ECHO off cleans up the console by hiding the commands from being printed at the prompt, ECHO prints the text “GeeksforGeeks” to the screen, and then waits for the user to press a key so the program can be ceased. Some basic commands of batch file:
ECHO – Prints out the input string. It can be ON or OFF, for ECHO to turn the echoing feature on or off. If ECHO is ON, the command prompt will display the command it is executing.
CLS – Clears the command prompt screen.
TITLE – Changes the title text displayed on top of prompt window.
EXIT – To exit the Command Prompt.
PAUSE – Used to stop the execution of a Windows batch file.
:: – Add a comment in the batch file.
COPY – Copy a file or files.
Types of “batch” files in Windows:
INI (*.ini) – Initialization file. These set the default variables in the system and programs.CFG (*.cfg) – These are the configuration files.SYS (*.sys) – System files, can sometimes be edited, mostly compiled machine code in new versions.COM (*.com) – Command files. These are the executable files for all the DOS commands. In early versions there was a separate file for each command. Now, most are inside COMMAND.COM.CMD (*.cmd) – These were the batch files used in NT operating systems.
INI (*.ini) – Initialization file. These set the default variables in the system and programs.
CFG (*.cfg) – These are the configuration files.
SYS (*.sys) – System files, can sometimes be edited, mostly compiled machine code in new versions.
COM (*.com) – Command files. These are the executable files for all the DOS commands. In early versions there was a separate file for each command. Now, most are inside COMMAND.COM.
CMD (*.cmd) – These were the batch files used in NT operating systems.
Lets take another example, Suppose we need to list down all the files/directory names inside a particular directory and save it to a text file, so batch script for it will be,
@ECHO OFF
// A comment line can be added to the batch file with the REM command.
REM This is a comment line.
REM Listing all the files in the directory Program files
DIR"C:\Program Files" > C:\geeks_list.txt
ECHO "Done!"
Now when we run this batch script, it will create a file name geeks_list.txt in your C:\ directory, displaying all the files/folder names in C:\Program Files. Another useful batch script that can be written to diagnose your network and check performance of it:
// This batch file checks for network connection problems.
ECHO OFF
// View network connection details
IPCONFIG /all
// Check if geeksforgeeks.com is reachable
PING geeksforgeeks.com
// Run a traceroute to check the route to geeksforgeeks.com
TRACERT geeksforgeeks.com
PAUSE
This script displays:
This script gives information about the current network and some network packet information. ipconfig /all helps to view the network information and ‘ping’ & ‘tracert’ to get each packet info. Learn about ping and traceroute here.
shubham_singh
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
What is Hashing | A Complete Tutorial
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa
Roadmap to Learn JavaScript For Beginners
How To Switch From A Service-Based To A Product-Based Company?
What is the Role of Fuzzy Logic in Algorithmic Trading?
What is Data Structure: Types, Classifications and Applications | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 376,
"s": 53,
"text": "In Windows, the batch file is a file that stores commands in a serial order. The command line interpreter takes the file as an input and executes in the same order. A batch file is simply a text file saved with the .bat file extension. It can be written using Notepad or any other text editor. A simple batch file will be:"
},
{
"code": null,
"e": 659,
"s": 376,
"text": "// When echo is turned off, the command prompt doesn't appear in the Command Prompt window.\nECHO OFF\n\n// The following command writes GeeksforGeeks to the console.\nECHO GeeksforGeeks\n\n// The following command suspends the processing of a batch program and displays the prompt.\nPAUSE"
},
{
"code": null,
"e": 748,
"s": 659,
"text": "After saving it with a .bat extension. Double click it to run the file. It prints shows:"
},
{
"code": null,
"e": 1019,
"s": 750,
"text": "In the above script, ECHO off cleans up the console by hiding the commands from being printed at the prompt, ECHO prints the text “GeeksforGeeks” to the screen, and then waits for the user to press a key so the program can be ceased. Some basic commands of batch file:"
},
{
"code": null,
"e": 1200,
"s": 1019,
"text": "ECHO – Prints out the input string. It can be ON or OFF, for ECHO to turn the echoing feature on or off. If ECHO is ON, the command prompt will display the command it is executing."
},
{
"code": null,
"e": 1240,
"s": 1200,
"text": "CLS – Clears the command prompt screen."
},
{
"code": null,
"e": 1307,
"s": 1240,
"text": "TITLE – Changes the title text displayed on top of prompt window."
},
{
"code": null,
"e": 1342,
"s": 1307,
"text": "EXIT – To exit the Command Prompt."
},
{
"code": null,
"e": 1402,
"s": 1342,
"text": "PAUSE – Used to stop the execution of a Windows batch file."
},
{
"code": null,
"e": 1440,
"s": 1402,
"text": ":: – Add a comment in the batch file."
},
{
"code": null,
"e": 1469,
"s": 1440,
"text": "COPY – Copy a file or files."
},
{
"code": null,
"e": 1504,
"s": 1469,
"text": "Types of “batch” files in Windows:"
},
{
"code": null,
"e": 1996,
"s": 1504,
"text": "INI (*.ini) – Initialization file. These set the default variables in the system and programs.CFG (*.cfg) – These are the configuration files.SYS (*.sys) – System files, can sometimes be edited, mostly compiled machine code in new versions.COM (*.com) – Command files. These are the executable files for all the DOS commands. In early versions there was a separate file for each command. Now, most are inside COMMAND.COM.CMD (*.cmd) – These were the batch files used in NT operating systems."
},
{
"code": null,
"e": 2091,
"s": 1996,
"text": "INI (*.ini) – Initialization file. These set the default variables in the system and programs."
},
{
"code": null,
"e": 2140,
"s": 2091,
"text": "CFG (*.cfg) – These are the configuration files."
},
{
"code": null,
"e": 2239,
"s": 2140,
"text": "SYS (*.sys) – System files, can sometimes be edited, mostly compiled machine code in new versions."
},
{
"code": null,
"e": 2421,
"s": 2239,
"text": "COM (*.com) – Command files. These are the executable files for all the DOS commands. In early versions there was a separate file for each command. Now, most are inside COMMAND.COM."
},
{
"code": null,
"e": 2492,
"s": 2421,
"text": "CMD (*.cmd) – These were the batch files used in NT operating systems."
},
{
"code": null,
"e": 2668,
"s": 2492,
"text": "Lets take another example, Suppose we need to list down all the files/directory names inside a particular directory and save it to a text file, so batch script for it will be,"
},
{
"code": null,
"e": 2894,
"s": 2668,
"text": "@ECHO OFF\n\n// A comment line can be added to the batch file with the REM command.\nREM This is a comment line.\n\nREM Listing all the files in the directory Program files \nDIR\"C:\\Program Files\" > C:\\geeks_list.txt \n\nECHO \"Done!\""
},
{
"code": null,
"e": 3155,
"s": 2894,
"text": "Now when we run this batch script, it will create a file name geeks_list.txt in your C:\\ directory, displaying all the files/folder names in C:\\Program Files. Another useful batch script that can be written to diagnose your network and check performance of it:"
},
{
"code": null,
"e": 3434,
"s": 3155,
"text": "// This batch file checks for network connection problems.\nECHO OFF\n\n// View network connection details\nIPCONFIG /all\n\n// Check if geeksforgeeks.com is reachable\nPING geeksforgeeks.com\n\n// Run a traceroute to check the route to geeksforgeeks.com\nTRACERT geeksforgeeks.com\n\nPAUSE"
},
{
"code": null,
"e": 3456,
"s": 3434,
"text": "This script displays:"
},
{
"code": null,
"e": 3689,
"s": 3458,
"text": "This script gives information about the current network and some network packet information. ipconfig /all helps to view the network information and ‘ping’ & ‘tracert’ to get each packet info. Learn about ping and traceroute here."
},
{
"code": null,
"e": 3703,
"s": 3689,
"text": "shubham_singh"
},
{
"code": null,
"e": 3709,
"s": 3703,
"text": "GBlog"
},
{
"code": null,
"e": 3807,
"s": 3709,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3832,
"s": 3807,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 3887,
"s": 3832,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 3924,
"s": 3887,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 3962,
"s": 3924,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 4028,
"s": 3962,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 4099,
"s": 4028,
"text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa"
},
{
"code": null,
"e": 4141,
"s": 4099,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4204,
"s": 4141,
"text": "How To Switch From A Service-Based To A Product-Based Company?"
},
{
"code": null,
"e": 4260,
"s": 4204,
"text": "What is the Role of Fuzzy Logic in Algorithmic Trading?"
}
] |
String concatenation in Scala | 02 Jul, 2021
A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. when a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two strings. we can also use ‘+’ operator to concatenate two strings. Syntax:
str1.concat(str2);
Or
"str1" + "str2";
Below is the example of concatenating two strings.Using concat() method: This method appends argument to the string.Example #1:
Scala
// Scala program to illustrate how to // concatenate stringsobject GFG{ // str1 and str2 are two strings var str1 = "Welcome! GeeksforGeeks " var str2 = " to Portal" // Main function def main(args: Array[String]) { // concatenate str1 and str2 strings // using concat() function var Newstr = str1.concat(str2); // Display strings println("String 1:" +str1); println("String 2:" +str2); println("New String :" +Newstr); // Concatenate strings using '+' operator println("This is the tutorial" + " of Scala language" + " on GFG portal"); }}
Output:
String 1:Welcome! GeeksforGeeks
String 2: to Portal
New String :Welcome! GeeksforGeeks to Portal
This is the tutorial of Scala language on GFG portal
In above example, we are joining the second string to the end of the first string by using concat() function. string 1 is Welcome! GeeksforGeeks string 2 is to Portal. After concatenating two string we get new string Welcome! GeeksforGeeks to Portal. Using + operator : we can add two string by using + operator.Example #2:
Scala
// Scala program to illustrate how to// concatenate strings // Creating objectobject GFG{ // Main method def main(args: Array[String]) { var str1 = "Welcome to "; var str2 = "GeeksforGeeks"; // Concatenating two string println("After concatenate two string: " + str1 + str2); }}
Output:
After concatenate two string: Welcome toGeeksforGeeks
In above example, string 1 is Welcome to string 2 is GeeksforGeeks. By using + operator concatenating two string we get output After concatenate two string: Welcome toGeeksforGeeks.
surindertarika1234
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 453,
"s": 28,
"text": "A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. when a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two strings. we can also use ‘+’ operator to concatenate two strings. Syntax: "
},
{
"code": null,
"e": 494,
"s": 453,
"text": "str1.concat(str2);\n\nOr\n\n\"str1\" + \"str2\";"
},
{
"code": null,
"e": 624,
"s": 494,
"text": "Below is the example of concatenating two strings.Using concat() method: This method appends argument to the string.Example #1: "
},
{
"code": null,
"e": 630,
"s": 624,
"text": "Scala"
},
{
"code": "// Scala program to illustrate how to // concatenate stringsobject GFG{ // str1 and str2 are two strings var str1 = \"Welcome! GeeksforGeeks \" var str2 = \" to Portal\" // Main function def main(args: Array[String]) { // concatenate str1 and str2 strings // using concat() function var Newstr = str1.concat(str2); // Display strings println(\"String 1:\" +str1); println(\"String 2:\" +str2); println(\"New String :\" +Newstr); // Concatenate strings using '+' operator println(\"This is the tutorial\" + \" of Scala language\" + \" on GFG portal\"); }}",
"e": 1341,
"s": 630,
"text": null
},
{
"code": null,
"e": 1351,
"s": 1341,
"text": "Output: "
},
{
"code": null,
"e": 1503,
"s": 1351,
"text": "String 1:Welcome! GeeksforGeeks \nString 2: to Portal\nNew String :Welcome! GeeksforGeeks to Portal\nThis is the tutorial of Scala language on GFG portal"
},
{
"code": null,
"e": 1830,
"s": 1503,
"text": "In above example, we are joining the second string to the end of the first string by using concat() function. string 1 is Welcome! GeeksforGeeks string 2 is to Portal. After concatenating two string we get new string Welcome! GeeksforGeeks to Portal. Using + operator : we can add two string by using + operator.Example #2: "
},
{
"code": null,
"e": 1836,
"s": 1830,
"text": "Scala"
},
{
"code": "// Scala program to illustrate how to// concatenate strings // Creating objectobject GFG{ // Main method def main(args: Array[String]) { var str1 = \"Welcome to \"; var str2 = \"GeeksforGeeks\"; // Concatenating two string println(\"After concatenate two string: \" + str1 + str2); }}",
"e": 2160,
"s": 1836,
"text": null
},
{
"code": null,
"e": 2170,
"s": 2160,
"text": "Output: "
},
{
"code": null,
"e": 2224,
"s": 2170,
"text": "After concatenate two string: Welcome toGeeksforGeeks"
},
{
"code": null,
"e": 2407,
"s": 2224,
"text": "In above example, string 1 is Welcome to string 2 is GeeksforGeeks. By using + operator concatenating two string we get output After concatenate two string: Welcome toGeeksforGeeks. "
},
{
"code": null,
"e": 2426,
"s": 2407,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2440,
"s": 2426,
"text": "Scala-Strings"
},
{
"code": null,
"e": 2446,
"s": 2440,
"text": "Scala"
}
] |
Seaborn | Regression Plots | 09 Dec, 2021
The regression plots in seaborn are primarily intended to add a visual guide that helps to emphasize patterns in a dataset during exploratory data analyses. Regression plots as the name suggests creates a regression line between 2 parameters and helps to visualize their linear relationships. This article deals with those kinds of plots in seaborn and shows the ways that can be adapted to change the size, aspect, ratio etc. of such plots.
Seaborn is not only a visualization library but also a provider of built-in datasets. Here, we will be working with one of such datasets in seaborn named ‘tips’. The tips dataset contains information about the people who probably had food at the restaurant and whether or not they left a tip. It also provides information about the gender of the people, whether they smoke, day, time and so on.
Let us have a look at the dataset first before we start with the regression plots.
Load the dataset
Python3
# import the libraryimport seaborn as sns # load the datasetdataset = sns.load_dataset('tips') # the first five entries of the datasetdataset.head()
Python3
sns.set_style('whitegrid')sns.lmplot(x ='total_bill', y ='tip', data = dataset)
Python3
sns.set_style('whitegrid')sns.lmplot(x ='total_bill', y ='tip', data = dataset, hue ='sex', markers =['o', 'v'])
Python3
sns.set_style('whitegrid')sns.lmplot(x ='total_bill', y ='tip', data = dataset, hue ='sex', markers =['o', 'v'], scatter_kws ={'s':100}, palette ='plasma')
Python3
sns.lmplot(x ='total_bill', y ='tip', data = dataset, col ='sex', row ='time', hue ='smoker')
Python3
sns.lmplot(x ='total_bill', y ='tip', data = dataset, col ='sex', row ='time', hue ='smoker', aspect = 0.6, size = 4, palette ='coolwarm')
sagar0719kumar
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 496,
"s": 54,
"text": "The regression plots in seaborn are primarily intended to add a visual guide that helps to emphasize patterns in a dataset during exploratory data analyses. Regression plots as the name suggests creates a regression line between 2 parameters and helps to visualize their linear relationships. This article deals with those kinds of plots in seaborn and shows the ways that can be adapted to change the size, aspect, ratio etc. of such plots."
},
{
"code": null,
"e": 891,
"s": 496,
"text": "Seaborn is not only a visualization library but also a provider of built-in datasets. Here, we will be working with one of such datasets in seaborn named ‘tips’. The tips dataset contains information about the people who probably had food at the restaurant and whether or not they left a tip. It also provides information about the gender of the people, whether they smoke, day, time and so on."
},
{
"code": null,
"e": 974,
"s": 891,
"text": "Let us have a look at the dataset first before we start with the regression plots."
},
{
"code": null,
"e": 991,
"s": 974,
"text": "Load the dataset"
},
{
"code": null,
"e": 999,
"s": 991,
"text": "Python3"
},
{
"code": "# import the libraryimport seaborn as sns # load the datasetdataset = sns.load_dataset('tips') # the first five entries of the datasetdataset.head()",
"e": 1150,
"s": 999,
"text": null
},
{
"code": null,
"e": 1158,
"s": 1150,
"text": "Python3"
},
{
"code": "sns.set_style('whitegrid')sns.lmplot(x ='total_bill', y ='tip', data = dataset)",
"e": 1238,
"s": 1158,
"text": null
},
{
"code": null,
"e": 1246,
"s": 1238,
"text": "Python3"
},
{
"code": "sns.set_style('whitegrid')sns.lmplot(x ='total_bill', y ='tip', data = dataset, hue ='sex', markers =['o', 'v'])",
"e": 1370,
"s": 1246,
"text": null
},
{
"code": null,
"e": 1378,
"s": 1370,
"text": "Python3"
},
{
"code": "sns.set_style('whitegrid')sns.lmplot(x ='total_bill', y ='tip', data = dataset, hue ='sex', markers =['o', 'v'], scatter_kws ={'s':100}, palette ='plasma')",
"e": 1556,
"s": 1378,
"text": null
},
{
"code": null,
"e": 1564,
"s": 1556,
"text": "Python3"
},
{
"code": "sns.lmplot(x ='total_bill', y ='tip', data = dataset, col ='sex', row ='time', hue ='smoker')",
"e": 1669,
"s": 1564,
"text": null
},
{
"code": null,
"e": 1677,
"s": 1669,
"text": "Python3"
},
{
"code": "sns.lmplot(x ='total_bill', y ='tip', data = dataset, col ='sex', row ='time', hue ='smoker', aspect = 0.6, size = 4, palette ='coolwarm')",
"e": 1838,
"s": 1677,
"text": null
},
{
"code": null,
"e": 1853,
"s": 1838,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 1870,
"s": 1853,
"text": "Machine Learning"
},
{
"code": null,
"e": 1877,
"s": 1870,
"text": "Python"
},
{
"code": null,
"e": 1894,
"s": 1877,
"text": "Machine Learning"
}
] |
What is a Web Application Firewall? | 07 Jan, 2022
Web Application Firewall protects the web application by filtering, monitoring, and blocking any malicious HTTP/S traffic that might penetrate the web application. In simple words, a Web Application Firewall acts as a shield between a web application and the Internet. This shield protects the web application from different types of attacks.
According to the OSI model, WAF is a protocol layer seven defense.
When a WAF is deployed in front of a web application, a shield is created between the web application and the Internet.
The advantage of WAF is that it functions independently from the application, but yet it can constantly adapt to the application behavior changes.
The clients are passed through the WAF before reaching the server in order to protect the server from exposure.
WAF can be set to various levels of examinations, usually in a range from low to high, which allows the WAF to provide a better level of security.
Network-based WAFs are usually hardware-based. They provide latency reduction due to local installation. Network-based WAFs are the most expensive and also require the storage and maintenance of physical equipment.
Host-based WAFs may be completely integrated into an application’s software. They exist as modules for a web server. It is a cheaper solution compared to hardware-based WAFs, which are used for small web applications. The disadvantage of a host-based WAF is the consumption of local server resources because of which the performance may degrade.
Cloud-based WAFs are low-cost and have fewer resources to manage. The cloud-based solution is the perfect choice when a person doesn’t want to restrict themselves with performance capabilities. The service providers can provide with unlimited hardware pool but after a certain point of time, the service fees might increase.
There are several hackers out there who are ready to execute their malicious attacks. The most common attacks such as XSS, SQL Injection, etc. can be prevented with the help of WAF and that will be discussed further. The purpose of WAF is to protect your webpage from such malicious attacks. The WAF constantly monitors for potential attacks, blocking these attacks they are found to be malicious in any way.
The set of rules through which a WAF operates is called a policy.
The purpose of these policies is to protect against the vulnerabilities in the application by filtering out malicious traffic.
The value of a WAF comes in part depending upon the speed and efficiency with which the policy modification is implemented.
DDOS Attack aims to target a particular web application/ website/ server with fake traffic.
Cross-Site Scripting (XSS) Attacks are aimed at those users who use vulnerable web applications/ websites in order to gain access to and control their browsers.
SQL Injection Attacks: A malicious SQL code is injected in the form of requests or queries in the user input box on the web applications that the user is using.
Man-in-the-middle attacks take place when the perpetrators position themselves in between the application and the legitimate users in order to extract confidential details.
Zero-day attacks are unexpected attacks that take place. The organization knows about the existence of vulnerabilities in the hardware/ software only when the attack has taken place.
Blocklist: A WAF that is based on a blocklist protects against known attacks. Visualize blocklist WAF as a college security guard who is instructed to deny admittance to the students who don’t bring their ID-Cards.
Allowlist: A WAF based on an allow list only admits traffic that has been pre-approved. This is like the college security guard who only admits people who are on the list.
Both Blocklist and Allowlist have equal advantages and disadvantages because of which many WAFs offer a hybrid security model, which implements both.
Low-cost for cloud-based WAF solution.
Prevent attacks which include SQL injections, cross-site scripting (XSS) attacks, etc.
It prevents cookie poisoning. Cookie poisoning is the manipulation of cookies in order to keep track of users’ information.
Prevents data from being compromised.
If the software has vulnerabilities, then there are chances that some attacks might bypass them.
Sometimes the complete solution comes at an expensive cost.
A lot of resources are consumed.
There is a lack of cloud support because WAFs are majorly deployed as hardware on-premise.
Picked
Computer Networks
Computer Subject
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Wireless Application Protocol
GSM in Wireless Communication
Secure Socket Layer (SSL)
Mobile Internet Protocol (or Mobile IP)
Advanced Encryption Standard (AES)
SDE SHEET - A Complete Guide for SDE Preparation
What is Algorithm | Introduction to Algorithms
Software Engineering | Coupling and Cohesion
Type Checking in Compiler Design
Difference between NP hard and NP complete problem | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 371,
"s": 28,
"text": "Web Application Firewall protects the web application by filtering, monitoring, and blocking any malicious HTTP/S traffic that might penetrate the web application. In simple words, a Web Application Firewall acts as a shield between a web application and the Internet. This shield protects the web application from different types of attacks."
},
{
"code": null,
"e": 438,
"s": 371,
"text": "According to the OSI model, WAF is a protocol layer seven defense."
},
{
"code": null,
"e": 558,
"s": 438,
"text": "When a WAF is deployed in front of a web application, a shield is created between the web application and the Internet."
},
{
"code": null,
"e": 705,
"s": 558,
"text": "The advantage of WAF is that it functions independently from the application, but yet it can constantly adapt to the application behavior changes."
},
{
"code": null,
"e": 817,
"s": 705,
"text": "The clients are passed through the WAF before reaching the server in order to protect the server from exposure."
},
{
"code": null,
"e": 964,
"s": 817,
"text": "WAF can be set to various levels of examinations, usually in a range from low to high, which allows the WAF to provide a better level of security."
},
{
"code": null,
"e": 1179,
"s": 964,
"text": "Network-based WAFs are usually hardware-based. They provide latency reduction due to local installation. Network-based WAFs are the most expensive and also require the storage and maintenance of physical equipment."
},
{
"code": null,
"e": 1525,
"s": 1179,
"text": "Host-based WAFs may be completely integrated into an application’s software. They exist as modules for a web server. It is a cheaper solution compared to hardware-based WAFs, which are used for small web applications. The disadvantage of a host-based WAF is the consumption of local server resources because of which the performance may degrade."
},
{
"code": null,
"e": 1850,
"s": 1525,
"text": "Cloud-based WAFs are low-cost and have fewer resources to manage. The cloud-based solution is the perfect choice when a person doesn’t want to restrict themselves with performance capabilities. The service providers can provide with unlimited hardware pool but after a certain point of time, the service fees might increase."
},
{
"code": null,
"e": 2259,
"s": 1850,
"text": "There are several hackers out there who are ready to execute their malicious attacks. The most common attacks such as XSS, SQL Injection, etc. can be prevented with the help of WAF and that will be discussed further. The purpose of WAF is to protect your webpage from such malicious attacks. The WAF constantly monitors for potential attacks, blocking these attacks they are found to be malicious in any way."
},
{
"code": null,
"e": 2325,
"s": 2259,
"text": "The set of rules through which a WAF operates is called a policy."
},
{
"code": null,
"e": 2452,
"s": 2325,
"text": "The purpose of these policies is to protect against the vulnerabilities in the application by filtering out malicious traffic."
},
{
"code": null,
"e": 2576,
"s": 2452,
"text": "The value of a WAF comes in part depending upon the speed and efficiency with which the policy modification is implemented."
},
{
"code": null,
"e": 2668,
"s": 2576,
"text": "DDOS Attack aims to target a particular web application/ website/ server with fake traffic."
},
{
"code": null,
"e": 2829,
"s": 2668,
"text": "Cross-Site Scripting (XSS) Attacks are aimed at those users who use vulnerable web applications/ websites in order to gain access to and control their browsers."
},
{
"code": null,
"e": 2990,
"s": 2829,
"text": "SQL Injection Attacks: A malicious SQL code is injected in the form of requests or queries in the user input box on the web applications that the user is using."
},
{
"code": null,
"e": 3163,
"s": 2990,
"text": "Man-in-the-middle attacks take place when the perpetrators position themselves in between the application and the legitimate users in order to extract confidential details."
},
{
"code": null,
"e": 3346,
"s": 3163,
"text": "Zero-day attacks are unexpected attacks that take place. The organization knows about the existence of vulnerabilities in the hardware/ software only when the attack has taken place."
},
{
"code": null,
"e": 3561,
"s": 3346,
"text": "Blocklist: A WAF that is based on a blocklist protects against known attacks. Visualize blocklist WAF as a college security guard who is instructed to deny admittance to the students who don’t bring their ID-Cards."
},
{
"code": null,
"e": 3733,
"s": 3561,
"text": "Allowlist: A WAF based on an allow list only admits traffic that has been pre-approved. This is like the college security guard who only admits people who are on the list."
},
{
"code": null,
"e": 3883,
"s": 3733,
"text": "Both Blocklist and Allowlist have equal advantages and disadvantages because of which many WAFs offer a hybrid security model, which implements both."
},
{
"code": null,
"e": 3922,
"s": 3883,
"text": "Low-cost for cloud-based WAF solution."
},
{
"code": null,
"e": 4009,
"s": 3922,
"text": "Prevent attacks which include SQL injections, cross-site scripting (XSS) attacks, etc."
},
{
"code": null,
"e": 4133,
"s": 4009,
"text": "It prevents cookie poisoning. Cookie poisoning is the manipulation of cookies in order to keep track of users’ information."
},
{
"code": null,
"e": 4171,
"s": 4133,
"text": "Prevents data from being compromised."
},
{
"code": null,
"e": 4268,
"s": 4171,
"text": "If the software has vulnerabilities, then there are chances that some attacks might bypass them."
},
{
"code": null,
"e": 4328,
"s": 4268,
"text": "Sometimes the complete solution comes at an expensive cost."
},
{
"code": null,
"e": 4361,
"s": 4328,
"text": "A lot of resources are consumed."
},
{
"code": null,
"e": 4452,
"s": 4361,
"text": "There is a lack of cloud support because WAFs are majorly deployed as hardware on-premise."
},
{
"code": null,
"e": 4459,
"s": 4452,
"text": "Picked"
},
{
"code": null,
"e": 4477,
"s": 4459,
"text": "Computer Networks"
},
{
"code": null,
"e": 4494,
"s": 4477,
"text": "Computer Subject"
},
{
"code": null,
"e": 4512,
"s": 4494,
"text": "Computer Networks"
},
{
"code": null,
"e": 4610,
"s": 4512,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4640,
"s": 4610,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 4670,
"s": 4640,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 4696,
"s": 4670,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 4736,
"s": 4696,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 4771,
"s": 4736,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 4820,
"s": 4771,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 4867,
"s": 4820,
"text": "What is Algorithm | Introduction to Algorithms"
},
{
"code": null,
"e": 4912,
"s": 4867,
"text": "Software Engineering | Coupling and Cohesion"
},
{
"code": null,
"e": 4945,
"s": 4912,
"text": "Type Checking in Compiler Design"
}
] |
Installing OpenVAS on Kali Linux | 23 Aug, 2021
OpenVAS, an endpoint scanning application and web application used to identify and detect vulnerabilities. It is widely used by companies as part of their risk mitigation solutions to quickly identify gaps in their production and even development servers or applications. This is not a complete solution, but it can help you fix common security vulnerabilities that may not be discovered.
The condition of Greenbone mode is open (APEVALV) from infected chemistry (GVM) of the quality of the storage and the GitHub area. it is used in the Greenbone Security Manager device and is a comprehensive scan. An engine that runs an advanced and constantly updated Network Vulnerability Test Package (NVT).
To install Openvas and its dependencies on our Kali Linux system run the following command:
sudo apt update
sudo apt upgrade -y
sudo apt dist-upgrade -y
sudo apt install openvas
The next step is to run the installer, which will configure OpenVAS and download various network vulnerability tests (NVT) or signatures. Due to a large number of NVTs (50.000+), the setting process may take some time and consume a lot of data. In the test setup we used for this tutorial, the complete setup process took 10 minutes, which is not bad.
Run the following command to start the setup process:
gvm-setup
After the configuration process is complete, all the necessary OpenVAS processes will start and the web interface will open automatically. The web interface is running locally on port 9392 and can be accessed through https://localhost:9392. OpenVAS will also set up an admin account and automatically generate a password for this account which is displayed in the last section of the setup output:
You can verify your installation with.
gvm-check-setup
Did you forget to note down the password? You can change the admin password using the following commands:
gvmd --user=admin --new-password=passwd;
The next step is to accept the self-signed certificate warning and use the automatically generated admin credentials to login on to the web interface:
Before starting to install the virtual appliance, the last step I have to consider is to start and stop the OpenVAS service. OpenVAS services consume a lot of unnecessary resources, so it is recommended that you disable these services when you are not using OpenVAS.
Run the following command to start the services:
Sudo gvm-start
To stop the OpenVAS services again, run:
sudo gvm-stop
*Note: To create a new user :
sudo runuser -u _gvm -- gvmd --create-user=admin2 --new-password=12345
To change the password of the existing user:
sudo runuser -u _gvm -- gvmd --user=admin --new-password=new_password
Begin by navigating to Scans > Tasks and clicking on the purple magic wand icon to begin the basic configuration wizard. After successfully navigating to the wizard, you should see a pop-up window similar to the one shown above. You can set up the initial scan of the local host here to make sure everything is set up correctly.
Scanning may take a while. Please allow OpenVAS enough time to complete the scan. You will then see a new dashboard for monitoring and analyzing your completed and ongoing scans, as shown below.
Now that we know everything is normal, we can take a closer look at OpenVAS and how it works. Expand the car to scan and> start the task of creating a scan task for the managed computer.
To create a custom task, navigate to the star icon in the upper right corner of the taskbar and select New task.
After selecting ” New Task” from the drop-down menu, you will see a large pop-up window with many options. We will introduce each option part and its purpose.
For this task, we’ll be specializing only in the Name, Scan Targets, and Scanner Type, and Scan Config. In later tasks, we will be focusing on the opposite choices for additional advanced configuration and implementation/automation.
Name: permits North American country to line the name the scan are going to be referred to as inside OpenVASScan Targets: The targets to scan, can embrace Hosts, Ports, and Credentials. to make a brand new target you may follow another pop-up, this can be lined later during this task.Scanner: The scanner to use by default will use the OpenVAS design but you’ll be able to set this to any scanner of your selecting within the settings menu.Scan Config: OpenVAS has seven totally different scan sorts you can choose from and can be used supported however you’re aggressive or what info you wish to gather from your scan.
Name: permits North American country to line the name the scan are going to be referred to as inside OpenVAS
Scan Targets: The targets to scan, can embrace Hosts, Ports, and Credentials. to make a brand new target you may follow another pop-up, this can be lined later during this task.
Scanner: The scanner to use by default will use the OpenVAS design but you’ll be able to set this to any scanner of your selecting within the settings menu.
Scan Config: OpenVAS has seven totally different scan sorts you can choose from and can be used supported however you’re aggressive or what info you wish to gather from your scan.
To scope a new target, navigate to the star icon next to Scan Targets.
Above is that the menu for configuring a replacement target. the 2 main choices you may have to be compelled to assemble are the Name and therefore the Hosts. This procedure is fairly uncomplicated and different options will solely be employed in advanced vulnerability management solutions. These are going to be lined in later tasks.
Now that we’ve got our target scoped we are able to still produce our task and start the scan. When the task is created, you’ll come to the scanning management panel, wherever you’ll track and execute the task. To run the task, navigate to the run icon within the operation.
It permits visualizing the vulnerability of the parts akin to hosts or in operation systems:
Allow adding common parameters to OpenVAS:
As the name suggests, you can manage passwords, users, etc.:
how-to-install
Linux-Tools
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 418,
"s": 28,
"text": "OpenVAS, an endpoint scanning application and web application used to identify and detect vulnerabilities. It is widely used by companies as part of their risk mitigation solutions to quickly identify gaps in their production and even development servers or applications. This is not a complete solution, but it can help you fix common security vulnerabilities that may not be discovered. "
},
{
"code": null,
"e": 727,
"s": 418,
"text": "The condition of Greenbone mode is open (APEVALV) from infected chemistry (GVM) of the quality of the storage and the GitHub area. it is used in the Greenbone Security Manager device and is a comprehensive scan. An engine that runs an advanced and constantly updated Network Vulnerability Test Package (NVT)."
},
{
"code": null,
"e": 819,
"s": 727,
"text": "To install Openvas and its dependencies on our Kali Linux system run the following command:"
},
{
"code": null,
"e": 904,
"s": 819,
"text": "sudo apt update \n\nsudo apt upgrade -y\n\nsudo apt dist-upgrade -y"
},
{
"code": null,
"e": 929,
"s": 904,
"text": "sudo apt install openvas"
},
{
"code": null,
"e": 1282,
"s": 929,
"text": "The next step is to run the installer, which will configure OpenVAS and download various network vulnerability tests (NVT) or signatures. Due to a large number of NVTs (50.000+), the setting process may take some time and consume a lot of data. In the test setup we used for this tutorial, the complete setup process took 10 minutes, which is not bad."
},
{
"code": null,
"e": 1336,
"s": 1282,
"text": "Run the following command to start the setup process:"
},
{
"code": null,
"e": 1346,
"s": 1336,
"text": "gvm-setup"
},
{
"code": null,
"e": 1744,
"s": 1346,
"text": "After the configuration process is complete, all the necessary OpenVAS processes will start and the web interface will open automatically. The web interface is running locally on port 9392 and can be accessed through https://localhost:9392. OpenVAS will also set up an admin account and automatically generate a password for this account which is displayed in the last section of the setup output:"
},
{
"code": null,
"e": 1783,
"s": 1744,
"text": "You can verify your installation with."
},
{
"code": null,
"e": 1799,
"s": 1783,
"text": "gvm-check-setup"
},
{
"code": null,
"e": 1905,
"s": 1799,
"text": "Did you forget to note down the password? You can change the admin password using the following commands:"
},
{
"code": null,
"e": 1946,
"s": 1905,
"text": "gvmd --user=admin --new-password=passwd;"
},
{
"code": null,
"e": 2097,
"s": 1946,
"text": "The next step is to accept the self-signed certificate warning and use the automatically generated admin credentials to login on to the web interface:"
},
{
"code": null,
"e": 2364,
"s": 2097,
"text": "Before starting to install the virtual appliance, the last step I have to consider is to start and stop the OpenVAS service. OpenVAS services consume a lot of unnecessary resources, so it is recommended that you disable these services when you are not using OpenVAS."
},
{
"code": null,
"e": 2413,
"s": 2364,
"text": "Run the following command to start the services:"
},
{
"code": null,
"e": 2428,
"s": 2413,
"text": "Sudo gvm-start"
},
{
"code": null,
"e": 2469,
"s": 2428,
"text": "To stop the OpenVAS services again, run:"
},
{
"code": null,
"e": 2483,
"s": 2469,
"text": "sudo gvm-stop"
},
{
"code": null,
"e": 2513,
"s": 2483,
"text": "*Note: To create a new user :"
},
{
"code": null,
"e": 2586,
"s": 2513,
"text": "sudo runuser -u _gvm -- gvmd --create-user=admin2 --new-password=12345 "
},
{
"code": null,
"e": 2631,
"s": 2586,
"text": "To change the password of the existing user:"
},
{
"code": null,
"e": 2702,
"s": 2631,
"text": "sudo runuser -u _gvm -- gvmd --user=admin --new-password=new_password "
},
{
"code": null,
"e": 3031,
"s": 2702,
"text": "Begin by navigating to Scans > Tasks and clicking on the purple magic wand icon to begin the basic configuration wizard. After successfully navigating to the wizard, you should see a pop-up window similar to the one shown above. You can set up the initial scan of the local host here to make sure everything is set up correctly."
},
{
"code": null,
"e": 3226,
"s": 3031,
"text": "Scanning may take a while. Please allow OpenVAS enough time to complete the scan. You will then see a new dashboard for monitoring and analyzing your completed and ongoing scans, as shown below."
},
{
"code": null,
"e": 3413,
"s": 3226,
"text": "Now that we know everything is normal, we can take a closer look at OpenVAS and how it works. Expand the car to scan and> start the task of creating a scan task for the managed computer."
},
{
"code": null,
"e": 3526,
"s": 3413,
"text": "To create a custom task, navigate to the star icon in the upper right corner of the taskbar and select New task."
},
{
"code": null,
"e": 3685,
"s": 3526,
"text": "After selecting ” New Task” from the drop-down menu, you will see a large pop-up window with many options. We will introduce each option part and its purpose."
},
{
"code": null,
"e": 3918,
"s": 3685,
"text": "For this task, we’ll be specializing only in the Name, Scan Targets, and Scanner Type, and Scan Config. In later tasks, we will be focusing on the opposite choices for additional advanced configuration and implementation/automation."
},
{
"code": null,
"e": 4539,
"s": 3918,
"text": "Name: permits North American country to line the name the scan are going to be referred to as inside OpenVASScan Targets: The targets to scan, can embrace Hosts, Ports, and Credentials. to make a brand new target you may follow another pop-up, this can be lined later during this task.Scanner: The scanner to use by default will use the OpenVAS design but you’ll be able to set this to any scanner of your selecting within the settings menu.Scan Config: OpenVAS has seven totally different scan sorts you can choose from and can be used supported however you’re aggressive or what info you wish to gather from your scan."
},
{
"code": null,
"e": 4648,
"s": 4539,
"text": "Name: permits North American country to line the name the scan are going to be referred to as inside OpenVAS"
},
{
"code": null,
"e": 4826,
"s": 4648,
"text": "Scan Targets: The targets to scan, can embrace Hosts, Ports, and Credentials. to make a brand new target you may follow another pop-up, this can be lined later during this task."
},
{
"code": null,
"e": 4983,
"s": 4826,
"text": "Scanner: The scanner to use by default will use the OpenVAS design but you’ll be able to set this to any scanner of your selecting within the settings menu."
},
{
"code": null,
"e": 5163,
"s": 4983,
"text": "Scan Config: OpenVAS has seven totally different scan sorts you can choose from and can be used supported however you’re aggressive or what info you wish to gather from your scan."
},
{
"code": null,
"e": 5234,
"s": 5163,
"text": "To scope a new target, navigate to the star icon next to Scan Targets."
},
{
"code": null,
"e": 5570,
"s": 5234,
"text": "Above is that the menu for configuring a replacement target. the 2 main choices you may have to be compelled to assemble are the Name and therefore the Hosts. This procedure is fairly uncomplicated and different options will solely be employed in advanced vulnerability management solutions. These are going to be lined in later tasks."
},
{
"code": null,
"e": 5845,
"s": 5570,
"text": "Now that we’ve got our target scoped we are able to still produce our task and start the scan. When the task is created, you’ll come to the scanning management panel, wherever you’ll track and execute the task. To run the task, navigate to the run icon within the operation."
},
{
"code": null,
"e": 5940,
"s": 5845,
"text": "It permits visualizing the vulnerability of the parts akin to hosts or in operation systems: "
},
{
"code": null,
"e": 5983,
"s": 5940,
"text": "Allow adding common parameters to OpenVAS:"
},
{
"code": null,
"e": 6044,
"s": 5983,
"text": "As the name suggests, you can manage passwords, users, etc.:"
},
{
"code": null,
"e": 6059,
"s": 6044,
"text": "how-to-install"
},
{
"code": null,
"e": 6071,
"s": 6059,
"text": "Linux-Tools"
},
{
"code": null,
"e": 6090,
"s": 6071,
"text": "Installation Guide"
},
{
"code": null,
"e": 6101,
"s": 6090,
"text": "Linux-Unix"
}
] |
map::empty() in C++ STL | 17 Jan, 2018
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.
empty() function is used to check if the map container is empty or not.
Syntax :
mapname.empty()
Parameters :
No parameters are passed.
Returns :
True, if map is empty
False, Otherwise
Examples:
Input : map
mymap['a']=10;
mymap['b']=20;
mymap.empty();
Output : False
Input : map
mymap.empty();
Output : True
Errors and Exceptions
1. It has a no exception throw guarantee.2. Shows error when a parameter is passed.
// Non Empty map example// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <map>using namespace std; int main(){ map<char, int> mymap; mymap['a'] = 1; mymap['b'] = 2; if (mymap.empty()) { cout << "True"; } else { cout << "False"; } return 0;}
Output:
False
// Empty map example// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <map>using namespace std; int main(){ map<char, int> mymap; if (mymap.empty()) { cout << "True"; } else { cout << "False"; } return 0;}
Output:
True
Time Complexity : O(1)
cpp-map
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++
vector erase() and clear() in C++
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
Inheritance in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
Substring in C++
Object Oriented Programming in C++
2D Vector In C++ With User Defined Size | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jan, 2018"
},
{
"code": null,
"e": 223,
"s": 54,
"text": "Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values."
},
{
"code": null,
"e": 295,
"s": 223,
"text": "empty() function is used to check if the map container is empty or not."
},
{
"code": null,
"e": 304,
"s": 295,
"text": "Syntax :"
},
{
"code": null,
"e": 409,
"s": 304,
"text": "mapname.empty()\nParameters :\nNo parameters are passed.\nReturns :\nTrue, if map is empty\nFalse, Otherwise\n"
},
{
"code": null,
"e": 419,
"s": 409,
"text": "Examples:"
},
{
"code": null,
"e": 574,
"s": 419,
"text": "Input : map \n mymap['a']=10;\n mymap['b']=20;\n mymap.empty();\nOutput : False\n\nInput : map \n mymap.empty();\nOutput : True\n"
},
{
"code": null,
"e": 596,
"s": 574,
"text": "Errors and Exceptions"
},
{
"code": null,
"e": 680,
"s": 596,
"text": "1. It has a no exception throw guarantee.2. Shows error when a parameter is passed."
},
{
"code": "// Non Empty map example// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <map>using namespace std; int main(){ map<char, int> mymap; mymap['a'] = 1; mymap['b'] = 2; if (mymap.empty()) { cout << \"True\"; } else { cout << \"False\"; } return 0;}",
"e": 1004,
"s": 680,
"text": null
},
{
"code": null,
"e": 1012,
"s": 1004,
"text": "Output:"
},
{
"code": null,
"e": 1018,
"s": 1012,
"text": "False"
},
{
"code": "// Empty map example// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <map>using namespace std; int main(){ map<char, int> mymap; if (mymap.empty()) { cout << \"True\"; } else { cout << \"False\"; } return 0;}",
"e": 1300,
"s": 1018,
"text": null
},
{
"code": null,
"e": 1308,
"s": 1300,
"text": "Output:"
},
{
"code": null,
"e": 1313,
"s": 1308,
"text": "True"
},
{
"code": null,
"e": 1336,
"s": 1313,
"text": "Time Complexity : O(1)"
},
{
"code": null,
"e": 1344,
"s": 1336,
"text": "cpp-map"
},
{
"code": null,
"e": 1348,
"s": 1344,
"text": "STL"
},
{
"code": null,
"e": 1352,
"s": 1348,
"text": "C++"
},
{
"code": null,
"e": 1356,
"s": 1352,
"text": "STL"
},
{
"code": null,
"e": 1360,
"s": 1356,
"text": "CPP"
},
{
"code": null,
"e": 1458,
"s": 1360,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1485,
"s": 1458,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 1519,
"s": 1485,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 1573,
"s": 1519,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1597,
"s": 1573,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1616,
"s": 1597,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 1656,
"s": 1616,
"text": "The C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1680,
"s": 1656,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 1697,
"s": 1680,
"text": "Substring in C++"
},
{
"code": null,
"e": 1732,
"s": 1697,
"text": "Object Oriented Programming in C++"
}
] |
Find maximum points which can be obtained by deleting elements from array - GeeksforGeeks | 11 May, 2021
Given an array A having N elements and two integers L and R where, and . You can choose any element of the array (let’s say ax) and delete it, and also delete all elements equal to ax+1, ax+2 ... ax+R and ax-1, ax-2 ... ax-L from the array. This step will cost ax points. The task is to maximize the total cost after deleting all the elements from the array.Examples:
Input : 2 1 2 3 2 2 1
L = 1, R = 1
Output : 8
We select 2 to delete, then (2-1)=1 and (2+1)=3 will need to be deleted,
for given L and R range respectively.
Repeat this until 2 is completely removed. So, total cost = 2*4 = 8.
Input : 2 4 2 9 5
L = 1, R = 2
Output : 18
We select 2 to delete, then 5 and then 9.
So total cost = 2*2 + 5 + 9 = 18.
Approach: We will find the count of all the elements. Now let’s say an element X is selected then, all elements in the range [X-L, X+R] will be deleted. Now we select the minimum range from L and R and finds up to which elements are to be deleted when element X is selected. Our results will be the maximum of previously deleted elements and when element X is deleted. We will use dynamic programming to store the result of previously deleted elements and use it further.
C++
Java
Python 3
C#
Javascript
// C++ program to find maximum cost after// deleting all the elements form the array#include <bits/stdc++.h>using namespace std; // function to return maximum cost obtainedint maxCost(int a[], int n, int l, int r){ int mx = 0, k; // find maximum element of the array. for (int i = 0; i < n; ++i) mx = max(mx, a[i]); // initialize count of all elements to zero. int count[mx + 1]; memset(count, 0, sizeof(count)); // calculate frequency of all elements of array. for (int i = 0; i < n; i++) count[a[i]]++; // stores cost of deleted elements. int res[mx + 1]; res[0] = 0; // selecting minimum range from L and R. l = min(l, r); for (int num = 1; num <= mx; num++) { // finds upto which elements are to be // deleted when element num is selected. k = max(num - l - 1, 0); // get maximum when selecting element num or not. res[num] = max(res[num - 1], num * count[num] + res[k]); } return res[mx];} // Driver programint main(){ int a[] = { 2, 1, 2, 3, 2, 2, 1 }, l = 1, r = 1; // size of array int n = sizeof(a) / sizeof(a[0]); // function call to find maximum cost cout << maxCost(a, n, l, r); return 0;}
//Java program to find maximum cost after//deleting all the elements form the array public class GFG { //function to return maximum cost obtained static int maxCost(int a[], int n, int l, int r) { int mx = 0, k; // find maximum element of the array. for (int i = 0; i < n; ++i) mx = Math.max(mx, a[i]); // initialize count of all elements to zero. int[] count = new int[mx + 1]; for(int i = 0; i < count.length; i++) count[i] = 0; // calculate frequency of all elements of array. for (int i = 0; i < n; i++) count[a[i]]++; // stores cost of deleted elements. int[] res = new int[mx + 1]; res[0] = 0; // selecting minimum range from L and R. l = Math.min(l, r); for (int num = 1; num <= mx; num++) { // finds upto which elements are to be // deleted when element num is selected. k = Math.max(num - l - 1, 0); // get maximum when selecting element num or not. res[num] = Math.max(res[num - 1], num * count[num] + res[k]); } return res[mx]; } //Driver program public static void main(String[] args) { int a[] = { 2, 1, 2, 3, 2, 2, 1 }, l = 1, r = 1; // size of array int n = a.length; // function call to find maximum cost System.out.println(maxCost(a, n, l, r)); }}
# Python 3 Program to find maximum cost after# deleting all the elements form the array # function to return maximum cost obtaineddef maxCost(a, n, l, r) : mx = 0 # find maximum element of the array. for i in range(n) : mx = max(mx, a[i]) # create and initialize count of all elements to zero. count = [0] * (mx + 1) # calculate frequency of all elements of array. for i in range(n) : count[a[i]] += 1 # stores cost of deleted elements. res = [0] * (mx + 1) res[0] = 0 # selecting minimum range from L and R. l = min(l, r) for num in range(1, mx + 1) : # finds upto which elements are to be # deleted when element num is selected. k = max(num - l - 1, 0) # get maximum when selecting element num or not. res[num] = max(res[num - 1], num * count[num] + res[k]) return res[mx] # Driver codeif __name__ == "__main__" : a = [2, 1, 2, 3, 2, 2, 1 ] l, r = 1, 1 # size of array n = len(a) # function call to find maximum cost print(maxCost(a, n, l, r)) # This code is contributed by ANKITRAI1
// C# program to find maximum cost// after deleting all the elements// form the arrayusing System; class GFG{ // function to return maximum// cost obtainedstatic int maxCost(int []a, int n, int l, int r){ int mx = 0, k; // find maximum element // of the array. for (int i = 0; i < n; ++i) mx = Math.Max(mx, a[i]); // initialize count of all // elements to zero. int[] count = new int[mx + 1]; for(int i = 0; i < count.Length; i++) count[i] = 0; // calculate frequency of all // elements of array. for (int i = 0; i < n; i++) count[a[i]]++; // stores cost of deleted elements. int[] res = new int[mx + 1]; res[0] = 0; // selecting minimum range // from L and R. l = Math.Min(l, r); for (int num = 1; num <= mx; num++) { // finds upto which elements // are to be deleted when // element num is selected. k = Math.Max(num - l - 1, 0); // get maximum when selecting // element num or not. res[num] = Math.Max(res[num - 1], num * count[num] + res[k]); } return res[mx];} // Driver Codepublic static void Main(){ int []a = { 2, 1, 2, 3, 2, 2, 1 }; int l = 1, r = 1; // size of array int n = a.Length; // function call to find maximum cost Console.WriteLine(maxCost(a, n, l, r));}} // This code is contributed// by inder_verma
<script> // Javascript program to find maximum cost after// deleting all the elements form the array // function to return maximum cost obtainedfunction maxCost(a, n, l, r){ var mx = 0, k; // find maximum element of the array. for (var i = 0; i < n; ++i) mx = Math.max(mx, a[i]); // initialize count of all elements to zero. var count = new Array(mx + 1); count.fill(0); // calculate frequency of all elements of array. for (var i = 0; i < n; i++) count[a[i]]++; // stores cost of deleted elements. var res = new Array(mx + 1); res[0] = 0; // selecting minimum range from L and R. l = Math.min(l, r); for (var num = 1; num <= mx; num++) { // finds upto which elements are to be // deleted when element num is selected. k = Math.max(num - l - 1, 0); // get maximum when selecting element num or not. res[num] = Math.max(res[num - 1], num * count[num] + res[k]); } return res[mx];} var a = [ 2, 1, 2, 3, 2, 2, 1 ];var l = 1, r = 1;// size of arrayvar n = a.length; // function call to find maximum costdocument.write(maxCost(a, n, l, r)); // This code is contributed by SoumikMondal </script>
8
Time Complexity: O(max(A))
ankthon
ukasp
inderDuMCA
SoumikMondal
array-range-queries
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16 | [
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 25192,
"s": 24822,
"text": "Given an array A having N elements and two integers L and R where, and . You can choose any element of the array (let’s say ax) and delete it, and also delete all elements equal to ax+1, ax+2 ... ax+R and ax-1, ax-2 ... ax-L from the array. This step will cost ax points. The task is to maximize the total cost after deleting all the elements from the array.Examples: "
},
{
"code": null,
"e": 25555,
"s": 25192,
"text": "Input : 2 1 2 3 2 2 1\n L = 1, R = 1\nOutput : 8\nWe select 2 to delete, then (2-1)=1 and (2+1)=3 will need to be deleted, \nfor given L and R range respectively.\nRepeat this until 2 is completely removed. So, total cost = 2*4 = 8.\n\nInput : 2 4 2 9 5\n L = 1, R = 2\nOutput : 18\nWe select 2 to delete, then 5 and then 9.\nSo total cost = 2*2 + 5 + 9 = 18."
},
{
"code": null,
"e": 26031,
"s": 25557,
"text": "Approach: We will find the count of all the elements. Now let’s say an element X is selected then, all elements in the range [X-L, X+R] will be deleted. Now we select the minimum range from L and R and finds up to which elements are to be deleted when element X is selected. Our results will be the maximum of previously deleted elements and when element X is deleted. We will use dynamic programming to store the result of previously deleted elements and use it further. "
},
{
"code": null,
"e": 26035,
"s": 26031,
"text": "C++"
},
{
"code": null,
"e": 26040,
"s": 26035,
"text": "Java"
},
{
"code": null,
"e": 26049,
"s": 26040,
"text": "Python 3"
},
{
"code": null,
"e": 26052,
"s": 26049,
"text": "C#"
},
{
"code": null,
"e": 26063,
"s": 26052,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum cost after// deleting all the elements form the array#include <bits/stdc++.h>using namespace std; // function to return maximum cost obtainedint maxCost(int a[], int n, int l, int r){ int mx = 0, k; // find maximum element of the array. for (int i = 0; i < n; ++i) mx = max(mx, a[i]); // initialize count of all elements to zero. int count[mx + 1]; memset(count, 0, sizeof(count)); // calculate frequency of all elements of array. for (int i = 0; i < n; i++) count[a[i]]++; // stores cost of deleted elements. int res[mx + 1]; res[0] = 0; // selecting minimum range from L and R. l = min(l, r); for (int num = 1; num <= mx; num++) { // finds upto which elements are to be // deleted when element num is selected. k = max(num - l - 1, 0); // get maximum when selecting element num or not. res[num] = max(res[num - 1], num * count[num] + res[k]); } return res[mx];} // Driver programint main(){ int a[] = { 2, 1, 2, 3, 2, 2, 1 }, l = 1, r = 1; // size of array int n = sizeof(a) / sizeof(a[0]); // function call to find maximum cost cout << maxCost(a, n, l, r); return 0;}",
"e": 27292,
"s": 26063,
"text": null
},
{
"code": "//Java program to find maximum cost after//deleting all the elements form the array public class GFG { //function to return maximum cost obtained static int maxCost(int a[], int n, int l, int r) { int mx = 0, k; // find maximum element of the array. for (int i = 0; i < n; ++i) mx = Math.max(mx, a[i]); // initialize count of all elements to zero. int[] count = new int[mx + 1]; for(int i = 0; i < count.length; i++) count[i] = 0; // calculate frequency of all elements of array. for (int i = 0; i < n; i++) count[a[i]]++; // stores cost of deleted elements. int[] res = new int[mx + 1]; res[0] = 0; // selecting minimum range from L and R. l = Math.min(l, r); for (int num = 1; num <= mx; num++) { // finds upto which elements are to be // deleted when element num is selected. k = Math.max(num - l - 1, 0); // get maximum when selecting element num or not. res[num] = Math.max(res[num - 1], num * count[num] + res[k]); } return res[mx]; } //Driver program public static void main(String[] args) { int a[] = { 2, 1, 2, 3, 2, 2, 1 }, l = 1, r = 1; // size of array int n = a.length; // function call to find maximum cost System.out.println(maxCost(a, n, l, r)); }}",
"e": 28671,
"s": 27292,
"text": null
},
{
"code": "# Python 3 Program to find maximum cost after# deleting all the elements form the array # function to return maximum cost obtaineddef maxCost(a, n, l, r) : mx = 0 # find maximum element of the array. for i in range(n) : mx = max(mx, a[i]) # create and initialize count of all elements to zero. count = [0] * (mx + 1) # calculate frequency of all elements of array. for i in range(n) : count[a[i]] += 1 # stores cost of deleted elements. res = [0] * (mx + 1) res[0] = 0 # selecting minimum range from L and R. l = min(l, r) for num in range(1, mx + 1) : # finds upto which elements are to be # deleted when element num is selected. k = max(num - l - 1, 0) # get maximum when selecting element num or not. res[num] = max(res[num - 1], num * count[num] + res[k]) return res[mx] # Driver codeif __name__ == \"__main__\" : a = [2, 1, 2, 3, 2, 2, 1 ] l, r = 1, 1 # size of array n = len(a) # function call to find maximum cost print(maxCost(a, n, l, r)) # This code is contributed by ANKITRAI1",
"e": 29780,
"s": 28671,
"text": null
},
{
"code": "// C# program to find maximum cost// after deleting all the elements// form the arrayusing System; class GFG{ // function to return maximum// cost obtainedstatic int maxCost(int []a, int n, int l, int r){ int mx = 0, k; // find maximum element // of the array. for (int i = 0; i < n; ++i) mx = Math.Max(mx, a[i]); // initialize count of all // elements to zero. int[] count = new int[mx + 1]; for(int i = 0; i < count.Length; i++) count[i] = 0; // calculate frequency of all // elements of array. for (int i = 0; i < n; i++) count[a[i]]++; // stores cost of deleted elements. int[] res = new int[mx + 1]; res[0] = 0; // selecting minimum range // from L and R. l = Math.Min(l, r); for (int num = 1; num <= mx; num++) { // finds upto which elements // are to be deleted when // element num is selected. k = Math.Max(num - l - 1, 0); // get maximum when selecting // element num or not. res[num] = Math.Max(res[num - 1], num * count[num] + res[k]); } return res[mx];} // Driver Codepublic static void Main(){ int []a = { 2, 1, 2, 3, 2, 2, 1 }; int l = 1, r = 1; // size of array int n = a.Length; // function call to find maximum cost Console.WriteLine(maxCost(a, n, l, r));}} // This code is contributed// by inder_verma",
"e": 31233,
"s": 29780,
"text": null
},
{
"code": "<script> // Javascript program to find maximum cost after// deleting all the elements form the array // function to return maximum cost obtainedfunction maxCost(a, n, l, r){ var mx = 0, k; // find maximum element of the array. for (var i = 0; i < n; ++i) mx = Math.max(mx, a[i]); // initialize count of all elements to zero. var count = new Array(mx + 1); count.fill(0); // calculate frequency of all elements of array. for (var i = 0; i < n; i++) count[a[i]]++; // stores cost of deleted elements. var res = new Array(mx + 1); res[0] = 0; // selecting minimum range from L and R. l = Math.min(l, r); for (var num = 1; num <= mx; num++) { // finds upto which elements are to be // deleted when element num is selected. k = Math.max(num - l - 1, 0); // get maximum when selecting element num or not. res[num] = Math.max(res[num - 1], num * count[num] + res[k]); } return res[mx];} var a = [ 2, 1, 2, 3, 2, 2, 1 ];var l = 1, r = 1;// size of arrayvar n = a.length; // function call to find maximum costdocument.write(maxCost(a, n, l, r)); // This code is contributed by SoumikMondal </script>",
"e": 32437,
"s": 31233,
"text": null
},
{
"code": null,
"e": 32439,
"s": 32437,
"text": "8"
},
{
"code": null,
"e": 32469,
"s": 32441,
"text": "Time Complexity: O(max(A)) "
},
{
"code": null,
"e": 32477,
"s": 32469,
"text": "ankthon"
},
{
"code": null,
"e": 32483,
"s": 32477,
"text": "ukasp"
},
{
"code": null,
"e": 32494,
"s": 32483,
"text": "inderDuMCA"
},
{
"code": null,
"e": 32507,
"s": 32494,
"text": "SoumikMondal"
},
{
"code": null,
"e": 32527,
"s": 32507,
"text": "array-range-queries"
},
{
"code": null,
"e": 32534,
"s": 32527,
"text": "Arrays"
},
{
"code": null,
"e": 32554,
"s": 32534,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 32561,
"s": 32554,
"text": "Arrays"
},
{
"code": null,
"e": 32581,
"s": 32561,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 32679,
"s": 32581,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32704,
"s": 32679,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32724,
"s": 32704,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 32762,
"s": 32724,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32847,
"s": 32762,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 32896,
"s": 32847,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32925,
"s": 32896,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 32955,
"s": 32925,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32989,
"s": 32955,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 33020,
"s": 32989,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
Vim - Plug-Ins | Using plug-ins, we can extends the functionality of Vim. Vim supports many plug-ins and most of them are available freely. This chapter is about Vim plug-ins and we will discuss following items −
Plug-in management
Some useful plug-ins
This section discusses plug-in management. Vim provides various plug-ins managers but we won’t be using any plug-in manager, instead we’ll be doing all these steps manually for better understanding. Once you understand these steps, you can go with plug-in manager.
To install any plug-in perform following steps −
Create .vim/bundle directory in user’s home directory
Copy plug-in inside this directory
Set runtimepath in vim
Let us install badwolf plug-in in Vim. It is a color scheme for vim.
$ mkdir -p ~/.vim/bundle
$ cd ~/.vim/bundle/
$ git clone https://github.com/sjl/badwolf.git
$ echo "set runtimepath^ = ~/.vim/bundle/badwolf" > ~/.vimrc
Now plug-in is installed, so we can use badwold color scheme as follows −
:colorscheme badwolf
If we observe carefully, plug-in is a just collection of files and if we want to update that plug-in then just update appropriate plug-in directory from ~/.vim/bundle.
Removing plug-in in Vim is really simple. To remove plug-in perform following steps −
Remove plug-in directory from ~/.vim/bundle
Modify runtimepath appropriately
Below is list of some useful Vim plug-ins
Disassemble C/C++ code
Indenting for AWK script
Vim package manager
Automatically save and load vim session based on switching of git branch
Provide liniting for python files
46 Lectures
5.5 hours
Jason Cannon
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2166,
"s": 1970,
"text": "Using plug-ins, we can extends the functionality of Vim. Vim supports many plug-ins and most of them are available freely. This chapter is about Vim plug-ins and we will discuss following items −"
},
{
"code": null,
"e": 2185,
"s": 2166,
"text": "Plug-in management"
},
{
"code": null,
"e": 2206,
"s": 2185,
"text": "Some useful plug-ins"
},
{
"code": null,
"e": 2471,
"s": 2206,
"text": "This section discusses plug-in management. Vim provides various plug-ins managers but we won’t be using any plug-in manager, instead we’ll be doing all these steps manually for better understanding. Once you understand these steps, you can go with plug-in manager."
},
{
"code": null,
"e": 2520,
"s": 2471,
"text": "To install any plug-in perform following steps −"
},
{
"code": null,
"e": 2574,
"s": 2520,
"text": "Create .vim/bundle directory in user’s home directory"
},
{
"code": null,
"e": 2609,
"s": 2574,
"text": "Copy plug-in inside this directory"
},
{
"code": null,
"e": 2632,
"s": 2609,
"text": "Set runtimepath in vim"
},
{
"code": null,
"e": 2701,
"s": 2632,
"text": "Let us install badwolf plug-in in Vim. It is a color scheme for vim."
},
{
"code": null,
"e": 2858,
"s": 2701,
"text": "$ mkdir -p ~/.vim/bundle \n$ cd ~/.vim/bundle/ \n$ git clone https://github.com/sjl/badwolf.git \n$ echo \"set runtimepath^ = ~/.vim/bundle/badwolf\" > ~/.vimrc\n"
},
{
"code": null,
"e": 2932,
"s": 2858,
"text": "Now plug-in is installed, so we can use badwold color scheme as follows −"
},
{
"code": null,
"e": 2954,
"s": 2932,
"text": ":colorscheme badwolf\n"
},
{
"code": null,
"e": 3122,
"s": 2954,
"text": "If we observe carefully, plug-in is a just collection of files and if we want to update that plug-in then just update appropriate plug-in directory from ~/.vim/bundle."
},
{
"code": null,
"e": 3208,
"s": 3122,
"text": "Removing plug-in in Vim is really simple. To remove plug-in perform following steps −"
},
{
"code": null,
"e": 3252,
"s": 3208,
"text": "Remove plug-in directory from ~/.vim/bundle"
},
{
"code": null,
"e": 3285,
"s": 3252,
"text": "Modify runtimepath appropriately"
},
{
"code": null,
"e": 3327,
"s": 3285,
"text": "Below is list of some useful Vim plug-ins"
},
{
"code": null,
"e": 3350,
"s": 3327,
"text": "Disassemble C/C++ code"
},
{
"code": null,
"e": 3375,
"s": 3350,
"text": "Indenting for AWK script"
},
{
"code": null,
"e": 3395,
"s": 3375,
"text": "Vim package manager"
},
{
"code": null,
"e": 3468,
"s": 3395,
"text": "Automatically save and load vim session based on switching of git branch"
},
{
"code": null,
"e": 3502,
"s": 3468,
"text": "Provide liniting for python files"
},
{
"code": null,
"e": 3537,
"s": 3502,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3551,
"s": 3537,
"text": " Jason Cannon"
},
{
"code": null,
"e": 3558,
"s": 3551,
"text": " Print"
},
{
"code": null,
"e": 3569,
"s": 3558,
"text": " Add Notes"
}
] |
The Top 5 Data Science Qualifications | Towards Data Science | IntroductionProgrammingBusiness Savvy and IntelligenceStatistics and MathematicsMachine LearningVisualizationSummaryReferences
Introduction
Programming
Business Savvy and Intelligence
Statistics and Mathematics
Machine Learning
Visualization
Summary
References
As someone who has interviewed with several companies for Data Scientist positions, as well as someone who has searched and explored countless required qualifications for interviews, I have compiled my top five Data Science qualifications. These qualifications are not only expected to be required by the time of interview, but also just important qualifications to keep in mind at your current work, even if you are not interviewing. Data Science is always evolving so it is critical to be aware of new technologies within the field. These requirements may differ from your personal experiences, so keep in mind this article is stemming from my opinion as a professional Data Scientist. These qualifications will be described as key skills, concepts, and various experiences that are expected to have before entering the new role or current role. Keep reading if you would like to learn more about the top five Data Science qualifications for interviewing and/or for your current job as a Data Scientist.
As a Data Scientist, when you first study, you might be surprised to find out that coding and programming are often skipped in the curriculum (sometimes), as the programs you might enroll in are already expecting you to know how to code. However, it is incredibly important to have some sort of proficiency in a programming language. You may first learn advanced mathematics, statistics, Machine Learning algorithms, general theory, and Data Science processes before learning how to code. Do not be overwhelmed if this situation is your case, as there is no better time to learn than now.
In my programming experience, I actually learned SAS first, then moved onto R, then finally on to Python. I think this progression is a nice way to slowly ease into programming. However, sometimes it is best to just jump into more object-oriented programming right away if you are in a rush to learn everything Data Science. But, in my case, I focused mainly on statistics and SAS was a great platform for turning theory into practice from the start.
SAS
SAS [3] stands for Statistical Analysis System. In this programming language, you can perform most of the statistical approaches of Data Science in some way. The main functions are to perform data manipulation, descriptive statistics, and reporting. Here are the main facets of the SAS product that they highlight:
intuitive and flexible programming
libraries with common procedures
automated management and monitoring
data analysis tools
cross-platform and multi-platform support
The benefits that I have experienced with SAS are the amount of statistical power and practical procedures that are not necessarily as common and robust as in other languages like R or Python. Import statements include, but are not limited to PROC GLM, which includes regression, multiple regression, ANOVA (analysis of variance), partial correlation, and MONOVA (multivariate analysis of variance). In addition to these different analyses, you can also visualize and describe your data with plots. Some of the ones that I have used the most are:
Fit Diagnostics:RStudentQuantileCook’s D
Overall, this is a great first programming language to learn as a Data Scientist as it serves as a proper transition from theory to practical application, especially with statistical importance.
R
This next language, R [4], is a step above SAS in the fact that you can use Machine Learning centered programming too. With this programming language and the addition of RStudio [5], you can also create valuable statistical solutions and descriptive plots. The process of using R code with Data Science applications usually starts with importing your dataset, importing your libraries, examining the data — with and without plots, and finally, building models. Some of the Machine Learning algorithms that I have used with R programming include LDA, KNN, and Random Forest. There are much more, but it is similar to Python and sklearn, which I will be discussing below. I always like to think of R as a balance of SAS and Python. Ultimately, it is up to you and the company you are applying for if you want to have this qualification. Some companies use it, some do not. If you like it, then you should find a company that requires R, especially since switching from R to Python can sometimes cause confusion and hence, slow down productivity.
Here are some of the reasons why I like R:
— statistical power
— visualizations
— documentation
Python
I prefer to use Python over R, mainly because it is easier to integrate with a company’s current infrastructure and codebase. I have not experienced too many companies that use R over Python. In addition to this benefit, I also feel like there are more Machine Learning libraries in Python. Some of my favorite libraries in Python include sklearn, TensorFlow, and seaborn. It is also useful to use Python when I am working alongside Software Engineers and Data Engineers. I find there to be more documentation on products that use Python for Data Science applications as well.
Here are some of the reasons I use Python:
ability to use powerful Machine Learning libraries
versatility in deployment and production
prefer to use Python in a Jupyter Notebook over R in RStudio
Next, I will take a break from the more technical qualifications and discuss the business side of Data Science.
This next qualification is often skipped with certifications and general educational experiences. Being business savvy and business intelligent means understanding the business well and knowing why you need Data Science in the first place. It can be easy to start applying advanced Machine Learning algorithms right away to the company data, but the business use case needs to be established and thoroughly vetted in order to provide the biggest return on investment. For example, if you are able to classify birds with some computer vision algorithm, you have to understand why classifying them is useful. Is it because it will be more efficient? Is it because manual, human classification is inaccurate? In addition to understanding the business problem, you will usually need to work with a Product Manager to lay down how much money and time your Data Science project will save your company.
Once you have an understanding of the needs of the business, and get used to finding the needs of the business faster, you will become well qualified in the business aspect of Data Science. You may need to provide proof of why the algorithm you chose is useful in solving this problem. Once you get buy-in, you can then work and improve upon the current process and start to show off your algorithmic results.
Here are some ways that you can ensure you have the business savvy and intelligence qualification:
learn products, common pitfalls, and popular product solutions
practice or study product management
have a strong knowledge of data analysis
understand key metrics for any business (e.g., clicks per user, etc.)
Overall, employing and studying business analysis in relation to Data Science, is an incredibly critical qualification to have on your resume and current job.
While this qualification might seem obvious, sometimes you can focus more on the libraries that perform a lot of the statistics and mathematics for you. Assuming you already are proficient in using Machine Learning libraries or packages, and if you have at least a general understanding of statistical calculations, you will then be well qualified. Certain mathematics and statistics can be especially useful to know when you are conducting experiments that deal with significance.
Some important Data Science statistics that can help you to be qualified include the following:
hypothesis-testing
probability distributions
Bayesian thinking
oversampling (and under)
I recommend using your GitHub account to show a company your aptitude in statistics and mathematics by writing your own functions and discussing the significance of tests.
This qualification is more of a reminder that there is almost a new, best Machine Learning algorithm every year that you should be studying and practicing. For instance, many Data Scientists were using the Random Forest Machine Learning algorithm, and then later realized that all of the Data Science competitions had been using XGBoost instead. Therefore, it is beneficial to keep up-to-date in the Data Science community. You are not guaranteed to have this knowledge handed down to you so it is important to look for it yourself.
A particularly prominent site for this updated knowledge is Kaggle [9]. This site serves as a Data Science community where you can collaborate, share your code, learn, and ask questions about Data Science.
Their main products consist of:
competitions
datasets
notebooks
learn
Overall, of course, practice the main Machine Learning algorithms, especially with an example use case for each one, and explore new algorithms that might be even more powerful than the ones before. Setting up a GitHub account with your code, notebook, and examples is a great way to fulfill this Machine Learning qualification.
Lastly, is the visualization qualification. As a Data Scientist, it is important to know how to code, use Machine Learning algorithms, and have a great sense of business, so one of the ways that you can tie all of these facets together is by visualizing.
Here are some popular and useful visualization tools:
Tableau
Google Data Studio
Looker
MatPlotLib
Seaborn
Pandas Profiling
new Python libraries that include stored visualizations
Some of the ways you can visualize the Data Science process is with exploratory data analysis, business problems and its respective data, error metrics or the accuracy, and how the results of the Data Science model have improved the business.
Data Science requires a lot, and interviews can be daunting; being well-qualified is one way to calm yourself and introduce more confidence into yourself. The top Data Science qualifications that I have stood by, include the following:
1. Programming2. Business Savvy and Intelligence3. Statistics and Mathematics4. Machine Learning5. Visualization
If you have practiced the above qualifications, then you will be a well-qualified Data Scientist. Having examples of programming, a business use case, an understanding of statistics and mathematics, several examples of Machine Learning algorithms, and an overall sense of visualizing your process and results, will allow you to either land the job, or make you a better Data Scientist.
I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with the Data Science qualifications that I have discussed. Have you fulfilled these qualifications?
These are my opinions, and I am not affiliated with any of these companies. Thank you for reading!
Please feel free to check out my profile and other articles, as well as reach out to me on LinkedIn.
[1] Photo by LinkedIn Sales Navigator on Unsplash, (2017)
[2] Photo by James Harrison on Unsplash, (2020)
[3] 2021 SAS Institute Inc., SAS, (2021)
[4] The R Foundation, R, (2021)
[5] 2021 RStudio, PBC, RStudio, (2021)
[6] Photo by Austin Distel on Unsplash, (2019)
[7] Photo by Jeswin Thomas on Unsplash, (2020)
[8] Photo by Arseny Togulev on Unsplash, (2019)
[9] Kaggle Inc., Kaggle, (2021)
[10] Photo by William Iven on Unsplash, (2015) | [
{
"code": null,
"e": 299,
"s": 172,
"text": "IntroductionProgrammingBusiness Savvy and IntelligenceStatistics and MathematicsMachine LearningVisualizationSummaryReferences"
},
{
"code": null,
"e": 312,
"s": 299,
"text": "Introduction"
},
{
"code": null,
"e": 324,
"s": 312,
"text": "Programming"
},
{
"code": null,
"e": 356,
"s": 324,
"text": "Business Savvy and Intelligence"
},
{
"code": null,
"e": 383,
"s": 356,
"text": "Statistics and Mathematics"
},
{
"code": null,
"e": 400,
"s": 383,
"text": "Machine Learning"
},
{
"code": null,
"e": 414,
"s": 400,
"text": "Visualization"
},
{
"code": null,
"e": 422,
"s": 414,
"text": "Summary"
},
{
"code": null,
"e": 433,
"s": 422,
"text": "References"
},
{
"code": null,
"e": 1439,
"s": 433,
"text": "As someone who has interviewed with several companies for Data Scientist positions, as well as someone who has searched and explored countless required qualifications for interviews, I have compiled my top five Data Science qualifications. These qualifications are not only expected to be required by the time of interview, but also just important qualifications to keep in mind at your current work, even if you are not interviewing. Data Science is always evolving so it is critical to be aware of new technologies within the field. These requirements may differ from your personal experiences, so keep in mind this article is stemming from my opinion as a professional Data Scientist. These qualifications will be described as key skills, concepts, and various experiences that are expected to have before entering the new role or current role. Keep reading if you would like to learn more about the top five Data Science qualifications for interviewing and/or for your current job as a Data Scientist."
},
{
"code": null,
"e": 2028,
"s": 1439,
"text": "As a Data Scientist, when you first study, you might be surprised to find out that coding and programming are often skipped in the curriculum (sometimes), as the programs you might enroll in are already expecting you to know how to code. However, it is incredibly important to have some sort of proficiency in a programming language. You may first learn advanced mathematics, statistics, Machine Learning algorithms, general theory, and Data Science processes before learning how to code. Do not be overwhelmed if this situation is your case, as there is no better time to learn than now."
},
{
"code": null,
"e": 2479,
"s": 2028,
"text": "In my programming experience, I actually learned SAS first, then moved onto R, then finally on to Python. I think this progression is a nice way to slowly ease into programming. However, sometimes it is best to just jump into more object-oriented programming right away if you are in a rush to learn everything Data Science. But, in my case, I focused mainly on statistics and SAS was a great platform for turning theory into practice from the start."
},
{
"code": null,
"e": 2483,
"s": 2479,
"text": "SAS"
},
{
"code": null,
"e": 2798,
"s": 2483,
"text": "SAS [3] stands for Statistical Analysis System. In this programming language, you can perform most of the statistical approaches of Data Science in some way. The main functions are to perform data manipulation, descriptive statistics, and reporting. Here are the main facets of the SAS product that they highlight:"
},
{
"code": null,
"e": 2833,
"s": 2798,
"text": "intuitive and flexible programming"
},
{
"code": null,
"e": 2866,
"s": 2833,
"text": "libraries with common procedures"
},
{
"code": null,
"e": 2902,
"s": 2866,
"text": "automated management and monitoring"
},
{
"code": null,
"e": 2922,
"s": 2902,
"text": "data analysis tools"
},
{
"code": null,
"e": 2964,
"s": 2922,
"text": "cross-platform and multi-platform support"
},
{
"code": null,
"e": 3511,
"s": 2964,
"text": "The benefits that I have experienced with SAS are the amount of statistical power and practical procedures that are not necessarily as common and robust as in other languages like R or Python. Import statements include, but are not limited to PROC GLM, which includes regression, multiple regression, ANOVA (analysis of variance), partial correlation, and MONOVA (multivariate analysis of variance). In addition to these different analyses, you can also visualize and describe your data with plots. Some of the ones that I have used the most are:"
},
{
"code": null,
"e": 3552,
"s": 3511,
"text": "Fit Diagnostics:RStudentQuantileCook’s D"
},
{
"code": null,
"e": 3747,
"s": 3552,
"text": "Overall, this is a great first programming language to learn as a Data Scientist as it serves as a proper transition from theory to practical application, especially with statistical importance."
},
{
"code": null,
"e": 3749,
"s": 3747,
"text": "R"
},
{
"code": null,
"e": 4793,
"s": 3749,
"text": "This next language, R [4], is a step above SAS in the fact that you can use Machine Learning centered programming too. With this programming language and the addition of RStudio [5], you can also create valuable statistical solutions and descriptive plots. The process of using R code with Data Science applications usually starts with importing your dataset, importing your libraries, examining the data — with and without plots, and finally, building models. Some of the Machine Learning algorithms that I have used with R programming include LDA, KNN, and Random Forest. There are much more, but it is similar to Python and sklearn, which I will be discussing below. I always like to think of R as a balance of SAS and Python. Ultimately, it is up to you and the company you are applying for if you want to have this qualification. Some companies use it, some do not. If you like it, then you should find a company that requires R, especially since switching from R to Python can sometimes cause confusion and hence, slow down productivity."
},
{
"code": null,
"e": 4836,
"s": 4793,
"text": "Here are some of the reasons why I like R:"
},
{
"code": null,
"e": 4856,
"s": 4836,
"text": "— statistical power"
},
{
"code": null,
"e": 4873,
"s": 4856,
"text": "— visualizations"
},
{
"code": null,
"e": 4889,
"s": 4873,
"text": "— documentation"
},
{
"code": null,
"e": 4896,
"s": 4889,
"text": "Python"
},
{
"code": null,
"e": 5473,
"s": 4896,
"text": "I prefer to use Python over R, mainly because it is easier to integrate with a company’s current infrastructure and codebase. I have not experienced too many companies that use R over Python. In addition to this benefit, I also feel like there are more Machine Learning libraries in Python. Some of my favorite libraries in Python include sklearn, TensorFlow, and seaborn. It is also useful to use Python when I am working alongside Software Engineers and Data Engineers. I find there to be more documentation on products that use Python for Data Science applications as well."
},
{
"code": null,
"e": 5516,
"s": 5473,
"text": "Here are some of the reasons I use Python:"
},
{
"code": null,
"e": 5567,
"s": 5516,
"text": "ability to use powerful Machine Learning libraries"
},
{
"code": null,
"e": 5608,
"s": 5567,
"text": "versatility in deployment and production"
},
{
"code": null,
"e": 5669,
"s": 5608,
"text": "prefer to use Python in a Jupyter Notebook over R in RStudio"
},
{
"code": null,
"e": 5781,
"s": 5669,
"text": "Next, I will take a break from the more technical qualifications and discuss the business side of Data Science."
},
{
"code": null,
"e": 6677,
"s": 5781,
"text": "This next qualification is often skipped with certifications and general educational experiences. Being business savvy and business intelligent means understanding the business well and knowing why you need Data Science in the first place. It can be easy to start applying advanced Machine Learning algorithms right away to the company data, but the business use case needs to be established and thoroughly vetted in order to provide the biggest return on investment. For example, if you are able to classify birds with some computer vision algorithm, you have to understand why classifying them is useful. Is it because it will be more efficient? Is it because manual, human classification is inaccurate? In addition to understanding the business problem, you will usually need to work with a Product Manager to lay down how much money and time your Data Science project will save your company."
},
{
"code": null,
"e": 7087,
"s": 6677,
"text": "Once you have an understanding of the needs of the business, and get used to finding the needs of the business faster, you will become well qualified in the business aspect of Data Science. You may need to provide proof of why the algorithm you chose is useful in solving this problem. Once you get buy-in, you can then work and improve upon the current process and start to show off your algorithmic results."
},
{
"code": null,
"e": 7186,
"s": 7087,
"text": "Here are some ways that you can ensure you have the business savvy and intelligence qualification:"
},
{
"code": null,
"e": 7249,
"s": 7186,
"text": "learn products, common pitfalls, and popular product solutions"
},
{
"code": null,
"e": 7286,
"s": 7249,
"text": "practice or study product management"
},
{
"code": null,
"e": 7327,
"s": 7286,
"text": "have a strong knowledge of data analysis"
},
{
"code": null,
"e": 7397,
"s": 7327,
"text": "understand key metrics for any business (e.g., clicks per user, etc.)"
},
{
"code": null,
"e": 7556,
"s": 7397,
"text": "Overall, employing and studying business analysis in relation to Data Science, is an incredibly critical qualification to have on your resume and current job."
},
{
"code": null,
"e": 8038,
"s": 7556,
"text": "While this qualification might seem obvious, sometimes you can focus more on the libraries that perform a lot of the statistics and mathematics for you. Assuming you already are proficient in using Machine Learning libraries or packages, and if you have at least a general understanding of statistical calculations, you will then be well qualified. Certain mathematics and statistics can be especially useful to know when you are conducting experiments that deal with significance."
},
{
"code": null,
"e": 8134,
"s": 8038,
"text": "Some important Data Science statistics that can help you to be qualified include the following:"
},
{
"code": null,
"e": 8153,
"s": 8134,
"text": "hypothesis-testing"
},
{
"code": null,
"e": 8179,
"s": 8153,
"text": "probability distributions"
},
{
"code": null,
"e": 8197,
"s": 8179,
"text": "Bayesian thinking"
},
{
"code": null,
"e": 8222,
"s": 8197,
"text": "oversampling (and under)"
},
{
"code": null,
"e": 8394,
"s": 8222,
"text": "I recommend using your GitHub account to show a company your aptitude in statistics and mathematics by writing your own functions and discussing the significance of tests."
},
{
"code": null,
"e": 8927,
"s": 8394,
"text": "This qualification is more of a reminder that there is almost a new, best Machine Learning algorithm every year that you should be studying and practicing. For instance, many Data Scientists were using the Random Forest Machine Learning algorithm, and then later realized that all of the Data Science competitions had been using XGBoost instead. Therefore, it is beneficial to keep up-to-date in the Data Science community. You are not guaranteed to have this knowledge handed down to you so it is important to look for it yourself."
},
{
"code": null,
"e": 9133,
"s": 8927,
"text": "A particularly prominent site for this updated knowledge is Kaggle [9]. This site serves as a Data Science community where you can collaborate, share your code, learn, and ask questions about Data Science."
},
{
"code": null,
"e": 9165,
"s": 9133,
"text": "Their main products consist of:"
},
{
"code": null,
"e": 9178,
"s": 9165,
"text": "competitions"
},
{
"code": null,
"e": 9187,
"s": 9178,
"text": "datasets"
},
{
"code": null,
"e": 9197,
"s": 9187,
"text": "notebooks"
},
{
"code": null,
"e": 9203,
"s": 9197,
"text": "learn"
},
{
"code": null,
"e": 9532,
"s": 9203,
"text": "Overall, of course, practice the main Machine Learning algorithms, especially with an example use case for each one, and explore new algorithms that might be even more powerful than the ones before. Setting up a GitHub account with your code, notebook, and examples is a great way to fulfill this Machine Learning qualification."
},
{
"code": null,
"e": 9787,
"s": 9532,
"text": "Lastly, is the visualization qualification. As a Data Scientist, it is important to know how to code, use Machine Learning algorithms, and have a great sense of business, so one of the ways that you can tie all of these facets together is by visualizing."
},
{
"code": null,
"e": 9841,
"s": 9787,
"text": "Here are some popular and useful visualization tools:"
},
{
"code": null,
"e": 9849,
"s": 9841,
"text": "Tableau"
},
{
"code": null,
"e": 9868,
"s": 9849,
"text": "Google Data Studio"
},
{
"code": null,
"e": 9875,
"s": 9868,
"text": "Looker"
},
{
"code": null,
"e": 9886,
"s": 9875,
"text": "MatPlotLib"
},
{
"code": null,
"e": 9894,
"s": 9886,
"text": "Seaborn"
},
{
"code": null,
"e": 9911,
"s": 9894,
"text": "Pandas Profiling"
},
{
"code": null,
"e": 9967,
"s": 9911,
"text": "new Python libraries that include stored visualizations"
},
{
"code": null,
"e": 10210,
"s": 9967,
"text": "Some of the ways you can visualize the Data Science process is with exploratory data analysis, business problems and its respective data, error metrics or the accuracy, and how the results of the Data Science model have improved the business."
},
{
"code": null,
"e": 10446,
"s": 10210,
"text": "Data Science requires a lot, and interviews can be daunting; being well-qualified is one way to calm yourself and introduce more confidence into yourself. The top Data Science qualifications that I have stood by, include the following:"
},
{
"code": null,
"e": 10559,
"s": 10446,
"text": "1. Programming2. Business Savvy and Intelligence3. Statistics and Mathematics4. Machine Learning5. Visualization"
},
{
"code": null,
"e": 10945,
"s": 10559,
"text": "If you have practiced the above qualifications, then you will be a well-qualified Data Scientist. Having examples of programming, a business use case, an understanding of statistics and mathematics, several examples of Machine Learning algorithms, and an overall sense of visualizing your process and results, will allow you to either land the job, or make you a better Data Scientist."
},
{
"code": null,
"e": 11167,
"s": 10945,
"text": "I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with the Data Science qualifications that I have discussed. Have you fulfilled these qualifications?"
},
{
"code": null,
"e": 11266,
"s": 11167,
"text": "These are my opinions, and I am not affiliated with any of these companies. Thank you for reading!"
},
{
"code": null,
"e": 11367,
"s": 11266,
"text": "Please feel free to check out my profile and other articles, as well as reach out to me on LinkedIn."
},
{
"code": null,
"e": 11425,
"s": 11367,
"text": "[1] Photo by LinkedIn Sales Navigator on Unsplash, (2017)"
},
{
"code": null,
"e": 11473,
"s": 11425,
"text": "[2] Photo by James Harrison on Unsplash, (2020)"
},
{
"code": null,
"e": 11514,
"s": 11473,
"text": "[3] 2021 SAS Institute Inc., SAS, (2021)"
},
{
"code": null,
"e": 11546,
"s": 11514,
"text": "[4] The R Foundation, R, (2021)"
},
{
"code": null,
"e": 11585,
"s": 11546,
"text": "[5] 2021 RStudio, PBC, RStudio, (2021)"
},
{
"code": null,
"e": 11632,
"s": 11585,
"text": "[6] Photo by Austin Distel on Unsplash, (2019)"
},
{
"code": null,
"e": 11679,
"s": 11632,
"text": "[7] Photo by Jeswin Thomas on Unsplash, (2020)"
},
{
"code": null,
"e": 11727,
"s": 11679,
"text": "[8] Photo by Arseny Togulev on Unsplash, (2019)"
},
{
"code": null,
"e": 11759,
"s": 11727,
"text": "[9] Kaggle Inc., Kaggle, (2021)"
}
] |
Opencv Python program for Face Detection - GeeksforGeeks | 17 Jun, 2017
The objective of the program given is to detect object of interest(face) in real time and to keep tracking of the same object.This is a simple example of how to detect face in Python. You can try to use training samples of any other object of your choice to be detected by training the classifier on required objects.
Here is the steps to download the requirements below.
Steps:
Download Python 2.7.x version, numpy and Opencv 2.7.x version.Check if your Windows either 32 bit or 64 bit is compatible and install accordingly.Make sure that numpy is running in your python then try to install opencv.Put the haarcascade_eye.xml & haarcascade_frontalface_default.xml files in the same folder(links given in below code).
Download Python 2.7.x version, numpy and Opencv 2.7.x version.Check if your Windows either 32 bit or 64 bit is compatible and install accordingly.
Make sure that numpy is running in your python then try to install opencv.
Put the haarcascade_eye.xml & haarcascade_frontalface_default.xml files in the same folder(links given in below code).
Implementation
# OpenCV program to detect face in real time# import libraries of python OpenCV # where its functionality residesimport cv2 # load the required trained XML classifiers# https://github.com/Itseez/opencv/blob/master/# data/haarcascades/haarcascade_frontalface_default.xml# Trained XML classifiers describes some features of some# object we want to detect a cascade function is trained# from a lot of positive(faces) and negative(non-faces)# images.face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # https://github.com/Itseez/opencv/blob/master# /data/haarcascades/haarcascade_eye.xml# Trained XML file for detecting eyeseye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') # capture frames from a cameracap = cv2.VideoCapture(0) # loop runs if capturing has been initialized.while 1: # reads frames from a camera ret, img = cap.read() # convert to gray scale of each frames gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detects faces of different sizes in the input image faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: # To draw a rectangle in a face cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] # Detects eyes of different sizes in the input image eyes = eye_cascade.detectMultiScale(roi_gray) #To draw a rectangle in eyes for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,127,255),2) # Display an image in a window cv2.imshow('img',img) # Wait for Esc key to stop k = cv2.waitKey(30) & 0xff if k == 27: break # Close the windowcap.release() # De-allocate any associated memory usagecv2.destroyAllWindows()
Output:
Next Article: Opencv C++ Program for face detection
References:
https://www.youtube.com/v=WfdYYNamHZ8
http://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html?highlight=cascadeclassifier#cascadeclassifier
http://www.multimedia-computing.de/mediawiki//images/5/52/MRL-TR-May02-revised-Dec02.pdf
This article is contributed by Afzal Ansari. 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.
Image-Processing
OpenCV
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Snake Game in C
Program for Employee Management System
Simple registration form using Python Tkinter
Banking Transaction System using Java
A Group chat application in Java
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": 24484,
"s": 24456,
"text": "\n17 Jun, 2017"
},
{
"code": null,
"e": 24802,
"s": 24484,
"text": "The objective of the program given is to detect object of interest(face) in real time and to keep tracking of the same object.This is a simple example of how to detect face in Python. You can try to use training samples of any other object of your choice to be detected by training the classifier on required objects."
},
{
"code": null,
"e": 24856,
"s": 24802,
"text": "Here is the steps to download the requirements below."
},
{
"code": null,
"e": 24863,
"s": 24856,
"text": "Steps:"
},
{
"code": null,
"e": 25202,
"s": 24863,
"text": "Download Python 2.7.x version, numpy and Opencv 2.7.x version.Check if your Windows either 32 bit or 64 bit is compatible and install accordingly.Make sure that numpy is running in your python then try to install opencv.Put the haarcascade_eye.xml & haarcascade_frontalface_default.xml files in the same folder(links given in below code)."
},
{
"code": null,
"e": 25349,
"s": 25202,
"text": "Download Python 2.7.x version, numpy and Opencv 2.7.x version.Check if your Windows either 32 bit or 64 bit is compatible and install accordingly."
},
{
"code": null,
"e": 25424,
"s": 25349,
"text": "Make sure that numpy is running in your python then try to install opencv."
},
{
"code": null,
"e": 25543,
"s": 25424,
"text": "Put the haarcascade_eye.xml & haarcascade_frontalface_default.xml files in the same folder(links given in below code)."
},
{
"code": null,
"e": 25558,
"s": 25543,
"text": "Implementation"
},
{
"code": "# OpenCV program to detect face in real time# import libraries of python OpenCV # where its functionality residesimport cv2 # load the required trained XML classifiers# https://github.com/Itseez/opencv/blob/master/# data/haarcascades/haarcascade_frontalface_default.xml# Trained XML classifiers describes some features of some# object we want to detect a cascade function is trained# from a lot of positive(faces) and negative(non-faces)# images.face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # https://github.com/Itseez/opencv/blob/master# /data/haarcascades/haarcascade_eye.xml# Trained XML file for detecting eyeseye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') # capture frames from a cameracap = cv2.VideoCapture(0) # loop runs if capturing has been initialized.while 1: # reads frames from a camera ret, img = cap.read() # convert to gray scale of each frames gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detects faces of different sizes in the input image faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: # To draw a rectangle in a face cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] # Detects eyes of different sizes in the input image eyes = eye_cascade.detectMultiScale(roi_gray) #To draw a rectangle in eyes for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,127,255),2) # Display an image in a window cv2.imshow('img',img) # Wait for Esc key to stop k = cv2.waitKey(30) & 0xff if k == 27: break # Close the windowcap.release() # De-allocate any associated memory usagecv2.destroyAllWindows() ",
"e": 27357,
"s": 25558,
"text": null
},
{
"code": null,
"e": 27365,
"s": 27357,
"text": "Output:"
},
{
"code": null,
"e": 27417,
"s": 27365,
"text": "Next Article: Opencv C++ Program for face detection"
},
{
"code": null,
"e": 27429,
"s": 27417,
"text": "References:"
},
{
"code": null,
"e": 27467,
"s": 27429,
"text": "https://www.youtube.com/v=WfdYYNamHZ8"
},
{
"code": null,
"e": 27590,
"s": 27467,
"text": "http://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html?highlight=cascadeclassifier#cascadeclassifier"
},
{
"code": null,
"e": 27679,
"s": 27590,
"text": "http://www.multimedia-computing.de/mediawiki//images/5/52/MRL-TR-May02-revised-Dec02.pdf"
},
{
"code": null,
"e": 27979,
"s": 27679,
"text": "This article is contributed by Afzal Ansari. 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": 28104,
"s": 27979,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28121,
"s": 28104,
"text": "Image-Processing"
},
{
"code": null,
"e": 28128,
"s": 28121,
"text": "OpenCV"
},
{
"code": null,
"e": 28136,
"s": 28128,
"text": "Project"
},
{
"code": null,
"e": 28143,
"s": 28136,
"text": "Python"
},
{
"code": null,
"e": 28241,
"s": 28143,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28257,
"s": 28241,
"text": "Snake Game in C"
},
{
"code": null,
"e": 28296,
"s": 28257,
"text": "Program for Employee Management System"
},
{
"code": null,
"e": 28342,
"s": 28296,
"text": "Simple registration form using Python Tkinter"
},
{
"code": null,
"e": 28380,
"s": 28342,
"text": "Banking Transaction System using Java"
},
{
"code": null,
"e": 28413,
"s": 28380,
"text": "A Group chat application in Java"
},
{
"code": null,
"e": 28441,
"s": 28413,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28491,
"s": 28441,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28513,
"s": 28491,
"text": "Python map() function"
}
] |
How to trigger setInterval loop immediately using JavaScript ? - GeeksforGeeks | 28 Jan, 2020
This article will show some simple ways in which the setInterval() method can be made to execute the function without delay. There are many procedures to do so, below all the procedures are described with the example.
Note: In this article setInterval() method will start immediately for the 1st time run.
Below examples illustrate the above approach:
Example 1: Here, the setInterval() method is returned in gfg() function. The gfg() function trigger itself for subsequent calls using setTimeout() instead. Multiply the output each time in this method.
<!DOCTYPE html><html> <head> <title> Start setInterval loop immediately </title></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <h4> Start setInterval loop immediately </h4> <script> function gfg() { document.write("Hello! geeks" + " for geeks<br>"); return setInterval(gfg, 3000); } // Function call gfg(); </script></body> </html>
Output:
Example 2: This can be implemented using immediately invoked function expressions (IIFE) . It defines the function gfg() and calls in one go. Multiply the output each time in this method.
<!DOCTYPE html><html> <head> <title> Start setInterval loop immediately </title></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <h4> Start setInterval loop immediately </h4> <script> // Using IIFE (function gfg() { document.write("Hello! geeks" + " for geeks<br>"); return setInterval(gfg, 3000); })(); </script></body> </html>
Output:
Example 3: The simplest way is calling the gfg() first and then starting the setInterval’s cycle of execution.
<!DOCTYPE html><html> <head> <title> Start setInterval loop immediately </title></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <h4> Start setInterval loop immediately </h4> <script> function gfg() { document.write("Hello! geeks" + " for geeks<br>") } gfg(); setInterval(gfg, 3000); </script></body> </html>
Output:
In all the above code, the first time “Hello! geeks for geeks” statement will be displayed immediately followed by the second and third and so on with a time interval of 3 seconds. The first time gfg() will be called immediately after running the code.
Note: All the above examples can be tested by typing them within the script tag of HTML or directly into the browser’s console.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24716,
"s": 24688,
"text": "\n28 Jan, 2020"
},
{
"code": null,
"e": 24934,
"s": 24716,
"text": "This article will show some simple ways in which the setInterval() method can be made to execute the function without delay. There are many procedures to do so, below all the procedures are described with the example."
},
{
"code": null,
"e": 25022,
"s": 24934,
"text": "Note: In this article setInterval() method will start immediately for the 1st time run."
},
{
"code": null,
"e": 25068,
"s": 25022,
"text": "Below examples illustrate the above approach:"
},
{
"code": null,
"e": 25270,
"s": 25068,
"text": "Example 1: Here, the setInterval() method is returned in gfg() function. The gfg() function trigger itself for subsequent calls using setTimeout() instead. Multiply the output each time in this method."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Start setInterval loop immediately </title></head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h4> Start setInterval loop immediately </h4> <script> function gfg() { document.write(\"Hello! geeks\" + \" for geeks<br>\"); return setInterval(gfg, 3000); } // Function call gfg(); </script></body> </html>",
"e": 25752,
"s": 25270,
"text": null
},
{
"code": null,
"e": 25760,
"s": 25752,
"text": "Output:"
},
{
"code": null,
"e": 25948,
"s": 25760,
"text": "Example 2: This can be implemented using immediately invoked function expressions (IIFE) . It defines the function gfg() and calls in one go. Multiply the output each time in this method."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Start setInterval loop immediately </title></head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h4> Start setInterval loop immediately </h4> <script> // Using IIFE (function gfg() { document.write(\"Hello! geeks\" + \" for geeks<br>\"); return setInterval(gfg, 3000); })(); </script></body> </html>",
"e": 26418,
"s": 25948,
"text": null
},
{
"code": null,
"e": 26426,
"s": 26418,
"text": "Output:"
},
{
"code": null,
"e": 26537,
"s": 26426,
"text": "Example 3: The simplest way is calling the gfg() first and then starting the setInterval’s cycle of execution."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Start setInterval loop immediately </title></head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h4> Start setInterval loop immediately </h4> <script> function gfg() { document.write(\"Hello! geeks\" + \" for geeks<br>\") } gfg(); setInterval(gfg, 3000); </script></body> </html>",
"e": 26983,
"s": 26537,
"text": null
},
{
"code": null,
"e": 26991,
"s": 26983,
"text": "Output:"
},
{
"code": null,
"e": 27244,
"s": 26991,
"text": "In all the above code, the first time “Hello! geeks for geeks” statement will be displayed immediately followed by the second and third and so on with a time interval of 3 seconds. The first time gfg() will be called immediately after running the code."
},
{
"code": null,
"e": 27372,
"s": 27244,
"text": "Note: All the above examples can be tested by typing them within the script tag of HTML or directly into the browser’s console."
},
{
"code": null,
"e": 27388,
"s": 27372,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27395,
"s": 27388,
"text": "Picked"
},
{
"code": null,
"e": 27406,
"s": 27395,
"text": "JavaScript"
},
{
"code": null,
"e": 27423,
"s": 27406,
"text": "Web Technologies"
},
{
"code": null,
"e": 27450,
"s": 27423,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27548,
"s": 27450,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27557,
"s": 27548,
"text": "Comments"
},
{
"code": null,
"e": 27570,
"s": 27557,
"text": "Old Comments"
},
{
"code": null,
"e": 27615,
"s": 27570,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27676,
"s": 27615,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27748,
"s": 27676,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27794,
"s": 27748,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 27835,
"s": 27794,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27877,
"s": 27835,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27910,
"s": 27877,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27953,
"s": 27910,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28015,
"s": 27953,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
ASP.NET - Debugging | Debugging allows the developers to see how the code works in a step-by-step manner, how the values of the variables change, how the objects are created and destroyed, etc.
When the site is executed for the first time, Visual Studio displays a prompt asking whether it should be enabled for debugging:
When debugging is enabled, the following lines of codes are shown in the web.config:
<system.web>
<compilation debug="true">
<assemblies>
..............
</assemblies>
</compilation>
</system.web>
The Debug toolbar provides all the tools available for debugging:
Breakpoints specifies the runtime to run a specific line of code and then stop execution so that the code could be examined and perform various debugging jobs such as, changing the value of the variables, step through the codes, moving in and out of functions and methods etc.
To set a breakpoint, right click on the code and choose insert break point. A red dot appears on the left margin and the line of code is highlighted as shown:
Next when you execute the code, you can observe its behavior.
At this stage, you can step through the code, observe the execution flow and examine the value of the variables, properties, objects, etc.
You can modify the properties of the breakpoint from the Properties menu obtained by right clicking the breakpoint glyph:
The location dialog box shows the location of the file, line number and the character number of the selected code. The condition menu item allows you to enter a valid expression, which is evaluated when the program execution reaches the breakpoint:
The Hit Count menu item displays a dialog box that shows the number of times the break point has been executed.
Clicking on any option presented by the drop down list opens an edit field where a target hit count is entered. This is particularly helpful in analyzing loop constructs in code.
The Filter menu item allows setting a filter for specifying machines, processes, or threads or any combination, for which the breakpoint will be effective.
The When Hit menu item allows you to specify what to do when the break point is hit.
Visual Studio provides the following debug windows, each of which shows some program information. The following table lists the windows:
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2519,
"s": 2347,
"text": "Debugging allows the developers to see how the code works in a step-by-step manner, how the values of the variables change, how the objects are created and destroyed, etc."
},
{
"code": null,
"e": 2648,
"s": 2519,
"text": "When the site is executed for the first time, Visual Studio displays a prompt asking whether it should be enabled for debugging:"
},
{
"code": null,
"e": 2733,
"s": 2648,
"text": "When debugging is enabled, the following lines of codes are shown in the web.config:"
},
{
"code": null,
"e": 2869,
"s": 2733,
"text": "<system.web>\n <compilation debug=\"true\">\n <assemblies>\n ..............\n </assemblies>\n </compilation>\t\n</system.web>"
},
{
"code": null,
"e": 2935,
"s": 2869,
"text": "The Debug toolbar provides all the tools available for debugging:"
},
{
"code": null,
"e": 3212,
"s": 2935,
"text": "Breakpoints specifies the runtime to run a specific line of code and then stop execution so that the code could be examined and perform various debugging jobs such as, changing the value of the variables, step through the codes, moving in and out of functions and methods etc."
},
{
"code": null,
"e": 3371,
"s": 3212,
"text": "To set a breakpoint, right click on the code and choose insert break point. A red dot appears on the left margin and the line of code is highlighted as shown:"
},
{
"code": null,
"e": 3433,
"s": 3371,
"text": "Next when you execute the code, you can observe its behavior."
},
{
"code": null,
"e": 3572,
"s": 3433,
"text": "At this stage, you can step through the code, observe the execution flow and examine the value of the variables, properties, objects, etc."
},
{
"code": null,
"e": 3694,
"s": 3572,
"text": "You can modify the properties of the breakpoint from the Properties menu obtained by right clicking the breakpoint glyph:"
},
{
"code": null,
"e": 3943,
"s": 3694,
"text": "The location dialog box shows the location of the file, line number and the character number of the selected code. The condition menu item allows you to enter a valid expression, which is evaluated when the program execution reaches the breakpoint:"
},
{
"code": null,
"e": 4055,
"s": 3943,
"text": "The Hit Count menu item displays a dialog box that shows the number of times the break point has been executed."
},
{
"code": null,
"e": 4234,
"s": 4055,
"text": "Clicking on any option presented by the drop down list opens an edit field where a target hit count is entered. This is particularly helpful in analyzing loop constructs in code."
},
{
"code": null,
"e": 4390,
"s": 4234,
"text": "The Filter menu item allows setting a filter for specifying machines, processes, or threads or any combination, for which the breakpoint will be effective."
},
{
"code": null,
"e": 4475,
"s": 4390,
"text": "The When Hit menu item allows you to specify what to do when the break point is hit."
},
{
"code": null,
"e": 4612,
"s": 4475,
"text": "Visual Studio provides the following debug windows, each of which shows some program information. The following table lists the windows:"
},
{
"code": null,
"e": 4647,
"s": 4612,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4661,
"s": 4647,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4696,
"s": 4661,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4719,
"s": 4696,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 4753,
"s": 4719,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 4773,
"s": 4753,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 4808,
"s": 4773,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4825,
"s": 4808,
"text": " University Code"
},
{
"code": null,
"e": 4860,
"s": 4825,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4877,
"s": 4860,
"text": " University Code"
},
{
"code": null,
"e": 4911,
"s": 4877,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4926,
"s": 4911,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 4933,
"s": 4926,
"text": " Print"
},
{
"code": null,
"e": 4944,
"s": 4933,
"text": " Add Notes"
}
] |
Fables of Data Science — Anscombe’s quartet | by dearC | Towards Data Science | ..in a land far far away there used to live a man called Francis John “Frank” Anscombe. He was a statistician of great repute.
He wandered far and wide meeting many fellow practitioners and sat in the Citadel training young apprentices in the sacred art of statistics. The more he talked and trained people he saw a dangerous trend. People tended to ignore visualizations in favor of summary statistics. Everyone said it was too much effort to plot the data.
This was a dangerous, Frank was very worried. This plague was spreading was spreading fast, he did not have the time counter it. He had to do something, something that would help stop it.
So he rushed to talk to the council of olders but every one just laughed at him.
“When you have the data’s mean,What else do you want to examine?Standard deviation is just sublime,Plotting is a big waste of time!” — Master PoorPoetrix
Frank had never anticipated that the Council too was poisoned, he had to open their eyes.
So he traveled, traveled northwards into the Lands of Always Winter, to the peak of the Frostfang mountains. There he sat, deep in meditation. And after 5 minutes he realized that it is shit cold out in the mountains and he should have packed more woolen clothes.
Shivering in cold he went around looking for a cave to settle in and as luck would have it he found one.
There Frank meditated and he mediated deep, though some claimed he just fell asleep.
In his dreams he saw numbers, numbers and more numbers and it was then that he realized that the numbers were the key to his solution. Day after day he pondered on those numbers and finally he solved their mystery.
He called a bird and through him he sent to the Council a parchment with 4 sets of 11 data-points and requested the council as his last wish to plot those points:
.
.
+-------+--------+-------+-------+-------+-------+-------+------+| I | II | III | IV |+-------+--------+-------+-------+-------+-------+-------+------+| x | y | x | y | x | y | x | y | +-------+--------+-------+-------+-------+-------+-------+------+| 10.0 | 8.04 | 10.0 | 9.14 | 10.0 | 7.46 | 8.0 | 6.58 || 8.0 | 6.95 | 8.0 | 8.14 | 8.0 | 6.77 | 8.0 | 5.76 || 13.0 | 7.58 | 13.0 | 8.74 | 13.0 | 12.74 | 8.0 | 7.71 || 9.0 | 8.81 | 9.0 | 8.77 | 9.0 | 7.11 | 8.0 | 8.84 || 11.0 | 8.33 | 11.0 | 9.26 | 11.0 | 7.81 | 8.0 | 8.47 || 14.0 | 9.96 | 14.0 | 8.10 | 14.0 | 8.84 | 8.0 | 7.04 || 6.0 | 7.24 | 6.0 | 6.13 | 6.0 | 6.08 | 8.0 | 5.25 || 4.0 | 4.26 | 4.0 | 3.10 | 4.0 | 5.39 | 19.0 |12.50 || 12.0 | 10.84 | 12.0 | 9.13 | 12.0 | 8.15 | 8.0 | 5.56 || 7.0 | 4.82 | 7.0 | 7.26 | 7.0 | 6.42 | 8.0 | 7.91 || 5.0 | 5.68 | 5.0 | 4.74 | 5.0 | 5.73 | 8.0 | 6.89 |+-------+--------+-------+-------+-------+-------+-------+------+
As was their habit the council analyzed them using only descriptive statistics they got exactly similar results, they wondered what the old fool Frank was upto again:
Summary+-----+---------+-------+---------+-------+----------+| Set | mean(X) | sd(X) | mean(Y) | sd(Y) | cor(X,Y) |+-----+---------+-------+---------+-------+----------+| 1 | 9 | 3.32 | 7.5 | 2.03 | 0.816 || 2 | 9 | 3.32 | 7.5 | 2.03 | 0.816 || 3 | 9 | 3.32 | 7.5 | 2.03 | 0.816 || 4 | 9 | 3.32 | 7.5 | 2.03 | 0.817 |+-----+---------+-------+---------+-------+----------+
But Master PoorPoetrix decided to honor his friend’s request and it was then that magic appeared when he plotted the data sets:
He saw that the graphs were completely different even though the summary was exactly similar.
The first scatter plot (top left) appeared to be a simple linear relationship, corresponding to two variables correlated and following the assumption of normality.
The second graph (top right) was not distributed normally; while a relationship between the two variables is obvious, it is not linear, and the Pearson correlation coefficient is not relevant. A more general regression and the corresponding coefficient of determination would be more appropriate.
In the third graph (bottom left), the distribution is linear, but should have a different regression line (a robust regression would have been called for). The calculated regression is offset by the one outlier which exerts enough influence to lower the correlation coefficient from 1 to 0.816.
Finally, the fourth graph (bottom right) shows an example when one high-leverage point is enough to produce a high correlation coefficient, even though the other data points do not indicate any relationship between the variables.
Master PoorPoetrix realized the folly of the Council’s ways and rectified them, this data-set came to be known as Anscombe’s quartet.
Frank had saved the world and lived out his last few days in the mountain cave as a happy old man.
.
.
Master PoorPoetrix is widely quoted to have summarized the incident with these immortal words:
To have analysis that you can trust,Plot your data, plot you must. — Master PoorPoetrix
https://en.wikipedia.org/wiki/Anscombe%27s_quartethttps://www.r-bloggers.com/using-and-abusing-data-visualization-anscombes-quartet-and-cheating-bonferroni/GIFs taken from https://giphy.com/
https://en.wikipedia.org/wiki/Anscombe%27s_quartet
https://www.r-bloggers.com/using-and-abusing-data-visualization-anscombes-quartet-and-cheating-bonferroni/
GIFs taken from https://giphy.com/ | [
{
"code": null,
"e": 299,
"s": 172,
"text": "..in a land far far away there used to live a man called Francis John “Frank” Anscombe. He was a statistician of great repute."
},
{
"code": null,
"e": 631,
"s": 299,
"text": "He wandered far and wide meeting many fellow practitioners and sat in the Citadel training young apprentices in the sacred art of statistics. The more he talked and trained people he saw a dangerous trend. People tended to ignore visualizations in favor of summary statistics. Everyone said it was too much effort to plot the data."
},
{
"code": null,
"e": 819,
"s": 631,
"text": "This was a dangerous, Frank was very worried. This plague was spreading was spreading fast, he did not have the time counter it. He had to do something, something that would help stop it."
},
{
"code": null,
"e": 900,
"s": 819,
"text": "So he rushed to talk to the council of olders but every one just laughed at him."
},
{
"code": null,
"e": 1054,
"s": 900,
"text": "“When you have the data’s mean,What else do you want to examine?Standard deviation is just sublime,Plotting is a big waste of time!” — Master PoorPoetrix"
},
{
"code": null,
"e": 1144,
"s": 1054,
"text": "Frank had never anticipated that the Council too was poisoned, he had to open their eyes."
},
{
"code": null,
"e": 1408,
"s": 1144,
"text": "So he traveled, traveled northwards into the Lands of Always Winter, to the peak of the Frostfang mountains. There he sat, deep in meditation. And after 5 minutes he realized that it is shit cold out in the mountains and he should have packed more woolen clothes."
},
{
"code": null,
"e": 1513,
"s": 1408,
"text": "Shivering in cold he went around looking for a cave to settle in and as luck would have it he found one."
},
{
"code": null,
"e": 1598,
"s": 1513,
"text": "There Frank meditated and he mediated deep, though some claimed he just fell asleep."
},
{
"code": null,
"e": 1813,
"s": 1598,
"text": "In his dreams he saw numbers, numbers and more numbers and it was then that he realized that the numbers were the key to his solution. Day after day he pondered on those numbers and finally he solved their mystery."
},
{
"code": null,
"e": 1976,
"s": 1813,
"text": "He called a bird and through him he sent to the Council a parchment with 4 sets of 11 data-points and requested the council as his last wish to plot those points:"
},
{
"code": null,
"e": 1978,
"s": 1976,
"text": "."
},
{
"code": null,
"e": 1980,
"s": 1978,
"text": "."
},
{
"code": null,
"e": 3087,
"s": 1980,
"text": "+-------+--------+-------+-------+-------+-------+-------+------+| I | II | III | IV |+-------+--------+-------+-------+-------+-------+-------+------+| x | y | x | y | x | y | x | y | +-------+--------+-------+-------+-------+-------+-------+------+| 10.0 | 8.04 | 10.0 | 9.14 | 10.0 | 7.46 | 8.0 | 6.58 || 8.0 | 6.95 | 8.0 | 8.14 | 8.0 | 6.77 | 8.0 | 5.76 || 13.0 | 7.58 | 13.0 | 8.74 | 13.0 | 12.74 | 8.0 | 7.71 || 9.0 | 8.81 | 9.0 | 8.77 | 9.0 | 7.11 | 8.0 | 8.84 || 11.0 | 8.33 | 11.0 | 9.26 | 11.0 | 7.81 | 8.0 | 8.47 || 14.0 | 9.96 | 14.0 | 8.10 | 14.0 | 8.84 | 8.0 | 7.04 || 6.0 | 7.24 | 6.0 | 6.13 | 6.0 | 6.08 | 8.0 | 5.25 || 4.0 | 4.26 | 4.0 | 3.10 | 4.0 | 5.39 | 19.0 |12.50 || 12.0 | 10.84 | 12.0 | 9.13 | 12.0 | 8.15 | 8.0 | 5.56 || 7.0 | 4.82 | 7.0 | 7.26 | 7.0 | 6.42 | 8.0 | 7.91 || 5.0 | 5.68 | 5.0 | 4.74 | 5.0 | 5.73 | 8.0 | 6.89 |+-------+--------+-------+-------+-------+-------+-------+------+"
},
{
"code": null,
"e": 3254,
"s": 3087,
"text": "As was their habit the council analyzed them using only descriptive statistics they got exactly similar results, they wondered what the old fool Frank was upto again:"
},
{
"code": null,
"e": 3717,
"s": 3254,
"text": " Summary+-----+---------+-------+---------+-------+----------+| Set | mean(X) | sd(X) | mean(Y) | sd(Y) | cor(X,Y) |+-----+---------+-------+---------+-------+----------+| 1 | 9 | 3.32 | 7.5 | 2.03 | 0.816 || 2 | 9 | 3.32 | 7.5 | 2.03 | 0.816 || 3 | 9 | 3.32 | 7.5 | 2.03 | 0.816 || 4 | 9 | 3.32 | 7.5 | 2.03 | 0.817 |+-----+---------+-------+---------+-------+----------+"
},
{
"code": null,
"e": 3845,
"s": 3717,
"text": "But Master PoorPoetrix decided to honor his friend’s request and it was then that magic appeared when he plotted the data sets:"
},
{
"code": null,
"e": 3939,
"s": 3845,
"text": "He saw that the graphs were completely different even though the summary was exactly similar."
},
{
"code": null,
"e": 4103,
"s": 3939,
"text": "The first scatter plot (top left) appeared to be a simple linear relationship, corresponding to two variables correlated and following the assumption of normality."
},
{
"code": null,
"e": 4400,
"s": 4103,
"text": "The second graph (top right) was not distributed normally; while a relationship between the two variables is obvious, it is not linear, and the Pearson correlation coefficient is not relevant. A more general regression and the corresponding coefficient of determination would be more appropriate."
},
{
"code": null,
"e": 4695,
"s": 4400,
"text": "In the third graph (bottom left), the distribution is linear, but should have a different regression line (a robust regression would have been called for). The calculated regression is offset by the one outlier which exerts enough influence to lower the correlation coefficient from 1 to 0.816."
},
{
"code": null,
"e": 4925,
"s": 4695,
"text": "Finally, the fourth graph (bottom right) shows an example when one high-leverage point is enough to produce a high correlation coefficient, even though the other data points do not indicate any relationship between the variables."
},
{
"code": null,
"e": 5059,
"s": 4925,
"text": "Master PoorPoetrix realized the folly of the Council’s ways and rectified them, this data-set came to be known as Anscombe’s quartet."
},
{
"code": null,
"e": 5158,
"s": 5059,
"text": "Frank had saved the world and lived out his last few days in the mountain cave as a happy old man."
},
{
"code": null,
"e": 5160,
"s": 5158,
"text": "."
},
{
"code": null,
"e": 5162,
"s": 5160,
"text": "."
},
{
"code": null,
"e": 5257,
"s": 5162,
"text": "Master PoorPoetrix is widely quoted to have summarized the incident with these immortal words:"
},
{
"code": null,
"e": 5345,
"s": 5257,
"text": "To have analysis that you can trust,Plot your data, plot you must. — Master PoorPoetrix"
},
{
"code": null,
"e": 5536,
"s": 5345,
"text": "https://en.wikipedia.org/wiki/Anscombe%27s_quartethttps://www.r-bloggers.com/using-and-abusing-data-visualization-anscombes-quartet-and-cheating-bonferroni/GIFs taken from https://giphy.com/"
},
{
"code": null,
"e": 5587,
"s": 5536,
"text": "https://en.wikipedia.org/wiki/Anscombe%27s_quartet"
},
{
"code": null,
"e": 5694,
"s": 5587,
"text": "https://www.r-bloggers.com/using-and-abusing-data-visualization-anscombes-quartet-and-cheating-bonferroni/"
}
] |
Subsets and Splits