title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to add space before and after specific character using regex in Python?
|
The following code shows how space is added before and after the pipe '|' character in given string.
import re
regex = r'\b[|:]\b'
s = "abracadabra abraca|dabara | abra cadabra abra ca dabra abra ca dabra abra"
print(re.sub(regex, ' \g<0> ', s))
This gives the output
abracadabra abraca | dabara | abra cadabra abra ca dabra abra ca dabra abra
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "The following code shows how space is added before and after the pipe '|' character in given string. "
},
{
"code": null,
"e": 1309,
"s": 1164,
"text": "import re\nregex = r'\\b[|:]\\b'\ns = \"abracadabra abraca|dabara | abra cadabra abra ca dabra abra ca dabra abra\"\nprint(re.sub(regex, ' \\g<0> ', s))"
},
{
"code": null,
"e": 1331,
"s": 1309,
"text": "This gives the output"
},
{
"code": null,
"e": 1407,
"s": 1331,
"text": "abracadabra abraca | dabara | abra cadabra abra ca dabra abra ca dabra abra"
}
] |
Angular Material 7 - Select
|
The <mat-select>, an Angular Directive, is used for <select> for enhance material design based styling..
In this chapter, we will showcase the configuration required to draw a select control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatSelectModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatSelectModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified ts file app.component.ts.
import { Component } from '@angular/core';
import { FormControl } from "@angular/forms";
export interface Food {
value: string;
display: string;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'materialApp';
selectedValue: string;
foods: Food[] = [
{value: 'steak', display: 'Steak'},
{value: 'pizza', display: 'Pizza'},
{value: 'tacos', display: 'Tacos'}
];
}
Following is the content of the modified HTML host file app.component.html.
<form>
<h4>mat-select</h4>
<mat-form-field>
<mat-select placeholder = "Favorite food"
[(ngModel)] = "selectedValue" name = "food">
<mat-option *ngFor = "let food of foods"
[value] = "food.value">
{{food.display}}
</mat-option>
</mat-select>
</mat-form-field>
<p> Selected food: {{selectedValue}} </p>
</form>
Verify the result.
As first, we've created a select using mat-select bound with ngModel.
As first, we've created a select using mat-select bound with ngModel.
Then, we've added options using mat-option.
Then, we've added options using mat-option.
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": 2860,
"s": 2755,
"text": "The <mat-select>, an Angular Directive, is used for <select> for enhance material design based styling.."
},
{
"code": null,
"e": 2970,
"s": 2860,
"text": "In this chapter, we will showcase the configuration required to draw a select control using Angular Material."
},
{
"code": null,
"e": 3081,
"s": 2970,
"text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −"
},
{
"code": null,
"e": 3155,
"s": 3081,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 3770,
"s": 3155,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatSelectModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatSelectModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3837,
"s": 3770,
"text": "Following is the content of the modified ts file app.component.ts."
},
{
"code": null,
"e": 4343,
"s": 3837,
"text": "import { Component } from '@angular/core';\nimport { FormControl } from \"@angular/forms\";\nexport interface Food {\n value: string;\n display: string;\n}\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'materialApp'; \n selectedValue: string; \n foods: Food[] = [\n {value: 'steak', display: 'Steak'},\n {value: 'pizza', display: 'Pizza'},\n {value: 'tacos', display: 'Tacos'}\n ];\n}"
},
{
"code": null,
"e": 4419,
"s": 4343,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 4806,
"s": 4419,
"text": "<form>\n <h4>mat-select</h4>\n <mat-form-field>\n <mat-select placeholder = \"Favorite food\" \n [(ngModel)] = \"selectedValue\" name = \"food\">\n <mat-option *ngFor = \"let food of foods\" \n [value] = \"food.value\">\n {{food.display}}\n </mat-option>\n </mat-select>\n </mat-form-field>\n <p> Selected food: {{selectedValue}} </p> \n</form>"
},
{
"code": null,
"e": 4825,
"s": 4806,
"text": "Verify the result."
},
{
"code": null,
"e": 4895,
"s": 4825,
"text": "As first, we've created a select using mat-select bound with ngModel."
},
{
"code": null,
"e": 4965,
"s": 4895,
"text": "As first, we've created a select using mat-select bound with ngModel."
},
{
"code": null,
"e": 5009,
"s": 4965,
"text": "Then, we've added options using mat-option."
},
{
"code": null,
"e": 5053,
"s": 5009,
"text": "Then, we've added options using mat-option."
},
{
"code": null,
"e": 5088,
"s": 5053,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5102,
"s": 5088,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5137,
"s": 5102,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5151,
"s": 5137,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5186,
"s": 5151,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5206,
"s": 5186,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5241,
"s": 5206,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5258,
"s": 5241,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5291,
"s": 5258,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5303,
"s": 5291,
"text": " Senol Atac"
},
{
"code": null,
"e": 5338,
"s": 5303,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5350,
"s": 5338,
"text": " Senol Atac"
},
{
"code": null,
"e": 5357,
"s": 5350,
"text": " Print"
},
{
"code": null,
"e": 5368,
"s": 5357,
"text": " Add Notes"
}
] |
Tryit Editor v3.7
|
CSS 2D Transforms
Tryit: The scale() method
|
[
{
"code": null,
"e": 27,
"s": 9,
"text": "CSS 2D Transforms"
}
] |
How to find the minimum and maximum values in a single MySQL Query?
|
To find the minimum and maximum values in a single query, use MySQL UNION. Let us first create a table −
mysql> create table DemoTable
(
Price int
);
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(98);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(120);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Price |
+-------+
| 88 |
| 100 |
| 98 |
| 120 |
+-------+
4 rows in set (0.00 sec)
Following is the query to find the minimum and maximum values in a single MySQL Query −
mysql> select Price from DemoTable where Price=(select min(Price) from DemoTable)
UNION
select Price from DemoTable where Price=(select max(Price) from DemoTable);
This will produce the following output −
+-------+
| Price |
+-------+
| 88 |
| 120 |
+-------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1167,
"s": 1062,
"text": "To find the minimum and maximum values in a single query, use MySQL UNION. Let us first create a table −"
},
{
"code": null,
"e": 1252,
"s": 1167,
"text": "mysql> create table DemoTable\n(\n Price int\n);\nQuery OK, 0 rows affected (0.57 sec)"
},
{
"code": null,
"e": 1308,
"s": 1252,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1618,
"s": 1308,
"text": "mysql> insert into DemoTable values(88);\nQuery OK, 1 row affected (0.30 sec)\nmysql> insert into DemoTable values(100);\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable values(98);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(120);\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1678,
"s": 1618,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1709,
"s": 1678,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1750,
"s": 1709,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1855,
"s": 1750,
"text": "+-------+\n| Price |\n+-------+\n| 88 |\n| 100 |\n| 98 |\n| 120 |\n+-------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1943,
"s": 1855,
"text": "Following is the query to find the minimum and maximum values in a single MySQL Query −"
},
{
"code": null,
"e": 2113,
"s": 1943,
"text": "mysql> select Price from DemoTable where Price=(select min(Price) from DemoTable)\n UNION\n select Price from DemoTable where Price=(select max(Price) from DemoTable);"
},
{
"code": null,
"e": 2154,
"s": 2113,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2239,
"s": 2154,
"text": "+-------+\n| Price |\n+-------+\n| 88 |\n| 120 |\n+-------+\n2 rows in set (0.00 sec)"
}
] |
Classifying MNIST Digits Using PCA + Deep Learning | by Muriel Kosaka | Towards Data Science
|
One of the many important concepts in Data Science includes Principal Component Analysis (PCA) which is an unsupervised learning method. It is often used to as a dimensionality reduction method for large datasets or simplify their complexity — this is done by transforming a large set of variables into a small one while retaining most of the variation in the dataset. PCA reduces data by geometrically projecting it onto lower dimensions which in turn are called as Principal Components(PC). This method’s goal is to find the best summary of our data by using the least amount of principal components, by choosing our principal components we minimize the distance between the original data and its projected values on the principal components.
Deep Learning is a subset of Machine Learning, inspired by the structure of a human brain. Deep learning algorithms attempt to draw similar conclusions as humans would by continually analyzing data with a given logical structure. To achieve this, deep learning uses a multi-layered structure of algorithms called neural networks. Whether it’s Alexa, Siri or Cortana, deep learning helps them understand speech and the language. Deep Learning uses different types of neural network architectures like object recognition, image and sound classification, and object detection for different types of problems. The more data a Deep Learning algorithm is trained on, the more accurate it is.
The MNIST Dataset (Modified National Institute of Standards and Technology database) is one of the more popular datasets among deep learning enthusiasts. This dataset contains 42,000 labeled grayscale images (28 x 28 pixel) of handwritten digits from 0–9 in their training set and 28,000 unlabeled test images.
In this blog, I will be demonstrating how to use PCA in building a CNN model to recognize handwritten digits from the MNIST Dataset to achieve high accuracy.
Import the libraries and load the dataset: Importing the necessary libraries, packages, and MNIST datasetPreprocess the dataPCA ImplementationCreate CNN modelTrain and Evaluate the Model
Import the libraries and load the dataset: Importing the necessary libraries, packages, and MNIST dataset
Preprocess the data
PCA Implementation
Create CNN model
Train and Evaluate the Model
We first import all the necessary libraries we will need to train our data, and then load our MNIST dataset which can be found here — you can also use keras.datasets to import the mnist dataset!
# Import Libraries%matplotlib inlineimport pandas as pdfrom sklearn.decomposition import PCAimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.preprocessing import StandardScalerfrom keras.utils.np_utils import to_categoricalfrom sklearn.preprocessing import LabelEncoderfrom tensorflow.keras.layers import Input,InputLayer, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2Dfrom tensorflow.keras.layers import AveragePooling2D, MaxPooling2D, Dropoutfrom tensorflow.keras.models import Sequential,Modelfrom tensorflow.keras.optimizers import SGDfrom tensorflow.keras.callbacks import ModelCheckpoint,LearningRateSchedulerimport kerasfrom tensorflow.keras import backend as Kfrom sklearn.preprocessing import StandardScalerfrom scipy.linalg import eigh# Load the Datasettrain = pd.read_csv("data/train.csv")test = pd.read_csv("data/test.csv")train.head()
Sample images from the dataset:
First, we will split the dataset into training and testing sets
y_train = train['label']X_train = train.drop(['label'], axis=1)X_test = testX_train.shape, y_train.shape, X_test.shape#Output((42000, 784), (42000,), (28000, 784))X_train = X_train/255X_test = X_test/255
Note that we do not have y_test because the labels were not given for the test set. Next, we will normalize the data which is important in PCA implementation as it projects your original data onto directions which maximize the variance.
Now, we will implement PCA on our data. First we will standardize our data and calculate our covariance matrix. Covariance can be thought of as the direction of linear relationship between the variables. The covariance matrix is the first step in dimensionality reduction because it gives an idea of the number of features that strongly relate, and it is usually the first step in dimensionality reduction because it gives an idea of the number of strongly related features so that those features can be discarded.
standardized_scalar = StandardScaler()standardized_data = standardized_scalar.fit_transform(X_train)standardized_data.shape# Output(42000, 784)cov_matrix = np.matmul(standardized_data.T, standardized_data)cov_matrix.shape# Output(784,784)
Next, we will calculate eigenvalues and eigenvectors. Eigenvectors and eigenvalues of a covariance matrix (or correlation) describe the source of the PCA. Eigenvectors (main components) determine the direction of the new attribute space, and eigenvalues determine its magnitude.
# Calculate eigenvalues and eigenvectorslambdas, vectors = eigh(cov_matrix, eigvals=(782, 783))vectors.shape# Output(784,2)vectors = vectors.Tvectors.shape# (2, 784)
Then, we will calculate unit vectors and its new coordinates. Unit vectors are vectors with a magnitude of 1, and we are trying to find the unit vector that maximizes the variance.
new_coordinates = np.matmul(vectors, standardized_data.T)print(new_coordinates.shape)new_coordinates = np.vstack((new_coordinates, y_train)).T# Output(2, 42000)df_new = pd.DataFrame(new_coordinates, columns=["f1", "f2", "labels"])df_new.head()
Let’s see a visualization of the cumulative variance retained across the number of components (784):
Before we build our CNN model, we will need to take some preprocessing steps. This includes converting the training set into an array, reshaping the input data to get it in the shape which the model expect to receive later, and encoding the image labels.
X_train = np.array(X_train)y_train = np.array(y_train)X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)print(X_train.shape, y_train.shape)# Output(42000, 28, 28, 1) (42000,)nclasses = y_train.max() - y_train.min() + 1y_train = to_categorical(y_train, num_classes = nclasses)print("Shape of ytrain after encoding: ", y_train.shape)# OutputShape of ytrain after encoding: (42000, 10)
Now we can build our CNN model, I built a 2D CNN model with 3 layers and 1 fully connected layer.
input_shape = (28,28,1)X_input = Input(input_shape)# layer 1x = Conv2D(64,(3,3),strides=(1,1),name='layer_conv1',padding='same')(X_input)x = BatchNormalization()(x)x = Activation('relu')(x)x = MaxPooling2D((2,2),name='maxPool1')(x)# layer 2x = Conv2D(32,(3,3),strides=(1,1),name='layer_conv2',padding='same')(x)x = BatchNormalization()(x)x = Activation('relu')(x)x = MaxPooling2D((2,2),name='maxPool2')(x)# layer 3x = Conv2D(32,(3,3),strides=(1,1),name='conv3',padding='same')(x)x = BatchNormalization()(x)x = Activation('relu')(x)x = MaxPooling2D((2,2), name='maxPool3')(x)# fcx = Flatten()(x)x = Dense(64,activation ='relu',name='fc0')(x)x = Dropout(0.25)(x)x = Dense(32,activation ='relu',name='fc1')(x)x = Dropout(0.25)(x)x = Dense(10,activation ='softmax',name='fc2')(x)conv_model = Model(inputs=X_input, outputs=x, name='Predict')conv_model.summary()
After 40 epochs, we achieved an accuracy of 99.8% !
From this article, we classify handwritten digits using neural networks and preprocessing the data using PCA. For more information about PCA and it’s uses, please see the following helpful articles. Thank you for reading and all code is available on my Github! :)
|
[
{
"code": null,
"e": 916,
"s": 171,
"text": "One of the many important concepts in Data Science includes Principal Component Analysis (PCA) which is an unsupervised learning method. It is often used to as a dimensionality reduction method for large datasets or simplify their complexity — this is done by transforming a large set of variables into a small one while retaining most of the variation in the dataset. PCA reduces data by geometrically projecting it onto lower dimensions which in turn are called as Principal Components(PC). This method’s goal is to find the best summary of our data by using the least amount of principal components, by choosing our principal components we minimize the distance between the original data and its projected values on the principal components."
},
{
"code": null,
"e": 1602,
"s": 916,
"text": "Deep Learning is a subset of Machine Learning, inspired by the structure of a human brain. Deep learning algorithms attempt to draw similar conclusions as humans would by continually analyzing data with a given logical structure. To achieve this, deep learning uses a multi-layered structure of algorithms called neural networks. Whether it’s Alexa, Siri or Cortana, deep learning helps them understand speech and the language. Deep Learning uses different types of neural network architectures like object recognition, image and sound classification, and object detection for different types of problems. The more data a Deep Learning algorithm is trained on, the more accurate it is."
},
{
"code": null,
"e": 1913,
"s": 1602,
"text": "The MNIST Dataset (Modified National Institute of Standards and Technology database) is one of the more popular datasets among deep learning enthusiasts. This dataset contains 42,000 labeled grayscale images (28 x 28 pixel) of handwritten digits from 0–9 in their training set and 28,000 unlabeled test images."
},
{
"code": null,
"e": 2071,
"s": 1913,
"text": "In this blog, I will be demonstrating how to use PCA in building a CNN model to recognize handwritten digits from the MNIST Dataset to achieve high accuracy."
},
{
"code": null,
"e": 2258,
"s": 2071,
"text": "Import the libraries and load the dataset: Importing the necessary libraries, packages, and MNIST datasetPreprocess the dataPCA ImplementationCreate CNN modelTrain and Evaluate the Model"
},
{
"code": null,
"e": 2364,
"s": 2258,
"text": "Import the libraries and load the dataset: Importing the necessary libraries, packages, and MNIST dataset"
},
{
"code": null,
"e": 2384,
"s": 2364,
"text": "Preprocess the data"
},
{
"code": null,
"e": 2403,
"s": 2384,
"text": "PCA Implementation"
},
{
"code": null,
"e": 2420,
"s": 2403,
"text": "Create CNN model"
},
{
"code": null,
"e": 2449,
"s": 2420,
"text": "Train and Evaluate the Model"
},
{
"code": null,
"e": 2644,
"s": 2449,
"text": "We first import all the necessary libraries we will need to train our data, and then load our MNIST dataset which can be found here — you can also use keras.datasets to import the mnist dataset!"
},
{
"code": null,
"e": 3528,
"s": 2644,
"text": "# Import Libraries%matplotlib inlineimport pandas as pdfrom sklearn.decomposition import PCAimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.preprocessing import StandardScalerfrom keras.utils.np_utils import to_categoricalfrom sklearn.preprocessing import LabelEncoderfrom tensorflow.keras.layers import Input,InputLayer, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2Dfrom tensorflow.keras.layers import AveragePooling2D, MaxPooling2D, Dropoutfrom tensorflow.keras.models import Sequential,Modelfrom tensorflow.keras.optimizers import SGDfrom tensorflow.keras.callbacks import ModelCheckpoint,LearningRateSchedulerimport kerasfrom tensorflow.keras import backend as Kfrom sklearn.preprocessing import StandardScalerfrom scipy.linalg import eigh# Load the Datasettrain = pd.read_csv(\"data/train.csv\")test = pd.read_csv(\"data/test.csv\")train.head()"
},
{
"code": null,
"e": 3560,
"s": 3528,
"text": "Sample images from the dataset:"
},
{
"code": null,
"e": 3624,
"s": 3560,
"text": "First, we will split the dataset into training and testing sets"
},
{
"code": null,
"e": 3828,
"s": 3624,
"text": "y_train = train['label']X_train = train.drop(['label'], axis=1)X_test = testX_train.shape, y_train.shape, X_test.shape#Output((42000, 784), (42000,), (28000, 784))X_train = X_train/255X_test = X_test/255"
},
{
"code": null,
"e": 4065,
"s": 3828,
"text": "Note that we do not have y_test because the labels were not given for the test set. Next, we will normalize the data which is important in PCA implementation as it projects your original data onto directions which maximize the variance."
},
{
"code": null,
"e": 4580,
"s": 4065,
"text": "Now, we will implement PCA on our data. First we will standardize our data and calculate our covariance matrix. Covariance can be thought of as the direction of linear relationship between the variables. The covariance matrix is the first step in dimensionality reduction because it gives an idea of the number of features that strongly relate, and it is usually the first step in dimensionality reduction because it gives an idea of the number of strongly related features so that those features can be discarded."
},
{
"code": null,
"e": 4819,
"s": 4580,
"text": "standardized_scalar = StandardScaler()standardized_data = standardized_scalar.fit_transform(X_train)standardized_data.shape# Output(42000, 784)cov_matrix = np.matmul(standardized_data.T, standardized_data)cov_matrix.shape# Output(784,784)"
},
{
"code": null,
"e": 5102,
"s": 4819,
"text": "Next, we will calculate eigenvalues and eigenvectors. Eigenvectors and eigenvalues of a covariance matrix (or correlation) describe the source of the PCA. Eigenvectors (main components) determine the direction of the new attribute space, and eigenvalues determine its magnitude."
},
{
"code": null,
"e": 5268,
"s": 5102,
"text": "# Calculate eigenvalues and eigenvectorslambdas, vectors = eigh(cov_matrix, eigvals=(782, 783))vectors.shape# Output(784,2)vectors = vectors.Tvectors.shape# (2, 784)"
},
{
"code": null,
"e": 5449,
"s": 5268,
"text": "Then, we will calculate unit vectors and its new coordinates. Unit vectors are vectors with a magnitude of 1, and we are trying to find the unit vector that maximizes the variance."
},
{
"code": null,
"e": 5693,
"s": 5449,
"text": "new_coordinates = np.matmul(vectors, standardized_data.T)print(new_coordinates.shape)new_coordinates = np.vstack((new_coordinates, y_train)).T# Output(2, 42000)df_new = pd.DataFrame(new_coordinates, columns=[\"f1\", \"f2\", \"labels\"])df_new.head()"
},
{
"code": null,
"e": 5794,
"s": 5693,
"text": "Let’s see a visualization of the cumulative variance retained across the number of components (784):"
},
{
"code": null,
"e": 6049,
"s": 5794,
"text": "Before we build our CNN model, we will need to take some preprocessing steps. This includes converting the training set into an array, reshaping the input data to get it in the shape which the model expect to receive later, and encoding the image labels."
},
{
"code": null,
"e": 6437,
"s": 6049,
"text": "X_train = np.array(X_train)y_train = np.array(y_train)X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)print(X_train.shape, y_train.shape)# Output(42000, 28, 28, 1) (42000,)nclasses = y_train.max() - y_train.min() + 1y_train = to_categorical(y_train, num_classes = nclasses)print(\"Shape of ytrain after encoding: \", y_train.shape)# OutputShape of ytrain after encoding: (42000, 10)"
},
{
"code": null,
"e": 6535,
"s": 6437,
"text": "Now we can build our CNN model, I built a 2D CNN model with 3 layers and 1 fully connected layer."
},
{
"code": null,
"e": 7392,
"s": 6535,
"text": "input_shape = (28,28,1)X_input = Input(input_shape)# layer 1x = Conv2D(64,(3,3),strides=(1,1),name='layer_conv1',padding='same')(X_input)x = BatchNormalization()(x)x = Activation('relu')(x)x = MaxPooling2D((2,2),name='maxPool1')(x)# layer 2x = Conv2D(32,(3,3),strides=(1,1),name='layer_conv2',padding='same')(x)x = BatchNormalization()(x)x = Activation('relu')(x)x = MaxPooling2D((2,2),name='maxPool2')(x)# layer 3x = Conv2D(32,(3,3),strides=(1,1),name='conv3',padding='same')(x)x = BatchNormalization()(x)x = Activation('relu')(x)x = MaxPooling2D((2,2), name='maxPool3')(x)# fcx = Flatten()(x)x = Dense(64,activation ='relu',name='fc0')(x)x = Dropout(0.25)(x)x = Dense(32,activation ='relu',name='fc1')(x)x = Dropout(0.25)(x)x = Dense(10,activation ='softmax',name='fc2')(x)conv_model = Model(inputs=X_input, outputs=x, name='Predict')conv_model.summary()"
},
{
"code": null,
"e": 7444,
"s": 7392,
"text": "After 40 epochs, we achieved an accuracy of 99.8% !"
}
] |
Objective-C Constants
|
The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their definition.
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of Integer literals −
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').
There are certain characters in C when they are proceeded by a backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence codes −
Following is the example to show few escape sequence characters −
#import <Foundation/Foundation.h>
int main() {
NSLog(@"Hello\tWorld\n\n");
return 0;
}
When the above code is compiled and executed, it produces the following result −
2013-09-07 22:17:17.923 demo[17871] Hello World
String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separating them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
There are two simple ways in C to define constants −
Using #define preprocessor.
Using #define preprocessor.
Using const keyword.
Using const keyword.
Following is the form to use #define preprocessor to define a constant −
#define identifier value
Following example explains it in detail −
#import <Foundation/Foundation.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
area = LENGTH * WIDTH;
NSLog(@"value of area : %d", area);
NSLog(@"%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
2013-09-07 22:18:16.637 demo[21460] value of area : 50
2013-09-07 22:18:16.638 demo[21460]
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
Following example explains it in detail −
#import <Foundation/Foundation.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
NSLog(@"value of area : %d", area);
NSLog(@"%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
2013-09-07 22:19:24.780 demo[25621] value of area : 50
2013-09-07 22:19:24.781 demo[25621]
Note that it is a good programming practice to define constants in CAPITALS.
18 Lectures
1 hours
PARTHA MAJUMDAR
6 Lectures
25 mins
Ken Burke
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2694,
"s": 2560,
"text": "The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals."
},
{
"code": null,
"e": 2878,
"s": 2694,
"text": "Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well."
},
{
"code": null,
"e": 3000,
"s": 2878,
"text": "The constants are treated just like regular variables except that their values cannot be modified after their definition."
},
{
"code": null,
"e": 3171,
"s": 3000,
"text": "An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal."
},
{
"code": null,
"e": 3350,
"s": 3171,
"text": "An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order."
},
{
"code": null,
"e": 3395,
"s": 3350,
"text": "Here are some examples of integer literals −"
},
{
"code": null,
"e": 3568,
"s": 3395,
"text": "212 /* Legal */\n215u /* Legal */\n0xFeeL /* Legal */\n078 /* Illegal: 8 is not an octal digit */\n032UU /* Illegal: cannot repeat a suffix */"
},
{
"code": null,
"e": 3636,
"s": 3568,
"text": "Following are other examples of various types of Integer literals −"
},
{
"code": null,
"e": 3817,
"s": 3636,
"text": "85 /* decimal */\n0213 /* octal */\n0x4b /* hexadecimal */\n30 /* int */\n30u /* unsigned int */\n30l /* long */\n30ul /* unsigned long */"
},
{
"code": null,
"e": 4007,
"s": 3817,
"text": "A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form."
},
{
"code": null,
"e": 4261,
"s": 4007,
"text": "While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E."
},
{
"code": null,
"e": 4313,
"s": 4261,
"text": "Here are some examples of floating-point literals −"
},
{
"code": null,
"e": 4523,
"s": 4313,
"text": "3.14159 /* Legal */\n314159E-5L /* Legal */\n510E /* Illegal: incomplete exponent */\n210f /* Illegal: no decimal or exponent */\n.e55 /* Illegal: missing integer or fraction */"
},
{
"code": null,
"e": 4635,
"s": 4523,
"text": "Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple variable of char type."
},
{
"code": null,
"e": 4769,
"s": 4635,
"text": "A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\\t'), or a universal character (e.g., '\\u02C0')."
},
{
"code": null,
"e": 4997,
"s": 4769,
"text": "There are certain characters in C when they are proceeded by a backslash they will have special meaning and they are used to represent like newline (\\n) or tab (\\t). Here, you have a list of some of such escape sequence codes −"
},
{
"code": null,
"e": 5063,
"s": 4997,
"text": "Following is the example to show few escape sequence characters −"
},
{
"code": null,
"e": 5157,
"s": 5063,
"text": "#import <Foundation/Foundation.h>\n\nint main() {\n NSLog(@\"Hello\\tWorld\\n\\n\");\n return 0;\n}"
},
{
"code": null,
"e": 5238,
"s": 5157,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5287,
"s": 5238,
"text": "2013-09-07 22:17:17.923 demo[17871] Hello\tWorld\n"
},
{
"code": null,
"e": 5588,
"s": 5287,
"text": "String literals or constants are enclosed in double quotes \"\". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separating them using whitespaces."
},
{
"code": null,
"e": 5674,
"s": 5588,
"text": "Here are some examples of string literals. All the three forms are identical strings."
},
{
"code": null,
"e": 5727,
"s": 5674,
"text": "\"hello, dear\"\n\n\"hello, \\\n\ndear\"\n\n\"hello, \" \"d\" \"ear\""
},
{
"code": null,
"e": 5780,
"s": 5727,
"text": "There are two simple ways in C to define constants −"
},
{
"code": null,
"e": 5808,
"s": 5780,
"text": "Using #define preprocessor."
},
{
"code": null,
"e": 5836,
"s": 5808,
"text": "Using #define preprocessor."
},
{
"code": null,
"e": 5857,
"s": 5836,
"text": "Using const keyword."
},
{
"code": null,
"e": 5878,
"s": 5857,
"text": "Using const keyword."
},
{
"code": null,
"e": 5951,
"s": 5878,
"text": "Following is the form to use #define preprocessor to define a constant −"
},
{
"code": null,
"e": 5976,
"s": 5951,
"text": "#define identifier value"
},
{
"code": null,
"e": 6018,
"s": 5976,
"text": "Following example explains it in detail −"
},
{
"code": null,
"e": 6246,
"s": 6018,
"text": "#import <Foundation/Foundation.h>\n\n#define LENGTH 10 \n#define WIDTH 5\n#define NEWLINE '\\n'\n\nint main() {\n int area;\n area = LENGTH * WIDTH;\n NSLog(@\"value of area : %d\", area);\n NSLog(@\"%c\", NEWLINE);\n\n return 0;\n}"
},
{
"code": null,
"e": 6327,
"s": 6246,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6419,
"s": 6327,
"text": "2013-09-07 22:18:16.637 demo[21460] value of area : 50\n2013-09-07 22:18:16.638 demo[21460] "
},
{
"code": null,
"e": 6499,
"s": 6419,
"text": "You can use const prefix to declare constants with a specific type as follows −"
},
{
"code": null,
"e": 6528,
"s": 6499,
"text": "const type variable = value;"
},
{
"code": null,
"e": 6570,
"s": 6528,
"text": "Following example explains it in detail −"
},
{
"code": null,
"e": 6827,
"s": 6570,
"text": "#import <Foundation/Foundation.h>\n\nint main() {\n const int LENGTH = 10;\n const int WIDTH = 5;\n const char NEWLINE = '\\n';\n int area; \n \n area = LENGTH * WIDTH;\n NSLog(@\"value of area : %d\", area);\n NSLog(@\"%c\", NEWLINE);\n\n return 0;\n}"
},
{
"code": null,
"e": 6908,
"s": 6827,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 7001,
"s": 6908,
"text": "2013-09-07 22:19:24.780 demo[25621] value of area : 50\n2013-09-07 22:19:24.781 demo[25621] \n"
},
{
"code": null,
"e": 7078,
"s": 7001,
"text": "Note that it is a good programming practice to define constants in CAPITALS."
},
{
"code": null,
"e": 7111,
"s": 7078,
"text": "\n 18 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7128,
"s": 7111,
"text": " PARTHA MAJUMDAR"
},
{
"code": null,
"e": 7159,
"s": 7128,
"text": "\n 6 Lectures \n 25 mins\n"
},
{
"code": null,
"e": 7170,
"s": 7159,
"text": " Ken Burke"
},
{
"code": null,
"e": 7177,
"s": 7170,
"text": " Print"
},
{
"code": null,
"e": 7188,
"s": 7177,
"text": " Add Notes"
}
] |
Seaborn | Distribution Plots - GeeksforGeeks
|
26 Aug, 2019
Seaborn is a Python data visualization library based on Matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. This article deals with the distribution plots in seaborn which is used for examining univariate and bivariate distributions. In this article we will be discussing 4 types of distribution plots namely:
joinplotdistplotpairplotrugplot
joinplot
distplot
pairplot
rugplot
Besides providing different kinds of visualization plots, seaborn also contains some built-in datasets. We will be using the tips dataset in this article. The “tips” dataset contains information about people who probably had food at a restaurant and whether or not they left a tip, their age, gender and so on. Lets have a look at it.
Code :
# import thr necessary librariesimport seaborn as snsimport matplotlib.pyplot as plt % matplotlib inline # to ignore the warnings from warnings import filterwarnings # load the datasetdf = sns.load_dataset('tips') # the first five entries of the datasetdf.head()
Now, lets proceed onto the plots.
It is used basically for univariant set of observations and visualizes it through a histogram i.e. only one observation and hence we choose one particular column of the dataset.Syntax:
distplot(a[, bins, hist, kde, rug, fit, ...])
Example:
# set the background style of the plotsns.set_style('whitegrid')sns.distplot(df['total_bill'], kde = False, color ='red', bins = 30)
Output:
Explanation:
KDE stands for Kernel Density Estimation and that is another kind of the plot in seaborn.
bins is used to set the number of bins you want in your plot and it actually depends on your dataset.
color is used to specify the color of the plot
Now looking at this we can say that most of the total bill given lies between 10 and 20.
It is used to draw a plot of two variables with bivariate and univariate graphs. It basically combines two different plots.Syntax:
jointplot(x, y[, data, kind, stat_func, ...])
Example:
sns.jointplot(x ='total_bill', y ='tip', data = df)
Output:
sns.jointplot(x ='total_bill', y ='tip', data = df, kind ='kde')# KDE shows the density where the points match up the most
Explanation:
kind is a variable that helps us play around with the fact as to how do you want to visualise the data.It helps to see whats going inside the joinplot. The default is scatter and can be hex, reg(regression) or kde.
x and y are two strings that are the column names and the data that column contains is used by specifying the data parameter.
here we can see tips on the y axis and total bill on the x axis as well as a linear relationship between the two that suggests that the total bill increases with the tips. PairplotIt represents pairwise relation across the entire dataframe and supports an additional argument called hue for categorical separation. What it does basically is create a jointplot between every possible numerical column and takes a while if the dataframe is really huge.Syntax:pairplot(data[, hue, hue_order, palette, ...]) Example:sns.pairplot(df, hue ="sex", palette ='coolwarm')Output:Explanation:hue sets up the categorical separation between the entries if the dataset.palette is used for designing the plots.RugplotIt plots datapoints in an array as sticks on an axis.Just like a distplot it takes a single column. Instead of drawing a histogram it creates dashes all across the plot. If you compare it with the joinplot you can see that what a jointplot does is that it counts the dashes and shows it as bins.Syntax:rugplot(a[, height, axis, ax]) Example:sns.rugplot(df['total_bill'])Output:My Personal Notes
arrow_drop_upSave
It represents pairwise relation across the entire dataframe and supports an additional argument called hue for categorical separation. What it does basically is create a jointplot between every possible numerical column and takes a while if the dataframe is really huge.
Syntax:
pairplot(data[, hue, hue_order, palette, ...])
Example:
sns.pairplot(df, hue ="sex", palette ='coolwarm')
Output:Explanation:
hue sets up the categorical separation between the entries if the dataset.
palette is used for designing the plots.
It plots datapoints in an array as sticks on an axis.Just like a distplot it takes a single column. Instead of drawing a histogram it creates dashes all across the plot. If you compare it with the joinplot you can see that what a jointplot does is that it counts the dashes and shows it as bins.
Syntax:
rugplot(a[, height, axis, ax])
Example:
sns.rugplot(df['total_bill'])
Output:
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Decision Tree
ML | Linear Regression
Python | Decision tree implementation
Decision Tree Introduction with example
ML | Underfitting and Overfitting
Read JSON file using Python
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
|
[
{
"code": null,
"e": 24874,
"s": 24846,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 25240,
"s": 24874,
"text": "Seaborn is a Python data visualization library based on Matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. This article deals with the distribution plots in seaborn which is used for examining univariate and bivariate distributions. In this article we will be discussing 4 types of distribution plots namely:"
},
{
"code": null,
"e": 25272,
"s": 25240,
"text": "joinplotdistplotpairplotrugplot"
},
{
"code": null,
"e": 25281,
"s": 25272,
"text": "joinplot"
},
{
"code": null,
"e": 25290,
"s": 25281,
"text": "distplot"
},
{
"code": null,
"e": 25299,
"s": 25290,
"text": "pairplot"
},
{
"code": null,
"e": 25307,
"s": 25299,
"text": "rugplot"
},
{
"code": null,
"e": 25642,
"s": 25307,
"text": "Besides providing different kinds of visualization plots, seaborn also contains some built-in datasets. We will be using the tips dataset in this article. The “tips” dataset contains information about people who probably had food at a restaurant and whether or not they left a tip, their age, gender and so on. Lets have a look at it."
},
{
"code": null,
"e": 25649,
"s": 25642,
"text": "Code :"
},
{
"code": "# import thr necessary librariesimport seaborn as snsimport matplotlib.pyplot as plt % matplotlib inline # to ignore the warnings from warnings import filterwarnings # load the datasetdf = sns.load_dataset('tips') # the first five entries of the datasetdf.head()",
"e": 25915,
"s": 25649,
"text": null
},
{
"code": null,
"e": 25950,
"s": 25915,
"text": "Now, lets proceed onto the plots. "
},
{
"code": null,
"e": 26135,
"s": 25950,
"text": "It is used basically for univariant set of observations and visualizes it through a histogram i.e. only one observation and hence we choose one particular column of the dataset.Syntax:"
},
{
"code": null,
"e": 26181,
"s": 26135,
"text": "distplot(a[, bins, hist, kde, rug, fit, ...])"
},
{
"code": null,
"e": 26190,
"s": 26181,
"text": "Example:"
},
{
"code": "# set the background style of the plotsns.set_style('whitegrid')sns.distplot(df['total_bill'], kde = False, color ='red', bins = 30)",
"e": 26323,
"s": 26190,
"text": null
},
{
"code": null,
"e": 26331,
"s": 26323,
"text": "Output:"
},
{
"code": null,
"e": 26344,
"s": 26331,
"text": "Explanation:"
},
{
"code": null,
"e": 26434,
"s": 26344,
"text": "KDE stands for Kernel Density Estimation and that is another kind of the plot in seaborn."
},
{
"code": null,
"e": 26536,
"s": 26434,
"text": "bins is used to set the number of bins you want in your plot and it actually depends on your dataset."
},
{
"code": null,
"e": 26583,
"s": 26536,
"text": "color is used to specify the color of the plot"
},
{
"code": null,
"e": 26672,
"s": 26583,
"text": "Now looking at this we can say that most of the total bill given lies between 10 and 20."
},
{
"code": null,
"e": 26803,
"s": 26672,
"text": "It is used to draw a plot of two variables with bivariate and univariate graphs. It basically combines two different plots.Syntax:"
},
{
"code": null,
"e": 26853,
"s": 26803,
"text": "jointplot(x, y[, data, kind, stat_func, ...]) "
},
{
"code": null,
"e": 26862,
"s": 26853,
"text": "Example:"
},
{
"code": "sns.jointplot(x ='total_bill', y ='tip', data = df)",
"e": 26914,
"s": 26862,
"text": null
},
{
"code": null,
"e": 26922,
"s": 26914,
"text": "Output:"
},
{
"code": "sns.jointplot(x ='total_bill', y ='tip', data = df, kind ='kde')# KDE shows the density where the points match up the most",
"e": 27045,
"s": 26922,
"text": null
},
{
"code": null,
"e": 27058,
"s": 27045,
"text": "Explanation:"
},
{
"code": null,
"e": 27273,
"s": 27058,
"text": "kind is a variable that helps us play around with the fact as to how do you want to visualise the data.It helps to see whats going inside the joinplot. The default is scatter and can be hex, reg(regression) or kde."
},
{
"code": null,
"e": 27399,
"s": 27273,
"text": "x and y are two strings that are the column names and the data that column contains is used by specifying the data parameter."
},
{
"code": null,
"e": 28517,
"s": 27399,
"text": "here we can see tips on the y axis and total bill on the x axis as well as a linear relationship between the two that suggests that the total bill increases with the tips. PairplotIt represents pairwise relation across the entire dataframe and supports an additional argument called hue for categorical separation. What it does basically is create a jointplot between every possible numerical column and takes a while if the dataframe is really huge.Syntax:pairplot(data[, hue, hue_order, palette, ...]) Example:sns.pairplot(df, hue =\"sex\", palette ='coolwarm')Output:Explanation:hue sets up the categorical separation between the entries if the dataset.palette is used for designing the plots.RugplotIt plots datapoints in an array as sticks on an axis.Just like a distplot it takes a single column. Instead of drawing a histogram it creates dashes all across the plot. If you compare it with the joinplot you can see that what a jointplot does is that it counts the dashes and shows it as bins.Syntax:rugplot(a[, height, axis, ax]) Example:sns.rugplot(df['total_bill'])Output:My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28788,
"s": 28517,
"text": "It represents pairwise relation across the entire dataframe and supports an additional argument called hue for categorical separation. What it does basically is create a jointplot between every possible numerical column and takes a while if the dataframe is really huge."
},
{
"code": null,
"e": 28796,
"s": 28788,
"text": "Syntax:"
},
{
"code": null,
"e": 28847,
"s": 28796,
"text": "pairplot(data[, hue, hue_order, palette, ...]) "
},
{
"code": null,
"e": 28856,
"s": 28847,
"text": "Example:"
},
{
"code": "sns.pairplot(df, hue =\"sex\", palette ='coolwarm')",
"e": 28906,
"s": 28856,
"text": null
},
{
"code": null,
"e": 28926,
"s": 28906,
"text": "Output:Explanation:"
},
{
"code": null,
"e": 29001,
"s": 28926,
"text": "hue sets up the categorical separation between the entries if the dataset."
},
{
"code": null,
"e": 29042,
"s": 29001,
"text": "palette is used for designing the plots."
},
{
"code": null,
"e": 29338,
"s": 29042,
"text": "It plots datapoints in an array as sticks on an axis.Just like a distplot it takes a single column. Instead of drawing a histogram it creates dashes all across the plot. If you compare it with the joinplot you can see that what a jointplot does is that it counts the dashes and shows it as bins."
},
{
"code": null,
"e": 29346,
"s": 29338,
"text": "Syntax:"
},
{
"code": null,
"e": 29379,
"s": 29346,
"text": "rugplot(a[, height, axis, ax]) "
},
{
"code": null,
"e": 29388,
"s": 29379,
"text": "Example:"
},
{
"code": "sns.rugplot(df['total_bill'])",
"e": 29418,
"s": 29388,
"text": null
},
{
"code": null,
"e": 29426,
"s": 29418,
"text": "Output:"
},
{
"code": null,
"e": 29443,
"s": 29426,
"text": "Machine Learning"
},
{
"code": null,
"e": 29450,
"s": 29443,
"text": "Python"
},
{
"code": null,
"e": 29467,
"s": 29450,
"text": "Machine Learning"
},
{
"code": null,
"e": 29565,
"s": 29467,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29574,
"s": 29565,
"text": "Comments"
},
{
"code": null,
"e": 29587,
"s": 29574,
"text": "Old Comments"
},
{
"code": null,
"e": 29601,
"s": 29587,
"text": "Decision Tree"
},
{
"code": null,
"e": 29624,
"s": 29601,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 29662,
"s": 29624,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 29702,
"s": 29662,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 29736,
"s": 29702,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 29764,
"s": 29736,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29786,
"s": 29764,
"text": "Python map() function"
},
{
"code": null,
"e": 29830,
"s": 29786,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 29848,
"s": 29830,
"text": "Python Dictionary"
}
] |
How to check if two strings are equal in Java?
|
You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
import java.lang.*
public class StringDemo {
public static void main(String[] args) {
String str1 = "Tutorialspoint";
String str2 = "Tutorialspoint";
String str3 = "Hi";
// checking for equality
boolean retval1 = str2.equals(str1);
boolean retval2 = str2.equals(str3);
// prints the return value
System.out.println("str2 is equal to str1 = " + retval1);
System.out.println("str2 is equal to str3 = " + retval2);
}
}
str2 is equal to str1 = true
str2 is equal to str3 = false
|
[
{
"code": null,
"e": 1343,
"s": 1062,
"text": "You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object."
},
{
"code": null,
"e": 1831,
"s": 1343,
"text": "import java.lang.*\npublic class StringDemo {\n public static void main(String[] args) {\n String str1 = \"Tutorialspoint\";\n String str2 = \"Tutorialspoint\";\n String str3 = \"Hi\";\n \n // checking for equality\n boolean retval1 = str2.equals(str1);\n boolean retval2 = str2.equals(str3);\n \n // prints the return value\n System.out.println(\"str2 is equal to str1 = \" + retval1);\n System.out.println(\"str2 is equal to str3 = \" + retval2);\n }\n}"
},
{
"code": null,
"e": 1890,
"s": 1831,
"text": "str2 is equal to str1 = true\nstr2 is equal to str3 = false"
}
] |
Data Preprocessing in Python. for Machine Learning with working code... | by Tarun Gupta | Towards Data Science
|
In one of my previous posts, I talked about Data Preprocessing in Data Mining & Machine Learning conceptually. This will continue on that, if you haven’t read it, read it here in order to have a proper grasp of the topics and concepts I am going to talk about in the article.
Data Preprocessing refers to the steps applied to make data more suitable for data mining. The steps used for Data Preprocessing usually fall into two categories:
selecting data objects and attributes for the analysis.creating/changing the attributes.
selecting data objects and attributes for the analysis.
creating/changing the attributes.
In this post I am going to walk through the implementation of Data Preprocessing methods using Python. I will cover the following, one at a time:
Importing the librariesImporting the DatasetHandling of Missing DataHandling of Categorical DataSplitting the dataset into training and testing datasetsFeature Scaling
Importing the libraries
Importing the Dataset
Handling of Missing Data
Handling of Categorical Data
Splitting the dataset into training and testing datasets
Feature Scaling
For this Data Preprocessing script, I am going to use Anaconda Navigator and specifically Spyder to write the following code. If Spyder is not already installed when you open up Anaconda Navigator for the first time, then you can easily install it using the user interface.
If you have not code in Python beforehand, I would recommend you to learn some basics of Python and then start here. But, if you have any idea of how to read Python code, then you are good to go. Getting on with our script, we will start with the first step.
Importing the libraries
# librariesimport numpy as np # used for handling numbersimport pandas as pd # used for handling the datasetfrom sklearn.impute import SimpleImputer # used for handling missing datafrom sklearn.preprocessing import LabelEncoder, OneHotEncoder # used for encoding categorical datafrom sklearn.model_selection import train_test_split # used for splitting training and testing datafrom sklearn.preprocessing import StandardScaler # used for feature scaling
If you select and run the above code in Spyder, you should see a similar output in your IPython console.
If you see any import errors, try to install those packages explicitly using pip command as follows.
pip install <package-name>
Importing the Dataset
First of all, let us have a look at the dataset we are going to use for this particular example. You can find the dataset here.
In order to import this dataset into our script, we are apparently going to use pandas as follows.
dataset = pd.read_csv('Data.csv') # to import the dataset into a variable# Splitting the attributes into independent and dependent attributesX = dataset.iloc[:, :-1].values # attributes to determine dependent variable / ClassY = dataset.iloc[:, -1].values # dependent variable / Class
When you run this code section, you should not see any errors, if you do make sure the script and the Data.csv are in the same folder. When successfully executed, you can move to variable explorer in the Spyder UI and you will see the following three variables.
When you double click on each of these variables, you should see something similar.
If you face any errors in order to see these data variables, try to upgrade Spyder to Spyder version 4.
Handling of Missing Data
I talk in detail about handling of missing data in the following post.
towardsdatascience.com
Well the first idea is to remove the lines in the observations where there is some missing data. But that can be quite dangerous because imagine this data set contains crucial information. It would be quite dangerous to remove an observation. So we need to figure out a better idea to handle this problem. And another idea that’s actually the most common idea to handle missing data is to take the mean of the columns.
If you noticed in our dataset, we have two values missing, one for age column in 7th data row and for Income column in 5th data row. Missing values should be handled during the data analysis. So, we do that as follows.
# handling the missing data and replace missing values with nan from numpy and replace with mean of all the other valuesimputer = SimpleImputer(missing_values=np.nan, strategy='mean') imputer = imputer.fit(X[:, 1:])X[:, 1:] = imputer.transform(X[:, 1:])
After execution of this code, the independent variable X will transform into the following.
Here you can see, that the missing values have been replaced by the average values of the respective columns.
Handling of Categorical Data
In this dataset we can see that we have two categorical variables. We have the Region variable and the Online Shopper variable. These two variables are categorical variables because simply they contain categories. The Region contains three categories. It’s India, USA & Brazil and the online shopper variable contains two categories. Yes and No that’s why they’re called categorical variables.
You can guess that since machine learning models are based on mathematical equations you can intuitively understand that it would cause some problem if we keep the text here in the categorical variables in the equations because we would only want numbers in the equations. So that’s why we need to encode the categorical variables. That is to encode the text that we have here into numbers. To do this we use the following code snippet.
# encode categorical datafrom sklearn.preprocessing import LabelEncoder, OneHotEncoderlabelencoder_X = LabelEncoder()X[:, 0] = labelencoder_X.fit_transform(X[:, 0])onehotencoder = OneHotEncoder(categorical_features=[0])X = onehotencoder.fit_transform(X).toarray()labelencoder_Y = LabelEncoder()Y = labelencoder_Y.fit_transform(Y)
After execution of this code, the independent variable X and dependent variable Y will transform into the following.
Here, you can see that the Region variable is now made up of a 3 bit binary variable. The left most bit represents India, 2nd bit represents Brazil and the last bit represents USA. If the bit is 1 then it represents data for that country otherwise not. For Online Shopper variable, 1 represents Yes and 0 represents No.
Splitting the dataset into training and testing datasets
Any machine learning algorithm needs to be tested for accuracy. In order to do that, we divide our data set into two parts: training set and testing set. As the name itself suggests, we use the training set to make the algorithm learn the behaviours present in the data and check the correctness of the algorithm by testing on testing set. In Python, we do that as follows:
# splitting the dataset into training set and test setX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)
Here, we are taking training set to be 80% of the original data set and testing set to be 20% of the original data set. This is usually the ratio in which they are split. But, you can come across sometimes to a 70–30% or 75–25% ratio split. But, you don’t want to split it 50–50%. This can lead to Model Overfitting. This topic is too huge to be covered in the same post. I will cover it in some future post. For now, we are going to split it in 80–20% ratio.
After split, our training set and testing set look like this.
Feature Scaling
I talk about Variable Transformation(Feature Scaling) in detail in the following post.
towardsdatascience.com
As you can see we have these two columns age and income that contains numerical numbers. You notice that the variables are not on the same scale because the age are going from 32 to 55 and the salaries going from 57.6 K to like 99.6 K.
So because this age variable in the salary variable don’t have the same scale. This will cause some issues in your machinery models. And why is that. It’s because your machine models a lot of machinery models are based on what is called the Euclidean distance.
We use feature scaling to convert different scales to a standard scale to make it easier for Machine Learning algorithms. We do this in Python as follows:
# feature scalingsc_X = StandardScaler()X_train = sc_X.fit_transform(X_train)X_test = sc_X.transform(X_test)
After the execution of this code, our training independent variable X and our testing independent variable X and look like this.
This data is now ready to be fed to a Machine Learning Algorithm.
This concludes this post on Data Preprocessing in Python.
P.S.: First, you should get my posts in your inbox. Do that here!
Secondly, if you like to experience Medium yourself, consider supporting me and thousands of other writers by signing up for a membership. It only costs $5 per month, it supports us, writers, greatly, and you have the chance to make money with your writing as well. Since I started, I have made more than $50 every month. By signing up with this link, you’ll support me directly with a portion of your fee, it won’t cost you more. If you do so, thank you a million times!
Thanks for reading. If you like this, you can find my other Data Science articles in the story below:
|
[
{
"code": null,
"e": 448,
"s": 172,
"text": "In one of my previous posts, I talked about Data Preprocessing in Data Mining & Machine Learning conceptually. This will continue on that, if you haven’t read it, read it here in order to have a proper grasp of the topics and concepts I am going to talk about in the article."
},
{
"code": null,
"e": 611,
"s": 448,
"text": "Data Preprocessing refers to the steps applied to make data more suitable for data mining. The steps used for Data Preprocessing usually fall into two categories:"
},
{
"code": null,
"e": 700,
"s": 611,
"text": "selecting data objects and attributes for the analysis.creating/changing the attributes."
},
{
"code": null,
"e": 756,
"s": 700,
"text": "selecting data objects and attributes for the analysis."
},
{
"code": null,
"e": 790,
"s": 756,
"text": "creating/changing the attributes."
},
{
"code": null,
"e": 936,
"s": 790,
"text": "In this post I am going to walk through the implementation of Data Preprocessing methods using Python. I will cover the following, one at a time:"
},
{
"code": null,
"e": 1104,
"s": 936,
"text": "Importing the librariesImporting the DatasetHandling of Missing DataHandling of Categorical DataSplitting the dataset into training and testing datasetsFeature Scaling"
},
{
"code": null,
"e": 1128,
"s": 1104,
"text": "Importing the libraries"
},
{
"code": null,
"e": 1150,
"s": 1128,
"text": "Importing the Dataset"
},
{
"code": null,
"e": 1175,
"s": 1150,
"text": "Handling of Missing Data"
},
{
"code": null,
"e": 1204,
"s": 1175,
"text": "Handling of Categorical Data"
},
{
"code": null,
"e": 1261,
"s": 1204,
"text": "Splitting the dataset into training and testing datasets"
},
{
"code": null,
"e": 1277,
"s": 1261,
"text": "Feature Scaling"
},
{
"code": null,
"e": 1551,
"s": 1277,
"text": "For this Data Preprocessing script, I am going to use Anaconda Navigator and specifically Spyder to write the following code. If Spyder is not already installed when you open up Anaconda Navigator for the first time, then you can easily install it using the user interface."
},
{
"code": null,
"e": 1810,
"s": 1551,
"text": "If you have not code in Python beforehand, I would recommend you to learn some basics of Python and then start here. But, if you have any idea of how to read Python code, then you are good to go. Getting on with our script, we will start with the first step."
},
{
"code": null,
"e": 1834,
"s": 1810,
"text": "Importing the libraries"
},
{
"code": null,
"e": 2288,
"s": 1834,
"text": "# librariesimport numpy as np # used for handling numbersimport pandas as pd # used for handling the datasetfrom sklearn.impute import SimpleImputer # used for handling missing datafrom sklearn.preprocessing import LabelEncoder, OneHotEncoder # used for encoding categorical datafrom sklearn.model_selection import train_test_split # used for splitting training and testing datafrom sklearn.preprocessing import StandardScaler # used for feature scaling"
},
{
"code": null,
"e": 2393,
"s": 2288,
"text": "If you select and run the above code in Spyder, you should see a similar output in your IPython console."
},
{
"code": null,
"e": 2494,
"s": 2393,
"text": "If you see any import errors, try to install those packages explicitly using pip command as follows."
},
{
"code": null,
"e": 2521,
"s": 2494,
"text": "pip install <package-name>"
},
{
"code": null,
"e": 2543,
"s": 2521,
"text": "Importing the Dataset"
},
{
"code": null,
"e": 2671,
"s": 2543,
"text": "First of all, let us have a look at the dataset we are going to use for this particular example. You can find the dataset here."
},
{
"code": null,
"e": 2770,
"s": 2671,
"text": "In order to import this dataset into our script, we are apparently going to use pandas as follows."
},
{
"code": null,
"e": 3055,
"s": 2770,
"text": "dataset = pd.read_csv('Data.csv') # to import the dataset into a variable# Splitting the attributes into independent and dependent attributesX = dataset.iloc[:, :-1].values # attributes to determine dependent variable / ClassY = dataset.iloc[:, -1].values # dependent variable / Class"
},
{
"code": null,
"e": 3317,
"s": 3055,
"text": "When you run this code section, you should not see any errors, if you do make sure the script and the Data.csv are in the same folder. When successfully executed, you can move to variable explorer in the Spyder UI and you will see the following three variables."
},
{
"code": null,
"e": 3401,
"s": 3317,
"text": "When you double click on each of these variables, you should see something similar."
},
{
"code": null,
"e": 3505,
"s": 3401,
"text": "If you face any errors in order to see these data variables, try to upgrade Spyder to Spyder version 4."
},
{
"code": null,
"e": 3530,
"s": 3505,
"text": "Handling of Missing Data"
},
{
"code": null,
"e": 3601,
"s": 3530,
"text": "I talk in detail about handling of missing data in the following post."
},
{
"code": null,
"e": 3624,
"s": 3601,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4043,
"s": 3624,
"text": "Well the first idea is to remove the lines in the observations where there is some missing data. But that can be quite dangerous because imagine this data set contains crucial information. It would be quite dangerous to remove an observation. So we need to figure out a better idea to handle this problem. And another idea that’s actually the most common idea to handle missing data is to take the mean of the columns."
},
{
"code": null,
"e": 4262,
"s": 4043,
"text": "If you noticed in our dataset, we have two values missing, one for age column in 7th data row and for Income column in 5th data row. Missing values should be handled during the data analysis. So, we do that as follows."
},
{
"code": null,
"e": 4516,
"s": 4262,
"text": "# handling the missing data and replace missing values with nan from numpy and replace with mean of all the other valuesimputer = SimpleImputer(missing_values=np.nan, strategy='mean') imputer = imputer.fit(X[:, 1:])X[:, 1:] = imputer.transform(X[:, 1:])"
},
{
"code": null,
"e": 4608,
"s": 4516,
"text": "After execution of this code, the independent variable X will transform into the following."
},
{
"code": null,
"e": 4718,
"s": 4608,
"text": "Here you can see, that the missing values have been replaced by the average values of the respective columns."
},
{
"code": null,
"e": 4747,
"s": 4718,
"text": "Handling of Categorical Data"
},
{
"code": null,
"e": 5141,
"s": 4747,
"text": "In this dataset we can see that we have two categorical variables. We have the Region variable and the Online Shopper variable. These two variables are categorical variables because simply they contain categories. The Region contains three categories. It’s India, USA & Brazil and the online shopper variable contains two categories. Yes and No that’s why they’re called categorical variables."
},
{
"code": null,
"e": 5578,
"s": 5141,
"text": "You can guess that since machine learning models are based on mathematical equations you can intuitively understand that it would cause some problem if we keep the text here in the categorical variables in the equations because we would only want numbers in the equations. So that’s why we need to encode the categorical variables. That is to encode the text that we have here into numbers. To do this we use the following code snippet."
},
{
"code": null,
"e": 5908,
"s": 5578,
"text": "# encode categorical datafrom sklearn.preprocessing import LabelEncoder, OneHotEncoderlabelencoder_X = LabelEncoder()X[:, 0] = labelencoder_X.fit_transform(X[:, 0])onehotencoder = OneHotEncoder(categorical_features=[0])X = onehotencoder.fit_transform(X).toarray()labelencoder_Y = LabelEncoder()Y = labelencoder_Y.fit_transform(Y)"
},
{
"code": null,
"e": 6025,
"s": 5908,
"text": "After execution of this code, the independent variable X and dependent variable Y will transform into the following."
},
{
"code": null,
"e": 6345,
"s": 6025,
"text": "Here, you can see that the Region variable is now made up of a 3 bit binary variable. The left most bit represents India, 2nd bit represents Brazil and the last bit represents USA. If the bit is 1 then it represents data for that country otherwise not. For Online Shopper variable, 1 represents Yes and 0 represents No."
},
{
"code": null,
"e": 6402,
"s": 6345,
"text": "Splitting the dataset into training and testing datasets"
},
{
"code": null,
"e": 6776,
"s": 6402,
"text": "Any machine learning algorithm needs to be tested for accuracy. In order to do that, we divide our data set into two parts: training set and testing set. As the name itself suggests, we use the training set to make the algorithm learn the behaviours present in the data and check the correctness of the algorithm by testing on testing set. In Python, we do that as follows:"
},
{
"code": null,
"e": 6919,
"s": 6776,
"text": "# splitting the dataset into training set and test setX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)"
},
{
"code": null,
"e": 7379,
"s": 6919,
"text": "Here, we are taking training set to be 80% of the original data set and testing set to be 20% of the original data set. This is usually the ratio in which they are split. But, you can come across sometimes to a 70–30% or 75–25% ratio split. But, you don’t want to split it 50–50%. This can lead to Model Overfitting. This topic is too huge to be covered in the same post. I will cover it in some future post. For now, we are going to split it in 80–20% ratio."
},
{
"code": null,
"e": 7441,
"s": 7379,
"text": "After split, our training set and testing set look like this."
},
{
"code": null,
"e": 7457,
"s": 7441,
"text": "Feature Scaling"
},
{
"code": null,
"e": 7544,
"s": 7457,
"text": "I talk about Variable Transformation(Feature Scaling) in detail in the following post."
},
{
"code": null,
"e": 7567,
"s": 7544,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7803,
"s": 7567,
"text": "As you can see we have these two columns age and income that contains numerical numbers. You notice that the variables are not on the same scale because the age are going from 32 to 55 and the salaries going from 57.6 K to like 99.6 K."
},
{
"code": null,
"e": 8064,
"s": 7803,
"text": "So because this age variable in the salary variable don’t have the same scale. This will cause some issues in your machinery models. And why is that. It’s because your machine models a lot of machinery models are based on what is called the Euclidean distance."
},
{
"code": null,
"e": 8219,
"s": 8064,
"text": "We use feature scaling to convert different scales to a standard scale to make it easier for Machine Learning algorithms. We do this in Python as follows:"
},
{
"code": null,
"e": 8328,
"s": 8219,
"text": "# feature scalingsc_X = StandardScaler()X_train = sc_X.fit_transform(X_train)X_test = sc_X.transform(X_test)"
},
{
"code": null,
"e": 8457,
"s": 8328,
"text": "After the execution of this code, our training independent variable X and our testing independent variable X and look like this."
},
{
"code": null,
"e": 8523,
"s": 8457,
"text": "This data is now ready to be fed to a Machine Learning Algorithm."
},
{
"code": null,
"e": 8581,
"s": 8523,
"text": "This concludes this post on Data Preprocessing in Python."
},
{
"code": null,
"e": 8647,
"s": 8581,
"text": "P.S.: First, you should get my posts in your inbox. Do that here!"
},
{
"code": null,
"e": 9119,
"s": 8647,
"text": "Secondly, if you like to experience Medium yourself, consider supporting me and thousands of other writers by signing up for a membership. It only costs $5 per month, it supports us, writers, greatly, and you have the chance to make money with your writing as well. Since I started, I have made more than $50 every month. By signing up with this link, you’ll support me directly with a portion of your fee, it won’t cost you more. If you do so, thank you a million times!"
}
] |
A Custom SpaCy Model Deployment with AWS ECR, SageMaker, and Lambda | by Cheng | Towards Data Science
|
SpaCy is one of my favourite NLP libraries. And I have been using spaCy to perform a lot of Named Entity Recognition (NER) tasks. Generally, we first need to load a spaCy pre-trained model of a specific language and fine-tune the model with our training dataset. The training process can be done offline with a local computer and we can even test the fine-tuned model performance by hosting it locally through Flask / Streamlit.
towardsdatascience.com
Although I have found many great tutorials on deploying a spaCy model locally with Flask / Streamlit, there are not many tutorials on how to deploy it on a larger scale, for example, how to deploy a spaCy model with AWS.
It’s a very interesting topic and after a great amount of work I summarized my solution into this article; hopefully it can be useful for people facing the same question.
In this article, I will explain my solution on how to deploy a custom spaCy model with AWS services including:
AWS ECR (Elastic Container Registry)
AWS SageMaker
AWS Lambda
AWS S3 Bucket (Optional)
Here is my plan 🧗🏻:
First, data input can be sent as an event into the AWS Lambda.
Then, within the Lambda, we invoke a SageMaker endpoint. The endpoint takes the data input coming from the Lambda event and returns a response containing the results from the spaCy model.
Finally, this endpoint response will display as an execution result. Hence we are able to check the response on the AWS Lambda result tab or debug on the AWS CloudWatch.
Through this process, the spaCy model is hosted on AWS SageMaker and can be invoked as an endpoint at any time. To create the SageMaker endpoint, we need to create our custom spaCy model container on the AWS ECR first and prepare our model artifact ready in the format of tar.gz.
To create the model artifact, we could do it either offline or online. Every time we finish training a spaCy model, the trained model is actually saved into a folder. The folder usually contains the following files:
*file names might be different
meta.json
ner (folder)
tokenizer
vocab (folder)
In terms of creating the model artifact, we could simply compress this folder into a tar.gz format and upload it to a S3 bucket. Alternatively, we could also train the model online with the AWS SageMaker by creating a training job under the SageMaker Training section. But we need to provide our custom training image from AWS ECR and training data from AWS S3 bucket.
Hopefully, you are now a bit clearer about the whole workflow. Now, let’s begin from creating our custom spaCy model container and uploading it onto the AWS ECR as our training image.
Because spaCy is not one of the SageMaker built-in algorithms. We have to create a spaCy model container first on the AWS ECR, and specify the container as the training image while creating a model endpoint on the SageMaker.
SageMaker provides 2 options wherein the first option is to use built-in algorithms that SageMaker offers that includes KNN, XgBoost, Linear Learner, etc. while the other option is to use your custom docker container from ECR.
towardsdatascience.com
The above article is an amazing reference that inspired me on how to deploy a custom spaCy container. I strongly encourage to read through this article and have a deeper understanding on how this docker container works internally. It was quite complicated to understand at first for me. 🧠
In brief, it will include the following steps:
Edit the files under the Github repo (mainly the docker file, train.py and predictor.py) in order to train a custom spaCy model and return predictions based on the data input.
Check the results by performing a local test for the spaCy docker container and debug the code if any error happens.
Finally, upload the spaCy container to the AWS ECR.
A bit more explanation about the train.py and predictor.py, because these are the two files that determine how we want to train the model and what we expect the input & output of the model to be like.
In the train file, the objective is to modify the code to train a custom spaCy model. After reading the data from CSV files into a dataframe called train_data, we need to convert the dataframe into a format that spaCy model can take as input. I would recommend to read a previous article I wrote about how to train a spaCy model for an NER task.
towardsdatascience.com
Essentially, we need to convert a dataframe into the following spaCy format:
TRAIN_DATA = [('Amazon co ca', {'entities': [(0, 6, 'BRD')]}),('AMZNMKTPLACE AMAZON CO', {'entities': [(13, 19, 'BRD')]}),('APPLE COM BILL', {'entities': [(0, 5, 'BRD')]}),('BOOKING COM New York City', {'entities': [(0, 7, 'BRD')]}),('STARBUCKS Vancouver', {'entities': [(0, 9, 'BRD')]}),('Uber BV', {'entities': [(0, 4, 'BRD')]}),('Hotel on Booking com Toronto', {'entities': [(9, 16, 'BRD')]}),('UBER com', {'entities': [(0, 4, 'BRD')]}),('Netflix com', {'entities': [(0, 7, 'BRD')]})]]
Then, in the train file, we define our train_spacy function to train the model. The train_spaCy function is similar to the one in the following article. Just be aware that the code within the article is written in spaCy version 2.
manivannan-ai.medium.com
In the predictor file, we need to edit the code under the predict function. The predict function only takes test_data as input. The test_data is in format of a dataframe already so we could apply the trained spaCy model onto the column which contains the source text input. Then we could create a new column for the model’s predictions. If it’s an NER task, then the new column would contain the extracted entities from each input. Also, we could adjust whether the predict function returns just a list of predictions or a whole dataframe that contains both the source and the prediction columns.
At the end of the predictor file, it requires a bit knowledge of Flask app to understand. Although it’s recommended to know how it works, in fact, we don’t need to modify many parts in the original Flask app. Just be sure that the output data format from the predict function is in consistent with the format used in the Flask app. The original function returns prediction in format of a list. For me, I changed it to return a dataframe so I modified the code in the Flask app to keep the consistency.
Finally, in the docker file, simply edit the code accordingly based on the libraries needed. For me, I added RUN pip3 install -U spacy==2.3.5 to install the correct version of spaCy I used.
Congratulations if you got here! 🥳
To push our container image to Amazon ECR, we could follow the code inside (from the above article’s Github)
build_and_push.sh file
Bring_Your_Own-Creating_Algorithm_and_Model_Package notebook
These files are well explained in that article. We could simply run through the code to push our own custom spaCy container onto the AWS ECR.
Until this step, we have finally uploaded our custom spaCy container to the AWS ECR. This is a critical step for the model deployment. Now, we will switch to AWS SageMaker and create a model endpoint.
As described in the AWS SageMaker developer guide:
Amazon SageMaker is a fully-managed service that enables data scientists and developers to quickly and easily build, train, and deploy machine learning models at any scale. Amazon SageMaker includes modules that can be used together or independently to build, train, and deploy your machine learning models.
Essentially, it has an interface structured as below:
Sections on the AWS SageMaker...--->Training------>Algorithms------>Training jobs ------>Hyperparameter tuning jobs--->Inference------>Compilation jobs------>Model packages------>Models------>Endpoint configurations------>Endpoints------>Batch transform jobs...
To create a spaCy model endpoint, we need to go through the following steps:
Create a training job under AWS SageMaker — Training. Or instead, simply train your spaCy model locally, compress it into tar.gz format and upload it to a S3 bucket. The goal is to prepare a model artifact at this step.
Create a model under AWS SageMaker — Inference. We need to specify the container image from AWS ECR and the model artifact from a AWS S3 bucket.
Create an endpoint configuration under AWS SageMaker — Inference. We need to specify a model for the endpoint configuration.
Create an endpoint under AWS SageMaker — Inference. We need to specify an endpoint configuration for the endpoint.
If you have any trouble during the above steps on AWS SageMaker, the following tutorial will be helpful! 🏂🏻
aws.amazon.com
As described in the AWS Lambda developer guide:
Lambda is a compute service that lets you run code without provisioning or managing servers. Lambda runs your code on a high-availability compute infrastructure and performs all of the administration of the compute resources, including server and operating system maintenance, capacity provisioning and automatic scaling, code monitoring and logging.
In terms of the spaCy deployment, we will use the AWS Lambda as an interface that can communicate between the user input and the spaCy model endpoint. Specifically, we want to input the inference text as a Lambda event and receive the model response on the Lambda execution tab.
Some details about how to invoke a SageMaker endpoint on the AWS Lambda can be found at the tutorial same as the one above. Essentially, we want to write a python handler function on the Lambda that can do the following steps:
Input event: a list of inference texts
Read the event into a dataframe (optional)
Write the dataframe into a CSV buffer (keep data format consistency with the Flask app)
Convert the values of the buffer into ASCII format (keep consistency with the AWS requirement otherwise may cause some errors)
Invoke the SageMaker endpoint and receive the response
Decode the response into UTF-8 format
Read the response into a dataframe (optional)
Output response: a list of model predictions
Some details about creating a CSV buffer or ASCII / UTF-8 conversion steps may not be necessary but eventually it works for me. If you have any better ideas, let me know! 😸
If everything works, now finally, we should be able to see that on the AWS Lambda execution results tab, the list of model predictions is printed out. 💯 And the model input is based on the AWS Lambda configure test event.
Finally, my article on deploying a custom spaCy model with the AWS will conclude here. As a summary, the workflow includes services:
1st step: AWS ECR
2nd step: AWS S3 Bucket (Optional)
3rd step: AWS SageMaker
4th step: AWS Lambda
Although this design may not be the best, it’s still the most stable one I could think of after a large amount of research. Hope it can help / inspire anyone who is working on the similar tasks 😋
Thank you for reading!
|
[
{
"code": null,
"e": 600,
"s": 171,
"text": "SpaCy is one of my favourite NLP libraries. And I have been using spaCy to perform a lot of Named Entity Recognition (NER) tasks. Generally, we first need to load a spaCy pre-trained model of a specific language and fine-tune the model with our training dataset. The training process can be done offline with a local computer and we can even test the fine-tuned model performance by hosting it locally through Flask / Streamlit."
},
{
"code": null,
"e": 623,
"s": 600,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 844,
"s": 623,
"text": "Although I have found many great tutorials on deploying a spaCy model locally with Flask / Streamlit, there are not many tutorials on how to deploy it on a larger scale, for example, how to deploy a spaCy model with AWS."
},
{
"code": null,
"e": 1015,
"s": 844,
"text": "It’s a very interesting topic and after a great amount of work I summarized my solution into this article; hopefully it can be useful for people facing the same question."
},
{
"code": null,
"e": 1126,
"s": 1015,
"text": "In this article, I will explain my solution on how to deploy a custom spaCy model with AWS services including:"
},
{
"code": null,
"e": 1163,
"s": 1126,
"text": "AWS ECR (Elastic Container Registry)"
},
{
"code": null,
"e": 1177,
"s": 1163,
"text": "AWS SageMaker"
},
{
"code": null,
"e": 1188,
"s": 1177,
"text": "AWS Lambda"
},
{
"code": null,
"e": 1213,
"s": 1188,
"text": "AWS S3 Bucket (Optional)"
},
{
"code": null,
"e": 1233,
"s": 1213,
"text": "Here is my plan 🧗🏻:"
},
{
"code": null,
"e": 1296,
"s": 1233,
"text": "First, data input can be sent as an event into the AWS Lambda."
},
{
"code": null,
"e": 1484,
"s": 1296,
"text": "Then, within the Lambda, we invoke a SageMaker endpoint. The endpoint takes the data input coming from the Lambda event and returns a response containing the results from the spaCy model."
},
{
"code": null,
"e": 1654,
"s": 1484,
"text": "Finally, this endpoint response will display as an execution result. Hence we are able to check the response on the AWS Lambda result tab or debug on the AWS CloudWatch."
},
{
"code": null,
"e": 1934,
"s": 1654,
"text": "Through this process, the spaCy model is hosted on AWS SageMaker and can be invoked as an endpoint at any time. To create the SageMaker endpoint, we need to create our custom spaCy model container on the AWS ECR first and prepare our model artifact ready in the format of tar.gz."
},
{
"code": null,
"e": 2150,
"s": 1934,
"text": "To create the model artifact, we could do it either offline or online. Every time we finish training a spaCy model, the trained model is actually saved into a folder. The folder usually contains the following files:"
},
{
"code": null,
"e": 2181,
"s": 2150,
"text": "*file names might be different"
},
{
"code": null,
"e": 2191,
"s": 2181,
"text": "meta.json"
},
{
"code": null,
"e": 2204,
"s": 2191,
"text": "ner (folder)"
},
{
"code": null,
"e": 2214,
"s": 2204,
"text": "tokenizer"
},
{
"code": null,
"e": 2229,
"s": 2214,
"text": "vocab (folder)"
},
{
"code": null,
"e": 2598,
"s": 2229,
"text": "In terms of creating the model artifact, we could simply compress this folder into a tar.gz format and upload it to a S3 bucket. Alternatively, we could also train the model online with the AWS SageMaker by creating a training job under the SageMaker Training section. But we need to provide our custom training image from AWS ECR and training data from AWS S3 bucket."
},
{
"code": null,
"e": 2782,
"s": 2598,
"text": "Hopefully, you are now a bit clearer about the whole workflow. Now, let’s begin from creating our custom spaCy model container and uploading it onto the AWS ECR as our training image."
},
{
"code": null,
"e": 3007,
"s": 2782,
"text": "Because spaCy is not one of the SageMaker built-in algorithms. We have to create a spaCy model container first on the AWS ECR, and specify the container as the training image while creating a model endpoint on the SageMaker."
},
{
"code": null,
"e": 3234,
"s": 3007,
"text": "SageMaker provides 2 options wherein the first option is to use built-in algorithms that SageMaker offers that includes KNN, XgBoost, Linear Learner, etc. while the other option is to use your custom docker container from ECR."
},
{
"code": null,
"e": 3257,
"s": 3234,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3546,
"s": 3257,
"text": "The above article is an amazing reference that inspired me on how to deploy a custom spaCy container. I strongly encourage to read through this article and have a deeper understanding on how this docker container works internally. It was quite complicated to understand at first for me. 🧠"
},
{
"code": null,
"e": 3593,
"s": 3546,
"text": "In brief, it will include the following steps:"
},
{
"code": null,
"e": 3769,
"s": 3593,
"text": "Edit the files under the Github repo (mainly the docker file, train.py and predictor.py) in order to train a custom spaCy model and return predictions based on the data input."
},
{
"code": null,
"e": 3886,
"s": 3769,
"text": "Check the results by performing a local test for the spaCy docker container and debug the code if any error happens."
},
{
"code": null,
"e": 3938,
"s": 3886,
"text": "Finally, upload the spaCy container to the AWS ECR."
},
{
"code": null,
"e": 4139,
"s": 3938,
"text": "A bit more explanation about the train.py and predictor.py, because these are the two files that determine how we want to train the model and what we expect the input & output of the model to be like."
},
{
"code": null,
"e": 4485,
"s": 4139,
"text": "In the train file, the objective is to modify the code to train a custom spaCy model. After reading the data from CSV files into a dataframe called train_data, we need to convert the dataframe into a format that spaCy model can take as input. I would recommend to read a previous article I wrote about how to train a spaCy model for an NER task."
},
{
"code": null,
"e": 4508,
"s": 4485,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4585,
"s": 4508,
"text": "Essentially, we need to convert a dataframe into the following spaCy format:"
},
{
"code": null,
"e": 5074,
"s": 4585,
"text": "TRAIN_DATA = [('Amazon co ca', {'entities': [(0, 6, 'BRD')]}),('AMZNMKTPLACE AMAZON CO', {'entities': [(13, 19, 'BRD')]}),('APPLE COM BILL', {'entities': [(0, 5, 'BRD')]}),('BOOKING COM New York City', {'entities': [(0, 7, 'BRD')]}),('STARBUCKS Vancouver', {'entities': [(0, 9, 'BRD')]}),('Uber BV', {'entities': [(0, 4, 'BRD')]}),('Hotel on Booking com Toronto', {'entities': [(9, 16, 'BRD')]}),('UBER com', {'entities': [(0, 4, 'BRD')]}),('Netflix com', {'entities': [(0, 7, 'BRD')]})]]"
},
{
"code": null,
"e": 5305,
"s": 5074,
"text": "Then, in the train file, we define our train_spacy function to train the model. The train_spaCy function is similar to the one in the following article. Just be aware that the code within the article is written in spaCy version 2."
},
{
"code": null,
"e": 5330,
"s": 5305,
"text": "manivannan-ai.medium.com"
},
{
"code": null,
"e": 5927,
"s": 5330,
"text": "In the predictor file, we need to edit the code under the predict function. The predict function only takes test_data as input. The test_data is in format of a dataframe already so we could apply the trained spaCy model onto the column which contains the source text input. Then we could create a new column for the model’s predictions. If it’s an NER task, then the new column would contain the extracted entities from each input. Also, we could adjust whether the predict function returns just a list of predictions or a whole dataframe that contains both the source and the prediction columns."
},
{
"code": null,
"e": 6429,
"s": 5927,
"text": "At the end of the predictor file, it requires a bit knowledge of Flask app to understand. Although it’s recommended to know how it works, in fact, we don’t need to modify many parts in the original Flask app. Just be sure that the output data format from the predict function is in consistent with the format used in the Flask app. The original function returns prediction in format of a list. For me, I changed it to return a dataframe so I modified the code in the Flask app to keep the consistency."
},
{
"code": null,
"e": 6619,
"s": 6429,
"text": "Finally, in the docker file, simply edit the code accordingly based on the libraries needed. For me, I added RUN pip3 install -U spacy==2.3.5 to install the correct version of spaCy I used."
},
{
"code": null,
"e": 6654,
"s": 6619,
"text": "Congratulations if you got here! 🥳"
},
{
"code": null,
"e": 6763,
"s": 6654,
"text": "To push our container image to Amazon ECR, we could follow the code inside (from the above article’s Github)"
},
{
"code": null,
"e": 6786,
"s": 6763,
"text": "build_and_push.sh file"
},
{
"code": null,
"e": 6847,
"s": 6786,
"text": "Bring_Your_Own-Creating_Algorithm_and_Model_Package notebook"
},
{
"code": null,
"e": 6989,
"s": 6847,
"text": "These files are well explained in that article. We could simply run through the code to push our own custom spaCy container onto the AWS ECR."
},
{
"code": null,
"e": 7190,
"s": 6989,
"text": "Until this step, we have finally uploaded our custom spaCy container to the AWS ECR. This is a critical step for the model deployment. Now, we will switch to AWS SageMaker and create a model endpoint."
},
{
"code": null,
"e": 7241,
"s": 7190,
"text": "As described in the AWS SageMaker developer guide:"
},
{
"code": null,
"e": 7549,
"s": 7241,
"text": "Amazon SageMaker is a fully-managed service that enables data scientists and developers to quickly and easily build, train, and deploy machine learning models at any scale. Amazon SageMaker includes modules that can be used together or independently to build, train, and deploy your machine learning models."
},
{
"code": null,
"e": 7603,
"s": 7549,
"text": "Essentially, it has an interface structured as below:"
},
{
"code": null,
"e": 7865,
"s": 7603,
"text": "Sections on the AWS SageMaker...--->Training------>Algorithms------>Training jobs ------>Hyperparameter tuning jobs--->Inference------>Compilation jobs------>Model packages------>Models------>Endpoint configurations------>Endpoints------>Batch transform jobs..."
},
{
"code": null,
"e": 7942,
"s": 7865,
"text": "To create a spaCy model endpoint, we need to go through the following steps:"
},
{
"code": null,
"e": 8162,
"s": 7942,
"text": "Create a training job under AWS SageMaker — Training. Or instead, simply train your spaCy model locally, compress it into tar.gz format and upload it to a S3 bucket. The goal is to prepare a model artifact at this step."
},
{
"code": null,
"e": 8307,
"s": 8162,
"text": "Create a model under AWS SageMaker — Inference. We need to specify the container image from AWS ECR and the model artifact from a AWS S3 bucket."
},
{
"code": null,
"e": 8432,
"s": 8307,
"text": "Create an endpoint configuration under AWS SageMaker — Inference. We need to specify a model for the endpoint configuration."
},
{
"code": null,
"e": 8547,
"s": 8432,
"text": "Create an endpoint under AWS SageMaker — Inference. We need to specify an endpoint configuration for the endpoint."
},
{
"code": null,
"e": 8655,
"s": 8547,
"text": "If you have any trouble during the above steps on AWS SageMaker, the following tutorial will be helpful! 🏂🏻"
},
{
"code": null,
"e": 8670,
"s": 8655,
"text": "aws.amazon.com"
},
{
"code": null,
"e": 8718,
"s": 8670,
"text": "As described in the AWS Lambda developer guide:"
},
{
"code": null,
"e": 9069,
"s": 8718,
"text": "Lambda is a compute service that lets you run code without provisioning or managing servers. Lambda runs your code on a high-availability compute infrastructure and performs all of the administration of the compute resources, including server and operating system maintenance, capacity provisioning and automatic scaling, code monitoring and logging."
},
{
"code": null,
"e": 9348,
"s": 9069,
"text": "In terms of the spaCy deployment, we will use the AWS Lambda as an interface that can communicate between the user input and the spaCy model endpoint. Specifically, we want to input the inference text as a Lambda event and receive the model response on the Lambda execution tab."
},
{
"code": null,
"e": 9575,
"s": 9348,
"text": "Some details about how to invoke a SageMaker endpoint on the AWS Lambda can be found at the tutorial same as the one above. Essentially, we want to write a python handler function on the Lambda that can do the following steps:"
},
{
"code": null,
"e": 9614,
"s": 9575,
"text": "Input event: a list of inference texts"
},
{
"code": null,
"e": 9657,
"s": 9614,
"text": "Read the event into a dataframe (optional)"
},
{
"code": null,
"e": 9745,
"s": 9657,
"text": "Write the dataframe into a CSV buffer (keep data format consistency with the Flask app)"
},
{
"code": null,
"e": 9872,
"s": 9745,
"text": "Convert the values of the buffer into ASCII format (keep consistency with the AWS requirement otherwise may cause some errors)"
},
{
"code": null,
"e": 9927,
"s": 9872,
"text": "Invoke the SageMaker endpoint and receive the response"
},
{
"code": null,
"e": 9965,
"s": 9927,
"text": "Decode the response into UTF-8 format"
},
{
"code": null,
"e": 10011,
"s": 9965,
"text": "Read the response into a dataframe (optional)"
},
{
"code": null,
"e": 10056,
"s": 10011,
"text": "Output response: a list of model predictions"
},
{
"code": null,
"e": 10229,
"s": 10056,
"text": "Some details about creating a CSV buffer or ASCII / UTF-8 conversion steps may not be necessary but eventually it works for me. If you have any better ideas, let me know! 😸"
},
{
"code": null,
"e": 10451,
"s": 10229,
"text": "If everything works, now finally, we should be able to see that on the AWS Lambda execution results tab, the list of model predictions is printed out. 💯 And the model input is based on the AWS Lambda configure test event."
},
{
"code": null,
"e": 10584,
"s": 10451,
"text": "Finally, my article on deploying a custom spaCy model with the AWS will conclude here. As a summary, the workflow includes services:"
},
{
"code": null,
"e": 10602,
"s": 10584,
"text": "1st step: AWS ECR"
},
{
"code": null,
"e": 10637,
"s": 10602,
"text": "2nd step: AWS S3 Bucket (Optional)"
},
{
"code": null,
"e": 10661,
"s": 10637,
"text": "3rd step: AWS SageMaker"
},
{
"code": null,
"e": 10682,
"s": 10661,
"text": "4th step: AWS Lambda"
},
{
"code": null,
"e": 10878,
"s": 10682,
"text": "Although this design may not be the best, it’s still the most stable one I could think of after a large amount of research. Hope it can help / inspire anyone who is working on the similar tasks 😋"
}
] |
Mathematics | Probability Distributions Set 3 (Normal Distribution) - GeeksforGeeks
|
10 Apr, 2020
The previous two articles introduced two Continuous Distributions: Uniform and Exponential. This article covers the Normal Probability Distribution, also a Continuous distribution, which is by far the most widely used model for continuous measurement.
Introduction –
Whenever a random experiment is replicated, the Random Variable that equals the average (or total) result over the replicates tends to have a normal distribution as the number of replicates becomes large.It is one of the cornerstones of probability theory and statistics, because of the role it plays in the Central Limit Theorem, and because many real-world phenomena involve random quantities that are approximately normal (e.g., errors in scientific measurement).It is also known by other names such as- Gaussian Distribution, Bell shaped Distribution.
It can be observed from the above graph that the distribution is symmetric about its center, which is also the mean (0 in this case). This makes the probability of events at equal deviations from the mean, equally probable. The density is highly centered around the mean, which translates to lower probabilities for values away from the mean.
Probability Density Function –
The probability density function of the general normal distribution is given as-In the above formula, all the symbols have their usual meanings, is the Standard Deviation and is the Mean.It is easy to get overwhelmed by the above formula while trying to understand everything in one glance, but we can try to break it down into smaller pieces so as to get an intuition as to what is going on.The z-score is a measure of how many standard deviations away a data point is from the mean. Mathematically,The exponent of in the above formula is the square of the z-score times . This is actually in accordance to the observations that we made above. Values away from the mean have a lower probability compared to the values near the mean. Values away from the mean will have a higher z-score and consequently a lower probability since the exponent is negative. The opposite is true for values closer to the mean.This gives way for the 68-95-99.7 rule, which states that the percentage of values that lie within a band around the mean in a normal distribution with a width of two, four and six standard deviations, comprise 68%, 95% and 99.7% of all the values. The figure given below shows this rule-
The effects of and on the distribution are shown below. Here is used to reposition the center of the distribution and consequently move the graph left or right, and is used to flatten or inflate the curve-
Expectationexpectation click here or expected value E[x] can be found by simply multiply the probability distribution function with x and integrate over all possible valuesLet ‘X’ be a normal distributed random variable with parameters ans.we know that area or the region inside normal distribution curve is 1 (because probability is 1)therefore = 1
writing x as (x-) + yields
letting y = x-
first one is symmetric about y-axis, hence value of that integral is 0.
therefore ,expectation
variance =
standard deviation =
Standard Normal Distribution –
In the General Normal Distribution, if the Mean is set to 0 and the Standard Deviation is set to 1, then the corresponding distribution obtained is called the Standard Normal Distribution.The Probability Density function now becomes-The cumulative density function of normal distribution does not give a closed formula. Hence precomputed values formulated in tables are used where-ever required. But these tables only contain data for the standard distribution. In order to find the cumulative probability for a general normal distribution, it is first standardized and then computed using the value tables.This is beneficial in two ways-1. First, there needs to be only one table to compute probabilities for all normal distributions.2. Second, the table size is limited to 40 to 50 rows and 10 columns. This is due 68-95-99.7 rule explained above, which says that values within 3 standard deviations of the mean account for 99.7% probability. So beyond X=3 () the probabilities are approximately 0.
If X is a normal random variable with E(X)= and V(X)=,
the random variable is a normal random variable with E(Z)=0 and V(Z)=1.
That is, Z is a standard normal random variable.
Example – Suppose that the current measurements in a strip of wire are assumed to follow a normal distribution with a mean of 10 milliamperes and a variance of four (milliamperes). What is the probability that a measurement exceeds 13 milliamperes?
Solution – Let X denote the current in milliamperes. The requested probability can be represented as P (X > 13).Let Z = (X ? 10) 2. With the Normal Distribution now standardized, the probability P(X > 13) = P(Z > 1.5) can now be easily computed.Looking at the above table, first we find 1.5 in the X column, and then since there are no more digits of significance we look for 0.00 in the Y column. The corresponding cell gives us the value of So,
Expected value , variance , standard deviationThe expected value of a standard normal random variable X isexpected value variance standard deviation
GATE CS Corner Questions
Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.
1. GATE CS 2008, Question 29
References-
Normal Distribution – Wikipedia68-95-99.7 Rule
dheeraj01
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inequalities in LaTeX
Newton's Divided Difference Interpolation Formula
Univariate, Bivariate and Multivariate data and its analysis
Activation Functions
Arrow Symbols in LaTeX
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
|
[
{
"code": null,
"e": 29952,
"s": 29924,
"text": "\n10 Apr, 2020"
},
{
"code": null,
"e": 30204,
"s": 29952,
"text": "The previous two articles introduced two Continuous Distributions: Uniform and Exponential. This article covers the Normal Probability Distribution, also a Continuous distribution, which is by far the most widely used model for continuous measurement."
},
{
"code": null,
"e": 30219,
"s": 30204,
"text": "Introduction –"
},
{
"code": null,
"e": 30775,
"s": 30219,
"text": "Whenever a random experiment is replicated, the Random Variable that equals the average (or total) result over the replicates tends to have a normal distribution as the number of replicates becomes large.It is one of the cornerstones of probability theory and statistics, because of the role it plays in the Central Limit Theorem, and because many real-world phenomena involve random quantities that are approximately normal (e.g., errors in scientific measurement).It is also known by other names such as- Gaussian Distribution, Bell shaped Distribution."
},
{
"code": null,
"e": 31118,
"s": 30775,
"text": "It can be observed from the above graph that the distribution is symmetric about its center, which is also the mean (0 in this case). This makes the probability of events at equal deviations from the mean, equally probable. The density is highly centered around the mean, which translates to lower probabilities for values away from the mean."
},
{
"code": null,
"e": 31149,
"s": 31118,
"text": "Probability Density Function –"
},
{
"code": null,
"e": 32348,
"s": 31149,
"text": "The probability density function of the general normal distribution is given as-In the above formula, all the symbols have their usual meanings, is the Standard Deviation and is the Mean.It is easy to get overwhelmed by the above formula while trying to understand everything in one glance, but we can try to break it down into smaller pieces so as to get an intuition as to what is going on.The z-score is a measure of how many standard deviations away a data point is from the mean. Mathematically,The exponent of in the above formula is the square of the z-score times . This is actually in accordance to the observations that we made above. Values away from the mean have a lower probability compared to the values near the mean. Values away from the mean will have a higher z-score and consequently a lower probability since the exponent is negative. The opposite is true for values closer to the mean.This gives way for the 68-95-99.7 rule, which states that the percentage of values that lie within a band around the mean in a normal distribution with a width of two, four and six standard deviations, comprise 68%, 95% and 99.7% of all the values. The figure given below shows this rule-"
},
{
"code": null,
"e": 32558,
"s": 32348,
"text": "The effects of and on the distribution are shown below. Here is used to reposition the center of the distribution and consequently move the graph left or right, and is used to flatten or inflate the curve-"
},
{
"code": null,
"e": 32910,
"s": 32558,
"text": "Expectationexpectation click here or expected value E[x] can be found by simply multiply the probability distribution function with x and integrate over all possible valuesLet ‘X’ be a normal distributed random variable with parameters ans.we know that area or the region inside normal distribution curve is 1 (because probability is 1)therefore = 1"
},
{
"code": null,
"e": 32938,
"s": 32910,
"text": "writing x as (x-) + yields"
},
{
"code": null,
"e": 32953,
"s": 32938,
"text": "letting y = x-"
},
{
"code": null,
"e": 33025,
"s": 32953,
"text": "first one is symmetric about y-axis, hence value of that integral is 0."
},
{
"code": null,
"e": 33049,
"s": 33025,
"text": "therefore ,expectation "
},
{
"code": null,
"e": 33061,
"s": 33049,
"text": "variance = "
},
{
"code": null,
"e": 33083,
"s": 33061,
"text": "standard deviation = "
},
{
"code": null,
"e": 33114,
"s": 33083,
"text": "Standard Normal Distribution –"
},
{
"code": null,
"e": 34115,
"s": 33114,
"text": "In the General Normal Distribution, if the Mean is set to 0 and the Standard Deviation is set to 1, then the corresponding distribution obtained is called the Standard Normal Distribution.The Probability Density function now becomes-The cumulative density function of normal distribution does not give a closed formula. Hence precomputed values formulated in tables are used where-ever required. But these tables only contain data for the standard distribution. In order to find the cumulative probability for a general normal distribution, it is first standardized and then computed using the value tables.This is beneficial in two ways-1. First, there needs to be only one table to compute probabilities for all normal distributions.2. Second, the table size is limited to 40 to 50 rows and 10 columns. This is due 68-95-99.7 rule explained above, which says that values within 3 standard deviations of the mean account for 99.7% probability. So beyond X=3 () the probabilities are approximately 0."
},
{
"code": null,
"e": 34295,
"s": 34115,
"text": "If X is a normal random variable with E(X)= and V(X)=, \nthe random variable is a normal random variable with E(Z)=0 and V(Z)=1. \nThat is, Z is a standard normal random variable.\n"
},
{
"code": null,
"e": 34544,
"s": 34295,
"text": "Example – Suppose that the current measurements in a strip of wire are assumed to follow a normal distribution with a mean of 10 milliamperes and a variance of four (milliamperes). What is the probability that a measurement exceeds 13 milliamperes?"
},
{
"code": null,
"e": 34991,
"s": 34544,
"text": "Solution – Let X denote the current in milliamperes. The requested probability can be represented as P (X > 13).Let Z = (X ? 10) 2. With the Normal Distribution now standardized, the probability P(X > 13) = P(Z > 1.5) can now be easily computed.Looking at the above table, first we find 1.5 in the X column, and then since there are no more digits of significance we look for 0.00 in the Y column. The corresponding cell gives us the value of So,"
},
{
"code": null,
"e": 35141,
"s": 34991,
"text": "Expected value , variance , standard deviationThe expected value of a standard normal random variable X isexpected value variance standard deviation "
},
{
"code": null,
"e": 35166,
"s": 35141,
"text": "GATE CS Corner Questions"
},
{
"code": null,
"e": 35364,
"s": 35166,
"text": "Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them."
},
{
"code": null,
"e": 35393,
"s": 35364,
"text": "1. GATE CS 2008, Question 29"
},
{
"code": null,
"e": 35405,
"s": 35393,
"text": "References-"
},
{
"code": null,
"e": 35452,
"s": 35405,
"text": "Normal Distribution – Wikipedia68-95-99.7 Rule"
},
{
"code": null,
"e": 35462,
"s": 35452,
"text": "dheeraj01"
},
{
"code": null,
"e": 35486,
"s": 35462,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 35494,
"s": 35486,
"text": "GATE CS"
},
{
"code": null,
"e": 35592,
"s": 35494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35601,
"s": 35592,
"text": "Comments"
},
{
"code": null,
"e": 35614,
"s": 35601,
"text": "Old Comments"
},
{
"code": null,
"e": 35636,
"s": 35614,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 35686,
"s": 35636,
"text": "Newton's Divided Difference Interpolation Formula"
},
{
"code": null,
"e": 35747,
"s": 35686,
"text": "Univariate, Bivariate and Multivariate data and its analysis"
},
{
"code": null,
"e": 35768,
"s": 35747,
"text": "Activation Functions"
},
{
"code": null,
"e": 35791,
"s": 35768,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 35811,
"s": 35791,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 35835,
"s": 35811,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 35862,
"s": 35835,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 35883,
"s": 35862,
"text": "Normal Forms in DBMS"
}
] |
Generate Meaningful Word Clouds in Python | by Bryan Dickinson | Towards Data Science
|
I’m sure you’ve seen a word cloud. Generally, it’s a photo filled with words where the size depends on the frequency of times the word appears in the text you’d like to analyze. I wasn’t privy to this, but apparently, there has been/is (not sure) some pretty strong feelings against/for word clouds. I have read that they are bad, lame, equating them to a modern pie chart and even comparing them as the new mullet. Ouch. A mullet? Come on.
I’ve also read some ways to improve word clouds and useful times to use them. Regardless of which camp you are in, I found that leveraging a compelling graphic or visualization in a presentation, engages your audience, prompts a reaction, can start a conversation, can be influential, and opens the door for more detailed analysis. A visually compelling word cloud art can draw readers in. With that said, I won’t get further into the pros and cons of word clouds, you check out the above links for that.
We will use a couple of different methods to extract some meaningful words out of the text. We will then generate some word clouds using the Python libraries WordCloud, pandas, and NumPy.
WordCloud is a word cloud generator in Python. You can install WordCloud by one of the following commands.pip install wordcloudconda install -c conda-forge wordcloudCheck out installation details here, and you can read through the WordCloud documentation here.
The data we will be using is the democratic primary debates for the 2020 presidency. You can find the full dataset here via Kaggle. The data has been cleaned and filtered. The Github repo has the cleaning steps included.
1| Import Libraries and Data
Before creating a word cloud the text stopwords should be updated specifically to the domain of the text. For example, if we were completing word clouds from customer tweets for an airline company, we would probably get words like ‘plane’, ‘fly’, ‘travel’ and they may not be of any significance to any analysis you are completing.
In this dataset, additional stopwords were included because they appeared a lot in the text but did not contribute to the analysis. For example words like ‘senator’, ‘congressman’, ‘people’, ‘fact’ were all words that were used by many candidates in sentences like ‘I agree with Senator Sanders...’ or ‘The fact is...’, ‘The American people want..’ and did not necessarily contribute to words of meaning for the word cloud.
2.1| Method 1 — Use WordCloud to ProcessThe simplest and fastest way to create a word cloud is to simply use WordCloud to process the text.
The text needs to be in one long string in order for WordCloud to process it. We filter the data to ‘biden’, create a list of his responses, and join the list to create one long string of text. We then create the word cloud object, use the generate() method, and pass our string of text. Lastly, we use plt.imshow to display the image.
Let's take a look at the parameters from the documentation:stopwords: this parameter takes in a set of strings (words) that will be eliminated from the word cloud. We used our updated list of stopwords here.collocations: This parameter takes a bool statement, and will generate bigrams from your text if set to ‘True’ We don’t actually see any bigrams here.background_color: sets the background color, default is black
The result ...looks a bit like gibberish and doesn’t look too informative. Words ‘re’, ‘said’, ‘make’, and ‘said’ seem to be the most frequent words. Those don’t seem to be too significant in Joe Biden’s message whereas words like ‘cost’, ‘medicare’, and ‘world’ in the background. An option could be to continue updating stop words. A challenge with that process is knowing when to stop. When do you know you have a good amount of words without removing useful words? I’m not dismissing this method, I’ve used it before.
We can use the process_text() and words_ methods to display the word count and relative counts from the text respectively.
# output[('re', 148), ('make', 117), ('ve', 106), ('said', 95), ('able', 88)][('re', 1.0), ('make', 0.7905405405405406), ('ve', 0.7162162162162162), ('said', 0.6418918918918919), ('able', 0.5945945945945946)]
You can take a peek at other candidates and you’ll notice there a similar result of non-meaningful words appearing high on the list. Let’s tweak some additional parameters of WordCloud to improve the words shown. min_word_length: is the minimum number of letters a word must have to be included in the word cloudcollocation_threshold: is a Dunning likelihood score. Bigrams in the text must reach a score greater than this parameter to be counted as a bigram. The default is set at 30.
We’ll add a min word length of 4 and a collocation_threshold of 3 to include more bigrams. Lastly, and perhaps most importantly, I will be utilizing a different set of stopwords. The original set was imported from WordCloud. I will import and use the stopwords offered in the SpaCy library and update that list with my own. No real reason for using SpaCy’s list other than I’ve used it in the past and have gotten good results. There are many different stop word libraries you can use.
We see a pretty good improvement! We are getting some different words, including bigrams like ‘Donald Trump’, ‘Barack Obama’, ‘public option’, and ‘middle class’. Some more tweaking/updating of stopwords might improve this.
2.2| Method 2— Utilizing Word FrequenciesThe previous method used a string of text. What if you don’t necessarily have access to the full text or want to use word frequencies directly? A WordCloud alternative to the generate() method is the generate_from_frequencies() method that will take a dictionary of words and their frequencies and create a word cloud from the counts. Let's give it a try.
We still have the full text, so we will utilize CountVectorizer to create a matrix of word counts. If you already have a dictionary of counts or a bag of words matrix, you can skip this step.
Now we just need to extract one row of this dataframe, create a dictionary, and place it into the WordCloud object.
The new word cloud looks somewhat similar to the previous version. There are similar top frequent words with some differences. When the generate_from_frequencies method is used, it ignores some of the parameters including the collocations and stopword parameters. CountVectorizer processes the text, including stop words and lemmatization. If we wanted to make additional tweaks to the words, it would need to be done prior to placing them into the WordCloud object. We can see that ‘Donald’ is lemmatized to ‘Don’ and that there are no bigrams in this version.
Another option to creating a word cloud from frequencies is to utilize the collections Counter object to create a dictionary that you can utilize with WordCloud. This would require preprocessing your text including tokenizing the words, then using the counter object to count each word. Given that you need the whole text it would be easier to utilize the full text with the WordCloud object to perform this for you.
2.3| Method 3— Log Odds RatioFrom the last two word clouds, we got pretty good groups of words that encompass what these candidates have said. If you look at top words from multiple candidates, you start to see that similar words start showing up for all — but what about words or phrases that are specific to a certain person? For example, if you’ve watched these debates you may have noticed that Amy Klobuchar mentions ‘lead democrat’ and Biden likes to count off his points (‘number one’, ‘number two’ ..) quite often. We could get a view of important words or phrases that are mentioned by a particular candidate, but not others.
Going back to our analyzing customer tweets for airplane company example. We may want to capture what segment of our customers are mentioning. What do our business travelers think vs other travelers? Many words may be the same such as ‘seat’ and ‘experience’, but they may have different thoughts and priorities than say urgent travelers who also mention words such as ‘seat’ and ‘experience’. Differentiating these words can help get a better understanding of these different segments of customers.
Put simply we want to see which words are most common from a specific candidate, say, Pete Buttigieg, relative to all other candidates. And we’ll do this with each candidate.
To do this we’ll use the measure of log odds ratio calculated for each word as:
We used the bag of words dataframe and transformed each row using the calculation above. The result is a data frame showing the log odds of each word being said by a particular candidate.
We tried to identify words that were most unique to each candidate. Here are the top 10 words for four candidates can you match them to the correct candidate?
Following the same steps above for generating a word cloud via word frequencies, we can now create a new word cloud.
The great thing about this method is that n-grams are generated using this method. We see Biden’s message of restoring the soul of America and his mentions of the Violence Against Women Act. There are other methods that can be used, such as weighted log-odds & tf-idf.
So which text do we use? With the premise of creating stunning visual vs analytical analysis with words. I combine both to give a general sense of frequent words and common words from and to that candidate.
2.4| Combine DictionariesWe have two different dictionaries/word frequencies (methods 1 & 3) that we can utilize separately or combine to create an all-encompassing word cloud. After combining them, we will make one more tweak. You’ll notice that a word may be spelled differently. Like healthcare and health care. We will add these together to give a better representation of the word.
This may look a little crazy. This code is setting the second dictionary’s most common word’s frequency equal to the first dictionary’s most common word’s frequency. We now combine the dictionaries and combine ‘healthcare’ and ‘health care’ into one key for a better representation. The top 5 entries and word cloud are displayed below.
[('number number', 56), ('argued', 44), ('special forces', 41), ('single solitary', 41), ('restore soul', 40)]
Great, we see a blending of both worlds that were very frequent of the candidate, and words that are common to that candidate alone. We have our text next up will be creating our custom word cloud.
3 |Prepare the photoThis step is not completed in python. You need to find an image to use. There are a lot of free stock photo sites to pick from like Unsplash, Pixabay, and Pexels to choose from. Once you have found a photo — it needs to be converted to black & white. The black portions of the photo will be where words are displayed, the white areas will show as white. You can complete this in photo editing software such as Photoshop or online with free photo editing software like Pixlr. I’ve used both to pretty easily separate out the background from the subject of the image. Some photos require a little more time than others.
Pro tip: Make sure when creating your photo, that the background is indeed white, and not transparent. The transparent pixel values will be imported as 0, or black, and will not give you a masked image.
3 |Import Photo and Create the WordCloudThere are multiple ways you can color the words in your word cloud. I will go through the details of two, you can see the third in the Github repo. The first will be utilizing a colormap.
Ok, let’s walk through this code. The first line imports your black and white image and the second line adjusts any slight variance in color when creating your image. I had Adobe Illustrator give me a larger range of ‘white’ pixel values between 240 and <255 creating an image that would not work. So this line turns all pixel values greater than 3 white, and the rest are their original values. We then create the WordCloud object with some new parameters.
font_path: this is a path to a font that you would like to use for the words. You can point this path to the font folder of your OS. (ie. C:\Windows\Fonts\font.tff)contour_color: the color of the outline of the imagemax_words: the maximum number of words to use in the imagemask: your image matrixcolormap: the color map to use for the wordscontour_width: the thickness of the outline
It looks great! Though the light colors are pretty hard to read. We could change the background or pick a different color or colormap. Another option is to pick the darker portion of the color map we want to use. We will add two lines that will import a colormap from matplotlib as a matrix of colors, then select the darker part of that matrix.
You can see that the completed product looks pretty good. The image on the right is the image from the code above with the darker colormap. I also used it to create the title image. The image on the left is a custom color. You can find the code for this word cloud in the Github repo. You can save the image using the to_file() method and passing a location to save the file. wordcloud.to_file(“path_to\\wordcloud_image.png”)
3.1 |Create an Image-Colored WordCloudAnother option is to use the colors of the photo itself to color the words. You’ll need to prep the photo as before but only remove the background, and leave the part of the image you would like the words to cover.
We create the mask again (without changing any values). A couple of changes were made to the WordCloud parameters. Some changes to the size and colors of the font and background were made to increase readability. The ImageColorGenerator is used to create the colors for the word cloud, and the recolor() method is used to change the color of the words.
We explored a few different ways to extract some meaningful text utilizing different stopwords from both full text and word frequencies. We also took a look at leveraging log odds ratios to find common words from a portion of the text. We also drew several types of word clouds, using different masks, fonts, and colors. Hopefully, this will help you create some useful visuals for a project.
Check out the Github repository here with the code to all the examples above.
If you are curious about learning and implementing other NLP techniques to extract insights from text, check out this blog post, by Neptune.ai, that covers more than 7 other NLP techniques including sentiment analysis and parts of speech tagging.
If this helped out, let me know! I’d love to hear your thoughts on word clouds and see some of your results.
|
[
{
"code": null,
"e": 613,
"s": 172,
"text": "I’m sure you’ve seen a word cloud. Generally, it’s a photo filled with words where the size depends on the frequency of times the word appears in the text you’d like to analyze. I wasn’t privy to this, but apparently, there has been/is (not sure) some pretty strong feelings against/for word clouds. I have read that they are bad, lame, equating them to a modern pie chart and even comparing them as the new mullet. Ouch. A mullet? Come on."
},
{
"code": null,
"e": 1118,
"s": 613,
"text": "I’ve also read some ways to improve word clouds and useful times to use them. Regardless of which camp you are in, I found that leveraging a compelling graphic or visualization in a presentation, engages your audience, prompts a reaction, can start a conversation, can be influential, and opens the door for more detailed analysis. A visually compelling word cloud art can draw readers in. With that said, I won’t get further into the pros and cons of word clouds, you check out the above links for that."
},
{
"code": null,
"e": 1306,
"s": 1118,
"text": "We will use a couple of different methods to extract some meaningful words out of the text. We will then generate some word clouds using the Python libraries WordCloud, pandas, and NumPy."
},
{
"code": null,
"e": 1567,
"s": 1306,
"text": "WordCloud is a word cloud generator in Python. You can install WordCloud by one of the following commands.pip install wordcloudconda install -c conda-forge wordcloudCheck out installation details here, and you can read through the WordCloud documentation here."
},
{
"code": null,
"e": 1788,
"s": 1567,
"text": "The data we will be using is the democratic primary debates for the 2020 presidency. You can find the full dataset here via Kaggle. The data has been cleaned and filtered. The Github repo has the cleaning steps included."
},
{
"code": null,
"e": 1817,
"s": 1788,
"text": "1| Import Libraries and Data"
},
{
"code": null,
"e": 2149,
"s": 1817,
"text": "Before creating a word cloud the text stopwords should be updated specifically to the domain of the text. For example, if we were completing word clouds from customer tweets for an airline company, we would probably get words like ‘plane’, ‘fly’, ‘travel’ and they may not be of any significance to any analysis you are completing."
},
{
"code": null,
"e": 2573,
"s": 2149,
"text": "In this dataset, additional stopwords were included because they appeared a lot in the text but did not contribute to the analysis. For example words like ‘senator’, ‘congressman’, ‘people’, ‘fact’ were all words that were used by many candidates in sentences like ‘I agree with Senator Sanders...’ or ‘The fact is...’, ‘The American people want..’ and did not necessarily contribute to words of meaning for the word cloud."
},
{
"code": null,
"e": 2713,
"s": 2573,
"text": "2.1| Method 1 — Use WordCloud to ProcessThe simplest and fastest way to create a word cloud is to simply use WordCloud to process the text."
},
{
"code": null,
"e": 3049,
"s": 2713,
"text": "The text needs to be in one long string in order for WordCloud to process it. We filter the data to ‘biden’, create a list of his responses, and join the list to create one long string of text. We then create the word cloud object, use the generate() method, and pass our string of text. Lastly, we use plt.imshow to display the image."
},
{
"code": null,
"e": 3468,
"s": 3049,
"text": "Let's take a look at the parameters from the documentation:stopwords: this parameter takes in a set of strings (words) that will be eliminated from the word cloud. We used our updated list of stopwords here.collocations: This parameter takes a bool statement, and will generate bigrams from your text if set to ‘True’ We don’t actually see any bigrams here.background_color: sets the background color, default is black"
},
{
"code": null,
"e": 3990,
"s": 3468,
"text": "The result ...looks a bit like gibberish and doesn’t look too informative. Words ‘re’, ‘said’, ‘make’, and ‘said’ seem to be the most frequent words. Those don’t seem to be too significant in Joe Biden’s message whereas words like ‘cost’, ‘medicare’, and ‘world’ in the background. An option could be to continue updating stop words. A challenge with that process is knowing when to stop. When do you know you have a good amount of words without removing useful words? I’m not dismissing this method, I’ve used it before."
},
{
"code": null,
"e": 4113,
"s": 3990,
"text": "We can use the process_text() and words_ methods to display the word count and relative counts from the text respectively."
},
{
"code": null,
"e": 4322,
"s": 4113,
"text": "# output[('re', 148), ('make', 117), ('ve', 106), ('said', 95), ('able', 88)][('re', 1.0), ('make', 0.7905405405405406), ('ve', 0.7162162162162162), ('said', 0.6418918918918919), ('able', 0.5945945945945946)]"
},
{
"code": null,
"e": 4808,
"s": 4322,
"text": "You can take a peek at other candidates and you’ll notice there a similar result of non-meaningful words appearing high on the list. Let’s tweak some additional parameters of WordCloud to improve the words shown. min_word_length: is the minimum number of letters a word must have to be included in the word cloudcollocation_threshold: is a Dunning likelihood score. Bigrams in the text must reach a score greater than this parameter to be counted as a bigram. The default is set at 30."
},
{
"code": null,
"e": 5294,
"s": 4808,
"text": "We’ll add a min word length of 4 and a collocation_threshold of 3 to include more bigrams. Lastly, and perhaps most importantly, I will be utilizing a different set of stopwords. The original set was imported from WordCloud. I will import and use the stopwords offered in the SpaCy library and update that list with my own. No real reason for using SpaCy’s list other than I’ve used it in the past and have gotten good results. There are many different stop word libraries you can use."
},
{
"code": null,
"e": 5518,
"s": 5294,
"text": "We see a pretty good improvement! We are getting some different words, including bigrams like ‘Donald Trump’, ‘Barack Obama’, ‘public option’, and ‘middle class’. Some more tweaking/updating of stopwords might improve this."
},
{
"code": null,
"e": 5915,
"s": 5518,
"text": "2.2| Method 2— Utilizing Word FrequenciesThe previous method used a string of text. What if you don’t necessarily have access to the full text or want to use word frequencies directly? A WordCloud alternative to the generate() method is the generate_from_frequencies() method that will take a dictionary of words and their frequencies and create a word cloud from the counts. Let's give it a try."
},
{
"code": null,
"e": 6107,
"s": 5915,
"text": "We still have the full text, so we will utilize CountVectorizer to create a matrix of word counts. If you already have a dictionary of counts or a bag of words matrix, you can skip this step."
},
{
"code": null,
"e": 6223,
"s": 6107,
"text": "Now we just need to extract one row of this dataframe, create a dictionary, and place it into the WordCloud object."
},
{
"code": null,
"e": 6785,
"s": 6223,
"text": "The new word cloud looks somewhat similar to the previous version. There are similar top frequent words with some differences. When the generate_from_frequencies method is used, it ignores some of the parameters including the collocations and stopword parameters. CountVectorizer processes the text, including stop words and lemmatization. If we wanted to make additional tweaks to the words, it would need to be done prior to placing them into the WordCloud object. We can see that ‘Donald’ is lemmatized to ‘Don’ and that there are no bigrams in this version."
},
{
"code": null,
"e": 7202,
"s": 6785,
"text": "Another option to creating a word cloud from frequencies is to utilize the collections Counter object to create a dictionary that you can utilize with WordCloud. This would require preprocessing your text including tokenizing the words, then using the counter object to count each word. Given that you need the whole text it would be easier to utilize the full text with the WordCloud object to perform this for you."
},
{
"code": null,
"e": 7837,
"s": 7202,
"text": "2.3| Method 3— Log Odds RatioFrom the last two word clouds, we got pretty good groups of words that encompass what these candidates have said. If you look at top words from multiple candidates, you start to see that similar words start showing up for all — but what about words or phrases that are specific to a certain person? For example, if you’ve watched these debates you may have noticed that Amy Klobuchar mentions ‘lead democrat’ and Biden likes to count off his points (‘number one’, ‘number two’ ..) quite often. We could get a view of important words or phrases that are mentioned by a particular candidate, but not others."
},
{
"code": null,
"e": 8337,
"s": 7837,
"text": "Going back to our analyzing customer tweets for airplane company example. We may want to capture what segment of our customers are mentioning. What do our business travelers think vs other travelers? Many words may be the same such as ‘seat’ and ‘experience’, but they may have different thoughts and priorities than say urgent travelers who also mention words such as ‘seat’ and ‘experience’. Differentiating these words can help get a better understanding of these different segments of customers."
},
{
"code": null,
"e": 8512,
"s": 8337,
"text": "Put simply we want to see which words are most common from a specific candidate, say, Pete Buttigieg, relative to all other candidates. And we’ll do this with each candidate."
},
{
"code": null,
"e": 8592,
"s": 8512,
"text": "To do this we’ll use the measure of log odds ratio calculated for each word as:"
},
{
"code": null,
"e": 8780,
"s": 8592,
"text": "We used the bag of words dataframe and transformed each row using the calculation above. The result is a data frame showing the log odds of each word being said by a particular candidate."
},
{
"code": null,
"e": 8939,
"s": 8780,
"text": "We tried to identify words that were most unique to each candidate. Here are the top 10 words for four candidates can you match them to the correct candidate?"
},
{
"code": null,
"e": 9056,
"s": 8939,
"text": "Following the same steps above for generating a word cloud via word frequencies, we can now create a new word cloud."
},
{
"code": null,
"e": 9325,
"s": 9056,
"text": "The great thing about this method is that n-grams are generated using this method. We see Biden’s message of restoring the soul of America and his mentions of the Violence Against Women Act. There are other methods that can be used, such as weighted log-odds & tf-idf."
},
{
"code": null,
"e": 9532,
"s": 9325,
"text": "So which text do we use? With the premise of creating stunning visual vs analytical analysis with words. I combine both to give a general sense of frequent words and common words from and to that candidate."
},
{
"code": null,
"e": 9919,
"s": 9532,
"text": "2.4| Combine DictionariesWe have two different dictionaries/word frequencies (methods 1 & 3) that we can utilize separately or combine to create an all-encompassing word cloud. After combining them, we will make one more tweak. You’ll notice that a word may be spelled differently. Like healthcare and health care. We will add these together to give a better representation of the word."
},
{
"code": null,
"e": 10256,
"s": 9919,
"text": "This may look a little crazy. This code is setting the second dictionary’s most common word’s frequency equal to the first dictionary’s most common word’s frequency. We now combine the dictionaries and combine ‘healthcare’ and ‘health care’ into one key for a better representation. The top 5 entries and word cloud are displayed below."
},
{
"code": null,
"e": 10367,
"s": 10256,
"text": "[('number number', 56), ('argued', 44), ('special forces', 41), ('single solitary', 41), ('restore soul', 40)]"
},
{
"code": null,
"e": 10565,
"s": 10367,
"text": "Great, we see a blending of both worlds that were very frequent of the candidate, and words that are common to that candidate alone. We have our text next up will be creating our custom word cloud."
},
{
"code": null,
"e": 11203,
"s": 10565,
"text": "3 |Prepare the photoThis step is not completed in python. You need to find an image to use. There are a lot of free stock photo sites to pick from like Unsplash, Pixabay, and Pexels to choose from. Once you have found a photo — it needs to be converted to black & white. The black portions of the photo will be where words are displayed, the white areas will show as white. You can complete this in photo editing software such as Photoshop or online with free photo editing software like Pixlr. I’ve used both to pretty easily separate out the background from the subject of the image. Some photos require a little more time than others."
},
{
"code": null,
"e": 11406,
"s": 11203,
"text": "Pro tip: Make sure when creating your photo, that the background is indeed white, and not transparent. The transparent pixel values will be imported as 0, or black, and will not give you a masked image."
},
{
"code": null,
"e": 11634,
"s": 11406,
"text": "3 |Import Photo and Create the WordCloudThere are multiple ways you can color the words in your word cloud. I will go through the details of two, you can see the third in the Github repo. The first will be utilizing a colormap."
},
{
"code": null,
"e": 12092,
"s": 11634,
"text": "Ok, let’s walk through this code. The first line imports your black and white image and the second line adjusts any slight variance in color when creating your image. I had Adobe Illustrator give me a larger range of ‘white’ pixel values between 240 and <255 creating an image that would not work. So this line turns all pixel values greater than 3 white, and the rest are their original values. We then create the WordCloud object with some new parameters."
},
{
"code": null,
"e": 12477,
"s": 12092,
"text": "font_path: this is a path to a font that you would like to use for the words. You can point this path to the font folder of your OS. (ie. C:\\Windows\\Fonts\\font.tff)contour_color: the color of the outline of the imagemax_words: the maximum number of words to use in the imagemask: your image matrixcolormap: the color map to use for the wordscontour_width: the thickness of the outline"
},
{
"code": null,
"e": 12823,
"s": 12477,
"text": "It looks great! Though the light colors are pretty hard to read. We could change the background or pick a different color or colormap. Another option is to pick the darker portion of the color map we want to use. We will add two lines that will import a colormap from matplotlib as a matrix of colors, then select the darker part of that matrix."
},
{
"code": null,
"e": 13249,
"s": 12823,
"text": "You can see that the completed product looks pretty good. The image on the right is the image from the code above with the darker colormap. I also used it to create the title image. The image on the left is a custom color. You can find the code for this word cloud in the Github repo. You can save the image using the to_file() method and passing a location to save the file. wordcloud.to_file(“path_to\\\\wordcloud_image.png”)"
},
{
"code": null,
"e": 13502,
"s": 13249,
"text": "3.1 |Create an Image-Colored WordCloudAnother option is to use the colors of the photo itself to color the words. You’ll need to prep the photo as before but only remove the background, and leave the part of the image you would like the words to cover."
},
{
"code": null,
"e": 13855,
"s": 13502,
"text": "We create the mask again (without changing any values). A couple of changes were made to the WordCloud parameters. Some changes to the size and colors of the font and background were made to increase readability. The ImageColorGenerator is used to create the colors for the word cloud, and the recolor() method is used to change the color of the words."
},
{
"code": null,
"e": 14248,
"s": 13855,
"text": "We explored a few different ways to extract some meaningful text utilizing different stopwords from both full text and word frequencies. We also took a look at leveraging log odds ratios to find common words from a portion of the text. We also drew several types of word clouds, using different masks, fonts, and colors. Hopefully, this will help you create some useful visuals for a project."
},
{
"code": null,
"e": 14326,
"s": 14248,
"text": "Check out the Github repository here with the code to all the examples above."
},
{
"code": null,
"e": 14573,
"s": 14326,
"text": "If you are curious about learning and implementing other NLP techniques to extract insights from text, check out this blog post, by Neptune.ai, that covers more than 7 other NLP techniques including sentiment analysis and parts of speech tagging."
}
] |
How to add percentage or count labels above percentage bar plot in R? - GeeksforGeeks
|
18 Jul, 2021
In this article, we will discuss how to add percentage or count above percentage bar plot in R programming language.
The ggplot() method of this package is used to initialize a ggplot object. It can be used to declare the input data frame for a graphic and can also be used to specify the set of plot aesthetics. The ggplot() function is used to construct the initial plot object and is almost always followed by components to add to the plot.
Syntax:
ggplot(data, mapping = aes())
Parameter :
data – The data frame used for data plotting
mapping – Default list of aesthetic mappings to use for plot.
geom_bar() is used to draw a bar plot.
The geom_bar() method is used which plots a number of cases appearing in each group against each bar value. Using the “stat” attribute as “identity” plots and displays the data as it is. The graph can also be annotated with displayed text on the top of the bars to plot the data as it is.
Syntax:
geom_text(aes(label = ), vjust )
The label can be assigned the value of the column to assign the value to each bar of the plot corresponding to each bar value.
Example:
R
library("ggplot") # creating a data framedata_frame <- data.frame(col1 = sample(letters[1:10]), col2 = 1:10, col3 = 1)# printing the data frameprint ("Original DataFrame")print (data_frame) # plotting a barplot with countsggplot(data_frame, aes(x = col1, y = col2, fill = col1)) + geom_bar(stat = "identity") + geom_text(aes(label = col2), vjust = 0)
Output
[1] "Original DataFrame"
col1 col2 col3
1 j 1 1
2 d 2 1
3 b 3 1
4 a 4 1
5 g 5 1
6 e 6 1
7 f 7 1
8 i 8 1
9 c 9 1
10 h 10 1
Similarly, percentages can be added to the plot, but in this case, the legend will be continuous, not discrete.
Example:
R
# importing the required librarieslibrary("ggplot")library("scales")library("dplyr") # creating a data framedata_frame <- data.frame(col1 = sample(letters[1:10]), col2 = 1:10 )# printing the data frameprint ("Original DataFrame")print (data_frame) # plotting a barplot with percentagesdata_frame %>% count(col1 = factor(col1), col2 = col2) %>% mutate(col4 = prop.table(col2)) %>% ggplot(aes(x = col1, y = col4, fill = col2, label = scales::percent(col4))) + geom_col(position = 'dodge') + geom_text( vjust = 0) + scale_y_continuous(labels = scales::percent)
Output
[1] "Original DataFrame"
col1 col2
1 g 1
2 d 2
3 j 3
4 f 4
5 i 5
6 e 6
7 h 7
8 a 8
9 c 9
10 b 10
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
Control Statements in R Programming
How to import an Excel File into R ?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
|
[
{
"code": null,
"e": 25162,
"s": 25134,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 25279,
"s": 25162,
"text": "In this article, we will discuss how to add percentage or count above percentage bar plot in R programming language."
},
{
"code": null,
"e": 25606,
"s": 25279,
"text": "The ggplot() method of this package is used to initialize a ggplot object. It can be used to declare the input data frame for a graphic and can also be used to specify the set of plot aesthetics. The ggplot() function is used to construct the initial plot object and is almost always followed by components to add to the plot."
},
{
"code": null,
"e": 25614,
"s": 25606,
"text": "Syntax:"
},
{
"code": null,
"e": 25644,
"s": 25614,
"text": "ggplot(data, mapping = aes())"
},
{
"code": null,
"e": 25656,
"s": 25644,
"text": "Parameter :"
},
{
"code": null,
"e": 25701,
"s": 25656,
"text": "data – The data frame used for data plotting"
},
{
"code": null,
"e": 25763,
"s": 25701,
"text": "mapping – Default list of aesthetic mappings to use for plot."
},
{
"code": null,
"e": 25802,
"s": 25763,
"text": "geom_bar() is used to draw a bar plot."
},
{
"code": null,
"e": 26092,
"s": 25802,
"text": "The geom_bar() method is used which plots a number of cases appearing in each group against each bar value. Using the “stat” attribute as “identity” plots and displays the data as it is. The graph can also be annotated with displayed text on the top of the bars to plot the data as it is. "
},
{
"code": null,
"e": 26100,
"s": 26092,
"text": "Syntax:"
},
{
"code": null,
"e": 26133,
"s": 26100,
"text": "geom_text(aes(label = ), vjust )"
},
{
"code": null,
"e": 26261,
"s": 26133,
"text": "The label can be assigned the value of the column to assign the value to each bar of the plot corresponding to each bar value. "
},
{
"code": null,
"e": 26270,
"s": 26261,
"text": "Example:"
},
{
"code": null,
"e": 26272,
"s": 26270,
"text": "R"
},
{
"code": "library(\"ggplot\") # creating a data framedata_frame <- data.frame(col1 = sample(letters[1:10]), col2 = 1:10, col3 = 1)# printing the data frameprint (\"Original DataFrame\")print (data_frame) # plotting a barplot with countsggplot(data_frame, aes(x = col1, y = col2, fill = col1)) + geom_bar(stat = \"identity\") + geom_text(aes(label = col2), vjust = 0)",
"e": 26676,
"s": 26272,
"text": null
},
{
"code": null,
"e": 26683,
"s": 26676,
"text": "Output"
},
{
"code": null,
"e": 26917,
"s": 26683,
"text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1 j 1 1 \n2 d 2 1 \n3 b 3 1 \n4 a 4 1 \n5 g 5 1 \n6 e 6 1 \n7 f 7 1 \n8 i 8 1 \n9 c 9 1 \n10 h 10 1"
},
{
"code": null,
"e": 27029,
"s": 26917,
"text": "Similarly, percentages can be added to the plot, but in this case, the legend will be continuous, not discrete."
},
{
"code": null,
"e": 27038,
"s": 27029,
"text": "Example:"
},
{
"code": null,
"e": 27040,
"s": 27038,
"text": "R"
},
{
"code": "# importing the required librarieslibrary(\"ggplot\")library(\"scales\")library(\"dplyr\") # creating a data framedata_frame <- data.frame(col1 = sample(letters[1:10]), col2 = 1:10 )# printing the data frameprint (\"Original DataFrame\")print (data_frame) # plotting a barplot with percentagesdata_frame %>% count(col1 = factor(col1), col2 = col2) %>% mutate(col4 = prop.table(col2)) %>% ggplot(aes(x = col1, y = col4, fill = col2, label = scales::percent(col4))) + geom_col(position = 'dodge') + geom_text( vjust = 0) + scale_y_continuous(labels = scales::percent)",
"e": 27660,
"s": 27040,
"text": null
},
{
"code": null,
"e": 27667,
"s": 27660,
"text": "Output"
},
{
"code": null,
"e": 27843,
"s": 27667,
"text": "[1] \"Original DataFrame\" \ncol1 col2 \n1 g 1 \n2 d 2 \n3 j 3 \n4 f 4 \n5 i 5 \n6 e 6 \n7 h 7 \n8 a 8 \n9 c 9 \n10 b 10"
},
{
"code": null,
"e": 27850,
"s": 27843,
"text": "Picked"
},
{
"code": null,
"e": 27859,
"s": 27850,
"text": "R-ggplot"
},
{
"code": null,
"e": 27870,
"s": 27859,
"text": "R Language"
},
{
"code": null,
"e": 27968,
"s": 27870,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27977,
"s": 27968,
"text": "Comments"
},
{
"code": null,
"e": 27990,
"s": 27977,
"text": "Old Comments"
},
{
"code": null,
"e": 28042,
"s": 27990,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28066,
"s": 28042,
"text": "Data Visualization in R"
},
{
"code": null,
"e": 28104,
"s": 28066,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28139,
"s": 28104,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28176,
"s": 28139,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 28234,
"s": 28176,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28270,
"s": 28234,
"text": "Control Statements in R Programming"
},
{
"code": null,
"e": 28307,
"s": 28270,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 28350,
"s": 28307,
"text": "Replace Specific Characters in String in R"
}
] |
Production Machine Learning Monitoring: Outliers, Drift, Explainers & Statistical Performance | by Alejandro Saucedo | Towards Data Science
|
“The lifecycle of a machine learning model only begins once it’s in production”
In this article we present an end-to-end example showcasing best practices, principles, patterns and techniques around monitoring of machine learning models in production. We will show how to adapt standard microservice monitoring techniques towards deployed machine learning models, as well as more advanced paradigms including concept drift, outlier detection and AI explainability.
We will train an image classification machine learning model from scratch, deploy it as a microservice in Kubernetes, and introduce a broad range of advanced monitoring components. The monitoring components will include outlier detectors, drift detectors, AI explainers and metrics servers — we will cover the underlying architectural patterns used for each, which are developed with scale in mind, and designed to work efficiently across hundreds or thousands of heterogeneous machine learning models.
You can also view this blog post in video form, which was presented as the keynote at the PyCon Hong Kong 2020 — the main delta is that the talk uses an Iris Sklearn model for the e2e example instead of the CIFAR10 Tensorflow model.
In this article we present an end-to-end hands on example covering each of the high level concepts outlined in the sections below.
Introduction to Monitoring Complex ML SystemsCIFAR10 Tensorflow Renset32 model trainingModel Packaging & DeploymentPerformance monitoringEventing Infrastructure for MonitoringStatistical monitoringOutlier detection monitoringConcept drift monitoringExplainability monitoring
Introduction to Monitoring Complex ML Systems
CIFAR10 Tensorflow Renset32 model training
Model Packaging & Deployment
Performance monitoring
Eventing Infrastructure for Monitoring
Statistical monitoring
Outlier detection monitoring
Concept drift monitoring
Explainability monitoring
We will be using the following open source frameworks in this tutorial:
Tensorflow — Widely used machine learning framework.
Alibi Explain — White-box and black-box ML model explanation library.
Albi Detect — Advanced machine learning monitoring algorithms for concept drift, outlier detection and adversarial detection.
Seldon Core — Machine learning deployment and orchestration of the models and monitoring components.
You can find the full code for this article in the jupyter notebook provided which will allow you to run all relevant steps throughout the model monitoring lifecycle.
Let’s get started.
Monitoring of production machine learning is hard, and it becomes exponentially more complex once the number of models and advanced monitoring components grows. This is partly due to how different production machine learning systems are compared to traditional software microservice-based systems — some of these key differences are outlined below.
Specialized hardware —Optimized implementation of machine learning algorithms often require access to GPUs, larger amounts of RAM, specialised TPUs/FPGAs, and other even dynamically changing requirements. This results in the need for specific configuration to ensure this specialised hardware can produce accurate usage metrics, and more importantly that these can be linked to the respective underlying algorithms.
Complex Dependency Graphs — The tools and underlying data involves complex dependencies that can span across complex graph structures. This means that the processing of a single datapoint may require stateful metric assessment across multiple hops, potentially introducing additional layers of domain-specific abstraction which may have to be taken into consideration for reliable interpretation of monitoring state.
Compliance Requirements — Production systems, especially in highly regulated environments may involve complex policies around auditing, data requirements, as well as collection of resources and artifacts at each stage of execution. Sometimes the metrics that are being displayed and analysed will have to be limited to the relevant individuals, based on the specified policies, which can vary in complexity across use-cases.
Reproducibility — On top of these complex technical requirements, there is a critical requirement around reproducibility of components, ensuring that the components that are run can be executed at another point with the same results. When it comes to monitoring, it is important that the systems are built with this in mind such that it’s possible to re-run particular machine learning executions to reproduce particular metrics, whether for monitoring or for auditing purposes.
The anatomy of production machine learning involves a broad range of complexities that range across the multiple stages of the model’s lifecycle. This includes experimentation, scoring, hyperparameter tuning, serving, offline batch, streaming and beyond. Each of these stages involve potentially different systems with a broad range of heterogeneous tools. This is why it is key to ensure we not only learn how we are able to introduce model-specific metrics to monitor, but that we identify the higher level architectural patterns that can be used to enable the deployed models to be monitored effectively at scale. This is what we will cover in each of the sections below.
We will be using the intuitive CIFAR10 dataset. This dataset consists of images that can be classified across one of 10 classes. The model will take as an input an array of shape 32x32x3 and as output an array with 10 probabilities for which of the classes it belongs to.
We are able to load the data from the Tensorflow datasets — namely:
The 10 classes include: cifar_classes = [“airplane”, “automobile”, “bird”, “cat”, “deer”, “dog”, “frog”, “horse”, “ship”, “truck”].
In order for us to train and deploy our machine learning model, we will follow the traditional machine learning workflow outlined in the diagram below. We will be training a model which we will then be able to export and deploy.
We will be using Tensorflow to train this model, leveraging the Residual Network which is arguably one of the most groundbreaking architectures as it makes it possible to train up to hundreds or even thousands of layers with good performance. For this tutorial we will be using the Resnet32 implementation, which fortunately we’ll be able to use through the utilities provided by the Alibi Detect Package.
Using my GPU this model took about 5 hours to train, luckily we will be able to use a pre-trained model which can be retrieved using the Alibi Detect fetch_tf_model utils.
If you want to still train the CIFAR10 resnet32 tensorflow model, you can use the helper utilities provided by the Alibi Detect package as outlined below, or even just import the raw Network and train it yourself.
We can now test the trained model on “unseen data”. We can test it using a CIFAR10 datapoint that would be classified as a truck. We can have a look at the datapoint by plotting it using Matplotlib.
We can now process that datapoint through the model, which as you can imagine should be predicted as a “truck”.
We can find the class predicted by finding the index with the highest probability, which in this case it is index 9with a high probability of 99%. From the names of the classes (e.g. cifar_classes[ np.argmax( X_curr_pred )]) we can see that class 9 is “truck”.
We will be using Seldon Core for the deployment of our model into Kubernetes, which provides multiple options to convert our model into a fully fledged microservice exposing REST, GRPC and Kafka interfaces.
The options we have to deploy models with Seldon Core include 1) the Language Wrappers to deploy our Python, Java, R, etc code classes, or 2) the Prepackaged Model Servers to deploy model artifacts directly. In this tutorial we will be using the Tensorflow Prepackaged Model server to deploy the Resnet32 model we were using earlier.
This approach will allow us to take advantage of the cloud native architecture of Kubernetes which powers large scale microservice systems through horizontally scalable infrastructure. We will be able to learn about and leverage cloud native and microservice patterns adopted to machine learning throughout this tutorial.
The diagram below summarises the options available to deploy model artifacts or the code itself, together with the abilities we have to deploy either a single model, or build complex inference graphs.
As a side note, you can get set up you on Kubernetes using a development environment like KIND (Kubernetes in Docker) or Minikube, and then following the instructions in the Notebook for this example, or in the Seldon documentation. You will need to make sure you install Seldon with a respective ingress provider like Istio or Ambassador so you can send the REST requests.
To simplify the tutorial, we have already uploaded the trained Tensorflow Resnet32 model, which can be found this public Google bucket: gs://seldon-models/tfserving/cifar10/resnet32. If you have trained your model, you are able to upload it to the bucket of your choice, which can be Google Bucket, Azure, S3 or local Minio. Specifically for Google you can do it using the gsutil command line with the command below:
We can deploy our model with Seldon using the custom resource definition configuration file. Below is the script that converts the model artifact into a fully fledged microservice.
We can now see that the model has been deployed and is currently running.
$ kubectl get pods | grep cifarcifar10-default-0-resnet32-6dc5f5777-sq765 2/2 Running 0 4m50s
We can now test our deployed model by sending the same image of the truck, and see if we still have the same prediction.
We will be able to do this by sending a REST request as outlined below, and then print the results.
The output of the code above is the JSON response of the POST request to the url that Seldon Core provides us through the ingress. We can see that the prediction is correctly resulting in the “truck” class.
{'predictions': [[1.26448288e-06, 4.88144e-09, 1.51532642e-09, 8.49054249e-09, 5.51306611e-10, 1.16171261e-09, 5.77286274e-10, 2.88394716e-07, 0.00061489339, 0.999383569]]}Prediction: truck
The first monitoring pillar we will be covering is the good old performance monitoring, which is the traditional and standard monitoring features that you would find in the microservices and infrastructure world. Of course in our case we will be adopting it towards deployed machine learning models.
Some high level principles of machine learning monitoring include:
Monitoring the performance of the running ML service
Identifying potential bottlenecks or runtime red flags
Debugging and diagnosing unexpected performance of ML services
For this we will be able to introduce the first two core frameworks which are commonly used across production systems:
Elasticsearch for logs — A document key-value store that is commonly used to store the logs from containers, which can then be used to diagnose errors through stack traces or information logs. In the case of machine learning we don’t only use it to store logs but also to store pre-processed inputs and outputs of machine learning models for further processing.
Prometheus for metrics —A time-series store that is commonly used to store real-time metrics data, which can then be visusalised leveraging tools like Grafana.
Seldon Core provides integration with Prometheus and Elasticsearch out of the box for any model deployed. During this tutorial we will be referencing Elasticsearch but to simplify the intuitive grasp of several advanced monitoring concepts we will be using mainly Prometheus for metrics and Grafana for the visualisations.
In the diagram below you can visualise how the exported microservice enables any containerised model to export both metrics and logs. The metrics are scraped by prometheus, and the logs are forwarded by the model into elasticsearch (which happens through the eventing infrastructure we cover in the next section. For explicitness it is worth mentioning that Seldon Core also supports Open Tracing metrics using Jaeger, which shows the latency throughout all microservice hops in the Seldon Core model graph.
Some examples of performance monitoring metrics that are exposed by Seldon Core models, and that can be also added through further integrations include:
Requests per second
Latency per request
CPU/memory/data utilisation
Custom application metrics
For this tutorial you can set up Prometheus and Grafana by using the Seldon Core Analytics package that sets everything up for metrics to be collected in real time, and then visualised on the dashboards.
We can now visualise the utilization metrics of the deployed models relative to their specific infrastructure. When deploying a model with Seldon you will have multiple attributes that you will want to take into consideration to ensure optimal processing of your models. This includes the allocated CPU, Memory and Filesystem store reserved for the application, but also the respective configuration for running processes and threads relative to the allocated resources and expected requests.
Similarly, we are also able to monitor the usage of the model itself — every seldon model exposes model usage metrics such as requests-per-second, latency per request, success/error codes for models, etc. These are important as they are able to map into the mode advanced/specialised concepts of the underlying machine learning model. Large latency spikes could be diagnosed and explained based on the underlying requirements of the model. Similarly errors that the model displays are abstracted into simple HTTP error codes, which allows for standardisation of advanced ML components into microservice patterns that then can be managed more easily at scale by DevOps / IT managers.
In order for us to be able to leverage the more advanced monitoring techniques, we will first introduce briefly the eventing infrastructure that allows Seldon to use advanced ML algorithms for monitoring of data asynchronously and in a scalable architecture.
Seldon Core leverages KNative Eventing to enable Machine Learning models to forward the inputs and outputs of the model into the more advanced machine learning monitoring components like outlier detectors, concept drift detectors, etc.
We will not be going into too much detail on the eventing infrastructure that KNative introduces, but if you are curious there are multiple hands on examples in the Seldon Core documentation in regards to how it leverages the KNative Eventing infrastructure to forward payloads to further components such as Elasticsearch, as well as how Seldon models can also be connected to process events.
For this tutorial, we need to enable our model to forward all the payload inputs and ouputs processed by the model into the KNative Eventing broker, which will enable all other advanced monitoring components to subscribe to these events.
The code below adds a “logger” attribute to the deployment configuration which specifies the broker location.
Performance metrics are useful for general monitoring of microservices, however for the specialised world of machine learning, there are widely-known and widely-used metrics that are critical throughout the lifecycle of the model beyond the training phase. More common metrics can include accuracy, precision, recall, but also metrics like RMSE, KL Divergence, between many many more.
The core theme of this article is not just to specify how these metrics can be calculated, as it’s not an arduous task to enable an individual microservice to expose this through some Flask-wrapper magic. The key here is to identify scalable architectural patterns that we can introduce across hundreds or thousands of models. This means that we require a level of standardisation on the interfaces and patterns that are required to map the models into their relevant infrastructure.
Some high level principles that revolve around more specialised machine learning metrics are the following:
Monitoring specific to statistical ML performance
Benchmarking multiple different models or different versions
Specialised for the data-type and the input/output format
Stateful asynchronous provisioning of “feedback” on previous requests (such as “annotations” or “corrections”)
Given that we have these requirements, Seldon Core introduces a set of architectural patterns that allow us to introduce the concept of “Extensible Metrics Servers”. These metric servers contain out-of-the-box ways to process data that the model processes by subscribing to the respective eventing topics, to ultimately expose metrics such as:
Raw metrics: True-Positives, True-Negatives, False-Positives, False-Negatives
Basic metrics: Accuracy, precision, recall, specificity
Specialised metrics: KL Divergence, RMSE, etc
Breakdowns per class, features, and other metadata
From an architectural perspective, this can be visualised more intuitively in the diagram above. This showcases how a single datapoint can be submitted through the model, and then processed by any respective Metric Servers. The metric servers can also process the “correct/annotated” labels once they are provided, which can be linked with the unique prediction ID that Seldon Core adds on every request. The specialised metrics are calculated and exposed by fetching the relevant data from the Elasticsearch store.
Currently, Seldon Core provides the following set of out-of-the-box Metrics Servers:
BinaryClassification — Processes data in the form of binary classifications (e.g. 0 or 1) to expose raw metrics to show basic statistical metrics (accuracy, precision, recall and specificity).
MultiClassOneHot — Processes data in the form of one hot predictions for classification tasks (e.g. [0, 0, 1] or [0, 0.2, 0.8]), which can then expose raw metrics to show basic statistical metrics.
MultiClassNumeric — Processes data in the form of numeric datapoints for classification tasks (e.g. 1, or [1]), which can then expose raw metrics to show basic statistical metrics.
For this example we will be able to deploy a Metric Server of the type “MulticlassOneHot” — you can see the parameters used in the summarised code below, but you can find the full YAML in the jupyter notebook.
Once we deploy our metrics server, we can now just send requests and feedback to our CIFAR10 model, through the same microservice endpoint. To simplify the workflow, we will not send asynchronous feedback (which would perform the comparisons with the elasticsearch data), but instead we’ll send “self-contained” feedback requests, which contain the inference “response” and the inference “truth”.
The following function provides us with a way to send a bunch of feedback requests to achieve an approximate accuracy percent (number of correct vs incorrect predictions) for our usecase.
Now we can first send feedback to get 90% accuracy, and then to make sure our graphs look pretty, we can send another batch request that would result in 40% accuracy.
This now basically gives us the ability to visualise the metrics that the MetricsServer calculates in real time.
From the dashboard above we can get a high level intuition of the type of metrics that we are able to get through this architectural pattern. The stateful statistical metrics above in particular require extra metadata to be provided asynchronously, however even though the metrics themselves may have very different ways of being calculated, we can see that the infrastructural and architectural requirements can be abstracted and standardised in order for these to be approached in a more scalable way.
We will continue seeing this pattern as we delve further into the more advanced statistical monitoring techniques.
For a more advanced monitoring technique, we will be leveraging the Alibi Detect library, particularly around some of the advanced outlier detector algorithms it provides. Seldon Core provides us with a way to perform the deployment of outlier detectors as an architectural pattern, but also provides us with a prepackaged server that is optimized to serve Alibi Detect outlier detector models.
Some of the key principles for outlier detection include:
Detecting anomalies in data instances
Flagging / alerting when outliers take place
Identifying potential metadata that could help diagnose outliers
Enable drill down of outliers that are identified
Enabling for continuous / automated retraining of detectors
In the case of outlier detectors it is especially important to allow for the calculations to be performed separate to the model, as these tend to be much heaver and may require more specialised components. An outlier detector that is deployed, may come with similar complexities to the ones from a machine learning model, so it’s important that the same concepts of compliance, governance and lineage are covered with these advanced components.
The diagram below shows how the requests are forwarded by the model using the eventing infrastructure. The outlier detector then processes the datapoint to calculate whether it’s an outlier. The component is then able to store the outlier data in the respective request entry asynchronously, or alternatively it is able to expose the metrics to prometheus, which is what we will visualise in this section.
For this example we will be using the Alibi Detect Variational Auto Encoder outlier detector technique. The outlier detector is trained on a batch of unlabeled but normal (inlier) data. The VAE detector tries to reconstruct the input it receives, if the input data cannot be reconstructed well, then it is flagged as an outlier.
Alibi Detect provides us with utilities that allow us to export the outlier detector from scratch. We can fetch it using the fetch_detector function.
If you want to train the outlier, you can do so by simply leveraging the OutlierVAE class together with the respective encoder and decoders.
To test the outlier detector we can take the same picture of the truck and see how the outlier detector behaves if noise is added to the image increasingly. We will also be able to plot it using the Alibi Detect visualisation function plot_feature_outlier_image.
We can create a set of modified images and run it through the outlier detector using the code below.
We now have an array of modified samples in the variable all_X_mask , each with an increasing amount of noise. We can now run all these 10 through the outlier detector.
When looking at the results, we can see that the first 3 were not marked as outliers, whereas the rest were marked as outliers — we can see it by printing the value print(od_preds[“data”][“is_outlier”]). Which displays the array below, where 0 is non-outliers and 1 is outliers.
array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1])
We can now visualise how the outlier instance level score maps against the threshold, which reflects the results in the array above.
Similarly we can dive deeper into the intuition of what the outlier detector score channels look like, as well as the reconstructed images, which should provide a clear picture of how its internals operate.
We will now be able to productionise our outlier detector. We will be leveraging a similar architectural pattern to the one from the metric servers. Namely the Alibi Detect Seldon Core server, which will be listening to the inference input/output of the data. For every data point that goes through the model, the respective outlier detector will be able to process it.
The main step required will be to first ensure the outlier detector we trained above is uploaded to an object store like Google bucket. We have already uploaded it to gs://seldon-models/alibi-detect/od/OutlierVAE/cifar10, but if you wish you can upload it and use your own model.
Once we deploy our outlier detector, we will be able to send a bunch of requests, many which will be outliers and others that won’t be.
We can now visualise some outliers in the dashboard — for every data point there will be a new entry point and will include whether it would be an outlier or not.
As time passes, data in real life production environments can change. Whilst this change is not drastic, it can be identified through drifts in the distribution of the data itself particularly in respect to the predicted outputs of the model.
Key principles in drift detection include:
Identifying drift in data distribution, as well as drifts in the relationship between input and output data from a model
Flagging drift that is found together with the relevant datapoints where it was identified
Allowing for the ability to drill down into the data that was used to calculate the drift
In the concept of drift detection we deal with further complexities when compared to the outlier detection usecase. The main one being the requirement to run each drift prediction on a batch input as opposed to a single datapoint. The diagram below shows a similar workflow to the one outlied in the outlier detector pattern, the main difference is that it keeps a tumbling or sliding window of data to perform the processing against.
For this example we will once again be using the Alibi Detect library, which provides us with the Kolmogorov-Smirnov data drift detector on CIFAR-10.
For this technique will be able to use the KSDrift class to create and train the drift detector, which also requires a preprocessing step which uses an “Untrained Autoencoder (UAE)”.
In order for us to test the outlier detector we will generate a set of detectors with corrupted data. Alibi Detect provides a great set of utilities that we can use to generate corruption/noise into images in an increasing way. In this case we will be using the following noise: [‘gaussian_noise’, ‘motion_blur’, ‘brightness’, ‘pixelate’]. These will be generated with the code below.
Below is one datapoint from the created corrupted dataset, which contains images with an increasing amount of corruption of the different types outlined above.
We can now attempt to run a couple of datapoints to compute whether drift is detected or not. The initial batch will consist of datapoints from the original dataset.
This as expected outputs: Drift? No!
Similarly we can run it against the corrupted dataset.
And we can see that all of them are marked as drift as expected:
Corruption type: gaussian_noiseDrift? Yes!Corruption type: motion_blurDrift? Yes!Corruption type: brightnessDrift? Yes!Corruption type: pixelateDrift? Yes!
Now we can move towards deploying our drift detector following the architectural pattern provided above. Similar to the outlier detector we first have to make sure that the drift detector we trained above can be uploaded to an object store. We currently will be able to use the Google bucket that we have prepared under gs://seldon-models/alibi-detect/cd/ks/drift to perform the deployment.
This will have a similar structure, the main difference is that we will also specify the desired batch size to use for the Alibi Detect server to keep as a buffer before running against the model. In this case we select a batch size of 1000.
Now that we have deployerd our outlier detector, we first try sending 1000 requests from the normal dataset.
Next we can send the corrupted data, which would result in drift detected after sending the 10k datapoints.
We are able to visualise each of the different drift points detected in the Grafana dashboard.
AI Explainability techniques are key to understanding the behaviour of complex black box machine learning models. There is a broad range of content that explores the different algorithmic techniques that can be used in different contexts. Our current focus in this context is to provide an intuition and a practical example of the architectural patterns that can allow for explainer components to be deployed at scale. Some key principles of model explainability include:
Human-interpretable insights for model behaviour
Introducing use-case-specific explainability capabilities
Identifying key metrics such as trust scores or statistical perf. thresholds
Enabling for use of some more complex ML techniques
There are a broad range of different techniques available around explainability, but it’s important to understand the high level themes around the different types of Explainers. These include:
Scope (local vs global)
Model type (black vs white box)
Task (classification, regression, etc)
Data type (tabular, images, text, etc)
Insight (feature attributions, counterfactuals, influential training instances, etc)
For explainers as interfaces, these have similarities in the data flow patterns. Namely many of them require interacting with the data that the model processes, as well as the ability to interact with the model itself — for black box techniques it includes the inputs/outputs whereas for white-box techniques it includes the internals of the models themselves.
From an architectural perspective, this involves primarily a separate microservice which instead of just receiving an inference request, it would be able to interact with the respective model and “reverse engineer” the model by sending the relevant data. This is shown in the diagram above, but it will become more intuitive once we dive into the example.
For the example, we will be using the Alibi Explain framework, and we will use the Anchor Explanation technique. This local explanation technique tells us what are the features in a particular data point with the highest predictive power.
We can simply create our Anchor explainer by specifying the structure of our dataset, together with a lambda that allows the explainer to interact with the model’s predict function.
We are able to identify what are the anchors in our model that would predict in this case the image of the truck.
We can visualise the anchors by displaying the output anchor of the explanation itself.
We can see that the anchors of the image include the windshield and the wheels of the truck.
Here you can see that the explainer interacts with our deployed model. When deploying the explainer we will be following the same principle but instead of using a lambda that runs the model locally, this will be a function that will call the remote model microservice.
We will follow a similar approach where we’ll just need to upload the image above to an object store bucket. Similar to the previous example, we have provided a bucket under gs://seldon-models/tfserving/cifar10/explainer-py36–0.5.2. We will now be able to deploy an explainer, which can be deployed as part of the CRD of the Seldon Deployment.
We can check that the explainer is running with kubectl get pods | grep cifar , which should output both running pods:
cifar10-default-0-resnet32-6dc5f5777-sq765 2/2 Running 0 18mcifar10-default-explainer-56cd6c76cd-mwjcp 1/1 Running 0 5m3s
Similar to how we send a request to the model, we are able to send a request to the explainer path. This is where the explainer will interact with the model itself and print the reverse engineered explanation.
We can see that the output of the explanation is the same as the one we saw above.
Finally we can also see some of the metric related components that come out of the explainer themselves, which can then be visualised through dashboards.
Coverage: 0.2475Precision: 1.0
Similar to the other microservice based machine learning components deployed, the explainers also can expose these and other more specialised metrics for performance or advanced monitoring.
Before wrapping up, one thing to outline is the importance of abstracting these advanced machine learning concepts into standardised architectural patterns. The reason why this is crucial is primarily to enable machine learning systems for scale, but also to allow for advanced integration of components across the stack.
All the advanced architectures covered above not only are applicable across each of the advanced components, but it is also possible to enable for what we can refer to as “ensemble patterns” — that is, connecting advanced components on the outputs of other advanced components.
It is also important to ensure there are structured and standardised architectural patterns also enable developers to provide the monitoring components, which are also advanced machine learning models, have the same level of governance, compliance and lineage required in order to manage the risk efficiently.
These patterns are continuously being refined and evolved through the Seldon Core project, and advanced state of the art algorithms on outlier detection, concept drift, explainability, etc are improving continuously — if you are interested on furthering the discussion, please feel free to reach out. All the examples in this tutorial are open source, so suggestions are greatly appreciated.
If you are interested in further hands on examples of scalable deployment strategies of machine learning models, you can check out:
Batch Processing with Argo Workflows
Serverless eventing with Knative
AI Explainability Patterns with Alibi
Seldon Model Containerisation Notebook
Kafka Seldon Core Stream Processing Deployment Notebook
|
[
{
"code": null,
"e": 252,
"s": 172,
"text": "“The lifecycle of a machine learning model only begins once it’s in production”"
},
{
"code": null,
"e": 637,
"s": 252,
"text": "In this article we present an end-to-end example showcasing best practices, principles, patterns and techniques around monitoring of machine learning models in production. We will show how to adapt standard microservice monitoring techniques towards deployed machine learning models, as well as more advanced paradigms including concept drift, outlier detection and AI explainability."
},
{
"code": null,
"e": 1140,
"s": 637,
"text": "We will train an image classification machine learning model from scratch, deploy it as a microservice in Kubernetes, and introduce a broad range of advanced monitoring components. The monitoring components will include outlier detectors, drift detectors, AI explainers and metrics servers — we will cover the underlying architectural patterns used for each, which are developed with scale in mind, and designed to work efficiently across hundreds or thousands of heterogeneous machine learning models."
},
{
"code": null,
"e": 1373,
"s": 1140,
"text": "You can also view this blog post in video form, which was presented as the keynote at the PyCon Hong Kong 2020 — the main delta is that the talk uses an Iris Sklearn model for the e2e example instead of the CIFAR10 Tensorflow model."
},
{
"code": null,
"e": 1504,
"s": 1373,
"text": "In this article we present an end-to-end hands on example covering each of the high level concepts outlined in the sections below."
},
{
"code": null,
"e": 1779,
"s": 1504,
"text": "Introduction to Monitoring Complex ML SystemsCIFAR10 Tensorflow Renset32 model trainingModel Packaging & DeploymentPerformance monitoringEventing Infrastructure for MonitoringStatistical monitoringOutlier detection monitoringConcept drift monitoringExplainability monitoring"
},
{
"code": null,
"e": 1825,
"s": 1779,
"text": "Introduction to Monitoring Complex ML Systems"
},
{
"code": null,
"e": 1868,
"s": 1825,
"text": "CIFAR10 Tensorflow Renset32 model training"
},
{
"code": null,
"e": 1897,
"s": 1868,
"text": "Model Packaging & Deployment"
},
{
"code": null,
"e": 1920,
"s": 1897,
"text": "Performance monitoring"
},
{
"code": null,
"e": 1959,
"s": 1920,
"text": "Eventing Infrastructure for Monitoring"
},
{
"code": null,
"e": 1982,
"s": 1959,
"text": "Statistical monitoring"
},
{
"code": null,
"e": 2011,
"s": 1982,
"text": "Outlier detection monitoring"
},
{
"code": null,
"e": 2036,
"s": 2011,
"text": "Concept drift monitoring"
},
{
"code": null,
"e": 2062,
"s": 2036,
"text": "Explainability monitoring"
},
{
"code": null,
"e": 2134,
"s": 2062,
"text": "We will be using the following open source frameworks in this tutorial:"
},
{
"code": null,
"e": 2187,
"s": 2134,
"text": "Tensorflow — Widely used machine learning framework."
},
{
"code": null,
"e": 2257,
"s": 2187,
"text": "Alibi Explain — White-box and black-box ML model explanation library."
},
{
"code": null,
"e": 2383,
"s": 2257,
"text": "Albi Detect — Advanced machine learning monitoring algorithms for concept drift, outlier detection and adversarial detection."
},
{
"code": null,
"e": 2484,
"s": 2383,
"text": "Seldon Core — Machine learning deployment and orchestration of the models and monitoring components."
},
{
"code": null,
"e": 2651,
"s": 2484,
"text": "You can find the full code for this article in the jupyter notebook provided which will allow you to run all relevant steps throughout the model monitoring lifecycle."
},
{
"code": null,
"e": 2670,
"s": 2651,
"text": "Let’s get started."
},
{
"code": null,
"e": 3019,
"s": 2670,
"text": "Monitoring of production machine learning is hard, and it becomes exponentially more complex once the number of models and advanced monitoring components grows. This is partly due to how different production machine learning systems are compared to traditional software microservice-based systems — some of these key differences are outlined below."
},
{
"code": null,
"e": 3435,
"s": 3019,
"text": "Specialized hardware —Optimized implementation of machine learning algorithms often require access to GPUs, larger amounts of RAM, specialised TPUs/FPGAs, and other even dynamically changing requirements. This results in the need for specific configuration to ensure this specialised hardware can produce accurate usage metrics, and more importantly that these can be linked to the respective underlying algorithms."
},
{
"code": null,
"e": 3852,
"s": 3435,
"text": "Complex Dependency Graphs — The tools and underlying data involves complex dependencies that can span across complex graph structures. This means that the processing of a single datapoint may require stateful metric assessment across multiple hops, potentially introducing additional layers of domain-specific abstraction which may have to be taken into consideration for reliable interpretation of monitoring state."
},
{
"code": null,
"e": 4277,
"s": 3852,
"text": "Compliance Requirements — Production systems, especially in highly regulated environments may involve complex policies around auditing, data requirements, as well as collection of resources and artifacts at each stage of execution. Sometimes the metrics that are being displayed and analysed will have to be limited to the relevant individuals, based on the specified policies, which can vary in complexity across use-cases."
},
{
"code": null,
"e": 4756,
"s": 4277,
"text": "Reproducibility — On top of these complex technical requirements, there is a critical requirement around reproducibility of components, ensuring that the components that are run can be executed at another point with the same results. When it comes to monitoring, it is important that the systems are built with this in mind such that it’s possible to re-run particular machine learning executions to reproduce particular metrics, whether for monitoring or for auditing purposes."
},
{
"code": null,
"e": 5431,
"s": 4756,
"text": "The anatomy of production machine learning involves a broad range of complexities that range across the multiple stages of the model’s lifecycle. This includes experimentation, scoring, hyperparameter tuning, serving, offline batch, streaming and beyond. Each of these stages involve potentially different systems with a broad range of heterogeneous tools. This is why it is key to ensure we not only learn how we are able to introduce model-specific metrics to monitor, but that we identify the higher level architectural patterns that can be used to enable the deployed models to be monitored effectively at scale. This is what we will cover in each of the sections below."
},
{
"code": null,
"e": 5703,
"s": 5431,
"text": "We will be using the intuitive CIFAR10 dataset. This dataset consists of images that can be classified across one of 10 classes. The model will take as an input an array of shape 32x32x3 and as output an array with 10 probabilities for which of the classes it belongs to."
},
{
"code": null,
"e": 5771,
"s": 5703,
"text": "We are able to load the data from the Tensorflow datasets — namely:"
},
{
"code": null,
"e": 5903,
"s": 5771,
"text": "The 10 classes include: cifar_classes = [“airplane”, “automobile”, “bird”, “cat”, “deer”, “dog”, “frog”, “horse”, “ship”, “truck”]."
},
{
"code": null,
"e": 6132,
"s": 5903,
"text": "In order for us to train and deploy our machine learning model, we will follow the traditional machine learning workflow outlined in the diagram below. We will be training a model which we will then be able to export and deploy."
},
{
"code": null,
"e": 6538,
"s": 6132,
"text": "We will be using Tensorflow to train this model, leveraging the Residual Network which is arguably one of the most groundbreaking architectures as it makes it possible to train up to hundreds or even thousands of layers with good performance. For this tutorial we will be using the Resnet32 implementation, which fortunately we’ll be able to use through the utilities provided by the Alibi Detect Package."
},
{
"code": null,
"e": 6710,
"s": 6538,
"text": "Using my GPU this model took about 5 hours to train, luckily we will be able to use a pre-trained model which can be retrieved using the Alibi Detect fetch_tf_model utils."
},
{
"code": null,
"e": 6924,
"s": 6710,
"text": "If you want to still train the CIFAR10 resnet32 tensorflow model, you can use the helper utilities provided by the Alibi Detect package as outlined below, or even just import the raw Network and train it yourself."
},
{
"code": null,
"e": 7123,
"s": 6924,
"text": "We can now test the trained model on “unseen data”. We can test it using a CIFAR10 datapoint that would be classified as a truck. We can have a look at the datapoint by plotting it using Matplotlib."
},
{
"code": null,
"e": 7235,
"s": 7123,
"text": "We can now process that datapoint through the model, which as you can imagine should be predicted as a “truck”."
},
{
"code": null,
"e": 7496,
"s": 7235,
"text": "We can find the class predicted by finding the index with the highest probability, which in this case it is index 9with a high probability of 99%. From the names of the classes (e.g. cifar_classes[ np.argmax( X_curr_pred )]) we can see that class 9 is “truck”."
},
{
"code": null,
"e": 7703,
"s": 7496,
"text": "We will be using Seldon Core for the deployment of our model into Kubernetes, which provides multiple options to convert our model into a fully fledged microservice exposing REST, GRPC and Kafka interfaces."
},
{
"code": null,
"e": 8037,
"s": 7703,
"text": "The options we have to deploy models with Seldon Core include 1) the Language Wrappers to deploy our Python, Java, R, etc code classes, or 2) the Prepackaged Model Servers to deploy model artifacts directly. In this tutorial we will be using the Tensorflow Prepackaged Model server to deploy the Resnet32 model we were using earlier."
},
{
"code": null,
"e": 8359,
"s": 8037,
"text": "This approach will allow us to take advantage of the cloud native architecture of Kubernetes which powers large scale microservice systems through horizontally scalable infrastructure. We will be able to learn about and leverage cloud native and microservice patterns adopted to machine learning throughout this tutorial."
},
{
"code": null,
"e": 8560,
"s": 8359,
"text": "The diagram below summarises the options available to deploy model artifacts or the code itself, together with the abilities we have to deploy either a single model, or build complex inference graphs."
},
{
"code": null,
"e": 8934,
"s": 8560,
"text": "As a side note, you can get set up you on Kubernetes using a development environment like KIND (Kubernetes in Docker) or Minikube, and then following the instructions in the Notebook for this example, or in the Seldon documentation. You will need to make sure you install Seldon with a respective ingress provider like Istio or Ambassador so you can send the REST requests."
},
{
"code": null,
"e": 9351,
"s": 8934,
"text": "To simplify the tutorial, we have already uploaded the trained Tensorflow Resnet32 model, which can be found this public Google bucket: gs://seldon-models/tfserving/cifar10/resnet32. If you have trained your model, you are able to upload it to the bucket of your choice, which can be Google Bucket, Azure, S3 or local Minio. Specifically for Google you can do it using the gsutil command line with the command below:"
},
{
"code": null,
"e": 9532,
"s": 9351,
"text": "We can deploy our model with Seldon using the custom resource definition configuration file. Below is the script that converts the model artifact into a fully fledged microservice."
},
{
"code": null,
"e": 9606,
"s": 9532,
"text": "We can now see that the model has been deployed and is currently running."
},
{
"code": null,
"e": 9717,
"s": 9606,
"text": "$ kubectl get pods | grep cifarcifar10-default-0-resnet32-6dc5f5777-sq765 2/2 Running 0 4m50s"
},
{
"code": null,
"e": 9838,
"s": 9717,
"text": "We can now test our deployed model by sending the same image of the truck, and see if we still have the same prediction."
},
{
"code": null,
"e": 9938,
"s": 9838,
"text": "We will be able to do this by sending a REST request as outlined below, and then print the results."
},
{
"code": null,
"e": 10145,
"s": 9938,
"text": "The output of the code above is the JSON response of the POST request to the url that Seldon Core provides us through the ingress. We can see that the prediction is correctly resulting in the “truck” class."
},
{
"code": null,
"e": 10335,
"s": 10145,
"text": "{'predictions': [[1.26448288e-06, 4.88144e-09, 1.51532642e-09, 8.49054249e-09, 5.51306611e-10, 1.16171261e-09, 5.77286274e-10, 2.88394716e-07, 0.00061489339, 0.999383569]]}Prediction: truck"
},
{
"code": null,
"e": 10635,
"s": 10335,
"text": "The first monitoring pillar we will be covering is the good old performance monitoring, which is the traditional and standard monitoring features that you would find in the microservices and infrastructure world. Of course in our case we will be adopting it towards deployed machine learning models."
},
{
"code": null,
"e": 10702,
"s": 10635,
"text": "Some high level principles of machine learning monitoring include:"
},
{
"code": null,
"e": 10755,
"s": 10702,
"text": "Monitoring the performance of the running ML service"
},
{
"code": null,
"e": 10810,
"s": 10755,
"text": "Identifying potential bottlenecks or runtime red flags"
},
{
"code": null,
"e": 10873,
"s": 10810,
"text": "Debugging and diagnosing unexpected performance of ML services"
},
{
"code": null,
"e": 10992,
"s": 10873,
"text": "For this we will be able to introduce the first two core frameworks which are commonly used across production systems:"
},
{
"code": null,
"e": 11354,
"s": 10992,
"text": "Elasticsearch for logs — A document key-value store that is commonly used to store the logs from containers, which can then be used to diagnose errors through stack traces or information logs. In the case of machine learning we don’t only use it to store logs but also to store pre-processed inputs and outputs of machine learning models for further processing."
},
{
"code": null,
"e": 11514,
"s": 11354,
"text": "Prometheus for metrics —A time-series store that is commonly used to store real-time metrics data, which can then be visusalised leveraging tools like Grafana."
},
{
"code": null,
"e": 11837,
"s": 11514,
"text": "Seldon Core provides integration with Prometheus and Elasticsearch out of the box for any model deployed. During this tutorial we will be referencing Elasticsearch but to simplify the intuitive grasp of several advanced monitoring concepts we will be using mainly Prometheus for metrics and Grafana for the visualisations."
},
{
"code": null,
"e": 12345,
"s": 11837,
"text": "In the diagram below you can visualise how the exported microservice enables any containerised model to export both metrics and logs. The metrics are scraped by prometheus, and the logs are forwarded by the model into elasticsearch (which happens through the eventing infrastructure we cover in the next section. For explicitness it is worth mentioning that Seldon Core also supports Open Tracing metrics using Jaeger, which shows the latency throughout all microservice hops in the Seldon Core model graph."
},
{
"code": null,
"e": 12498,
"s": 12345,
"text": "Some examples of performance monitoring metrics that are exposed by Seldon Core models, and that can be also added through further integrations include:"
},
{
"code": null,
"e": 12518,
"s": 12498,
"text": "Requests per second"
},
{
"code": null,
"e": 12538,
"s": 12518,
"text": "Latency per request"
},
{
"code": null,
"e": 12566,
"s": 12538,
"text": "CPU/memory/data utilisation"
},
{
"code": null,
"e": 12593,
"s": 12566,
"text": "Custom application metrics"
},
{
"code": null,
"e": 12797,
"s": 12593,
"text": "For this tutorial you can set up Prometheus and Grafana by using the Seldon Core Analytics package that sets everything up for metrics to be collected in real time, and then visualised on the dashboards."
},
{
"code": null,
"e": 13290,
"s": 12797,
"text": "We can now visualise the utilization metrics of the deployed models relative to their specific infrastructure. When deploying a model with Seldon you will have multiple attributes that you will want to take into consideration to ensure optimal processing of your models. This includes the allocated CPU, Memory and Filesystem store reserved for the application, but also the respective configuration for running processes and threads relative to the allocated resources and expected requests."
},
{
"code": null,
"e": 13973,
"s": 13290,
"text": "Similarly, we are also able to monitor the usage of the model itself — every seldon model exposes model usage metrics such as requests-per-second, latency per request, success/error codes for models, etc. These are important as they are able to map into the mode advanced/specialised concepts of the underlying machine learning model. Large latency spikes could be diagnosed and explained based on the underlying requirements of the model. Similarly errors that the model displays are abstracted into simple HTTP error codes, which allows for standardisation of advanced ML components into microservice patterns that then can be managed more easily at scale by DevOps / IT managers."
},
{
"code": null,
"e": 14232,
"s": 13973,
"text": "In order for us to be able to leverage the more advanced monitoring techniques, we will first introduce briefly the eventing infrastructure that allows Seldon to use advanced ML algorithms for monitoring of data asynchronously and in a scalable architecture."
},
{
"code": null,
"e": 14468,
"s": 14232,
"text": "Seldon Core leverages KNative Eventing to enable Machine Learning models to forward the inputs and outputs of the model into the more advanced machine learning monitoring components like outlier detectors, concept drift detectors, etc."
},
{
"code": null,
"e": 14861,
"s": 14468,
"text": "We will not be going into too much detail on the eventing infrastructure that KNative introduces, but if you are curious there are multiple hands on examples in the Seldon Core documentation in regards to how it leverages the KNative Eventing infrastructure to forward payloads to further components such as Elasticsearch, as well as how Seldon models can also be connected to process events."
},
{
"code": null,
"e": 15099,
"s": 14861,
"text": "For this tutorial, we need to enable our model to forward all the payload inputs and ouputs processed by the model into the KNative Eventing broker, which will enable all other advanced monitoring components to subscribe to these events."
},
{
"code": null,
"e": 15209,
"s": 15099,
"text": "The code below adds a “logger” attribute to the deployment configuration which specifies the broker location."
},
{
"code": null,
"e": 15594,
"s": 15209,
"text": "Performance metrics are useful for general monitoring of microservices, however for the specialised world of machine learning, there are widely-known and widely-used metrics that are critical throughout the lifecycle of the model beyond the training phase. More common metrics can include accuracy, precision, recall, but also metrics like RMSE, KL Divergence, between many many more."
},
{
"code": null,
"e": 16078,
"s": 15594,
"text": "The core theme of this article is not just to specify how these metrics can be calculated, as it’s not an arduous task to enable an individual microservice to expose this through some Flask-wrapper magic. The key here is to identify scalable architectural patterns that we can introduce across hundreds or thousands of models. This means that we require a level of standardisation on the interfaces and patterns that are required to map the models into their relevant infrastructure."
},
{
"code": null,
"e": 16186,
"s": 16078,
"text": "Some high level principles that revolve around more specialised machine learning metrics are the following:"
},
{
"code": null,
"e": 16236,
"s": 16186,
"text": "Monitoring specific to statistical ML performance"
},
{
"code": null,
"e": 16297,
"s": 16236,
"text": "Benchmarking multiple different models or different versions"
},
{
"code": null,
"e": 16355,
"s": 16297,
"text": "Specialised for the data-type and the input/output format"
},
{
"code": null,
"e": 16466,
"s": 16355,
"text": "Stateful asynchronous provisioning of “feedback” on previous requests (such as “annotations” or “corrections”)"
},
{
"code": null,
"e": 16810,
"s": 16466,
"text": "Given that we have these requirements, Seldon Core introduces a set of architectural patterns that allow us to introduce the concept of “Extensible Metrics Servers”. These metric servers contain out-of-the-box ways to process data that the model processes by subscribing to the respective eventing topics, to ultimately expose metrics such as:"
},
{
"code": null,
"e": 16888,
"s": 16810,
"text": "Raw metrics: True-Positives, True-Negatives, False-Positives, False-Negatives"
},
{
"code": null,
"e": 16944,
"s": 16888,
"text": "Basic metrics: Accuracy, precision, recall, specificity"
},
{
"code": null,
"e": 16990,
"s": 16944,
"text": "Specialised metrics: KL Divergence, RMSE, etc"
},
{
"code": null,
"e": 17041,
"s": 16990,
"text": "Breakdowns per class, features, and other metadata"
},
{
"code": null,
"e": 17557,
"s": 17041,
"text": "From an architectural perspective, this can be visualised more intuitively in the diagram above. This showcases how a single datapoint can be submitted through the model, and then processed by any respective Metric Servers. The metric servers can also process the “correct/annotated” labels once they are provided, which can be linked with the unique prediction ID that Seldon Core adds on every request. The specialised metrics are calculated and exposed by fetching the relevant data from the Elasticsearch store."
},
{
"code": null,
"e": 17642,
"s": 17557,
"text": "Currently, Seldon Core provides the following set of out-of-the-box Metrics Servers:"
},
{
"code": null,
"e": 17835,
"s": 17642,
"text": "BinaryClassification — Processes data in the form of binary classifications (e.g. 0 or 1) to expose raw metrics to show basic statistical metrics (accuracy, precision, recall and specificity)."
},
{
"code": null,
"e": 18033,
"s": 17835,
"text": "MultiClassOneHot — Processes data in the form of one hot predictions for classification tasks (e.g. [0, 0, 1] or [0, 0.2, 0.8]), which can then expose raw metrics to show basic statistical metrics."
},
{
"code": null,
"e": 18214,
"s": 18033,
"text": "MultiClassNumeric — Processes data in the form of numeric datapoints for classification tasks (e.g. 1, or [1]), which can then expose raw metrics to show basic statistical metrics."
},
{
"code": null,
"e": 18424,
"s": 18214,
"text": "For this example we will be able to deploy a Metric Server of the type “MulticlassOneHot” — you can see the parameters used in the summarised code below, but you can find the full YAML in the jupyter notebook."
},
{
"code": null,
"e": 18821,
"s": 18424,
"text": "Once we deploy our metrics server, we can now just send requests and feedback to our CIFAR10 model, through the same microservice endpoint. To simplify the workflow, we will not send asynchronous feedback (which would perform the comparisons with the elasticsearch data), but instead we’ll send “self-contained” feedback requests, which contain the inference “response” and the inference “truth”."
},
{
"code": null,
"e": 19009,
"s": 18821,
"text": "The following function provides us with a way to send a bunch of feedback requests to achieve an approximate accuracy percent (number of correct vs incorrect predictions) for our usecase."
},
{
"code": null,
"e": 19176,
"s": 19009,
"text": "Now we can first send feedback to get 90% accuracy, and then to make sure our graphs look pretty, we can send another batch request that would result in 40% accuracy."
},
{
"code": null,
"e": 19289,
"s": 19176,
"text": "This now basically gives us the ability to visualise the metrics that the MetricsServer calculates in real time."
},
{
"code": null,
"e": 19793,
"s": 19289,
"text": "From the dashboard above we can get a high level intuition of the type of metrics that we are able to get through this architectural pattern. The stateful statistical metrics above in particular require extra metadata to be provided asynchronously, however even though the metrics themselves may have very different ways of being calculated, we can see that the infrastructural and architectural requirements can be abstracted and standardised in order for these to be approached in a more scalable way."
},
{
"code": null,
"e": 19908,
"s": 19793,
"text": "We will continue seeing this pattern as we delve further into the more advanced statistical monitoring techniques."
},
{
"code": null,
"e": 20303,
"s": 19908,
"text": "For a more advanced monitoring technique, we will be leveraging the Alibi Detect library, particularly around some of the advanced outlier detector algorithms it provides. Seldon Core provides us with a way to perform the deployment of outlier detectors as an architectural pattern, but also provides us with a prepackaged server that is optimized to serve Alibi Detect outlier detector models."
},
{
"code": null,
"e": 20361,
"s": 20303,
"text": "Some of the key principles for outlier detection include:"
},
{
"code": null,
"e": 20399,
"s": 20361,
"text": "Detecting anomalies in data instances"
},
{
"code": null,
"e": 20444,
"s": 20399,
"text": "Flagging / alerting when outliers take place"
},
{
"code": null,
"e": 20509,
"s": 20444,
"text": "Identifying potential metadata that could help diagnose outliers"
},
{
"code": null,
"e": 20559,
"s": 20509,
"text": "Enable drill down of outliers that are identified"
},
{
"code": null,
"e": 20619,
"s": 20559,
"text": "Enabling for continuous / automated retraining of detectors"
},
{
"code": null,
"e": 21064,
"s": 20619,
"text": "In the case of outlier detectors it is especially important to allow for the calculations to be performed separate to the model, as these tend to be much heaver and may require more specialised components. An outlier detector that is deployed, may come with similar complexities to the ones from a machine learning model, so it’s important that the same concepts of compliance, governance and lineage are covered with these advanced components."
},
{
"code": null,
"e": 21470,
"s": 21064,
"text": "The diagram below shows how the requests are forwarded by the model using the eventing infrastructure. The outlier detector then processes the datapoint to calculate whether it’s an outlier. The component is then able to store the outlier data in the respective request entry asynchronously, or alternatively it is able to expose the metrics to prometheus, which is what we will visualise in this section."
},
{
"code": null,
"e": 21799,
"s": 21470,
"text": "For this example we will be using the Alibi Detect Variational Auto Encoder outlier detector technique. The outlier detector is trained on a batch of unlabeled but normal (inlier) data. The VAE detector tries to reconstruct the input it receives, if the input data cannot be reconstructed well, then it is flagged as an outlier."
},
{
"code": null,
"e": 21949,
"s": 21799,
"text": "Alibi Detect provides us with utilities that allow us to export the outlier detector from scratch. We can fetch it using the fetch_detector function."
},
{
"code": null,
"e": 22090,
"s": 21949,
"text": "If you want to train the outlier, you can do so by simply leveraging the OutlierVAE class together with the respective encoder and decoders."
},
{
"code": null,
"e": 22353,
"s": 22090,
"text": "To test the outlier detector we can take the same picture of the truck and see how the outlier detector behaves if noise is added to the image increasingly. We will also be able to plot it using the Alibi Detect visualisation function plot_feature_outlier_image."
},
{
"code": null,
"e": 22454,
"s": 22353,
"text": "We can create a set of modified images and run it through the outlier detector using the code below."
},
{
"code": null,
"e": 22623,
"s": 22454,
"text": "We now have an array of modified samples in the variable all_X_mask , each with an increasing amount of noise. We can now run all these 10 through the outlier detector."
},
{
"code": null,
"e": 22902,
"s": 22623,
"text": "When looking at the results, we can see that the first 3 were not marked as outliers, whereas the rest were marked as outliers — we can see it by printing the value print(od_preds[“data”][“is_outlier”]). Which displays the array below, where 0 is non-outliers and 1 is outliers."
},
{
"code": null,
"e": 22940,
"s": 22902,
"text": "array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1])"
},
{
"code": null,
"e": 23073,
"s": 22940,
"text": "We can now visualise how the outlier instance level score maps against the threshold, which reflects the results in the array above."
},
{
"code": null,
"e": 23280,
"s": 23073,
"text": "Similarly we can dive deeper into the intuition of what the outlier detector score channels look like, as well as the reconstructed images, which should provide a clear picture of how its internals operate."
},
{
"code": null,
"e": 23650,
"s": 23280,
"text": "We will now be able to productionise our outlier detector. We will be leveraging a similar architectural pattern to the one from the metric servers. Namely the Alibi Detect Seldon Core server, which will be listening to the inference input/output of the data. For every data point that goes through the model, the respective outlier detector will be able to process it."
},
{
"code": null,
"e": 23930,
"s": 23650,
"text": "The main step required will be to first ensure the outlier detector we trained above is uploaded to an object store like Google bucket. We have already uploaded it to gs://seldon-models/alibi-detect/od/OutlierVAE/cifar10, but if you wish you can upload it and use your own model."
},
{
"code": null,
"e": 24066,
"s": 23930,
"text": "Once we deploy our outlier detector, we will be able to send a bunch of requests, many which will be outliers and others that won’t be."
},
{
"code": null,
"e": 24229,
"s": 24066,
"text": "We can now visualise some outliers in the dashboard — for every data point there will be a new entry point and will include whether it would be an outlier or not."
},
{
"code": null,
"e": 24472,
"s": 24229,
"text": "As time passes, data in real life production environments can change. Whilst this change is not drastic, it can be identified through drifts in the distribution of the data itself particularly in respect to the predicted outputs of the model."
},
{
"code": null,
"e": 24515,
"s": 24472,
"text": "Key principles in drift detection include:"
},
{
"code": null,
"e": 24636,
"s": 24515,
"text": "Identifying drift in data distribution, as well as drifts in the relationship between input and output data from a model"
},
{
"code": null,
"e": 24727,
"s": 24636,
"text": "Flagging drift that is found together with the relevant datapoints where it was identified"
},
{
"code": null,
"e": 24817,
"s": 24727,
"text": "Allowing for the ability to drill down into the data that was used to calculate the drift"
},
{
"code": null,
"e": 25252,
"s": 24817,
"text": "In the concept of drift detection we deal with further complexities when compared to the outlier detection usecase. The main one being the requirement to run each drift prediction on a batch input as opposed to a single datapoint. The diagram below shows a similar workflow to the one outlied in the outlier detector pattern, the main difference is that it keeps a tumbling or sliding window of data to perform the processing against."
},
{
"code": null,
"e": 25402,
"s": 25252,
"text": "For this example we will once again be using the Alibi Detect library, which provides us with the Kolmogorov-Smirnov data drift detector on CIFAR-10."
},
{
"code": null,
"e": 25585,
"s": 25402,
"text": "For this technique will be able to use the KSDrift class to create and train the drift detector, which also requires a preprocessing step which uses an “Untrained Autoencoder (UAE)”."
},
{
"code": null,
"e": 25970,
"s": 25585,
"text": "In order for us to test the outlier detector we will generate a set of detectors with corrupted data. Alibi Detect provides a great set of utilities that we can use to generate corruption/noise into images in an increasing way. In this case we will be using the following noise: [‘gaussian_noise’, ‘motion_blur’, ‘brightness’, ‘pixelate’]. These will be generated with the code below."
},
{
"code": null,
"e": 26130,
"s": 25970,
"text": "Below is one datapoint from the created corrupted dataset, which contains images with an increasing amount of corruption of the different types outlined above."
},
{
"code": null,
"e": 26296,
"s": 26130,
"text": "We can now attempt to run a couple of datapoints to compute whether drift is detected or not. The initial batch will consist of datapoints from the original dataset."
},
{
"code": null,
"e": 26333,
"s": 26296,
"text": "This as expected outputs: Drift? No!"
},
{
"code": null,
"e": 26388,
"s": 26333,
"text": "Similarly we can run it against the corrupted dataset."
},
{
"code": null,
"e": 26453,
"s": 26388,
"text": "And we can see that all of them are marked as drift as expected:"
},
{
"code": null,
"e": 26609,
"s": 26453,
"text": "Corruption type: gaussian_noiseDrift? Yes!Corruption type: motion_blurDrift? Yes!Corruption type: brightnessDrift? Yes!Corruption type: pixelateDrift? Yes!"
},
{
"code": null,
"e": 27000,
"s": 26609,
"text": "Now we can move towards deploying our drift detector following the architectural pattern provided above. Similar to the outlier detector we first have to make sure that the drift detector we trained above can be uploaded to an object store. We currently will be able to use the Google bucket that we have prepared under gs://seldon-models/alibi-detect/cd/ks/drift to perform the deployment."
},
{
"code": null,
"e": 27242,
"s": 27000,
"text": "This will have a similar structure, the main difference is that we will also specify the desired batch size to use for the Alibi Detect server to keep as a buffer before running against the model. In this case we select a batch size of 1000."
},
{
"code": null,
"e": 27351,
"s": 27242,
"text": "Now that we have deployerd our outlier detector, we first try sending 1000 requests from the normal dataset."
},
{
"code": null,
"e": 27459,
"s": 27351,
"text": "Next we can send the corrupted data, which would result in drift detected after sending the 10k datapoints."
},
{
"code": null,
"e": 27554,
"s": 27459,
"text": "We are able to visualise each of the different drift points detected in the Grafana dashboard."
},
{
"code": null,
"e": 28026,
"s": 27554,
"text": "AI Explainability techniques are key to understanding the behaviour of complex black box machine learning models. There is a broad range of content that explores the different algorithmic techniques that can be used in different contexts. Our current focus in this context is to provide an intuition and a practical example of the architectural patterns that can allow for explainer components to be deployed at scale. Some key principles of model explainability include:"
},
{
"code": null,
"e": 28075,
"s": 28026,
"text": "Human-interpretable insights for model behaviour"
},
{
"code": null,
"e": 28133,
"s": 28075,
"text": "Introducing use-case-specific explainability capabilities"
},
{
"code": null,
"e": 28210,
"s": 28133,
"text": "Identifying key metrics such as trust scores or statistical perf. thresholds"
},
{
"code": null,
"e": 28262,
"s": 28210,
"text": "Enabling for use of some more complex ML techniques"
},
{
"code": null,
"e": 28455,
"s": 28262,
"text": "There are a broad range of different techniques available around explainability, but it’s important to understand the high level themes around the different types of Explainers. These include:"
},
{
"code": null,
"e": 28479,
"s": 28455,
"text": "Scope (local vs global)"
},
{
"code": null,
"e": 28511,
"s": 28479,
"text": "Model type (black vs white box)"
},
{
"code": null,
"e": 28550,
"s": 28511,
"text": "Task (classification, regression, etc)"
},
{
"code": null,
"e": 28589,
"s": 28550,
"text": "Data type (tabular, images, text, etc)"
},
{
"code": null,
"e": 28674,
"s": 28589,
"text": "Insight (feature attributions, counterfactuals, influential training instances, etc)"
},
{
"code": null,
"e": 29035,
"s": 28674,
"text": "For explainers as interfaces, these have similarities in the data flow patterns. Namely many of them require interacting with the data that the model processes, as well as the ability to interact with the model itself — for black box techniques it includes the inputs/outputs whereas for white-box techniques it includes the internals of the models themselves."
},
{
"code": null,
"e": 29391,
"s": 29035,
"text": "From an architectural perspective, this involves primarily a separate microservice which instead of just receiving an inference request, it would be able to interact with the respective model and “reverse engineer” the model by sending the relevant data. This is shown in the diagram above, but it will become more intuitive once we dive into the example."
},
{
"code": null,
"e": 29630,
"s": 29391,
"text": "For the example, we will be using the Alibi Explain framework, and we will use the Anchor Explanation technique. This local explanation technique tells us what are the features in a particular data point with the highest predictive power."
},
{
"code": null,
"e": 29812,
"s": 29630,
"text": "We can simply create our Anchor explainer by specifying the structure of our dataset, together with a lambda that allows the explainer to interact with the model’s predict function."
},
{
"code": null,
"e": 29926,
"s": 29812,
"text": "We are able to identify what are the anchors in our model that would predict in this case the image of the truck."
},
{
"code": null,
"e": 30014,
"s": 29926,
"text": "We can visualise the anchors by displaying the output anchor of the explanation itself."
},
{
"code": null,
"e": 30107,
"s": 30014,
"text": "We can see that the anchors of the image include the windshield and the wheels of the truck."
},
{
"code": null,
"e": 30376,
"s": 30107,
"text": "Here you can see that the explainer interacts with our deployed model. When deploying the explainer we will be following the same principle but instead of using a lambda that runs the model locally, this will be a function that will call the remote model microservice."
},
{
"code": null,
"e": 30720,
"s": 30376,
"text": "We will follow a similar approach where we’ll just need to upload the image above to an object store bucket. Similar to the previous example, we have provided a bucket under gs://seldon-models/tfserving/cifar10/explainer-py36–0.5.2. We will now be able to deploy an explainer, which can be deployed as part of the CRD of the Seldon Deployment."
},
{
"code": null,
"e": 30839,
"s": 30720,
"text": "We can check that the explainer is running with kubectl get pods | grep cifar , which should output both running pods:"
},
{
"code": null,
"e": 30995,
"s": 30839,
"text": "cifar10-default-0-resnet32-6dc5f5777-sq765 2/2 Running 0 18mcifar10-default-explainer-56cd6c76cd-mwjcp 1/1 Running 0 5m3s"
},
{
"code": null,
"e": 31205,
"s": 30995,
"text": "Similar to how we send a request to the model, we are able to send a request to the explainer path. This is where the explainer will interact with the model itself and print the reverse engineered explanation."
},
{
"code": null,
"e": 31288,
"s": 31205,
"text": "We can see that the output of the explanation is the same as the one we saw above."
},
{
"code": null,
"e": 31442,
"s": 31288,
"text": "Finally we can also see some of the metric related components that come out of the explainer themselves, which can then be visualised through dashboards."
},
{
"code": null,
"e": 31473,
"s": 31442,
"text": "Coverage: 0.2475Precision: 1.0"
},
{
"code": null,
"e": 31663,
"s": 31473,
"text": "Similar to the other microservice based machine learning components deployed, the explainers also can expose these and other more specialised metrics for performance or advanced monitoring."
},
{
"code": null,
"e": 31985,
"s": 31663,
"text": "Before wrapping up, one thing to outline is the importance of abstracting these advanced machine learning concepts into standardised architectural patterns. The reason why this is crucial is primarily to enable machine learning systems for scale, but also to allow for advanced integration of components across the stack."
},
{
"code": null,
"e": 32263,
"s": 31985,
"text": "All the advanced architectures covered above not only are applicable across each of the advanced components, but it is also possible to enable for what we can refer to as “ensemble patterns” — that is, connecting advanced components on the outputs of other advanced components."
},
{
"code": null,
"e": 32573,
"s": 32263,
"text": "It is also important to ensure there are structured and standardised architectural patterns also enable developers to provide the monitoring components, which are also advanced machine learning models, have the same level of governance, compliance and lineage required in order to manage the risk efficiently."
},
{
"code": null,
"e": 32965,
"s": 32573,
"text": "These patterns are continuously being refined and evolved through the Seldon Core project, and advanced state of the art algorithms on outlier detection, concept drift, explainability, etc are improving continuously — if you are interested on furthering the discussion, please feel free to reach out. All the examples in this tutorial are open source, so suggestions are greatly appreciated."
},
{
"code": null,
"e": 33097,
"s": 32965,
"text": "If you are interested in further hands on examples of scalable deployment strategies of machine learning models, you can check out:"
},
{
"code": null,
"e": 33134,
"s": 33097,
"text": "Batch Processing with Argo Workflows"
},
{
"code": null,
"e": 33167,
"s": 33134,
"text": "Serverless eventing with Knative"
},
{
"code": null,
"e": 33205,
"s": 33167,
"text": "AI Explainability Patterns with Alibi"
},
{
"code": null,
"e": 33244,
"s": 33205,
"text": "Seldon Model Containerisation Notebook"
}
] |
What is dot operator in C++?
|
The dot and arrow operator are both used in C++ to access the members of a class. They are just used in different scenarios. In C++, types declared as a class, struct, or union are considered "of class type". So the following refers to both of them.
a.b is only used if b is a member of the object (or reference[1] to an object) a. So for a.b, a will always be an actual object (or a reference to an object) of a class.
a →b is essentially a shorthand notation for (*a).b, ie, if a is a pointer to an object, then a →b is accessing the property b of the object that points to.
Note that . is not overloadable. → is an overloadable operator, so we can define our own function(operator →()) that should be called when this operator is used. so if a is an object of a class that overloads operator → (common such types are smart pointers and iterators), then the meaning is whatever the class designer implemented.
[1] References are, semantically, aliases to objects, so I should have added "or reference to a pointer" to the #3 as well. However, I thought this would be more confusing than helpful since references to pointers (T*&) are rarely ever used.
#include<iostream>
class A {
public: int b;
A() { b = 5; }
};
int main() {
A a = A();
A* x = &a;
std::cout << "a.b = " << a.b << "\n";
std::cout << "x->b = " << x->b << "\n";
return 0;
}
This will give the output −
5
5
|
[
{
"code": null,
"e": 1312,
"s": 1062,
"text": "The dot and arrow operator are both used in C++ to access the members of a class. They are just used in different scenarios. In C++, types declared as a class, struct, or union are considered \"of class type\". So the following refers to both of them."
},
{
"code": null,
"e": 1482,
"s": 1312,
"text": "a.b is only used if b is a member of the object (or reference[1] to an object) a. So for a.b, a will always be an actual object (or a reference to an object) of a class."
},
{
"code": null,
"e": 1639,
"s": 1482,
"text": "a →b is essentially a shorthand notation for (*a).b, ie, if a is a pointer to an object, then a →b is accessing the property b of the object that points to."
},
{
"code": null,
"e": 1974,
"s": 1639,
"text": "Note that . is not overloadable. → is an overloadable operator, so we can define our own function(operator →()) that should be called when this operator is used. so if a is an object of a class that overloads operator → (common such types are smart pointers and iterators), then the meaning is whatever the class designer implemented."
},
{
"code": null,
"e": 2216,
"s": 1974,
"text": "[1] References are, semantically, aliases to objects, so I should have added \"or reference to a pointer\" to the #3 as well. However, I thought this would be more confusing than helpful since references to pointers (T*&) are rarely ever used."
},
{
"code": null,
"e": 2424,
"s": 2216,
"text": "#include<iostream>\nclass A {\n public: int b;\n A() { b = 5; }\n};\nint main() {\n A a = A();\n A* x = &a;\n std::cout << \"a.b = \" << a.b << \"\\n\";\n std::cout << \"x->b = \" << x->b << \"\\n\";\n return 0;\n}"
},
{
"code": null,
"e": 2452,
"s": 2424,
"text": "This will give the output −"
},
{
"code": null,
"e": 2456,
"s": 2452,
"text": "5\n5"
}
] |
Merge Two Sets in Java - GeeksforGeeks
|
09 Dec, 2021
The set interface is present in java.util package and extends the Collection interface is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Collection interface and adds a feature that restricts the insertion of the duplicate elements. There are two interfaces that extend the set implementation namely SortedSet and NavigableSet.
Methods: Following are the various ways to merge two sets in Java:
Using double brace initializationUsing the addAll() method of the Set classUsing user-defined methodUsing Java 8 stream in the user-defined functionUsing Java 8 stream in the user-defined functionUsing of() and forEach() Methods of Stream classUsing of() and flatMap() Method of Stream class with CollectorUsing concat() method of Stream Class with CollectorUsing Apache Common CollectionsUsing Guava Iterables.concat()
Using double brace initialization
Using the addAll() method of the Set classUsing user-defined methodUsing Java 8 stream in the user-defined function
Using user-defined method
Using Java 8 stream in the user-defined function
Using Java 8 stream in the user-defined function
Using of() and forEach() Methods of Stream class
Using of() and flatMap() Method of Stream class with Collector
Using concat() method of Stream Class with Collector
Using Apache Common Collections
Using Guava Iterables.concat()
Method 1: Using Double brace Initialization
Illustration:
Input : a = [1, 3, 5, 7, 9]
b = [0, 2, 4, 6, 8]
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example
Java
// Java Program to Demonstrate Merging of two sets in Java// Using Double brace Initialization // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classpublic class GFG { // Method 1 // To merge two sets // using DoubleBrace Initialisation public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding all elements of respective Sets // using addAll() method return new HashSet<T>() { { addAll(a); addAll(b); } }; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); // Applying Arrays.asList() a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); // Applying Arrays.asList() b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling Method 1 to merge above Sets System.out.println("Merged Set: " + mergeSet(a, b)); }}
Set a: [1, 3, 5, 7, 9]
Set b: [0, 2, 4, 6, 8]
Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 2: Using addAll() Method of Set Class
The addAll() method is provided by the Set interface. It adds the elements passed as parameters at the last of this set.
2-A. Using user-defined method
Illustration:
Input : a = [1, 3, 5, 7, 9]
b = [0, 2, 4, 6, 8]
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example:
Java
// Java program to demonstrate Merging of Two Sets// Using SetAll() method // Importing required classesimport java.util.*; // Main classpublic class GFG { // Method 1 // To merge two sets // using addAll() public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Creating an empty HashSet Set<T> mergedSet = new HashSet<T>(); // Adding the two sets to be merged // into the new Set using addAll() method mergedSet.addAll(a); mergedSet.addAll(b); // Returning the merged set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First Set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second Set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge above Sets // and printing it System.out.println("Merged Set: " + mergeSet(a, b)); }}
Set a: [1, 3, 5, 7, 9]
Set b: [0, 2, 4, 6, 8]
Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2-B. Using Java 8 stream in the user-defined function
Illustration:
Input : a = [1, 3, 5, 7, 9]
b = [0, 2, 4, 6, 8]
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example
Java
// Java program to demonstrate Merging of Two Sets// Using Stream // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classpublic class GFG { // Method 1 // To merge two Sets // using addAll() public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Creating a Set with 'a' Set<T> mergedSet = a.stream().collect(Collectors.toSet()); // Adding the second set to be merged mergedSet.addAll(b); // Returning the merged Set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the Sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing above Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge two Sets System.out.println("Merged Set: " + mergeSet(a, b)); }}
Set a: [1, 3, 5, 7, 9]
Set b: [0, 2, 4, 6, 8]
Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 3: Using addAll() method of Collections Class
Illustration:
Input : a = [1, 3, 5, 7, 9]
b = [0, 2, 4, 6, 8]
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example:
Java
// Java Program to Merge Two Arrays// of Same Type into an Object Array // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Method 1 // To merging two Sets // using addAll() public static Set<Integer> mergeSet(Set<Integer> a, Set<Integer> b) { // Creating an empty HashSet of Integer type Set<Integer> mergedSet = new HashSet<>(); // Adding the two sets to be merged // into the new Set Collections.addAll(mergedSet, a.toArray(new Integer[0])); Collections.addAll(mergedSet, b.toArray(new Integer[0])); // Returning the merged Set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling above method 1 to merge two sets System.out.println("Merged Set: " + mergeSet(a, b)); }}
Set a: [1, 3, 5, 7, 9]
Set b: [0, 2, 4, 6, 8]
Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 4: Using of() and forEach() Methods of Stream class
Illustration:
Input : a = [1, 3, 5, 7, 9]
b = [0, 2, 4, 6, 8]
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example:
Java
// Java Program to Demonstrate Merging of Two Sets// Using Stream // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classpublic class GFG { // Method 1 // To merge two sets // using Stream of() and forEach() methods public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Creating an empty set Set<T> mergedSet = new HashSet<T>(); // add the two sets to be merged // into the new set Stream.of(a, b).forEach(mergedSet::addAll); // returning the merged set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge two Sets System.out.println("Merged Set: " + mergeSet(a, b)); }}
Set a: [1, 3, 5, 7, 9]
Set b: [0, 2, 4, 6, 8]
Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 5: Using of() and flatMap() Method of Stream class with Collector
Illustration:
Input : a = [1, 3, 5, 7, 9]
b = [0, 2, 4, 6, 8]
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example:
Java
// Java Program to Demonstrate Merging of Two Sets// Using stream // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classpublic class GFG { // Method 1 // To merge two Sets // using Stream of(), flatMap() and Collector public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two Sets to be merged // into the new Set and // returning the merged set return Stream.of(a, b) .flatMap(x -> x.stream()) .collect(Collectors.toSet()); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First Set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second Set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge above two Sets System.out.println("Merged Set: " + mergeSet(a, b)); }}
Set a: [1, 3, 5, 7, 9]
Set b: [0, 2, 4, 6, 8]
Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 6: Using concat() method of Stream Class with Collector
Illustration:
Input : a = [1, 3, 5, 7, 9]
b = [0, 2, 4, 6, 8]
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The concatenate function is used to merge to string and make a single string that contains both the string. Stream.concat() method creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
Example
Java
// Java program to Demonstrate Merging of two Sets// using Stream // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classpublic class GFG { // Method 1 // To merge two sets // using Stream concat() and Collectors public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two sets to be merged // into the new Set and // returning the merged set return Stream.concat(a.stream(), b.stream()) .collect(Collectors.toSet()); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First Set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second Set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling the method 1 to merge two Sets System.out.println("Merged Set: " + mergeSet(a, b)); }}
Set a: [1, 3, 5, 7, 9]
Set b: [0, 2, 4, 6, 8]
Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 7: Using Apache Common Collections
Illustration:
Input : a = [1, 3, 5, 7, 9]
b = [0, 2, 4, 6, 8]
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example
Java
// Java Program to Demonstrate Merging of Two Sets// Using Apache Common Collection // Importing required classesimport java.io.*;import java.util.*;import org.apache.commons.collections4.SetUtils; // Main classpublic class GFG { // Method 1 // To merge two Sets // using addAll() method public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two Sets to be merged // into the new Set and // returning the merged Set return SetUtils.union(a, b); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the Sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge two Sets System.out.println("Merged Set: " + mergeSet(a, b)); }}
Set a: [1, 3, 5, 7, 9]
Set b: [0, 2, 4, 6, 8]
Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 8: Using Guava Iterables.concat()
Illustration:
Input : a = [1, 3, 5, 7, 9]
b = [0, 2, 4, 6, 8]
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example
Java
// Java Program to Demonstrate Merging of Two Sets// Using Guava Library // Importing required classesimport com.google.common.collect.Iterables;import com.google.common.collect.Sets;import java.io.*;import java.util.*; // Main classpublic class GFG { // Method 1 // To merge two sets // using Guava Iterables.concat() public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two sets to be merged // into the new set and // returning the merged set return Sets.newHashSet(Iterables.concat(a, b)); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the Sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge two Sets System.out.println("Merged Set: " + mergeSet(a, b)); }}
Set a: [1, 3, 5, 7, 9]
Set b: [0, 2, 4, 6, 8]
Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Note: Any duplicate element presented in the sets will be discarded during the merge in all the above methods.
solankimayank
Java-Collections
java-set
Java-Set-Programs
Picked
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
Overriding in Java
Queue Interface In Java
Functional Interfaces in Java
How to add an element to an Array in Java?
|
[
{
"code": null,
"e": 23793,
"s": 23765,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 24265,
"s": 23793,
"text": "The set interface is present in java.util package and extends the Collection interface is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Collection interface and adds a feature that restricts the insertion of the duplicate elements. There are two interfaces that extend the set implementation namely SortedSet and NavigableSet."
},
{
"code": null,
"e": 24333,
"s": 24265,
"text": "Methods: Following are the various ways to merge two sets in Java: "
},
{
"code": null,
"e": 24754,
"s": 24333,
"text": "Using double brace initializationUsing the addAll() method of the Set classUsing user-defined methodUsing Java 8 stream in the user-defined functionUsing Java 8 stream in the user-defined functionUsing of() and forEach() Methods of Stream classUsing of() and flatMap() Method of Stream class with CollectorUsing concat() method of Stream Class with CollectorUsing Apache Common CollectionsUsing Guava Iterables.concat() "
},
{
"code": null,
"e": 24788,
"s": 24754,
"text": "Using double brace initialization"
},
{
"code": null,
"e": 24904,
"s": 24788,
"text": "Using the addAll() method of the Set classUsing user-defined methodUsing Java 8 stream in the user-defined function"
},
{
"code": null,
"e": 24930,
"s": 24904,
"text": "Using user-defined method"
},
{
"code": null,
"e": 24979,
"s": 24930,
"text": "Using Java 8 stream in the user-defined function"
},
{
"code": null,
"e": 25028,
"s": 24979,
"text": "Using Java 8 stream in the user-defined function"
},
{
"code": null,
"e": 25077,
"s": 25028,
"text": "Using of() and forEach() Methods of Stream class"
},
{
"code": null,
"e": 25140,
"s": 25077,
"text": "Using of() and flatMap() Method of Stream class with Collector"
},
{
"code": null,
"e": 25193,
"s": 25140,
"text": "Using concat() method of Stream Class with Collector"
},
{
"code": null,
"e": 25225,
"s": 25193,
"text": "Using Apache Common Collections"
},
{
"code": null,
"e": 25257,
"s": 25225,
"text": "Using Guava Iterables.concat() "
},
{
"code": null,
"e": 25301,
"s": 25257,
"text": "Method 1: Using Double brace Initialization"
},
{
"code": null,
"e": 25315,
"s": 25301,
"text": "Illustration:"
},
{
"code": null,
"e": 25413,
"s": 25315,
"text": "Input : a = [1, 3, 5, 7, 9]\n b = [0, 2, 4, 6, 8]\nOutput : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 25421,
"s": 25413,
"text": "Example"
},
{
"code": null,
"e": 25426,
"s": 25421,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Merging of two sets in Java// Using Double brace Initialization // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classpublic class GFG { // Method 1 // To merge two sets // using DoubleBrace Initialisation public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding all elements of respective Sets // using addAll() method return new HashSet<T>() { { addAll(a); addAll(b); } }; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); // Applying Arrays.asList() a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); // Applying Arrays.asList() b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the Sets System.out.println(\"Set a: \" + a); System.out.println(\"Set b: \" + b); // Calling Method 1 to merge above Sets System.out.println(\"Merged Set: \" + mergeSet(a, b)); }}",
"e": 26724,
"s": 25426,
"text": null
},
{
"code": null,
"e": 26813,
"s": 26724,
"text": "Set a: [1, 3, 5, 7, 9]\nSet b: [0, 2, 4, 6, 8]\nMerged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 26860,
"s": 26815,
"text": "Method 2: Using addAll() Method of Set Class"
},
{
"code": null,
"e": 26982,
"s": 26860,
"text": "The addAll() method is provided by the Set interface. It adds the elements passed as parameters at the last of this set. "
},
{
"code": null,
"e": 27013,
"s": 26982,
"text": "2-A. Using user-defined method"
},
{
"code": null,
"e": 27027,
"s": 27013,
"text": "Illustration:"
},
{
"code": null,
"e": 27125,
"s": 27027,
"text": "Input : a = [1, 3, 5, 7, 9]\n b = [0, 2, 4, 6, 8]\nOutput : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 27134,
"s": 27125,
"text": "Example:"
},
{
"code": null,
"e": 27139,
"s": 27134,
"text": "Java"
},
{
"code": "// Java program to demonstrate Merging of Two Sets// Using SetAll() method // Importing required classesimport java.util.*; // Main classpublic class GFG { // Method 1 // To merge two sets // using addAll() public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Creating an empty HashSet Set<T> mergedSet = new HashSet<T>(); // Adding the two sets to be merged // into the new Set using addAll() method mergedSet.addAll(a); mergedSet.addAll(b); // Returning the merged set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First Set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second Set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the Sets System.out.println(\"Set a: \" + a); System.out.println(\"Set b: \" + b); // Calling method 1 to merge above Sets // and printing it System.out.println(\"Merged Set: \" + mergeSet(a, b)); }}",
"e": 28402,
"s": 27139,
"text": null
},
{
"code": null,
"e": 28491,
"s": 28402,
"text": "Set a: [1, 3, 5, 7, 9]\nSet b: [0, 2, 4, 6, 8]\nMerged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 28547,
"s": 28493,
"text": "2-B. Using Java 8 stream in the user-defined function"
},
{
"code": null,
"e": 28562,
"s": 28547,
"text": "Illustration: "
},
{
"code": null,
"e": 28658,
"s": 28562,
"text": "Input : a = [1, 3, 5, 7, 9]\n b = [0, 2, 4, 6, 8]\nOutput : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 28666,
"s": 28658,
"text": "Example"
},
{
"code": null,
"e": 28671,
"s": 28666,
"text": "Java"
},
{
"code": "// Java program to demonstrate Merging of Two Sets// Using Stream // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classpublic class GFG { // Method 1 // To merge two Sets // using addAll() public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Creating a Set with 'a' Set<T> mergedSet = a.stream().collect(Collectors.toSet()); // Adding the second set to be merged mergedSet.addAll(b); // Returning the merged Set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the Sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing above Sets System.out.println(\"Set a: \" + a); System.out.println(\"Set b: \" + b); // Calling method 1 to merge two Sets System.out.println(\"Merged Set: \" + mergeSet(a, b)); }}",
"e": 29896,
"s": 28671,
"text": null
},
{
"code": null,
"e": 29985,
"s": 29896,
"text": "Set a: [1, 3, 5, 7, 9]\nSet b: [0, 2, 4, 6, 8]\nMerged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 30042,
"s": 29987,
"text": "Method 3: Using addAll() method of Collections Class "
},
{
"code": null,
"e": 30056,
"s": 30042,
"text": "Illustration:"
},
{
"code": null,
"e": 30157,
"s": 30056,
"text": "Input : a = [1, 3, 5, 7, 9]\n b = [0, 2, 4, 6, 8]\nOutput : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 30166,
"s": 30157,
"text": "Example:"
},
{
"code": null,
"e": 30171,
"s": 30166,
"text": "Java"
},
{
"code": "// Java Program to Merge Two Arrays// of Same Type into an Object Array // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Method 1 // To merging two Sets // using addAll() public static Set<Integer> mergeSet(Set<Integer> a, Set<Integer> b) { // Creating an empty HashSet of Integer type Set<Integer> mergedSet = new HashSet<>(); // Adding the two sets to be merged // into the new Set Collections.addAll(mergedSet, a.toArray(new Integer[0])); Collections.addAll(mergedSet, b.toArray(new Integer[0])); // Returning the merged Set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println(\"Set a: \" + a); System.out.println(\"Set b: \" + b); // Calling above method 1 to merge two sets System.out.println(\"Merged Set: \" + mergeSet(a, b)); }}",
"e": 31609,
"s": 30171,
"text": null
},
{
"code": null,
"e": 31698,
"s": 31609,
"text": "Set a: [1, 3, 5, 7, 9]\nSet b: [0, 2, 4, 6, 8]\nMerged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 31760,
"s": 31700,
"text": "Method 4: Using of() and forEach() Methods of Stream class "
},
{
"code": null,
"e": 31775,
"s": 31760,
"text": "Illustration: "
},
{
"code": null,
"e": 31871,
"s": 31775,
"text": "Input : a = [1, 3, 5, 7, 9]\n b = [0, 2, 4, 6, 8]\nOutput : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 31880,
"s": 31871,
"text": "Example:"
},
{
"code": null,
"e": 31885,
"s": 31880,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Merging of Two Sets// Using Stream // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classpublic class GFG { // Method 1 // To merge two sets // using Stream of() and forEach() methods public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Creating an empty set Set<T> mergedSet = new HashSet<T>(); // add the two sets to be merged // into the new set Stream.of(a, b).forEach(mergedSet::addAll); // returning the merged set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println(\"Set a: \" + a); System.out.println(\"Set b: \" + b); // Calling method 1 to merge two Sets System.out.println(\"Merged Set: \" + mergeSet(a, b)); }}",
"e": 33156,
"s": 31885,
"text": null
},
{
"code": null,
"e": 33245,
"s": 33156,
"text": "Set a: [1, 3, 5, 7, 9]\nSet b: [0, 2, 4, 6, 8]\nMerged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 33320,
"s": 33247,
"text": "Method 5: Using of() and flatMap() Method of Stream class with Collector"
},
{
"code": null,
"e": 33334,
"s": 33320,
"text": "Illustration:"
},
{
"code": null,
"e": 33432,
"s": 33334,
"text": "Input : a = [1, 3, 5, 7, 9]\n b = [0, 2, 4, 6, 8]\nOutput : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 33441,
"s": 33432,
"text": "Example:"
},
{
"code": null,
"e": 33446,
"s": 33441,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Merging of Two Sets// Using stream // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classpublic class GFG { // Method 1 // To merge two Sets // using Stream of(), flatMap() and Collector public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two Sets to be merged // into the new Set and // returning the merged set return Stream.of(a, b) .flatMap(x -> x.stream()) .collect(Collectors.toSet()); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First Set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second Set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the sets System.out.println(\"Set a: \" + a); System.out.println(\"Set b: \" + b); // Calling method 1 to merge above two Sets System.out.println(\"Merged Set: \" + mergeSet(a, b)); }}",
"e": 34672,
"s": 33446,
"text": null
},
{
"code": null,
"e": 34761,
"s": 34672,
"text": "Set a: [1, 3, 5, 7, 9]\nSet b: [0, 2, 4, 6, 8]\nMerged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 34826,
"s": 34763,
"text": "Method 6: Using concat() method of Stream Class with Collector"
},
{
"code": null,
"e": 34841,
"s": 34826,
"text": "Illustration: "
},
{
"code": null,
"e": 34937,
"s": 34841,
"text": "Input : a = [1, 3, 5, 7, 9]\n b = [0, 2, 4, 6, 8]\nOutput : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 35212,
"s": 34937,
"text": "The concatenate function is used to merge to string and make a single string that contains both the string. Stream.concat() method creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream."
},
{
"code": null,
"e": 35221,
"s": 35212,
"text": "Example "
},
{
"code": null,
"e": 35226,
"s": 35221,
"text": "Java"
},
{
"code": "// Java program to Demonstrate Merging of two Sets// using Stream // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classpublic class GFG { // Method 1 // To merge two sets // using Stream concat() and Collectors public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two sets to be merged // into the new Set and // returning the merged set return Stream.concat(a.stream(), b.stream()) .collect(Collectors.toSet()); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First Set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second Set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println(\"Set a: \" + a); System.out.println(\"Set b: \" + b); // Calling the method 1 to merge two Sets System.out.println(\"Merged Set: \" + mergeSet(a, b)); }}",
"e": 36439,
"s": 35226,
"text": null
},
{
"code": null,
"e": 36528,
"s": 36439,
"text": "Set a: [1, 3, 5, 7, 9]\nSet b: [0, 2, 4, 6, 8]\nMerged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 36572,
"s": 36530,
"text": "Method 7: Using Apache Common Collections"
},
{
"code": null,
"e": 36586,
"s": 36572,
"text": "Illustration:"
},
{
"code": null,
"e": 36684,
"s": 36586,
"text": "Input : a = [1, 3, 5, 7, 9]\n b = [0, 2, 4, 6, 8]\nOutput : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 36692,
"s": 36684,
"text": "Example"
},
{
"code": null,
"e": 36697,
"s": 36692,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Merging of Two Sets// Using Apache Common Collection // Importing required classesimport java.io.*;import java.util.*;import org.apache.commons.collections4.SetUtils; // Main classpublic class GFG { // Method 1 // To merge two Sets // using addAll() method public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two Sets to be merged // into the new Set and // returning the merged Set return SetUtils.union(a, b); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the Sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println(\"Set a: \" + a); System.out.println(\"Set b: \" + b); // Calling method 1 to merge two Sets System.out.println(\"Merged Set: \" + mergeSet(a, b)); }}",
"e": 37876,
"s": 36697,
"text": null
},
{
"code": null,
"e": 37965,
"s": 37876,
"text": "Set a: [1, 3, 5, 7, 9]\nSet b: [0, 2, 4, 6, 8]\nMerged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 38008,
"s": 37967,
"text": "Method 8: Using Guava Iterables.concat()"
},
{
"code": null,
"e": 38022,
"s": 38008,
"text": "Illustration:"
},
{
"code": null,
"e": 38118,
"s": 38022,
"text": "Input : a = [1, 3, 5, 7, 9]\n b = [0, 2, 4, 6, 8]\nOutput : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 38126,
"s": 38118,
"text": "Example"
},
{
"code": null,
"e": 38131,
"s": 38126,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Merging of Two Sets// Using Guava Library // Importing required classesimport com.google.common.collect.Iterables;import com.google.common.collect.Sets;import java.io.*;import java.util.*; // Main classpublic class GFG { // Method 1 // To merge two sets // using Guava Iterables.concat() public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two sets to be merged // into the new set and // returning the merged set return Sets.newHashSet(Iterables.concat(a, b)); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the Sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println(\"Set a: \" + a); System.out.println(\"Set b: \" + b); // Calling method 1 to merge two Sets System.out.println(\"Merged Set: \" + mergeSet(a, b)); }}",
"e": 39360,
"s": 38131,
"text": null
},
{
"code": null,
"e": 39449,
"s": 39360,
"text": "Set a: [1, 3, 5, 7, 9]\nSet b: [0, 2, 4, 6, 8]\nMerged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 39562,
"s": 39451,
"text": "Note: Any duplicate element presented in the sets will be discarded during the merge in all the above methods."
},
{
"code": null,
"e": 39576,
"s": 39562,
"text": "solankimayank"
},
{
"code": null,
"e": 39593,
"s": 39576,
"text": "Java-Collections"
},
{
"code": null,
"e": 39602,
"s": 39593,
"text": "java-set"
},
{
"code": null,
"e": 39620,
"s": 39602,
"text": "Java-Set-Programs"
},
{
"code": null,
"e": 39627,
"s": 39620,
"text": "Picked"
},
{
"code": null,
"e": 39632,
"s": 39627,
"text": "Java"
},
{
"code": null,
"e": 39637,
"s": 39632,
"text": "Java"
},
{
"code": null,
"e": 39654,
"s": 39637,
"text": "Java-Collections"
},
{
"code": null,
"e": 39752,
"s": 39654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39761,
"s": 39752,
"text": "Comments"
},
{
"code": null,
"e": 39774,
"s": 39761,
"text": "Old Comments"
},
{
"code": null,
"e": 39793,
"s": 39774,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 39811,
"s": 39793,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 39831,
"s": 39811,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 39855,
"s": 39831,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 39874,
"s": 39855,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 39894,
"s": 39874,
"text": "Collections in Java"
},
{
"code": null,
"e": 39913,
"s": 39894,
"text": "Overriding in Java"
},
{
"code": null,
"e": 39937,
"s": 39913,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 39967,
"s": 39937,
"text": "Functional Interfaces in Java"
}
] |
Flex - Data Binding
|
Data Binding is a process in which data of one object is tied to another object. It requires a source property, a destination property and a triggering event which indicates, when to copy the data from source to destination.
Flex provides three ways to do Data Binding as below
Curly brace syntax in MXML Script ({})
<fx:binding> tag in MXML
BindingUtils in ActionScript
The following example demonstrates how to use curly braces to specify data binding of a source to destination.
<s:TextInput id = "txtInput1" />
<s:TextInput id = "txtInput2" text = "{txtInput1.text}" />
The following example demonstrates how to use tag to specify data binding of a source to destination.
<fx:Binding source = "txtInput1.text" destination = "txtInput2.text" />
<s:TextInput id = "txtInput1" />
<s:TextInput id = "txtInput2" />
The following example demonstrates how to use BindingUtils to specify data binding of a source to destination.
<fx:Script>
<![CDATA[
import mx.binding.utils.BindingUtils;
import mx.events.FlexEvent;
protected function txtInput2_preinitializeHandler(event:FlexEvent):void {
BindingUtils.bindProperty(txtInput2,"text",txtInput1, "text");
}
]]>
</fx:Script>
<s:TextInput id = "txtInput1" />
<s:TextInput id = "txtInput2"
preinitialize = "txtInput2_preinitializeHandler(event)" />
Let us follow the steps given below to see skinning in action in a Flex application by creating a test application −
Following is the content of the modified HelloWorld.mxml filesrc/com/tutorialspoint/client/HelloWorld.mxml.
<?xml version = "1.0" encoding = "utf-8"?>
<s:Application xmlns:fx = "http://ns.adobe.com/mxml/2009"
xmlns:s = "library://ns.adobe.com/flex/spark"
xmlns:mx = "library://ns.adobe.com/flex/mx
width = "100%" height = "100%" minWidth = "500" minHeight = "500">
<fx:Style source = "/com/tutorialspoint/client/Style.css" />
<fx:Script>
<![CDATA[
import mx.binding.utils.BindingUtils;
import mx.events.FlexEvent;
protected function txtInput6_preinitializeHandler(event:FlexEvent):void {
BindingUtils.bindProperty(txtInput6,"text",txtInput5, "text");
}
]]>
</fx:Script>
<fx:Binding source = "txtInput3.text" destination = "txtInput4.text" />
<s:BorderContainer width = "500" height = "550" id = "mainContainer"
styleName = "container">
<s:VGroup width = "100%" height = "100%" gap = "50" horizontalAlign = "center"
verticalAlign = "middle">
<s:Label id = "lblHeader" text = "Data Binding Demonstration"
fontSize = "40" color = "0x777777" styleName = "heading" />
<s:Panel title = "Example #1 (Using Curly Braces,\{\})" width = "400"
height = "100" >
<s:layout>
<s:VerticalLayout paddingTop = "10" paddingLeft = "10" />
</s:layout>
<s:HGroup >
<s:Label text = "Type here: " width = "100" paddingTop = "6" />
<s:TextInput id = "txtInput1" />
</s:HGroup>
<s:HGroup >
<s:Label text = "Copied text: " width = "100" paddingTop = "6" />
<s:TextInput id = "txtInput2" text = "{txtInput1.text}" />
</s:HGroup>
</s:Panel>
<s:Panel title = "Example #2 (Using <fx:Binding>)" width = "400"
height = "100" >
<s:layout>
<s:VerticalLayout paddingTop = "10" paddingLeft = "10" />
</s:layout>
<s:HGroup >
<s:Label text = "Type here: " width = "100" paddingTop = "6" />
<s:TextInput id = "txtInput3" />
</s:HGroup>
<s:HGroup >
<s:Label text = "Copied text: " width = "100" paddingTop = "6" />
<s:Label id = "txtInput4" />
</s:HGroup>
</s:Panel>
<s:Panel title = "Example #3 (Using BindingUtils)" width = "400"
height = "100" >
<s:layout>
<s:VerticalLayout paddingTop = "10" paddingLeft = "10" />
</s:layout>
<s:HGroup >
<s:Label text = "Type here: " width = "100" paddingTop = "6" />
<s:TextInput id = "txtInput5" />
</s:HGroup>
<s:HGroup >
<s:Label text = "Copied text: " width = "100" paddingTop = "6" />
<s:TextInput enabled = "false" id = "txtInput6"
preinitialize = "txtInput6_preinitializeHandler(event)" />
</s:HGroup>
</s:Panel>
</s:VGroup>
</s:BorderContainer>
</s:Application>
Once you are ready with all the changes done, let us compile and run the application in normal mode as we did in Flex - Create Application chapter. If everything is fine with your application, it will produce the following result: [ Try it online ]
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
12 Lectures
1 hours
Prof. Paul Cline, Ed.D
87 Lectures
11 hours
Code And Create
30 Lectures
1 hours
Faigy Liebermann
11 Lectures
1.5 hours
Prof Krishna N Sharma
32 Lectures
34 mins
Prof Krishna N Sharma
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2272,
"s": 2047,
"text": "Data Binding is a process in which data of one object is tied to another object. It requires a source property, a destination property and a triggering event which indicates, when to copy the data from source to destination."
},
{
"code": null,
"e": 2325,
"s": 2272,
"text": "Flex provides three ways to do Data Binding as below"
},
{
"code": null,
"e": 2364,
"s": 2325,
"text": "Curly brace syntax in MXML Script ({})"
},
{
"code": null,
"e": 2389,
"s": 2364,
"text": "<fx:binding> tag in MXML"
},
{
"code": null,
"e": 2418,
"s": 2389,
"text": "BindingUtils in ActionScript"
},
{
"code": null,
"e": 2529,
"s": 2418,
"text": "The following example demonstrates how to use curly braces to specify data binding of a source to destination."
},
{
"code": null,
"e": 2621,
"s": 2529,
"text": "<s:TextInput id = \"txtInput1\" />\n<s:TextInput id = \"txtInput2\" text = \"{txtInput1.text}\" />"
},
{
"code": null,
"e": 2724,
"s": 2621,
"text": "The following example demonstrates how to use tag to specify data binding of a source to destination."
},
{
"code": null,
"e": 2862,
"s": 2724,
"text": "<fx:Binding source = \"txtInput1.text\" destination = \"txtInput2.text\" />\n<s:TextInput id = \"txtInput1\" />\n<s:TextInput id = \"txtInput2\" />"
},
{
"code": null,
"e": 2973,
"s": 2862,
"text": "The following example demonstrates how to use BindingUtils to specify data binding of a source to destination."
},
{
"code": null,
"e": 3390,
"s": 2973,
"text": "<fx:Script>\n <![CDATA[\n import mx.binding.utils.BindingUtils;\n import mx.events.FlexEvent;\n\n protected function txtInput2_preinitializeHandler(event:FlexEvent):void {\n BindingUtils.bindProperty(txtInput2,\"text\",txtInput1, \"text\");\n } \n ]]>\n</fx:Script>\n\n<s:TextInput id = \"txtInput1\" />\n<s:TextInput id = \"txtInput2\" \n preinitialize = \"txtInput2_preinitializeHandler(event)\" />"
},
{
"code": null,
"e": 3507,
"s": 3390,
"text": "Let us follow the steps given below to see skinning in action in a Flex application by creating a test application −"
},
{
"code": null,
"e": 3615,
"s": 3507,
"text": "Following is the content of the modified HelloWorld.mxml filesrc/com/tutorialspoint/client/HelloWorld.mxml."
},
{
"code": null,
"e": 6805,
"s": 3615,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<s:Application xmlns:fx = \"http://ns.adobe.com/mxml/2009\"\n xmlns:s = \"library://ns.adobe.com/flex/spark\"\n xmlns:mx = \"library://ns.adobe.com/flex/mx\n width = \"100%\" height = \"100%\" minWidth = \"500\" minHeight = \"500\">\n \n <fx:Style source = \"/com/tutorialspoint/client/Style.css\" />\n <fx:Script>\n <![CDATA[\n import mx.binding.utils.BindingUtils; \n import mx.events.FlexEvent;\n\n protected function txtInput6_preinitializeHandler(event:FlexEvent):void {\n BindingUtils.bindProperty(txtInput6,\"text\",txtInput5, \"text\");\n }\n ]]>\n </fx:Script>\n \n <fx:Binding source = \"txtInput3.text\" destination = \"txtInput4.text\" />\n <s:BorderContainer width = \"500\" height = \"550\" id = \"mainContainer\" \n styleName = \"container\">\n <s:VGroup width = \"100%\" height = \"100%\" gap = \"50\" horizontalAlign = \"center\" \n verticalAlign = \"middle\">\n <s:Label id = \"lblHeader\" text = \"Data Binding Demonstration\"\n fontSize = \"40\" color = \"0x777777\" styleName = \"heading\" />\n <s:Panel title = \"Example #1 (Using Curly Braces,\\{\\})\" width = \"400\" \n height = \"100\" >\n <s:layout>\n <s:VerticalLayout paddingTop = \"10\" paddingLeft = \"10\" />\n </s:layout>\n \n <s:HGroup >\n <s:Label text = \"Type here: \" width = \"100\" paddingTop = \"6\" />\n <s:TextInput id = \"txtInput1\" />\t\n </s:HGroup>\n \n <s:HGroup >\n <s:Label text = \"Copied text: \" width = \"100\" paddingTop = \"6\" />\n <s:TextInput id = \"txtInput2\" text = \"{txtInput1.text}\" />\n </s:HGroup>\t\t\t\t\t\t\n </s:Panel>\n \n <s:Panel title = \"Example #2 (Using <fx:Binding>)\" width = \"400\" \n height = \"100\" >\n <s:layout>\n <s:VerticalLayout paddingTop = \"10\" paddingLeft = \"10\" />\n </s:layout>\n \n <s:HGroup >\n <s:Label text = \"Type here: \" width = \"100\" paddingTop = \"6\" />\n <s:TextInput id = \"txtInput3\" />\t\n </s:HGroup>\n \n <s:HGroup >\n <s:Label text = \"Copied text: \" width = \"100\" paddingTop = \"6\" />\n <s:Label id = \"txtInput4\" />\n </s:HGroup>\t\t\t\t\t\t\n </s:Panel>\n \n <s:Panel title = \"Example #3 (Using BindingUtils)\" width = \"400\" \n height = \"100\" >\n <s:layout>\n <s:VerticalLayout paddingTop = \"10\" paddingLeft = \"10\" />\n </s:layout>\n \n <s:HGroup >\n <s:Label text = \"Type here: \" width = \"100\" paddingTop = \"6\" />\n <s:TextInput id = \"txtInput5\" />\t\n </s:HGroup>\n \n <s:HGroup >\n <s:Label text = \"Copied text: \" width = \"100\" paddingTop = \"6\" />\n <s:TextInput enabled = \"false\" id = \"txtInput6\" \n preinitialize = \"txtInput6_preinitializeHandler(event)\" />\n </s:HGroup>\t\t\t\t\t\t\n </s:Panel>\n </s:VGroup>\t \n </s:BorderContainer>\t\n</s:Application>"
},
{
"code": null,
"e": 7054,
"s": 6805,
"text": "Once you are ready with all the changes done, let us compile and run the application in normal mode as we did in Flex - Create Application chapter. If everything is fine with your application, it will produce the following result: [ Try it online ]"
},
{
"code": null,
"e": 7089,
"s": 7054,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7120,
"s": 7089,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7153,
"s": 7120,
"text": "\n 12 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7177,
"s": 7153,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 7211,
"s": 7177,
"text": "\n 87 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 7228,
"s": 7211,
"text": " Code And Create"
},
{
"code": null,
"e": 7261,
"s": 7228,
"text": "\n 30 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7279,
"s": 7261,
"text": " Faigy Liebermann"
},
{
"code": null,
"e": 7314,
"s": 7279,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7337,
"s": 7314,
"text": " Prof Krishna N Sharma"
},
{
"code": null,
"e": 7369,
"s": 7337,
"text": "\n 32 Lectures \n 34 mins\n"
},
{
"code": null,
"e": 7392,
"s": 7369,
"text": " Prof Krishna N Sharma"
},
{
"code": null,
"e": 7399,
"s": 7392,
"text": " Print"
},
{
"code": null,
"e": 7410,
"s": 7399,
"text": " Add Notes"
}
] |
How to create half of the string in uppercase and the other half in lowercase? - GeeksforGeeks
|
30 Mar, 2022
The first thing that we have to keep in my mind while solving this kind of problem is that the strings are immutable i.e,
If I am taking the following string
var string1 = "geeksforgeeks";
string1[0] = "G";
console.log(string1);
As strings are immutable, so we cannot change the character of the string, so the output of the above code will be the following.
Output:
geeksforgeeks
Approach:
There are several ways to solve this problem. Some of them are as follows.
Splitting the string into 2 different parts and changing the first part to the UPPERCASE and concatenating the new strings to get the output.
Create an empty string and add each character of the string to it using FOR loop.
Using the slicing property of strings to get the output.
Method 1: This method is implemented using 2 new variables.
Add the string into the variable.
Store the length of the string into a variable using string.length function.
Create two empty strings which are used in the future to store the newly created strings.
Use of for loops to traverse in the string.
Convert the first string to the upper case using toUpperCase().
Concatenate both of the strings to get the output.
C++
Python3
Javascript
#include <iostream>using namespace std; int main() { string str = "geeksforgeeks",ans; int len = str.length(); for(int i = 0;i<len;i++){ if(i<=len/2){ char a = toupper(str[i]); ans.push_back(a); }else ans.push_back(str[i]); } cout<<ans; return 0;} // This code is co ntributed by rohitsingh07052
import math string1 = 'geeksforgeeks'string1_len = len(string1)part_a = ''part_b = '' for i in range(int(math.ceil(string1_len // 2 + 1))): part_a += string1[i] for i in range(int(math.ceil(string1_len // 2)) + 1, string1_len): part_b += string1[i] new_part_a = part_a.upper() changed_string = new_part_a + part_b print(changed_string) # This code is contributed by ukasp
<script>var string1 = 'geeksforgeeks';var string1_len = string1.length;var part_a = '';var part_b = ''; for(var i=0 ; i<Math.ceil(string1_len/2) ; i++){ part_a+=string1[i];} for(var i=Math.ceil(string1_len/2) ; i<string1_len ; i++){ part_b+=string1[i];} var new_part_a = part_a.toUpperCase(); var changed_string = new_part_a + part_b; console.log(changed_string);</script>
Output:
GEEKSFOrgeeks
Time Complexity: O(N)
Auxiliary Space: O(1)
Method 2: This method is implemented using a single new variable.
Add the string into the variable.
Store the length of the string into a variable using string.length function.
Create an empty string that is used in the future to store the newly created string.
Use of for loops to traverse the string.
Log the final string to get the output.
Javascript
Python3
<script>var string1 = 'gfg';var string1_len = string1.length;var changed_string = ''; for(var i=0 ; i<Math.ceil(string1_len/2) ; i++){ changed_string+=string1[i].toUpperCase();} for(var i=Math.ceil(string1_len/2) ; i<string1_len ; i++){ changed_string+=string1[i];} console.log(changed_string);</script>
import math string1 = 'gfg';string1_len = len(string1) changed_string = '' for i in range(math.ceil(string1_len/2)): changed_string += string1[i].upper(); for i in range(math.ceil(string1_len/2), string1_len): changed_string += string1[i] print(changed_string) # This code is contributed by avanitrachhadiya2155
Output:
GFg
Time Complexity: O(N)
Auxiliary Space: O(1)
Method 3: This method is implemented using the JavaScript Slice property.
Add the string into the variable.
Store the length of the string into a variable using string.length function.
Store the ceil value of half of the length of the string to the new variable.
Create 2 empty strings which are used in the future to store the newly created strings.
Add string to the variables using string slicing property.
Convert the first string to the upper case using toUpperCase().
Concatenate both of the strings to get the output.
Python3
Javascript
import math string1 = 'geeks for geeks' string1_len = len(string1) half_string = math.ceil(string1_len/2) part_a = ''part_b = '' part_a = string1[:half_string]new_part_a = part_a.upper() part_b = string1[half_string:string1_len] changed_string = new_part_a+part_b print(changed_string) # This code is contributed by rag2127
<script>var string1 = 'geeks for geeks';var string1_len = string1.length;var half_string = Math.ceil(string1_len/2);var part_a;var part_b; part_a = string1.slice(0,half_string);var new_part_a = part_a.toUpperCase();part_b = string1.slice(half_string,string1_len); var changed_string = new_part_a+part_b; console.log(changed_string);</script>
Output:
GEEKS FOr geeks
Time Complexity: O(N)
Auxiliary Space: O(N)
In these ways, you can solve these kinds of problems.
ukasp
avanitrachhadiya2155
rag2127
rohitsingh07052
rohitkumarsinghcna
javascript-string
Picked
Technical Scripter 2020
JavaScript
Strings
Technical Scripter
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
|
[
{
"code": null,
"e": 24907,
"s": 24879,
"text": "\n30 Mar, 2022"
},
{
"code": null,
"e": 25029,
"s": 24907,
"text": "The first thing that we have to keep in my mind while solving this kind of problem is that the strings are immutable i.e,"
},
{
"code": null,
"e": 25065,
"s": 25029,
"text": "If I am taking the following string"
},
{
"code": null,
"e": 25137,
"s": 25065,
"text": "var string1 = \"geeksforgeeks\";\nstring1[0] = \"G\";\n\nconsole.log(string1);"
},
{
"code": null,
"e": 25267,
"s": 25137,
"text": "As strings are immutable, so we cannot change the character of the string, so the output of the above code will be the following."
},
{
"code": null,
"e": 25275,
"s": 25267,
"text": "Output:"
},
{
"code": null,
"e": 25289,
"s": 25275,
"text": "geeksforgeeks"
},
{
"code": null,
"e": 25299,
"s": 25289,
"text": "Approach:"
},
{
"code": null,
"e": 25374,
"s": 25299,
"text": "There are several ways to solve this problem. Some of them are as follows."
},
{
"code": null,
"e": 25516,
"s": 25374,
"text": "Splitting the string into 2 different parts and changing the first part to the UPPERCASE and concatenating the new strings to get the output."
},
{
"code": null,
"e": 25598,
"s": 25516,
"text": "Create an empty string and add each character of the string to it using FOR loop."
},
{
"code": null,
"e": 25655,
"s": 25598,
"text": "Using the slicing property of strings to get the output."
},
{
"code": null,
"e": 25715,
"s": 25655,
"text": "Method 1: This method is implemented using 2 new variables."
},
{
"code": null,
"e": 25749,
"s": 25715,
"text": "Add the string into the variable."
},
{
"code": null,
"e": 25826,
"s": 25749,
"text": "Store the length of the string into a variable using string.length function."
},
{
"code": null,
"e": 25916,
"s": 25826,
"text": "Create two empty strings which are used in the future to store the newly created strings."
},
{
"code": null,
"e": 25960,
"s": 25916,
"text": "Use of for loops to traverse in the string."
},
{
"code": null,
"e": 26024,
"s": 25960,
"text": "Convert the first string to the upper case using toUpperCase()."
},
{
"code": null,
"e": 26075,
"s": 26024,
"text": "Concatenate both of the strings to get the output."
},
{
"code": null,
"e": 26079,
"s": 26075,
"text": "C++"
},
{
"code": null,
"e": 26087,
"s": 26079,
"text": "Python3"
},
{
"code": null,
"e": 26098,
"s": 26087,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; int main() { string str = \"geeksforgeeks\",ans; int len = str.length(); for(int i = 0;i<len;i++){ if(i<=len/2){ char a = toupper(str[i]); ans.push_back(a); }else ans.push_back(str[i]); } cout<<ans; return 0;} // This code is co ntributed by rohitsingh07052",
"e": 26429,
"s": 26098,
"text": null
},
{
"code": "import math string1 = 'geeksforgeeks'string1_len = len(string1)part_a = ''part_b = '' for i in range(int(math.ceil(string1_len // 2 + 1))): part_a += string1[i] for i in range(int(math.ceil(string1_len // 2)) + 1, string1_len): part_b += string1[i] new_part_a = part_a.upper() changed_string = new_part_a + part_b print(changed_string) # This code is contributed by ukasp",
"e": 26821,
"s": 26429,
"text": null
},
{
"code": "<script>var string1 = 'geeksforgeeks';var string1_len = string1.length;var part_a = '';var part_b = ''; for(var i=0 ; i<Math.ceil(string1_len/2) ; i++){ part_a+=string1[i];} for(var i=Math.ceil(string1_len/2) ; i<string1_len ; i++){ part_b+=string1[i];} var new_part_a = part_a.toUpperCase(); var changed_string = new_part_a + part_b; console.log(changed_string);</script>",
"e": 27200,
"s": 26821,
"text": null
},
{
"code": null,
"e": 27208,
"s": 27200,
"text": "Output:"
},
{
"code": null,
"e": 27222,
"s": 27208,
"text": "GEEKSFOrgeeks"
},
{
"code": null,
"e": 27244,
"s": 27222,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 27266,
"s": 27244,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27332,
"s": 27266,
"text": "Method 2: This method is implemented using a single new variable."
},
{
"code": null,
"e": 27366,
"s": 27332,
"text": "Add the string into the variable."
},
{
"code": null,
"e": 27443,
"s": 27366,
"text": "Store the length of the string into a variable using string.length function."
},
{
"code": null,
"e": 27528,
"s": 27443,
"text": "Create an empty string that is used in the future to store the newly created string."
},
{
"code": null,
"e": 27569,
"s": 27528,
"text": "Use of for loops to traverse the string."
},
{
"code": null,
"e": 27609,
"s": 27569,
"text": "Log the final string to get the output."
},
{
"code": null,
"e": 27620,
"s": 27609,
"text": "Javascript"
},
{
"code": null,
"e": 27628,
"s": 27620,
"text": "Python3"
},
{
"code": "<script>var string1 = 'gfg';var string1_len = string1.length;var changed_string = ''; for(var i=0 ; i<Math.ceil(string1_len/2) ; i++){ changed_string+=string1[i].toUpperCase();} for(var i=Math.ceil(string1_len/2) ; i<string1_len ; i++){ changed_string+=string1[i];} console.log(changed_string);</script>",
"e": 27938,
"s": 27628,
"text": null
},
{
"code": "import math string1 = 'gfg';string1_len = len(string1) changed_string = '' for i in range(math.ceil(string1_len/2)): changed_string += string1[i].upper(); for i in range(math.ceil(string1_len/2), string1_len): changed_string += string1[i] print(changed_string) # This code is contributed by avanitrachhadiya2155",
"e": 28256,
"s": 27938,
"text": null
},
{
"code": null,
"e": 28264,
"s": 28256,
"text": "Output:"
},
{
"code": null,
"e": 28268,
"s": 28264,
"text": "GFg"
},
{
"code": null,
"e": 28290,
"s": 28268,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 28312,
"s": 28290,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28386,
"s": 28312,
"text": "Method 3: This method is implemented using the JavaScript Slice property."
},
{
"code": null,
"e": 28420,
"s": 28386,
"text": "Add the string into the variable."
},
{
"code": null,
"e": 28497,
"s": 28420,
"text": "Store the length of the string into a variable using string.length function."
},
{
"code": null,
"e": 28575,
"s": 28497,
"text": "Store the ceil value of half of the length of the string to the new variable."
},
{
"code": null,
"e": 28663,
"s": 28575,
"text": "Create 2 empty strings which are used in the future to store the newly created strings."
},
{
"code": null,
"e": 28722,
"s": 28663,
"text": "Add string to the variables using string slicing property."
},
{
"code": null,
"e": 28786,
"s": 28722,
"text": "Convert the first string to the upper case using toUpperCase()."
},
{
"code": null,
"e": 28837,
"s": 28786,
"text": "Concatenate both of the strings to get the output."
},
{
"code": null,
"e": 28845,
"s": 28837,
"text": "Python3"
},
{
"code": null,
"e": 28856,
"s": 28845,
"text": "Javascript"
},
{
"code": "import math string1 = 'geeks for geeks' string1_len = len(string1) half_string = math.ceil(string1_len/2) part_a = ''part_b = '' part_a = string1[:half_string]new_part_a = part_a.upper() part_b = string1[half_string:string1_len] changed_string = new_part_a+part_b print(changed_string) # This code is contributed by rag2127",
"e": 29180,
"s": 28856,
"text": null
},
{
"code": "<script>var string1 = 'geeks for geeks';var string1_len = string1.length;var half_string = Math.ceil(string1_len/2);var part_a;var part_b; part_a = string1.slice(0,half_string);var new_part_a = part_a.toUpperCase();part_b = string1.slice(half_string,string1_len); var changed_string = new_part_a+part_b; console.log(changed_string);</script>",
"e": 29522,
"s": 29180,
"text": null
},
{
"code": null,
"e": 29530,
"s": 29522,
"text": "Output:"
},
{
"code": null,
"e": 29546,
"s": 29530,
"text": "GEEKS FOr geeks"
},
{
"code": null,
"e": 29568,
"s": 29546,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 29590,
"s": 29568,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 29644,
"s": 29590,
"text": "In these ways, you can solve these kinds of problems."
},
{
"code": null,
"e": 29650,
"s": 29644,
"text": "ukasp"
},
{
"code": null,
"e": 29671,
"s": 29650,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 29679,
"s": 29671,
"text": "rag2127"
},
{
"code": null,
"e": 29695,
"s": 29679,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 29714,
"s": 29695,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 29732,
"s": 29714,
"text": "javascript-string"
},
{
"code": null,
"e": 29739,
"s": 29732,
"text": "Picked"
},
{
"code": null,
"e": 29763,
"s": 29739,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29774,
"s": 29763,
"text": "JavaScript"
},
{
"code": null,
"e": 29782,
"s": 29774,
"text": "Strings"
},
{
"code": null,
"e": 29801,
"s": 29782,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29809,
"s": 29801,
"text": "Strings"
},
{
"code": null,
"e": 29907,
"s": 29809,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29916,
"s": 29907,
"text": "Comments"
},
{
"code": null,
"e": 29929,
"s": 29916,
"text": "Old Comments"
},
{
"code": null,
"e": 29990,
"s": 29929,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30031,
"s": 29990,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30071,
"s": 30031,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30125,
"s": 30071,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30187,
"s": 30125,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 30212,
"s": 30187,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30258,
"s": 30212,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 30292,
"s": 30258,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 30352,
"s": 30292,
"text": "Write a program to print all permutations of a given string"
}
] |
How to change files and folders attributes using PowerShell?
|
There are multiple files and folders attribute supported by the Windows Operating System. To check which attributes that files and folders support use DOS command attrib /?
You can see the attributes listed like Read-Only, Archive, etc. You can set the attribute using PowerShell.
For example, we have a file called TestFile.txt and its attribute is ReadOnly and we need to change it to the Archive.
PS C:\> (Get-ChildItem C:\Temp\TestFile.txt).Attributes
ReadOnly
Change Attribute code −
$file = Get-ChildItem C:\Temp\TestFile.txt
$file.Attributes = 'Archive'
So we have set the attribute to the ‘Archive’ from ‘ReadOnly’ and when you check it, the attribute should be changed.
PS C:\> (Get-ChildItem C:\Temp\TestFile.txt).Attributes
Archive
To set the multiple attributes, you can separate the values by a comma. For example,
$file = Get-ChildItem C:\Temp\TestFile.txt
$file.Attributes = 'Archive','ReadOnly'
(Get-ChildItem C:\Temp\TestFile.txt).Attributes
ReadOnly, Archive
Similar way you can change the attributes of the folder. For example,
$folder = Get-Item C:\Temp
$folder.Attributes = 'Directory','Hidden'
We will check the folder attributes now. This folder is hidden so we need to use -Hidden parameter.
PS C:\> (Get-ChildItem C:\Temp\ -Hidden).Attributes
Hidden, Directory
To change attributes on the multiple files in the same folder, you need to use foreach loop. For example,
Get-ChildItem C:\Test1\ -Recurse | foreach{$_.Attributes = 'Hidden'}
When we check their values, they should be hidden.
PS C:\> Get-ChildItem C:\Test1 -Recurse -Force
Directory: C:\Test1
Mode LastWriteTime Length Name
---- ------------- ------ ----
---h-- 8/28/2020 7:27 AM 11 File1.txt
---h-- 8/28/2020 7:49 AM 11 File2.txt
-Recurse parameter is to retrieve the data from subfolders. If you need only parent folder data attribute change then remove -Recure parameter.
|
[
{
"code": null,
"e": 1235,
"s": 1062,
"text": "There are multiple files and folders attribute supported by the Windows Operating System. To check which attributes that files and folders support use DOS command attrib /?"
},
{
"code": null,
"e": 1343,
"s": 1235,
"text": "You can see the attributes listed like Read-Only, Archive, etc. You can set the attribute using PowerShell."
},
{
"code": null,
"e": 1462,
"s": 1343,
"text": "For example, we have a file called TestFile.txt and its attribute is ReadOnly and we need to change it to the Archive."
},
{
"code": null,
"e": 1527,
"s": 1462,
"text": "PS C:\\> (Get-ChildItem C:\\Temp\\TestFile.txt).Attributes\nReadOnly"
},
{
"code": null,
"e": 1551,
"s": 1527,
"text": "Change Attribute code −"
},
{
"code": null,
"e": 1623,
"s": 1551,
"text": "$file = Get-ChildItem C:\\Temp\\TestFile.txt\n$file.Attributes = 'Archive'"
},
{
"code": null,
"e": 1741,
"s": 1623,
"text": "So we have set the attribute to the ‘Archive’ from ‘ReadOnly’ and when you check it, the attribute should be changed."
},
{
"code": null,
"e": 1805,
"s": 1741,
"text": "PS C:\\> (Get-ChildItem C:\\Temp\\TestFile.txt).Attributes\nArchive"
},
{
"code": null,
"e": 1890,
"s": 1805,
"text": "To set the multiple attributes, you can separate the values by a comma. For example,"
},
{
"code": null,
"e": 2039,
"s": 1890,
"text": "$file = Get-ChildItem C:\\Temp\\TestFile.txt\n$file.Attributes = 'Archive','ReadOnly'\n(Get-ChildItem C:\\Temp\\TestFile.txt).Attributes\nReadOnly, Archive"
},
{
"code": null,
"e": 2109,
"s": 2039,
"text": "Similar way you can change the attributes of the folder. For example,"
},
{
"code": null,
"e": 2178,
"s": 2109,
"text": "$folder = Get-Item C:\\Temp\n$folder.Attributes = 'Directory','Hidden'"
},
{
"code": null,
"e": 2278,
"s": 2178,
"text": "We will check the folder attributes now. This folder is hidden so we need to use -Hidden parameter."
},
{
"code": null,
"e": 2348,
"s": 2278,
"text": "PS C:\\> (Get-ChildItem C:\\Temp\\ -Hidden).Attributes\nHidden, Directory"
},
{
"code": null,
"e": 2454,
"s": 2348,
"text": "To change attributes on the multiple files in the same folder, you need to use foreach loop. For example,"
},
{
"code": null,
"e": 2523,
"s": 2454,
"text": "Get-ChildItem C:\\Test1\\ -Recurse | foreach{$_.Attributes = 'Hidden'}"
},
{
"code": null,
"e": 2574,
"s": 2523,
"text": "When we check their values, they should be hidden."
},
{
"code": null,
"e": 2805,
"s": 2574,
"text": "PS C:\\> Get-ChildItem C:\\Test1 -Recurse -Force\n\nDirectory: C:\\Test1\n\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n---h-- 8/28/2020 7:27 AM 11 File1.txt\n---h-- 8/28/2020 7:49 AM 11 File2.txt"
},
{
"code": null,
"e": 2949,
"s": 2805,
"text": "-Recurse parameter is to retrieve the data from subfolders. If you need only parent folder data attribute change then remove -Recure parameter."
}
] |
Dataprep.eda: Accelerate your EDA | by Slavvy Coelho | Towards Data Science
|
Authors: Slavvy Coelho, Ruchita Rozario
Mentor: Dr. Jiannan Wang, Director, SFU’s Professional Master’s Programs (Big Data and Cybersecurity and Visual Computing)
“Numbers have an important story to tell. They rely on you to give them a clear and convincing voice” — Stephen Few
Most of the industries today have recognized data as a valuable asset. However, what you do with the data and how you utilize it is what helps you get those additional profit figures or that new discovery that is going to create a revolution.
When you start working with a dataset most of the trends and patterns are not apparent. Exploratory data analysis helps one to carefully analyze data through an analytical lens. It helps us draw conclusions to get an overall sense of what’s happening with the data. Uncovering these hidden relationships and patterns are critical to build analytical and learning models on the top of the data.
The general workflow of EDA looks as follows:
Dataprepare is an initiative by SFU Data Science Research Group to speed up Data Science. Dataprep.eda attempts to simplify the entire EDA process with very minimal lines of code. Since we know that EDA is a very essential and time-consuming part of the data science pipeline, having a tool that eases the process is a boon.
This blog intends on providing you an easy and hands-on experience of everything you can do with dataprepare.eda. So let’s dive into it, shall we?
#installing dataprep.eda#open your terminalpip install dataprep
In order to simplify things, we have worked on a Fraud Detection dataset. The data has columns like amount, original balance, origin account, destination account, etc. and finally a label column that indicates if this transaction was in fact a fraudulent transaction or not.
#importing all the librariesimport pandas as pdfrom dataprep.eda import plot, plot_correlation, plot_missing#importing data and dropping missing valuesdf = pd.read_csv("capdata.csv")
The data looks as follows:
The dataprep.eda package has 4 submodules. We shall explain each one of them:
plot(): analyze distributions
plot(): analyze distributions
We provide an API plot() to allow users to analyze the basic characteristics of the dataset. It plots the distribution or bar chart for each column to give the user a basic sense of the dataset.
#API Plotplot(df)
If a user is interested in one or two specific columns, it provides a more detailed plot for the specific columns by passing column names as the parameter.
plot(df, "newbalanceDest", bins=20)
If x contains categorical values, a bar chart and pie chart are plotted.
plot(df,"type")
If x contains numerical values, a histogram, kernel density estimate plot, box plot, and qq plot are plotted.
plot(df, "newbalanceDest", "oldbalanceDest")
If x and y contain numerical values, a scatter plot, hexbin plot, and binned box plot are plotted. If one of x and y contain categorical values and the other contains numerical values, a box plot and multi-line histogram are plotted. If x and y contain categorical vales, a nested bar chart, stacked bar chart, and heat map are plotted.
2. plot_correlation(): analyze correlations
We provide an API plot_correlation to analyze the correlation between columns. It plots the correlation matrix between columns. If a user is interested in the correlated columns for a specific column, e.g the most correlated columns to column ‘A’, the API can provide a more detailed analysis by passing column names as the parameter.
#API Correlationplot_correlation(df)
plot_correlation(df, k=1)
Top ‘k’ attributes’ correlation heatmap (here, k=1)
plot_correlation(df, "newbalanceOrig")
Correlation of specified element with all other attributes. (ie. newbalanceOrig with everything else).
plot_correlation(df, "newbalanceOrig", value_range=[-1, 0.3])
All the correlation values that lie within the given range. (-1, 0.3) for newbalanceOrig will appear in the plot.
plot_correlation(df, x="newbalanceDest", y="oldbalanceDest", k=5)
Correlation between two attributes with line of best fit and most influential points.
3. plot_missing(): analyze missing values
We provide an API plot_missing to analyze the pattern and impact of missing values. At the first glance, it shows the position of missing values, which allows the user to be aware of data quality for each column or find any underlying pattern of missing values.
#API Missing Valueplot_missing(df)
To understand the impact of missing values from a specific column, users can pass the column name into the parameter. It will compare the distribution of each column with and without missing values from the given column, such that the user could understand the impact of the missing values.
plot_missing(df, "isFraud", "type") #count of rows with and without dropping the missing values
4. create_report: generate profile reports from a Pandas dataframe.
The goal of create_report is to generate profile reports from a pandas DataFrame. create_report utilizes the functionalities and formats the plots from dataprep. It provides information like overview, variables, quantile statistics (minimum value, Q1, median, Q3, maximum, range, interquartile range), descriptive statistics (mean, mode, standard deviation, sum, median absolute deviation, coefficient of variation, kurtosis, skewness), text analysis for length, sample and letter, correlations and missing values.
from dataprepare.eda import create_reportdf = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv")create_report(df)
The above 3 APIs in combination work towards easing the EDA process.
To support this, we conducted a survey to compare dataprep.eda to traditional python EDA implementation. We surveyed 10 people (a mix of real-world Data Scientists and University students studying Data Science). The survey was based on 3 key performance indicators:
Need: Here we analyzed the number of minutes data professionals spend on EDA per project.
Need: Here we analyzed the number of minutes data professionals spend on EDA per project.
As we can see, most people spend about an hour and half over EDA on an average. This result establishes the fact that we need tools to speed up EDA process.
2. Readability: Here we made a comparison of the two approaches to see how readable they are.
Clearly, dataprepare.eda provides a more lucid and readable code.
3. Lines of code: Does dataprep.eda really reduce the length of code?
In addition to the above key performance indicators, dataprep.eda also proves to be better at several other aspects compared to normal python implementation and even existing data profiling libraries like pandas profiling. Let’s take a look at how these three approaches perform when pitted against each other.
When we compare the efficiency of the other two approaches versus Dataprep.eda, it proves to be more efficient.
When we compare the efficiency of the other two approaches versus Dataprep.eda, it proves to be more efficient.
2. When we talk about these methods and their capabilities to support out of memory data, Dataprepare.eda is the only one that supports out-of-memory data processing. This proves to be very useful in today’s era of Big Data.
3. The plots generated by dataprep.eda are all interactive but matplotlib and seaborn only create static plots. This facilitates deeper understanding of the plot.
We asked several industry professionals and university students to give their feedback on this amazing tool.
Here’s what some of them have to say:
“The library looks really good. Eases the work by a great margin. All the best for the venture” — Dhruva Gaidhani, Software Developer at Amazon
“Spotting missing values is efficient. I usually spend a lot of time on EDA. The library has definitely eased a few functionalities.” — Manan Parasher, Alumni of SFU
Data science is adapting every second as we speak. We are exploring the lengths and breadths of almost all the domains right from sport analysis to medical imaging. These times call for us to channel the power of AI and Machine Learning into developing things that will make an impact and save those few seconds. Having tools like data prepare at our disposal enables us to carry out the preparatory tasks more efficiently.
Dataprepare.eda excels at tasks like checking the data-distribution, correlation, missing values and the EDA process in general. The ease of coding and readability also facilitates novices to use dataprepare library. All in all, Dataprepare.eda serves as your one-stop library for carrying out all the preparatory analysis tasks. It’s an upcoming library with a promising future!
|
[
{
"code": null,
"e": 212,
"s": 172,
"text": "Authors: Slavvy Coelho, Ruchita Rozario"
},
{
"code": null,
"e": 335,
"s": 212,
"text": "Mentor: Dr. Jiannan Wang, Director, SFU’s Professional Master’s Programs (Big Data and Cybersecurity and Visual Computing)"
},
{
"code": null,
"e": 451,
"s": 335,
"text": "“Numbers have an important story to tell. They rely on you to give them a clear and convincing voice” — Stephen Few"
},
{
"code": null,
"e": 694,
"s": 451,
"text": "Most of the industries today have recognized data as a valuable asset. However, what you do with the data and how you utilize it is what helps you get those additional profit figures or that new discovery that is going to create a revolution."
},
{
"code": null,
"e": 1088,
"s": 694,
"text": "When you start working with a dataset most of the trends and patterns are not apparent. Exploratory data analysis helps one to carefully analyze data through an analytical lens. It helps us draw conclusions to get an overall sense of what’s happening with the data. Uncovering these hidden relationships and patterns are critical to build analytical and learning models on the top of the data."
},
{
"code": null,
"e": 1134,
"s": 1088,
"text": "The general workflow of EDA looks as follows:"
},
{
"code": null,
"e": 1459,
"s": 1134,
"text": "Dataprepare is an initiative by SFU Data Science Research Group to speed up Data Science. Dataprep.eda attempts to simplify the entire EDA process with very minimal lines of code. Since we know that EDA is a very essential and time-consuming part of the data science pipeline, having a tool that eases the process is a boon."
},
{
"code": null,
"e": 1606,
"s": 1459,
"text": "This blog intends on providing you an easy and hands-on experience of everything you can do with dataprepare.eda. So let’s dive into it, shall we?"
},
{
"code": null,
"e": 1670,
"s": 1606,
"text": "#installing dataprep.eda#open your terminalpip install dataprep"
},
{
"code": null,
"e": 1945,
"s": 1670,
"text": "In order to simplify things, we have worked on a Fraud Detection dataset. The data has columns like amount, original balance, origin account, destination account, etc. and finally a label column that indicates if this transaction was in fact a fraudulent transaction or not."
},
{
"code": null,
"e": 2128,
"s": 1945,
"text": "#importing all the librariesimport pandas as pdfrom dataprep.eda import plot, plot_correlation, plot_missing#importing data and dropping missing valuesdf = pd.read_csv(\"capdata.csv\")"
},
{
"code": null,
"e": 2155,
"s": 2128,
"text": "The data looks as follows:"
},
{
"code": null,
"e": 2233,
"s": 2155,
"text": "The dataprep.eda package has 4 submodules. We shall explain each one of them:"
},
{
"code": null,
"e": 2263,
"s": 2233,
"text": "plot(): analyze distributions"
},
{
"code": null,
"e": 2293,
"s": 2263,
"text": "plot(): analyze distributions"
},
{
"code": null,
"e": 2488,
"s": 2293,
"text": "We provide an API plot() to allow users to analyze the basic characteristics of the dataset. It plots the distribution or bar chart for each column to give the user a basic sense of the dataset."
},
{
"code": null,
"e": 2507,
"s": 2488,
"text": "#API Plotplot(df) "
},
{
"code": null,
"e": 2663,
"s": 2507,
"text": "If a user is interested in one or two specific columns, it provides a more detailed plot for the specific columns by passing column names as the parameter."
},
{
"code": null,
"e": 2699,
"s": 2663,
"text": "plot(df, \"newbalanceDest\", bins=20)"
},
{
"code": null,
"e": 2772,
"s": 2699,
"text": "If x contains categorical values, a bar chart and pie chart are plotted."
},
{
"code": null,
"e": 2788,
"s": 2772,
"text": "plot(df,\"type\")"
},
{
"code": null,
"e": 2898,
"s": 2788,
"text": "If x contains numerical values, a histogram, kernel density estimate plot, box plot, and qq plot are plotted."
},
{
"code": null,
"e": 2943,
"s": 2898,
"text": "plot(df, \"newbalanceDest\", \"oldbalanceDest\")"
},
{
"code": null,
"e": 3280,
"s": 2943,
"text": "If x and y contain numerical values, a scatter plot, hexbin plot, and binned box plot are plotted. If one of x and y contain categorical values and the other contains numerical values, a box plot and multi-line histogram are plotted. If x and y contain categorical vales, a nested bar chart, stacked bar chart, and heat map are plotted."
},
{
"code": null,
"e": 3324,
"s": 3280,
"text": "2. plot_correlation(): analyze correlations"
},
{
"code": null,
"e": 3659,
"s": 3324,
"text": "We provide an API plot_correlation to analyze the correlation between columns. It plots the correlation matrix between columns. If a user is interested in the correlated columns for a specific column, e.g the most correlated columns to column ‘A’, the API can provide a more detailed analysis by passing column names as the parameter."
},
{
"code": null,
"e": 3696,
"s": 3659,
"text": "#API Correlationplot_correlation(df)"
},
{
"code": null,
"e": 3722,
"s": 3696,
"text": "plot_correlation(df, k=1)"
},
{
"code": null,
"e": 3774,
"s": 3722,
"text": "Top ‘k’ attributes’ correlation heatmap (here, k=1)"
},
{
"code": null,
"e": 3814,
"s": 3774,
"text": "plot_correlation(df, \"newbalanceOrig\") "
},
{
"code": null,
"e": 3917,
"s": 3814,
"text": "Correlation of specified element with all other attributes. (ie. newbalanceOrig with everything else)."
},
{
"code": null,
"e": 3979,
"s": 3917,
"text": "plot_correlation(df, \"newbalanceOrig\", value_range=[-1, 0.3])"
},
{
"code": null,
"e": 4093,
"s": 3979,
"text": "All the correlation values that lie within the given range. (-1, 0.3) for newbalanceOrig will appear in the plot."
},
{
"code": null,
"e": 4159,
"s": 4093,
"text": "plot_correlation(df, x=\"newbalanceDest\", y=\"oldbalanceDest\", k=5)"
},
{
"code": null,
"e": 4245,
"s": 4159,
"text": "Correlation between two attributes with line of best fit and most influential points."
},
{
"code": null,
"e": 4287,
"s": 4245,
"text": "3. plot_missing(): analyze missing values"
},
{
"code": null,
"e": 4549,
"s": 4287,
"text": "We provide an API plot_missing to analyze the pattern and impact of missing values. At the first glance, it shows the position of missing values, which allows the user to be aware of data quality for each column or find any underlying pattern of missing values."
},
{
"code": null,
"e": 4585,
"s": 4549,
"text": "#API Missing Valueplot_missing(df) "
},
{
"code": null,
"e": 4876,
"s": 4585,
"text": "To understand the impact of missing values from a specific column, users can pass the column name into the parameter. It will compare the distribution of each column with and without missing values from the given column, such that the user could understand the impact of the missing values."
},
{
"code": null,
"e": 4972,
"s": 4876,
"text": "plot_missing(df, \"isFraud\", \"type\") #count of rows with and without dropping the missing values"
},
{
"code": null,
"e": 5040,
"s": 4972,
"text": "4. create_report: generate profile reports from a Pandas dataframe."
},
{
"code": null,
"e": 5555,
"s": 5040,
"text": "The goal of create_report is to generate profile reports from a pandas DataFrame. create_report utilizes the functionalities and formats the plots from dataprep. It provides information like overview, variables, quantile statistics (minimum value, Q1, median, Q3, maximum, range, interquartile range), descriptive statistics (mean, mode, standard deviation, sum, median absolute deviation, coefficient of variation, kurtosis, skewness), text analysis for length, sample and letter, correlations and missing values."
},
{
"code": null,
"e": 5711,
"s": 5555,
"text": "from dataprepare.eda import create_reportdf = pd.read_csv(\"https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv\")create_report(df)"
},
{
"code": null,
"e": 5780,
"s": 5711,
"text": "The above 3 APIs in combination work towards easing the EDA process."
},
{
"code": null,
"e": 6046,
"s": 5780,
"text": "To support this, we conducted a survey to compare dataprep.eda to traditional python EDA implementation. We surveyed 10 people (a mix of real-world Data Scientists and University students studying Data Science). The survey was based on 3 key performance indicators:"
},
{
"code": null,
"e": 6136,
"s": 6046,
"text": "Need: Here we analyzed the number of minutes data professionals spend on EDA per project."
},
{
"code": null,
"e": 6226,
"s": 6136,
"text": "Need: Here we analyzed the number of minutes data professionals spend on EDA per project."
},
{
"code": null,
"e": 6383,
"s": 6226,
"text": "As we can see, most people spend about an hour and half over EDA on an average. This result establishes the fact that we need tools to speed up EDA process."
},
{
"code": null,
"e": 6477,
"s": 6383,
"text": "2. Readability: Here we made a comparison of the two approaches to see how readable they are."
},
{
"code": null,
"e": 6543,
"s": 6477,
"text": "Clearly, dataprepare.eda provides a more lucid and readable code."
},
{
"code": null,
"e": 6613,
"s": 6543,
"text": "3. Lines of code: Does dataprep.eda really reduce the length of code?"
},
{
"code": null,
"e": 6924,
"s": 6613,
"text": "In addition to the above key performance indicators, dataprep.eda also proves to be better at several other aspects compared to normal python implementation and even existing data profiling libraries like pandas profiling. Let’s take a look at how these three approaches perform when pitted against each other."
},
{
"code": null,
"e": 7036,
"s": 6924,
"text": "When we compare the efficiency of the other two approaches versus Dataprep.eda, it proves to be more efficient."
},
{
"code": null,
"e": 7148,
"s": 7036,
"text": "When we compare the efficiency of the other two approaches versus Dataprep.eda, it proves to be more efficient."
},
{
"code": null,
"e": 7373,
"s": 7148,
"text": "2. When we talk about these methods and their capabilities to support out of memory data, Dataprepare.eda is the only one that supports out-of-memory data processing. This proves to be very useful in today’s era of Big Data."
},
{
"code": null,
"e": 7536,
"s": 7373,
"text": "3. The plots generated by dataprep.eda are all interactive but matplotlib and seaborn only create static plots. This facilitates deeper understanding of the plot."
},
{
"code": null,
"e": 7645,
"s": 7536,
"text": "We asked several industry professionals and university students to give their feedback on this amazing tool."
},
{
"code": null,
"e": 7683,
"s": 7645,
"text": "Here’s what some of them have to say:"
},
{
"code": null,
"e": 7827,
"s": 7683,
"text": "“The library looks really good. Eases the work by a great margin. All the best for the venture” — Dhruva Gaidhani, Software Developer at Amazon"
},
{
"code": null,
"e": 7993,
"s": 7827,
"text": "“Spotting missing values is efficient. I usually spend a lot of time on EDA. The library has definitely eased a few functionalities.” — Manan Parasher, Alumni of SFU"
},
{
"code": null,
"e": 8417,
"s": 7993,
"text": "Data science is adapting every second as we speak. We are exploring the lengths and breadths of almost all the domains right from sport analysis to medical imaging. These times call for us to channel the power of AI and Machine Learning into developing things that will make an impact and save those few seconds. Having tools like data prepare at our disposal enables us to carry out the preparatory tasks more efficiently."
}
] |
Probability Sampling Methods Explained with Python | by 👩🏻💻 Kessie Zhang | Towards Data Science
|
Sampling is used when we try to draw a conclusion without knowing the population. Population refers to the complete collection of observations we want to study, and a sample is a subset of the target population. Here’s an example. A Gallup poll1, conducted between July 15 to 31 last year, found that 42% of Americans approve of the way Donald Trump is handling his job as president. The results were based on telephone interviews of a random sample of ~4500 calls (assuming one adult per call. ~4500 adults), aged 18 and older, living in the U.S. The poll was conducted during a period of controversy over Trump’s social media comments. For this survey, the population is ALL the U.S citizens aged 18 and older, and the sample is 4500 adults.
If sampling is done wrong, it will lead to biases that affect the accuracy of your research/survey results. To avoid selection biases, we have to carefully choose a subset of a population that can be representative of the group as a whole.
Simple random sampling means we randomly select samples from the population where every unit has the same probability of being selected.
Pros: there’s no need to divide the population into subgroups or take any other additional steps before selecting members of the population at random.
Cons: the samples might not be representative, and it could be time-consuming for large populations.
Use Case: it’s used when we don’t know too much about the population.
#let's create a dataframe first!import numpy as npimport pandas as pdfrom numpy.random import randn# Define total number of customersnumber_of_customers = 10# Create data dictionarydata = {'customer_id':np.arange(1, number_of_customers+1).tolist(), 'customer_life_time_value':randn(10)}# Transform dictionary into a data framedf = pd.DataFrame(data)# View data framedf
#only using random(), we can generate 4 samples from this dataset# Obtain simple random samplesimple_random_sample = df.sample(n=4).sort_values(by='customer_id')simple_random_sample
For stratified sampling the population is divided into subgroups (called strata), then randomly select samples from each stratum.
Pros: it captures key population characteristics, so the sample is more representative of the population.
Cons: it’s ineffective if subgroups cannot be formed.
Use Case: it’s commonly used in geographic sampling where strata can be states, countries, or ecoregions.
#Let's add subgroup labels to the datasetdf['strata']=[0, 0, 0, 1, 1, 1, 1, 1, 2, 2]sss = StratifiedShuffleSplit(n_splits=5, test_size=0.5, random_state=0)for x, y in sss.split(df, df['strata']): stratified_random_sample = df.iloc[y].sort_values(by='customer_id')stratified_random_sample
For clustering sampling, the population is divided into different clusters. Then a fixed number of clusters are randomly sampled and all units within each of the selected clusters are included in the sample.
Pros: it reduces variability, and it’s easy to conduct.
Cons: it is possible to introduce bias during sampling.
Use Case: it’s used when all individuals in each cluster can be representative of the populations.
#create 4 different clusters based on customers' lift time valuesdf['cluster'] = pd.cut(df['customer_life_time_value'], bins=4, labels=False) +1
# predefine which clusters/groups we want to select samples fromn=[2,4]def clustering_sampling(df,n): df_list=[] for i in range(len(n)): df1=df[df['cluster']==n[i]] df_list.append(df1) final_df=pd.concat(df_list, ignore_index=True) return final_dfclustering_sampling(df,n)
A systematic sample is drawn by selecting units systematically from a sample frame. (i.e every other unit is included in the sample)
Pros: it can eliminate clustered selection, and it’s simple to execute.
Cons: we need to predetermine the estimated population size. It doesn’t work well if the population has a type of standardized pattern.
Use Case: it’s used when the relevant data does not exhibit patterns.
def systematic_sampling(df, step): indexes = np.arange(0,len(df),step=step) systematic_sample = df.iloc[indexes] return systematic_sample systematic_sampling(df, 1)
|
[
{
"code": null,
"e": 916,
"s": 172,
"text": "Sampling is used when we try to draw a conclusion without knowing the population. Population refers to the complete collection of observations we want to study, and a sample is a subset of the target population. Here’s an example. A Gallup poll1, conducted between July 15 to 31 last year, found that 42% of Americans approve of the way Donald Trump is handling his job as president. The results were based on telephone interviews of a random sample of ~4500 calls (assuming one adult per call. ~4500 adults), aged 18 and older, living in the U.S. The poll was conducted during a period of controversy over Trump’s social media comments. For this survey, the population is ALL the U.S citizens aged 18 and older, and the sample is 4500 adults."
},
{
"code": null,
"e": 1156,
"s": 916,
"text": "If sampling is done wrong, it will lead to biases that affect the accuracy of your research/survey results. To avoid selection biases, we have to carefully choose a subset of a population that can be representative of the group as a whole."
},
{
"code": null,
"e": 1293,
"s": 1156,
"text": "Simple random sampling means we randomly select samples from the population where every unit has the same probability of being selected."
},
{
"code": null,
"e": 1444,
"s": 1293,
"text": "Pros: there’s no need to divide the population into subgroups or take any other additional steps before selecting members of the population at random."
},
{
"code": null,
"e": 1545,
"s": 1444,
"text": "Cons: the samples might not be representative, and it could be time-consuming for large populations."
},
{
"code": null,
"e": 1615,
"s": 1545,
"text": "Use Case: it’s used when we don’t know too much about the population."
},
{
"code": null,
"e": 1990,
"s": 1615,
"text": "#let's create a dataframe first!import numpy as npimport pandas as pdfrom numpy.random import randn# Define total number of customersnumber_of_customers = 10# Create data dictionarydata = {'customer_id':np.arange(1, number_of_customers+1).tolist(), 'customer_life_time_value':randn(10)}# Transform dictionary into a data framedf = pd.DataFrame(data)# View data framedf"
},
{
"code": null,
"e": 2172,
"s": 1990,
"text": "#only using random(), we can generate 4 samples from this dataset# Obtain simple random samplesimple_random_sample = df.sample(n=4).sort_values(by='customer_id')simple_random_sample"
},
{
"code": null,
"e": 2302,
"s": 2172,
"text": "For stratified sampling the population is divided into subgroups (called strata), then randomly select samples from each stratum."
},
{
"code": null,
"e": 2408,
"s": 2302,
"text": "Pros: it captures key population characteristics, so the sample is more representative of the population."
},
{
"code": null,
"e": 2462,
"s": 2408,
"text": "Cons: it’s ineffective if subgroups cannot be formed."
},
{
"code": null,
"e": 2568,
"s": 2462,
"text": "Use Case: it’s commonly used in geographic sampling where strata can be states, countries, or ecoregions."
},
{
"code": null,
"e": 2859,
"s": 2568,
"text": "#Let's add subgroup labels to the datasetdf['strata']=[0, 0, 0, 1, 1, 1, 1, 1, 2, 2]sss = StratifiedShuffleSplit(n_splits=5, test_size=0.5, random_state=0)for x, y in sss.split(df, df['strata']): stratified_random_sample = df.iloc[y].sort_values(by='customer_id')stratified_random_sample"
},
{
"code": null,
"e": 3067,
"s": 2859,
"text": "For clustering sampling, the population is divided into different clusters. Then a fixed number of clusters are randomly sampled and all units within each of the selected clusters are included in the sample."
},
{
"code": null,
"e": 3123,
"s": 3067,
"text": "Pros: it reduces variability, and it’s easy to conduct."
},
{
"code": null,
"e": 3179,
"s": 3123,
"text": "Cons: it is possible to introduce bias during sampling."
},
{
"code": null,
"e": 3278,
"s": 3179,
"text": "Use Case: it’s used when all individuals in each cluster can be representative of the populations."
},
{
"code": null,
"e": 3423,
"s": 3278,
"text": "#create 4 different clusters based on customers' lift time valuesdf['cluster'] = pd.cut(df['customer_life_time_value'], bins=4, labels=False) +1"
},
{
"code": null,
"e": 3726,
"s": 3423,
"text": "# predefine which clusters/groups we want to select samples fromn=[2,4]def clustering_sampling(df,n): df_list=[] for i in range(len(n)): df1=df[df['cluster']==n[i]] df_list.append(df1) final_df=pd.concat(df_list, ignore_index=True) return final_dfclustering_sampling(df,n)"
},
{
"code": null,
"e": 3859,
"s": 3726,
"text": "A systematic sample is drawn by selecting units systematically from a sample frame. (i.e every other unit is included in the sample)"
},
{
"code": null,
"e": 3931,
"s": 3859,
"text": "Pros: it can eliminate clustered selection, and it’s simple to execute."
},
{
"code": null,
"e": 4067,
"s": 3931,
"text": "Cons: we need to predetermine the estimated population size. It doesn’t work well if the population has a type of standardized pattern."
},
{
"code": null,
"e": 4137,
"s": 4067,
"text": "Use Case: it’s used when the relevant data does not exhibit patterns."
}
] |
SQL - Numeric Functions
|
SQL numeric functions are used primarily for numeric manipulation and/or mathematical calculations. The following table details the numeric functions −
Returns the absolute value of numeric expression.
Returns the arccosine of numeric expression. Returns NULL if the value is not in the range -1 to 1.
Returns the arcsine of numeric expression. Returns NULL if value is not in the range -1 to 1
Returns the arctangent of numeric expression.
Returns the arctangent of the two variables passed to it.
Returns the bitwise AND all the bits in expression.
Returns the string representation of the binary value passed to it.
Returns the bitwise OR of all the bits in the passed expression.
Returns the smallest integer value that is not less than passed numeric expression
Returns the smallest integer value that is not less than passed numeric expression
Convert numeric expression from one base to another.
Returns the cosine of passed numeric expression. The numeric expression should be expressed in radians.
Returns the cotangent of passed numeric expression.
Returns numeric expression converted from radians to degrees.
Returns the base of the natural logarithm (e) raised to the power of passed numeric expression.
Returns the largest integer value that is not greater than passed numeric expression.
Returns a numeric expression rounded to a number of decimal places.
Returns the largest value of the input expressions.
Takes multiple expressions exp1, exp2 and exp3 so on.. and returns 0 if exp1 is less than exp2, returns 1 if exp1 is less than exp3 and so on.
Returns the minimum-valued input when given two or more.
Returns the natural logarithm of the passed numeric expression.
Returns the base-10 logarithm of the passed numeric expression.
Returns the remainder of one expression by diving by another expression.
Returns the string representation of the octal value of the passed numeric expression. Returns NULL if passed value is NULL.
Returns the value of pi
Returns the value of one expression raised to the power of another expression
Returns the value of one expression raised to the power of another expression
Returns the value of passed expression converted from degrees to radians.
Returns numeric expression rounded to an integer. Can be used to round an expression to a number of decimal points
Returns the sine of numeric expression given in radians.
Returns the non-negative square root of numeric expression.
Returns the standard deviation of the numeric expression.
Returns the standard deviation of the numeric expression.
Returns the tangent of numeric expression expressed in radians.
Returns numeric exp1 truncated to exp2 decimal places. If exp2 is 0, then the result will have no decimal point.
The ABS() function returns the absolute value of X. Consider the following example −
SQL> SELECT ABS(2);
+---------------------------------------------------------+
| ABS(2) |
+---------------------------------------------------------+
| 2 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SQL> SELECT ABS(-2);
+---------------------------------------------------------+
| ABS(2) |
+---------------------------------------------------------+
| 2 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the arccosine of X. The value of X must range between -1 and 1 or NULL will be returned. Consider the following example −
SQL> SELECT ACOS(1);
+---------------------------------------------------------+
| ACOS(1) |
+---------------------------------------------------------+
| 0.000000 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The ASIN() function returns the arcsine of X. The value of X must be in the range of -1 to 1 or NULL is returned.
SQL> SELECT ASIN(1);
+---------------------------------------------------------+
| ASIN(1) |
+---------------------------------------------------------+
| 1.5707963267949 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the arctangent of X.
SQL> SELECT ATAN(1);
+---------------------------------------------------------+
| ATAN(1) |
+---------------------------------------------------------+
| 0.78539816339745 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the arctangent of the two arguments: X and Y. It is similar to the arctangent of Y/X, except that the signs of both are used to find the quadrant of the result.
SQL> SELECT ATAN2(3,6);
+---------------------------------------------------------+
| ATAN2(3,6) |
+---------------------------------------------------------+
| 0.46364760900081 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The BIT_AND function returns the bitwise AND of all bits in expression. The basic premise is that if two corresponding bits are the same, then a bitwise AND operation will return 1, while if they are different, a bitwise AND operation will return 0. The function itself returns a 64-bit integer value. If there are no matches, then it will return 18446744073709551615. The following example performs the BIT_AND function on the PRICE column grouped by the MAKER of the car −
SQL> SELECT
MAKER, BIT_AND(PRICE) BITS
FROM CARS GROUP BY MAKER
+---------------------------------------------------------+
|MAKER BITS |
+---------------------------------------------------------+
|CHRYSLER 512 |
|FORD 12488 |
|HONDA 2144 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The BIT_COUNT() function returns the number of bits that are active in numeric_value. The following example demonstrates using the BIT_COUNT() function to return the number of active bits for a range of numbers −
SQL> SELECT
BIT_COUNT(2) AS TWO,
BIT_COUNT(4) AS FOUR,
BIT_COUNT(7) AS SEVEN
+-----+------+-------+
| TWO | FOUR | SEVEN |
+-----+------+-------+
| 1 | 1 | 3 |
+-----+------+-------+
1 row in set (0.00 sec)
The BIT_OR() function returns the bitwise OR of all the bits in expression. The basic premise of the bitwise
OR function is that it returns 0 if the corresponding bits match and 1 if they do not. The function returns a
64-bit integer, and if there are no matching rows, then it returns 0. The following example performs the
BIT_OR() function on the PRICE column of the CARS table, grouped by the MAKER −
SQL> SELECT
MAKER, BIT_OR(PRICE) BITS
FROM CARS GROUP BY MAKER
+---------------------------------------------------------+
|MAKER BITS |
+---------------------------------------------------------+
|CHRYSLER 62293 |
|FORD 16127 |
|HONDA 32766 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
These functions return the smallest integer value that is not smaller than X. Consider the following example −
SQL> SELECT CEILING(3.46);
+---------------------------------------------------------+
| CEILING(3.46) |
+---------------------------------------------------------+
| 4 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SQL> SELECT CEIL(-6.43);
+---------------------------------------------------------+
| CEIL(-6.43) |
+---------------------------------------------------------+
| -6 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The purpose of the CONV() function is to convert numbers between different number bases. The function returns a string of the value N converted from from_base to to_base. The minimum base value is 2 and the maximum is 36. If any of the arguments are NULL, then the function returns NULL. Consider the following example, which converts the number 5 from base 16 to base 2 −
SQL> SELECT CONV(5,16,2);
+---------------------------------------------------------+
| CONV(5,16,2) |
+---------------------------------------------------------+
| 101 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the cosine of X. The value of X is given in radians.
SQL>SELECT COS(90);
+---------------------------------------------------------+
| COS(90) |
+---------------------------------------------------------+
| -0.44807361612917 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the cotangent of X. Consider the following example −
SQL>SELECT COT(1);
+---------------------------------------------------------+
| COT(1) |
+---------------------------------------------------------+
| 0.64209261593433 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the value of X converted from radians to degrees.
SQL>SELECT DEGREES(PI());
+---------------------------------------------------------+
| DEGREES(PI()) |
+---------------------------------------------------------+
| 180.000000 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the value of e (the base of the natural logarithm) raised to the power of X.
SQL>SELECT EXP(3);
+---------------------------------------------------------+
| EXP(3) |
+---------------------------------------------------------+
| 20.085537 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the largest integer value that is not greater than X.
SQL>SELECT FLOOR(7.55);
+---------------------------------------------------------+
| FLOOR(7.55) |
+---------------------------------------------------------+
| 7 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The FORMAT() function is used to format the number X in the following format: ###,###,###.## truncated
to D decimal places. The following example demonstrates the use and output of the FORMAT() function −
SQL>SELECT FORMAT(423423234.65434453,2);
+---------------------------------------------------------+
| FORMAT(423423234.65434453,2) |
+---------------------------------------------------------+
| 423,423,234.65 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The GREATEST() function returns the greatest value in the set of input parameters (n1, n2, n3, a nd so on). The following example uses the GREATEST() function to return the largest number from a set of numeric values −
SQL>SELECT GREATEST(3,5,1,8,33,99,34,55,67,43);
+---------------------------------------------------------+
| GREATEST(3,5,1,8,33,99,34,55,67,43) |
+---------------------------------------------------------+
| 99 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The INTERVAL() function compares the value of N to the value list (N1, N2, N3, and so on ). The function returns 0 if N < N1, 1 if N < N2, 2 if N <N3, and so on. It will return .1 if N is NULL. The value list must be in the form N1 < N2 < N3 in order to work properly. The following code is a simple example of how the INTERVAL() function works −
SQL>SELECT INTERVAL(6,1,2,3,4,5,6,7,8,9,10);
+---------------------------------------------------------+
| INTERVAL(6,1,2,3,4,5,6,7,8,9,10) |
+---------------------------------------------------------+
| 6 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The INTERVAL() function compares the value of N to the value list (N1, N2, N3, and so on ). The function returns 0 if N < N1, 1 if N < N2, 2 if N <N3, and so on. It will return .1 if N is NULL. The value list must be in the form N1 < N2 < N3 in order to work properly. The following code is a simple example of how the INTERVAL() function works −
SQL>SELECT INTERVAL(6,1,2,3,4,5,6,7,8,9,10);
+---------------------------------------------------------+
| INTERVAL(6,1,2,3,4,5,6,7,8,9,10) |
+---------------------------------------------------------+
| 6 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
Remember that 6 is the zero-based index in the value list of the first value that was greater than N. In our case, 7 was the offending value and is located in the sixth index slot.
The LEAST() function is the opposite of the GREATEST() function. Its purpose is to return the least-valued item from the value list (N1, N2, N3, and so on). The following example shows the proper usage and output for the LEAST() function −
SQL>SELECT LEAST(3,5,1,8,33,99,34,55,67,43);
+---------------------------------------------------------+
| LEAST(3,5,1,8,33,99,34,55,67,43) |
+---------------------------------------------------------+
| 1 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The single argument version of the function will return the natural logarithm of X. If it is called with two arguments, it returns the logarithm of X for an arbitrary base B. Consider the following example −
SQL>SELECT LOG(45);
+---------------------------------------------------------+
| LOG(45) |
+---------------------------------------------------------+
| 3.806662 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SQL>SELECT LOG(2,65536);
+---------------------------------------------------------+
| LOG(2,65536) |
+---------------------------------------------------------+
| 16.000000 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the base-10 logarithm of X.
SQL>SELECT LOG10(100);
+---------------------------------------------------------+
| LOG10(100) |
+---------------------------------------------------------+
| 2.000000 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the remainder of N divided by M. Consider the following example −
SQL>SELECT MOD(29,3);
+---------------------------------------------------------+
| MOD(29,3) |
+---------------------------------------------------------+
| 2 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The OCT() function returns the string representation of the octal number N. This is equivalent to using CONV(N,10,8).
SQL>SELECT OCT(12);
+---------------------------------------------------------+
| OCT(12) |
+---------------------------------------------------------+
| 14 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function simply returns the value of pi. SQL internally stores the full double-precision value of pi.
SQL>SELECT PI();
+---------------------------------------------------------+
| PI() |
+---------------------------------------------------------+
| 3.141593 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
These two functions return the value of X raised to the power of Y.
SQL> SELECT POWER(3,3);
+---------------------------------------------------------+
| POWER(3,3) |
+---------------------------------------------------------+
| 27 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the value of X, converted from degrees to radians.
SQL>SELECT RADIANS(90);
+---------------------------------------------------------+
| RADIANS(90) |
+---------------------------------------------------------+
|1.570796 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns X rounded to the nearest integer. If a second argument, D, is supplied, then the function returns X rounded to D decimal places. D must be positive or all digits to the right of the decimal point will be removed. Consider the following example −
SQL>SELECT ROUND(5.693893);
+---------------------------------------------------------+
| ROUND(5.693893) |
+---------------------------------------------------------+
| 6 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SQL>SELECT ROUND(5.693893,2);
+---------------------------------------------------------+
| ROUND(5.693893,2) |
+---------------------------------------------------------+
| 5.69 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the sign of X (negative, zero, or positive) as -1, 0, or 1.
SQL>SELECT SIGN(-4.65);
+---------------------------------------------------------+
| SIGN(-4.65) |
+---------------------------------------------------------+
| -1 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SQL>SELECT SIGN(0);
+---------------------------------------------------------+
| SIGN(0) |
+---------------------------------------------------------+
| 0 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SQL>SELECT SIGN(4.65);
+---------------------------------------------------------+
| SIGN(4.65) |
+---------------------------------------------------------+
| 1 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the sine of X. Consider the following example −
SQL>SELECT SIN(90);
+---------------------------------------------------------+
| SIN(90) |
+---------------------------------------------------------+
| 0.893997 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the non-negative square root of X. Consider the following example −
SQL>SELECT SQRT(49);
+---------------------------------------------------------+
| SQRT(49) |
+---------------------------------------------------------+
| 7 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
The STD() function is used to return the standard deviation of expression. This is equivalent to taking the square root of the VARIANCE() of expression. The following example computes the standard deviation of the PRICE column in our CARS table −
SQL>SELECT STD(PRICE) STD_DEVIATION FROM CARS;
+---------------------------------------------------------+
| STD_DEVIATION |
+---------------------------------------------------------+
| 7650.2146 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function returns the tangent of the argument X, which is expressed in radians.
SQL>SELECT TAN(45);
+---------------------------------------------------------+
| TAN(45) |
+---------------------------------------------------------+
| 1.619775 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
This function is used to return the value of X truncated to D number of decimal places. If D is 0, then the decimal point is removed. If D is negative, then D number of values in the integer part of the value is truncated. Consider the following example −
SQL>SELECT TRUNCATE(7.536432,2);
+---------------------------------------------------------+
| TRUNCATE(7.536432,2) |
+---------------------------------------------------------+
| 7.53 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2605,
"s": 2453,
"text": "SQL numeric functions are used primarily for numeric manipulation and/or mathematical calculations. The following table details the numeric functions −"
},
{
"code": null,
"e": 2655,
"s": 2605,
"text": "Returns the absolute value of numeric expression."
},
{
"code": null,
"e": 2755,
"s": 2655,
"text": "Returns the arccosine of numeric expression. Returns NULL if the value is not in the range -1 to 1."
},
{
"code": null,
"e": 2848,
"s": 2755,
"text": "Returns the arcsine of numeric expression. Returns NULL if value is not in the range -1 to 1"
},
{
"code": null,
"e": 2894,
"s": 2848,
"text": "Returns the arctangent of numeric expression."
},
{
"code": null,
"e": 2952,
"s": 2894,
"text": "Returns the arctangent of the two variables passed to it."
},
{
"code": null,
"e": 3004,
"s": 2952,
"text": "Returns the bitwise AND all the bits in expression."
},
{
"code": null,
"e": 3072,
"s": 3004,
"text": "Returns the string representation of the binary value passed to it."
},
{
"code": null,
"e": 3137,
"s": 3072,
"text": "Returns the bitwise OR of all the bits in the passed expression."
},
{
"code": null,
"e": 3220,
"s": 3137,
"text": "Returns the smallest integer value that is not less than passed numeric expression"
},
{
"code": null,
"e": 3303,
"s": 3220,
"text": "Returns the smallest integer value that is not less than passed numeric expression"
},
{
"code": null,
"e": 3356,
"s": 3303,
"text": "Convert numeric expression from one base to another."
},
{
"code": null,
"e": 3461,
"s": 3356,
"text": "Returns the cosine of passed numeric expression. The numeric expression should be expressed in radians."
},
{
"code": null,
"e": 3514,
"s": 3461,
"text": "Returns the cotangent of passed numeric expression."
},
{
"code": null,
"e": 3576,
"s": 3514,
"text": "Returns numeric expression converted from radians to degrees."
},
{
"code": null,
"e": 3672,
"s": 3576,
"text": "Returns the base of the natural logarithm (e) raised to the power of passed numeric expression."
},
{
"code": null,
"e": 3758,
"s": 3672,
"text": "Returns the largest integer value that is not greater than passed numeric expression."
},
{
"code": null,
"e": 3828,
"s": 3758,
"text": "Returns a numeric expression rounded to a number of decimal places."
},
{
"code": null,
"e": 3880,
"s": 3828,
"text": "Returns the largest value of the input expressions."
},
{
"code": null,
"e": 4023,
"s": 3880,
"text": "Takes multiple expressions exp1, exp2 and exp3 so on.. and returns 0 if exp1 is less than exp2, returns 1 if exp1 is less than exp3 and so on."
},
{
"code": null,
"e": 4080,
"s": 4023,
"text": "Returns the minimum-valued input when given two or more."
},
{
"code": null,
"e": 4144,
"s": 4080,
"text": "Returns the natural logarithm of the passed numeric expression."
},
{
"code": null,
"e": 4208,
"s": 4144,
"text": "Returns the base-10 logarithm of the passed numeric expression."
},
{
"code": null,
"e": 4281,
"s": 4208,
"text": "Returns the remainder of one expression by diving by another expression."
},
{
"code": null,
"e": 4406,
"s": 4281,
"text": "Returns the string representation of the octal value of the passed numeric expression. Returns NULL if passed value is NULL."
},
{
"code": null,
"e": 4430,
"s": 4406,
"text": "Returns the value of pi"
},
{
"code": null,
"e": 4508,
"s": 4430,
"text": "Returns the value of one expression raised to the power of another expression"
},
{
"code": null,
"e": 4586,
"s": 4508,
"text": "Returns the value of one expression raised to the power of another expression"
},
{
"code": null,
"e": 4660,
"s": 4586,
"text": "Returns the value of passed expression converted from degrees to radians."
},
{
"code": null,
"e": 4775,
"s": 4660,
"text": "Returns numeric expression rounded to an integer. Can be used to round an expression to a number of decimal points"
},
{
"code": null,
"e": 4832,
"s": 4775,
"text": "Returns the sine of numeric expression given in radians."
},
{
"code": null,
"e": 4892,
"s": 4832,
"text": "Returns the non-negative square root of numeric expression."
},
{
"code": null,
"e": 4950,
"s": 4892,
"text": "Returns the standard deviation of the numeric expression."
},
{
"code": null,
"e": 5008,
"s": 4950,
"text": "Returns the standard deviation of the numeric expression."
},
{
"code": null,
"e": 5072,
"s": 5008,
"text": "Returns the tangent of numeric expression expressed in radians."
},
{
"code": null,
"e": 5185,
"s": 5072,
"text": "Returns numeric exp1 truncated to exp2 decimal places. If exp2 is 0, then the result will have no decimal point."
},
{
"code": null,
"e": 5270,
"s": 5185,
"text": "The ABS() function returns the absolute value of X. Consider the following example −"
},
{
"code": null,
"e": 5960,
"s": 5270,
"text": "SQL> SELECT ABS(2);\n+---------------------------------------------------------+\n| ABS(2) |\n+---------------------------------------------------------+\n| 2 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nSQL> SELECT ABS(-2);\n+---------------------------------------------------------+\n| ABS(2) |\n+---------------------------------------------------------+\n| 2 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 6104,
"s": 5960,
"text": "This function returns the arccosine of X. The value of X must range between -1 and 1 or NULL will be returned. Consider the following example −"
},
{
"code": null,
"e": 6449,
"s": 6104,
"text": "SQL> SELECT ACOS(1);\n+---------------------------------------------------------+\n| ACOS(1) |\n+---------------------------------------------------------+\n| 0.000000 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 6563,
"s": 6449,
"text": "The ASIN() function returns the arcsine of X. The value of X must be in the range of -1 to 1 or NULL is returned."
},
{
"code": null,
"e": 6908,
"s": 6563,
"text": "SQL> SELECT ASIN(1);\n+---------------------------------------------------------+\n| ASIN(1) |\n+---------------------------------------------------------+\n| 1.5707963267949 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 6951,
"s": 6908,
"text": "This function returns the arctangent of X."
},
{
"code": null,
"e": 7296,
"s": 6951,
"text": "SQL> SELECT ATAN(1);\n+---------------------------------------------------------+\n| ATAN(1) |\n+---------------------------------------------------------+\n| 0.78539816339745 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 7479,
"s": 7296,
"text": "This function returns the arctangent of the two arguments: X and Y. It is similar to the arctangent of Y/X, except that the signs of both are used to find the quadrant of the result."
},
{
"code": null,
"e": 7827,
"s": 7479,
"text": "SQL> SELECT ATAN2(3,6);\n+---------------------------------------------------------+\n| ATAN2(3,6) |\n+---------------------------------------------------------+\n| 0.46364760900081 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 8302,
"s": 7827,
"text": "The BIT_AND function returns the bitwise AND of all bits in expression. The basic premise is that if two corresponding bits are the same, then a bitwise AND operation will return 1, while if they are different, a bitwise AND operation will return 0. The function itself returns a 64-bit integer value. If there are no matches, then it will return 18446744073709551615. The following example performs the BIT_AND function on the PRICE column grouped by the MAKER of the car −"
},
{
"code": null,
"e": 8831,
"s": 8302,
"text": "SQL> SELECT \n MAKER, BIT_AND(PRICE) BITS\n FROM CARS GROUP BY MAKER\n+---------------------------------------------------------+\n|MAKER BITS |\n+---------------------------------------------------------+\n|CHRYSLER 512 |\n|FORD 12488 |\n|HONDA 2144 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 9044,
"s": 8831,
"text": "The BIT_COUNT() function returns the number of bits that are active in numeric_value. The following example demonstrates using the BIT_COUNT() function to return the number of active bits for a range of numbers −"
},
{
"code": null,
"e": 9290,
"s": 9044,
"text": "SQL> SELECT\n BIT_COUNT(2) AS TWO,\n BIT_COUNT(4) AS FOUR,\n BIT_COUNT(7) AS SEVEN\n+-----+------+-------+\n| TWO | FOUR | SEVEN |\n+-----+------+-------+\n| 1 | 1 | 3 |\n+-----+------+-------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 9694,
"s": 9290,
"text": "The BIT_OR() function returns the bitwise OR of all the bits in expression. The basic premise of the bitwise\nOR function is that it returns 0 if the corresponding bits match and 1 if they do not. The function returns a\n64-bit integer, and if there are no matching rows, then it returns 0. The following example performs the\nBIT_OR() function on the PRICE column of the CARS table, grouped by the MAKER −"
},
{
"code": null,
"e": 10222,
"s": 9694,
"text": "SQL> SELECT \n MAKER, BIT_OR(PRICE) BITS\n FROM CARS GROUP BY MAKER\n+---------------------------------------------------------+\n|MAKER BITS |\n+---------------------------------------------------------+\n|CHRYSLER 62293 |\n|FORD 16127 |\n|HONDA 32766 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 10333,
"s": 10222,
"text": "These functions return the smallest integer value that is not smaller than X. Consider the following example −"
},
{
"code": null,
"e": 11034,
"s": 10333,
"text": "SQL> SELECT CEILING(3.46);\n+---------------------------------------------------------+\n| CEILING(3.46) |\n+---------------------------------------------------------+\n| 4 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nSQL> SELECT CEIL(-6.43);\n+---------------------------------------------------------+\n| CEIL(-6.43) |\n+---------------------------------------------------------+\n| -6 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 11407,
"s": 11034,
"text": "The purpose of the CONV() function is to convert numbers between different number bases. The function returns a string of the value N converted from from_base to to_base. The minimum base value is 2 and the maximum is 36. If any of the arguments are NULL, then the function returns NULL. Consider the following example, which converts the number 5 from base 16 to base 2 −"
},
{
"code": null,
"e": 11757,
"s": 11407,
"text": "SQL> SELECT CONV(5,16,2);\n+---------------------------------------------------------+\n| CONV(5,16,2) |\n+---------------------------------------------------------+\n| 101 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 11832,
"s": 11757,
"text": "This function returns the cosine of X. The value of X is given in radians."
},
{
"code": null,
"e": 12176,
"s": 11832,
"text": "SQL>SELECT COS(90);\n+---------------------------------------------------------+\n| COS(90) |\n+---------------------------------------------------------+\n| -0.44807361612917 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 12251,
"s": 12176,
"text": "This function returns the cotangent of X. Consider the following example −"
},
{
"code": null,
"e": 12594,
"s": 12251,
"text": "SQL>SELECT COT(1);\n+---------------------------------------------------------+\n| COT(1) |\n+---------------------------------------------------------+\n| 0.64209261593433 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 12666,
"s": 12594,
"text": "This function returns the value of X converted from radians to degrees."
},
{
"code": null,
"e": 13016,
"s": 12666,
"text": "SQL>SELECT DEGREES(PI());\n+---------------------------------------------------------+\n| DEGREES(PI()) |\n+---------------------------------------------------------+\n| 180.000000 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 13115,
"s": 13016,
"text": "This function returns the value of e (the base of the natural logarithm) raised to the power of X."
},
{
"code": null,
"e": 13458,
"s": 13115,
"text": "SQL>SELECT EXP(3);\n+---------------------------------------------------------+\n| EXP(3) |\n+---------------------------------------------------------+\n| 20.085537 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 13534,
"s": 13458,
"text": "This function returns the largest integer value that is not greater than X."
},
{
"code": null,
"e": 13882,
"s": 13534,
"text": "SQL>SELECT FLOOR(7.55);\n+---------------------------------------------------------+\n| FLOOR(7.55) |\n+---------------------------------------------------------+\n| 7 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 14087,
"s": 13882,
"text": "The FORMAT() function is used to format the number X in the following format: ###,###,###.## truncated\nto D decimal places. The following example demonstrates the use and output of the FORMAT() function −"
},
{
"code": null,
"e": 14452,
"s": 14087,
"text": "SQL>SELECT FORMAT(423423234.65434453,2);\n+---------------------------------------------------------+\n| FORMAT(423423234.65434453,2) |\n+---------------------------------------------------------+\n| 423,423,234.65 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 14671,
"s": 14452,
"text": "The GREATEST() function returns the greatest value in the set of input parameters (n1, n2, n3, a nd so on). The following example uses the GREATEST() function to return the largest number from a set of numeric values −"
},
{
"code": null,
"e": 15043,
"s": 14671,
"text": "SQL>SELECT GREATEST(3,5,1,8,33,99,34,55,67,43);\n+---------------------------------------------------------+\n| GREATEST(3,5,1,8,33,99,34,55,67,43) |\n+---------------------------------------------------------+\n| 99 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 15390,
"s": 15043,
"text": "The INTERVAL() function compares the value of N to the value list (N1, N2, N3, and so on ). The function returns 0 if N < N1, 1 if N < N2, 2 if N <N3, and so on. It will return .1 if N is NULL. The value list must be in the form N1 < N2 < N3 in order to work properly. The following code is a simple example of how the INTERVAL() function works −"
},
{
"code": null,
"e": 15759,
"s": 15390,
"text": "SQL>SELECT INTERVAL(6,1,2,3,4,5,6,7,8,9,10);\n+---------------------------------------------------------+\n| INTERVAL(6,1,2,3,4,5,6,7,8,9,10) |\n+---------------------------------------------------------+\n| 6 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 16106,
"s": 15759,
"text": "The INTERVAL() function compares the value of N to the value list (N1, N2, N3, and so on ). The function returns 0 if N < N1, 1 if N < N2, 2 if N <N3, and so on. It will return .1 if N is NULL. The value list must be in the form N1 < N2 < N3 in order to work properly. The following code is a simple example of how the INTERVAL() function works −"
},
{
"code": null,
"e": 16475,
"s": 16106,
"text": "SQL>SELECT INTERVAL(6,1,2,3,4,5,6,7,8,9,10);\n+---------------------------------------------------------+\n| INTERVAL(6,1,2,3,4,5,6,7,8,9,10) |\n+---------------------------------------------------------+\n| 6 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 16656,
"s": 16475,
"text": "Remember that 6 is the zero-based index in the value list of the first value that was greater than N. In our case, 7 was the offending value and is located in the sixth index slot."
},
{
"code": null,
"e": 16896,
"s": 16656,
"text": "The LEAST() function is the opposite of the GREATEST() function. Its purpose is to return the least-valued item from the value list (N1, N2, N3, and so on). The following example shows the proper usage and output for the LEAST() function −"
},
{
"code": null,
"e": 17265,
"s": 16896,
"text": "SQL>SELECT LEAST(3,5,1,8,33,99,34,55,67,43);\n+---------------------------------------------------------+\n| LEAST(3,5,1,8,33,99,34,55,67,43) |\n+---------------------------------------------------------+\n| 1 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 17473,
"s": 17265,
"text": "The single argument version of the function will return the natural logarithm of X. If it is called with two arguments, it returns the logarithm of X for an arbitrary base B. Consider the following example −"
},
{
"code": null,
"e": 18167,
"s": 17473,
"text": "SQL>SELECT LOG(45);\n+---------------------------------------------------------+\n| LOG(45) |\n+---------------------------------------------------------+\n| 3.806662 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nSQL>SELECT LOG(2,65536);\n+---------------------------------------------------------+\n| LOG(2,65536) |\n+---------------------------------------------------------+\n| 16.000000 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 18217,
"s": 18167,
"text": "This function returns the base-10 logarithm of X."
},
{
"code": null,
"e": 18564,
"s": 18217,
"text": "SQL>SELECT LOG10(100);\n+---------------------------------------------------------+\n| LOG10(100) |\n+---------------------------------------------------------+\n| 2.000000 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 18652,
"s": 18564,
"text": "This function returns the remainder of N divided by M. Consider the following example −"
},
{
"code": null,
"e": 18998,
"s": 18652,
"text": "SQL>SELECT MOD(29,3);\n+---------------------------------------------------------+\n| MOD(29,3) |\n+---------------------------------------------------------+\n| 2 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 19116,
"s": 18998,
"text": "The OCT() function returns the string representation of the octal number N. This is equivalent to using CONV(N,10,8)."
},
{
"code": null,
"e": 19460,
"s": 19116,
"text": "SQL>SELECT OCT(12);\n+---------------------------------------------------------+\n| OCT(12) |\n+---------------------------------------------------------+\n| 14 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 19567,
"s": 19460,
"text": "This function simply returns the value of pi. SQL internally stores the full double-precision value of pi."
},
{
"code": null,
"e": 19908,
"s": 19567,
"text": "SQL>SELECT PI();\n+---------------------------------------------------------+\n| PI() |\n+---------------------------------------------------------+\n| 3.141593 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 19976,
"s": 19908,
"text": "These two functions return the value of X raised to the power of Y."
},
{
"code": null,
"e": 20324,
"s": 19976,
"text": "SQL> SELECT POWER(3,3);\n+---------------------------------------------------------+\n| POWER(3,3) |\n+---------------------------------------------------------+\n| 27 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 20397,
"s": 20324,
"text": "This function returns the value of X, converted from degrees to radians."
},
{
"code": null,
"e": 20745,
"s": 20397,
"text": "SQL>SELECT RADIANS(90);\n+---------------------------------------------------------+\n| RADIANS(90) |\n+---------------------------------------------------------+\n|1.570796 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 21013,
"s": 20745,
"text": "This function returns X rounded to the nearest integer. If a second argument, D, is supplied, then the function returns X rounded to D decimal places. D must be positive or all digits to the right of the decimal point will be removed. Consider the following example −"
},
{
"code": null,
"e": 21720,
"s": 21013,
"text": "SQL>SELECT ROUND(5.693893);\n+---------------------------------------------------------+\n| ROUND(5.693893) |\n+---------------------------------------------------------+\n| 6 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nSQL>SELECT ROUND(5.693893,2);\n+---------------------------------------------------------+\n| ROUND(5.693893,2) |\n+---------------------------------------------------------+\n| 5.69 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 21802,
"s": 21720,
"text": "This function returns the sign of X (negative, zero, or positive) as -1, 0, or 1."
},
{
"code": null,
"e": 22843,
"s": 21802,
"text": "SQL>SELECT SIGN(-4.65);\n+---------------------------------------------------------+\n| SIGN(-4.65) |\n+---------------------------------------------------------+\n| -1 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nSQL>SELECT SIGN(0);\n+---------------------------------------------------------+\n| SIGN(0) |\n+---------------------------------------------------------+\n| 0 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)\n\nSQL>SELECT SIGN(4.65);\n+---------------------------------------------------------+\n| SIGN(4.65) |\n+---------------------------------------------------------+\n| 1 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 22913,
"s": 22843,
"text": "This function returns the sine of X. Consider the following example −"
},
{
"code": null,
"e": 23257,
"s": 22913,
"text": "SQL>SELECT SIN(90);\n+---------------------------------------------------------+\n| SIN(90) |\n+---------------------------------------------------------+\n| 0.893997 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 23347,
"s": 23257,
"text": "This function returns the non-negative square root of X. Consider the following example −"
},
{
"code": null,
"e": 23692,
"s": 23347,
"text": "SQL>SELECT SQRT(49);\n+---------------------------------------------------------+\n| SQRT(49) |\n+---------------------------------------------------------+\n| 7 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 23939,
"s": 23692,
"text": "The STD() function is used to return the standard deviation of expression. This is equivalent to taking the square root of the VARIANCE() of expression. The following example computes the standard deviation of the PRICE column in our CARS table −"
},
{
"code": null,
"e": 24310,
"s": 23939,
"text": "SQL>SELECT STD(PRICE) STD_DEVIATION FROM CARS;\n+---------------------------------------------------------+\n| STD_DEVIATION |\n+---------------------------------------------------------+\n| 7650.2146 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 24394,
"s": 24310,
"text": "This function returns the tangent of the argument X, which is expressed in radians."
},
{
"code": null,
"e": 24738,
"s": 24394,
"text": "SQL>SELECT TAN(45);\n+---------------------------------------------------------+\n| TAN(45) |\n+---------------------------------------------------------+\n| 1.619775 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 24994,
"s": 24738,
"text": "This function is used to return the value of X truncated to D number of decimal places. If D is 0, then the decimal point is removed. If D is negative, then D number of values in the integer part of the value is truncated. Consider the following example −"
},
{
"code": null,
"e": 25351,
"s": 24994,
"text": "SQL>SELECT TRUNCATE(7.536432,2);\n+---------------------------------------------------------+\n| TRUNCATE(7.536432,2) |\n+---------------------------------------------------------+\n| 7.53 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 25384,
"s": 25351,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 25398,
"s": 25384,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 25431,
"s": 25398,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 25445,
"s": 25431,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 25480,
"s": 25445,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 25494,
"s": 25480,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 25527,
"s": 25494,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 25549,
"s": 25527,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 25584,
"s": 25549,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 25638,
"s": 25584,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 25671,
"s": 25638,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 25699,
"s": 25671,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 25706,
"s": 25699,
"text": " Print"
},
{
"code": null,
"e": 25717,
"s": 25706,
"text": " Add Notes"
}
] |
Differences between orTimeout() and completeOnTimeOut() methods in Java 9?
|
Both orTimeout() and completeOnTimeOut() methods are defined in CompletableFuture class and these two methods are introduced in Java 9. The orTimeout() method can be used to specify that if a given task doesn't complete within a certain period of time, the program stops execution and throws TimeoutException whereas completeOnTimeOut() method completes the CompletableFuture with the provided value. If not, it complete before the given timeout.
public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class OrTimeoutMethodTest {
public static void main(String args[]) throws InterruptedException {
int a = 10;
int b = 15;
CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch(InterruptedException e) {
e.printStackTrace();
}
return a + b;
})
.orTimeout(4, TimeUnit.SECONDS)
.whenComplete((result, exception) -> {
System.out.println(result);
if(exception != null)
exception.printStackTrace();
});
TimeUnit.SECONDS.sleep(10);
}
}
25
public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class CompleteOnTimeOutMethodTest {
public static void main(String args[]) throws InterruptedException {
int a = 10;
int b = 15;
CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch(InterruptedException e) {
e.printStackTrace();
}
return a + b;
})
.completeOnTimeout(0, 4, TimeUnit.SECONDS)
.thenAccept(result -> System.out.println(result));
TimeUnit.SECONDS.sleep(10);
}
}
25
|
[
{
"code": null,
"e": 1509,
"s": 1062,
"text": "Both orTimeout() and completeOnTimeOut() methods are defined in CompletableFuture class and these two methods are introduced in Java 9. The orTimeout() method can be used to specify that if a given task doesn't complete within a certain period of time, the program stops execution and throws TimeoutException whereas completeOnTimeOut() method completes the CompletableFuture with the provided value. If not, it complete before the given timeout."
},
{
"code": null,
"e": 1576,
"s": 1509,
"text": "public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)"
},
{
"code": null,
"e": 2264,
"s": 1576,
"text": "import java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.TimeUnit;\npublic class OrTimeoutMethodTest {\n public static void main(String args[]) throws InterruptedException {\n int a = 10;\n int b = 15;\n CompletableFuture.supplyAsync(() -> {\n try {\n TimeUnit.SECONDS.sleep(5);\n } catch(InterruptedException e) {\n e.printStackTrace();\n }\n return a + b;\n })\n .orTimeout(4, TimeUnit.SECONDS)\n .whenComplete((result, exception) -> {\n System.out.println(result);\n if(exception != null)\n exception.printStackTrace();\n });\n TimeUnit.SECONDS.sleep(10);\n }\n}"
},
{
"code": null,
"e": 2268,
"s": 2264,
"text": "25\n"
},
{
"code": null,
"e": 2352,
"s": 2268,
"text": "public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)"
},
{
"code": null,
"e": 2952,
"s": 2352,
"text": "import java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.TimeUnit;\npublic class CompleteOnTimeOutMethodTest {\n public static void main(String args[]) throws InterruptedException {\n int a = 10;\n int b = 15;\n CompletableFuture.supplyAsync(() -> {\n try {\n TimeUnit.SECONDS.sleep(5);\n } catch(InterruptedException e) {\n e.printStackTrace();\n }\n return a + b;\n })\n .completeOnTimeout(0, 4, TimeUnit.SECONDS)\n .thenAccept(result -> System.out.println(result));\n TimeUnit.SECONDS.sleep(10);\n }\n}"
},
{
"code": null,
"e": 2955,
"s": 2952,
"text": "25"
}
] |
isprintable() in Python and its application
|
In this article, we will learn about isprintable() in Python and its application.
Is printable() is a built-in method used for the purpose of string handling. The isprintable() methods return “True” when all characters present in the string are of type printable or the string is empty, Otherwise, It returns a boolean value of “False”.
Arguments − It doesn’t take any argument when called
List of printable characters include digits, letter, special symbols & spaces.
Let’s look at this illustration to check that whether the characters of string are printable or not.
Live Demo
# checking for printable characters
st= 'Tutorialspoint'
print(st.isprintable())
# checking if \n is a printable character
st= 'Tutorials \n point'
print(st.isprintable())
# checking if space is a printable character
string = ''
print( string.isprintable())
True
False
True
Live Demo
# checking for printable characters
st= 'Tutorials$$point&&'
print(st.isprintable())
# checking if \t is a printable character
st= 'Tutorials \t point'
print(st.isprintable())
# checking if underscore is a printable character
string = '_'
print( string.isprintable())
True
False
True
To rectify the error of printing error at runtime we can handle this exception and replace all non-printable characters with the desired symbol to print onto the console
To rectify the error of printing error at runtime we can handle this exception and replace all non-printable characters with the desired symbol to print onto the console
This is also useful when we have to format the output in a specific manner so as to remove the unwanted things like escape sequences
This is also useful when we have to format the output in a specific manner so as to remove the unwanted things like escape sequences
In this article, we learnt about the isprintable() function and its application in Python 3.x. Or earlier.
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "In this article, we will learn about isprintable() in Python and its application."
},
{
"code": null,
"e": 1399,
"s": 1144,
"text": "Is printable() is a built-in method used for the purpose of string handling. The isprintable() methods return “True” when all characters present in the string are of type printable or the string is empty, Otherwise, It returns a boolean value of “False”."
},
{
"code": null,
"e": 1452,
"s": 1399,
"text": "Arguments − It doesn’t take any argument when called"
},
{
"code": null,
"e": 1531,
"s": 1452,
"text": "List of printable characters include digits, letter, special symbols & spaces."
},
{
"code": null,
"e": 1632,
"s": 1531,
"text": "Let’s look at this illustration to check that whether the characters of string are printable or not."
},
{
"code": null,
"e": 1643,
"s": 1632,
"text": " Live Demo"
},
{
"code": null,
"e": 1901,
"s": 1643,
"text": "# checking for printable characters\nst= 'Tutorialspoint'\nprint(st.isprintable())\n# checking if \\n is a printable character\nst= 'Tutorials \\n point'\nprint(st.isprintable())\n# checking if space is a printable character\nstring = ''\nprint( string.isprintable())"
},
{
"code": null,
"e": 1917,
"s": 1901,
"text": "True\nFalse\nTrue"
},
{
"code": null,
"e": 1928,
"s": 1917,
"text": " Live Demo"
},
{
"code": null,
"e": 2196,
"s": 1928,
"text": "# checking for printable characters\nst= 'Tutorials$$point&&'\nprint(st.isprintable())\n# checking if \\t is a printable character\nst= 'Tutorials \\t point'\nprint(st.isprintable())\n# checking if underscore is a printable character\nstring = '_'\nprint( string.isprintable())"
},
{
"code": null,
"e": 2212,
"s": 2196,
"text": "True\nFalse\nTrue"
},
{
"code": null,
"e": 2382,
"s": 2212,
"text": "To rectify the error of printing error at runtime we can handle this exception and replace all non-printable characters with the desired symbol to print onto the console"
},
{
"code": null,
"e": 2552,
"s": 2382,
"text": "To rectify the error of printing error at runtime we can handle this exception and replace all non-printable characters with the desired symbol to print onto the console"
},
{
"code": null,
"e": 2685,
"s": 2552,
"text": "This is also useful when we have to format the output in a specific manner so as to remove the unwanted things like escape sequences"
},
{
"code": null,
"e": 2818,
"s": 2685,
"text": "This is also useful when we have to format the output in a specific manner so as to remove the unwanted things like escape sequences"
},
{
"code": null,
"e": 2925,
"s": 2818,
"text": "In this article, we learnt about the isprintable() function and its application in Python 3.x. Or earlier."
}
] |
Ansible — Ports Monitoring.. Today I will show you how Ansible can... | by Abdelilah OUASSINI | Towards Data Science
|
Indeed in highly sensitive businesses like banking, ports are strictly supervised, and only required ports are allowed to be opened by SecOps.Otherwise, not supervised ports can be attractive targets for network attacks like DDOS.
To explain things more easily, let’s imagine a set of hosts called sources that should communicate with another set of hosts called targets, only through authorized ports.
Hosts can be cloud, docker, VM, metal server ... and port could be any ( https 443, SMTP 25, PostgreSQL 5432, Ldap 389, elk 9200, Redis 6379 or any other customized ports ).
Now we came to the interesting part :)
As we know, most important part of the SRE/DevOps role is monitoring stuff. So how can the SRE team monitor inter-server port communications easily and effectively, especially on large inventories?
How can they perform health-check after each network patches to confirm there is no regression?
And more importantly, how they can, quickly and reliably, check during a service interruption if the issue is coming from hosts network inter-communication problems?
Before orchestration ( Ansible, Terraform .. ), the solution was to create a shell, PowerShell, or python script to telnet or ping any of the targets hosts. The big downside of this solution is the necessity to launch the script manually in all the source servers, one by one.
With Ansible, things became smarter, automated, and easier.
Indeed, we can create a task ( could be cron job ) that will be executed from all the source hosts to check communications with all target hosts through defined ports and send reports/alerts in case of issues.
Let’s move now to the coding parts :)
We will start by creating the ansible main tasks:roles/ansible-role-ports/tasks/main.yml
---- name: Check global ports wait_for: host: "{{ item.name }}" port: "{{ item.port }}" state: started # Port should be open delay: 0 # No wait before first check (sec) timeout: 3 # Stop checking after timeout (sec) ignore_errors: yes with_items: "{{ server_to_test }}"
This is the main ansible role task indicating that telnet will be done from the “item.name” to the list of hosts in “server_to_test” through port “item.port”.
Let now create our play:plays/ports/ports.yml
---- name: check ports hosts: "{{ host }}" become: yes become_user: root roles: - ansible-role-ports
This is the ansible play that will call the task by using source and target hosts from the inventory.
Regarding the inventory, it is just listing the hosts ( sources and targets ), each with a group_vars parameter that specifies the target host and the targeted port to use for each set of sources servers.
inventory/hosts-update.yml
source1: hosts: host1: ansible_host: ip-source1-host1 host_name: source1-host1 host2: ansible_host: ip-source1-host2 host_name: source1-host2 source2: hosts: host1: ansible_host: ip-source2-host1 host_name: source2-host1 host2: ansible_host: ip-source2-host2 host_name: source2-host2 target1: hosts: host1: ansible_host: ip-target1-host1 host_name: target1-host1 host2: ansible_host: ip-target1-host2 host_name: target1-host2 target2: hosts: host1: ansible_host: ip-target2-host1 host_name: target2-host1 host2: ansible_host: ip-target2-host2 host_name: target2-host2
And finally the group_vars for each set of source hosts :
inventory/group_vars/source1.yml
---server_to_test: - {name: 'target1', port: 'port1'}#target1 - {name: 'target1', port: 'port2'}#target1 - {name: 'target2', port: 'port1'}#target2 - {name: 'target2', port: 'port2'}#target2
inventory/group_vars/source2.yml
---server_to_test: - {name: 'target1', port: 'port3'}#target1 - {name: 'target1', port: 'port4'}#target1
The usage of the play is as follows:
---ansible-playbook -i inventory/hosts-update.yml plays/ports/ports.yml — extra-vars ‘{“host”:”source1,source2”}’ -k -K -vv -u “USER”
Source1, source2 can be changed by any other set of hosts.
We are done, so as always, I hope you have learned something new.see you later :)
|
[
{
"code": null,
"e": 403,
"s": 172,
"text": "Indeed in highly sensitive businesses like banking, ports are strictly supervised, and only required ports are allowed to be opened by SecOps.Otherwise, not supervised ports can be attractive targets for network attacks like DDOS."
},
{
"code": null,
"e": 575,
"s": 403,
"text": "To explain things more easily, let’s imagine a set of hosts called sources that should communicate with another set of hosts called targets, only through authorized ports."
},
{
"code": null,
"e": 749,
"s": 575,
"text": "Hosts can be cloud, docker, VM, metal server ... and port could be any ( https 443, SMTP 25, PostgreSQL 5432, Ldap 389, elk 9200, Redis 6379 or any other customized ports )."
},
{
"code": null,
"e": 788,
"s": 749,
"text": "Now we came to the interesting part :)"
},
{
"code": null,
"e": 986,
"s": 788,
"text": "As we know, most important part of the SRE/DevOps role is monitoring stuff. So how can the SRE team monitor inter-server port communications easily and effectively, especially on large inventories?"
},
{
"code": null,
"e": 1082,
"s": 986,
"text": "How can they perform health-check after each network patches to confirm there is no regression?"
},
{
"code": null,
"e": 1248,
"s": 1082,
"text": "And more importantly, how they can, quickly and reliably, check during a service interruption if the issue is coming from hosts network inter-communication problems?"
},
{
"code": null,
"e": 1525,
"s": 1248,
"text": "Before orchestration ( Ansible, Terraform .. ), the solution was to create a shell, PowerShell, or python script to telnet or ping any of the targets hosts. The big downside of this solution is the necessity to launch the script manually in all the source servers, one by one."
},
{
"code": null,
"e": 1585,
"s": 1525,
"text": "With Ansible, things became smarter, automated, and easier."
},
{
"code": null,
"e": 1795,
"s": 1585,
"text": "Indeed, we can create a task ( could be cron job ) that will be executed from all the source hosts to check communications with all target hosts through defined ports and send reports/alerts in case of issues."
},
{
"code": null,
"e": 1833,
"s": 1795,
"text": "Let’s move now to the coding parts :)"
},
{
"code": null,
"e": 1922,
"s": 1833,
"text": "We will start by creating the ansible main tasks:roles/ansible-role-ports/tasks/main.yml"
},
{
"code": null,
"e": 2244,
"s": 1922,
"text": "---- name: Check global ports wait_for: host: \"{{ item.name }}\" port: \"{{ item.port }}\" state: started # Port should be open delay: 0 # No wait before first check (sec) timeout: 3 # Stop checking after timeout (sec) ignore_errors: yes with_items: \"{{ server_to_test }}\""
},
{
"code": null,
"e": 2403,
"s": 2244,
"text": "This is the main ansible role task indicating that telnet will be done from the “item.name” to the list of hosts in “server_to_test” through port “item.port”."
},
{
"code": null,
"e": 2449,
"s": 2403,
"text": "Let now create our play:plays/ports/ports.yml"
},
{
"code": null,
"e": 2557,
"s": 2449,
"text": "---- name: check ports hosts: \"{{ host }}\" become: yes become_user: root roles: - ansible-role-ports"
},
{
"code": null,
"e": 2659,
"s": 2557,
"text": "This is the ansible play that will call the task by using source and target hosts from the inventory."
},
{
"code": null,
"e": 2864,
"s": 2659,
"text": "Regarding the inventory, it is just listing the hosts ( sources and targets ), each with a group_vars parameter that specifies the target host and the targeted port to use for each set of sources servers."
},
{
"code": null,
"e": 2891,
"s": 2864,
"text": "inventory/hosts-update.yml"
},
{
"code": null,
"e": 3587,
"s": 2891,
"text": "source1: hosts: host1: ansible_host: ip-source1-host1 host_name: source1-host1 host2: ansible_host: ip-source1-host2 host_name: source1-host2 source2: hosts: host1: ansible_host: ip-source2-host1 host_name: source2-host1 host2: ansible_host: ip-source2-host2 host_name: source2-host2 target1: hosts: host1: ansible_host: ip-target1-host1 host_name: target1-host1 host2: ansible_host: ip-target1-host2 host_name: target1-host2 target2: hosts: host1: ansible_host: ip-target2-host1 host_name: target2-host1 host2: ansible_host: ip-target2-host2 host_name: target2-host2"
},
{
"code": null,
"e": 3645,
"s": 3587,
"text": "And finally the group_vars for each set of source hosts :"
},
{
"code": null,
"e": 3678,
"s": 3645,
"text": "inventory/group_vars/source1.yml"
},
{
"code": null,
"e": 3875,
"s": 3678,
"text": "---server_to_test: - {name: 'target1', port: 'port1'}#target1 - {name: 'target1', port: 'port2'}#target1 - {name: 'target2', port: 'port1'}#target2 - {name: 'target2', port: 'port2'}#target2"
},
{
"code": null,
"e": 3908,
"s": 3875,
"text": "inventory/group_vars/source2.yml"
},
{
"code": null,
"e": 4015,
"s": 3908,
"text": "---server_to_test: - {name: 'target1', port: 'port3'}#target1 - {name: 'target1', port: 'port4'}#target1"
},
{
"code": null,
"e": 4052,
"s": 4015,
"text": "The usage of the play is as follows:"
},
{
"code": null,
"e": 4186,
"s": 4052,
"text": "---ansible-playbook -i inventory/hosts-update.yml plays/ports/ports.yml — extra-vars ‘{“host”:”source1,source2”}’ -k -K -vv -u “USER”"
},
{
"code": null,
"e": 4245,
"s": 4186,
"text": "Source1, source2 can be changed by any other set of hosts."
}
] |
Handle mouse events in Python - OpenCV - GeeksforGeeks
|
26 Mar, 2020
OpenCV is one of the most popular computer vision libraries. If you want to start your journey in the field of computer vision, then a thorough understanding of the concepts of OpenCV is of paramount importance.
Note: For more information, refer to Introduction to OpenCV
OpenCV sometimes helps to control and manage different types of mouse events and gives us the flexibility to manage them. There can be different types of mouse events such as left button click, right button click, double_click, etc. To manage these events we need to design callback functions for each type of mouse click event while the window or frame is opened by OpenCV.The callback function will be helpful to implement what type of functionality you want with a particular mouse click event.
Below is the code to show how we can perform operations with a right click and left click events.
Code:
import cv2 # read imageimg = cv2.imread('image.jpg') # show imagecv2.imshow('image', img) #define the events for the# mouse_click.def mouse_click(event, x, y, flags, param): # to check if left mouse # button was clicked if event == cv2.EVENT_LBUTTONDOWN: # font for left click event font = cv2.FONT_HERSHEY_TRIPLEX LB = 'Left Button' # display that left button # was clicked. cv2.putText(img, LB, (x, y), font, 1, (255, 255, 0), 2) cv2.imshow('image', img) # to check if right mouse # button was clicked if event == cv2.EVENT_RBUTTONDOWN: # font for right click event font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX RB = 'Right Button' # display that right button # was clicked. cv2.putText(img, RB, (x, y), font, 1, (0, 255, 255), 2) cv2.imshow('image', img) cv2.setMouseCallback('image', mouse_click) cv2.waitKey(0) # close all the opened windows.cv2.destroyAllWindows()
Output:
Python-OpenCV
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": 24124,
"s": 24096,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 24336,
"s": 24124,
"text": "OpenCV is one of the most popular computer vision libraries. If you want to start your journey in the field of computer vision, then a thorough understanding of the concepts of OpenCV is of paramount importance."
},
{
"code": null,
"e": 24396,
"s": 24336,
"text": "Note: For more information, refer to Introduction to OpenCV"
},
{
"code": null,
"e": 24894,
"s": 24396,
"text": "OpenCV sometimes helps to control and manage different types of mouse events and gives us the flexibility to manage them. There can be different types of mouse events such as left button click, right button click, double_click, etc. To manage these events we need to design callback functions for each type of mouse click event while the window or frame is opened by OpenCV.The callback function will be helpful to implement what type of functionality you want with a particular mouse click event."
},
{
"code": null,
"e": 24992,
"s": 24894,
"text": "Below is the code to show how we can perform operations with a right click and left click events."
},
{
"code": null,
"e": 24998,
"s": 24992,
"text": "Code:"
},
{
"code": "import cv2 # read imageimg = cv2.imread('image.jpg') # show imagecv2.imshow('image', img) #define the events for the# mouse_click.def mouse_click(event, x, y, flags, param): # to check if left mouse # button was clicked if event == cv2.EVENT_LBUTTONDOWN: # font for left click event font = cv2.FONT_HERSHEY_TRIPLEX LB = 'Left Button' # display that left button # was clicked. cv2.putText(img, LB, (x, y), font, 1, (255, 255, 0), 2) cv2.imshow('image', img) # to check if right mouse # button was clicked if event == cv2.EVENT_RBUTTONDOWN: # font for right click event font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX RB = 'Right Button' # display that right button # was clicked. cv2.putText(img, RB, (x, y), font, 1, (0, 255, 255), 2) cv2.imshow('image', img) cv2.setMouseCallback('image', mouse_click) cv2.waitKey(0) # close all the opened windows.cv2.destroyAllWindows()",
"e": 26194,
"s": 24998,
"text": null
},
{
"code": null,
"e": 26202,
"s": 26194,
"text": "Output:"
},
{
"code": null,
"e": 26216,
"s": 26202,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 26223,
"s": 26216,
"text": "Python"
},
{
"code": null,
"e": 26321,
"s": 26223,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26330,
"s": 26321,
"text": "Comments"
},
{
"code": null,
"e": 26343,
"s": 26330,
"text": "Old Comments"
},
{
"code": null,
"e": 26361,
"s": 26343,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26383,
"s": 26361,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26415,
"s": 26383,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26457,
"s": 26415,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26483,
"s": 26457,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26527,
"s": 26483,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26552,
"s": 26527,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26589,
"s": 26552,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26645,
"s": 26589,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Python | Column wise sum of nested list
|
07 Aug, 2020
Given a nested list (where sublists are of equal length), write a Python program to find the column-wise sum of the given list and return it in a new list.
Examples:
Input : [[1, 5, 3],
[2, 7, 8],
[4, 6, 9]]
Output : [7, 18, 20]
Input : [[20, 5],
[2, 54],
[45, 9],
[72, 3]]
Output : [139, 71]
Method #1 : zip using list comprehension
We can find sum of each column of the given nested list using zip function of python enclosing it within list comprehension.
# Python3 program to Column wise sum of nested list def column_sum(lst): return [sum(i) for i in zip(*lst)] # Driver codelst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]print(column_sum(lst))
[7, 18, 20]
Method #2 : Using map() method
Another approach is to use map(). We apply the sum function to each element in a column and find sum of each column accordingly.
# Python3 program to Column wise sum of nested list def column_sum(lst): return list(map(sum, zip(*lst))) # Driver codelst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]print(column_sum(lst))
[7, 18, 20]
Method #3 : Using numpy.sum()
numpy.sum() function returns the sum of array elements over the specified axis.
# Python3 program to Column wise sum of nested listfrom numpy import array def column_sum(lst): arr = array(lst) return sum(arr, 0).tolist() # Driver codelst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]print(column_sum(lst))
[7, 18, 20]
Akanksha_Rai
Python list-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": "\n07 Aug, 2020"
},
{
"code": null,
"e": 184,
"s": 28,
"text": "Given a nested list (where sublists are of equal length), write a Python program to find the column-wise sum of the given list and return it in a new list."
},
{
"code": null,
"e": 194,
"s": 184,
"text": "Examples:"
},
{
"code": null,
"e": 369,
"s": 194,
"text": "Input : [[1, 5, 3],\n [2, 7, 8],\n [4, 6, 9]]\nOutput : [7, 18, 20]\n\nInput : [[20, 5],\n [2, 54],\n [45, 9], \n [72, 3]]\nOutput : [139, 71]\n"
},
{
"code": null,
"e": 410,
"s": 369,
"text": "Method #1 : zip using list comprehension"
},
{
"code": null,
"e": 535,
"s": 410,
"text": "We can find sum of each column of the given nested list using zip function of python enclosing it within list comprehension."
},
{
"code": "# Python3 program to Column wise sum of nested list def column_sum(lst): return [sum(i) for i in zip(*lst)] # Driver codelst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]print(column_sum(lst))",
"e": 734,
"s": 535,
"text": null
},
{
"code": null,
"e": 747,
"s": 734,
"text": "[7, 18, 20]\n"
},
{
"code": null,
"e": 780,
"s": 749,
"text": "Method #2 : Using map() method"
},
{
"code": null,
"e": 909,
"s": 780,
"text": "Another approach is to use map(). We apply the sum function to each element in a column and find sum of each column accordingly."
},
{
"code": "# Python3 program to Column wise sum of nested list def column_sum(lst): return list(map(sum, zip(*lst))) # Driver codelst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]print(column_sum(lst))",
"e": 1105,
"s": 909,
"text": null
},
{
"code": null,
"e": 1118,
"s": 1105,
"text": "[7, 18, 20]\n"
},
{
"code": null,
"e": 1149,
"s": 1118,
"text": " Method #3 : Using numpy.sum()"
},
{
"code": null,
"e": 1229,
"s": 1149,
"text": "numpy.sum() function returns the sum of array elements over the specified axis."
},
{
"code": "# Python3 program to Column wise sum of nested listfrom numpy import array def column_sum(lst): arr = array(lst) return sum(arr, 0).tolist() # Driver codelst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]print(column_sum(lst))",
"e": 1457,
"s": 1229,
"text": null
},
{
"code": null,
"e": 1470,
"s": 1457,
"text": "[7, 18, 20]\n"
},
{
"code": null,
"e": 1483,
"s": 1470,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1504,
"s": 1483,
"text": "Python list-programs"
},
{
"code": null,
"e": 1511,
"s": 1504,
"text": "Python"
},
{
"code": null,
"e": 1527,
"s": 1511,
"text": "Python Programs"
}
] |
numpy.isfortran() in Python
|
29 Nov, 2018
numpy.isfortran(array) : This is a logical function that checks whether array is Fortran contiguous or not.
Order : [C-contiguous, F-contiguous, A-contiguous; optional]
C-contiguous order in memory(last index varies the fastest). C order means that operating row-rise on the array will be slightly quicker.FORTRAN-contiguous order in memory (first index varies the fastest). F order means that column-wise operations will be faster.‘A’ means to read / write the elements in Fortran-like index order if, array is Fortran contiguous in memory, C-like order otherwise.
Parameters :
array : [array_like]Input array
Return :
True, if array is Fortran; else False
Code 1 :
# Python program explaining# isfortran() functionimport numpy as np in_array = np.array([[1, 2, 3], [4, 5, 6]], order='C')print ("Input array : \n", in_array) exp2_values = np.exp2(in_array)print ("\nisfortran : ", np.isfortran(in_array))
Output :
Input array :
[[1 2 3]
[4 5 6]]
isfortran : False
Code 2 :
# Python program explaining# isfortran() functionimport numpy as np in_array = np.array([[1, 2, 3], [4, 5, 6]], order='F')print ("Input array : \n", in_array) exp2_values = np.exp2(in_array)print ("\nisfortran : ", np.isfortran(in_array))
Output :
Input array :
[[1 2 3]
[4 5 6]]
isfortran : True
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isfortran.html#numpy.isfortran.
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "numpy.isfortran(array) : This is a logical function that checks whether array is Fortran contiguous or not."
},
{
"code": null,
"e": 197,
"s": 136,
"text": "Order : [C-contiguous, F-contiguous, A-contiguous; optional]"
},
{
"code": null,
"e": 594,
"s": 197,
"text": "C-contiguous order in memory(last index varies the fastest). C order means that operating row-rise on the array will be slightly quicker.FORTRAN-contiguous order in memory (first index varies the fastest). F order means that column-wise operations will be faster.‘A’ means to read / write the elements in Fortran-like index order if, array is Fortran contiguous in memory, C-like order otherwise."
},
{
"code": null,
"e": 607,
"s": 594,
"text": "Parameters :"
},
{
"code": null,
"e": 644,
"s": 607,
"text": "array : [array_like]Input array \n"
},
{
"code": null,
"e": 653,
"s": 644,
"text": "Return :"
},
{
"code": null,
"e": 692,
"s": 653,
"text": "True, if array is Fortran; else False\n"
},
{
"code": null,
"e": 701,
"s": 692,
"text": "Code 1 :"
},
{
"code": "# Python program explaining# isfortran() functionimport numpy as np in_array = np.array([[1, 2, 3], [4, 5, 6]], order='C')print (\"Input array : \\n\", in_array) exp2_values = np.exp2(in_array)print (\"\\nisfortran : \", np.isfortran(in_array))",
"e": 942,
"s": 701,
"text": null
},
{
"code": null,
"e": 951,
"s": 942,
"text": "Output :"
},
{
"code": null,
"e": 1007,
"s": 951,
"text": "Input array : \n [[1 2 3]\n [4 5 6]]\n\nisfortran : False\n"
},
{
"code": null,
"e": 1017,
"s": 1007,
"text": " Code 2 :"
},
{
"code": "# Python program explaining# isfortran() functionimport numpy as np in_array = np.array([[1, 2, 3], [4, 5, 6]], order='F')print (\"Input array : \\n\", in_array) exp2_values = np.exp2(in_array)print (\"\\nisfortran : \", np.isfortran(in_array))",
"e": 1258,
"s": 1017,
"text": null
},
{
"code": null,
"e": 1267,
"s": 1258,
"text": "Output :"
},
{
"code": null,
"e": 1321,
"s": 1267,
"text": "Input array : \n [[1 2 3]\n [4 5 6]]\n\nisfortran : True"
},
{
"code": null,
"e": 1431,
"s": 1321,
"text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isfortran.html#numpy.isfortran."
},
{
"code": null,
"e": 1460,
"s": 1431,
"text": "Python numpy-Logic Functions"
},
{
"code": null,
"e": 1473,
"s": 1460,
"text": "Python-numpy"
},
{
"code": null,
"e": 1480,
"s": 1473,
"text": "Python"
},
{
"code": null,
"e": 1578,
"s": 1480,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1596,
"s": 1578,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1638,
"s": 1596,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1673,
"s": 1638,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1699,
"s": 1673,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1731,
"s": 1699,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1760,
"s": 1731,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1787,
"s": 1760,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1808,
"s": 1787,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1831,
"s": 1808,
"text": "Introduction To PYTHON"
}
] |
Python | Pandas Series.filter()
|
13 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.filter() function returns subset rows or columns of dataframe according to labels in the specified index. Please note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index.
Syntax: Series.filter(items=None, like=None, regex=None, axis=None)
Parameter :items : List of axis to restrict to (must not all be present).like : Keep axis where “arg in col == True”.regex : Keep axis with re.search(regex, col) == True.axis : The axis to filter on. By default this is the info axis, ‘index’ for Series, ‘columns’ for DataFrame.
Returns : same type as input object
Example #1: Use Series.filter() function to filter out some values in the given series object using a regular expressions.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([80, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.filter() function to filter those values from the given series object whose index label name has a space in its name.
# filter valuesresult = sr.filter(regex = '. .') # Print the resultprint(result)
Output :As we can see in the output, the Series.filter() function has successfully returned the desired values from the given series object. Example #2 : Use Series.filter() function to filter out some values in the given series object using a list of index labels.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :Now we will use Series.filter() function to filter the values corresponding to the passed index labels in the given series object.
# filter valuesresult = sr.filter(items = ['City 2', 'City 4']) # Print the resultprint(result)
Output :As we can see in the output, the Series.filter() function has successfully returned the desired values from the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 530,
"s": 285,
"text": "Pandas Series.filter() function returns subset rows or columns of dataframe according to labels in the specified index. Please note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index."
},
{
"code": null,
"e": 598,
"s": 530,
"text": "Syntax: Series.filter(items=None, like=None, regex=None, axis=None)"
},
{
"code": null,
"e": 877,
"s": 598,
"text": "Parameter :items : List of axis to restrict to (must not all be present).like : Keep axis where “arg in col == True”.regex : Keep axis with re.search(regex, col) == True.axis : The axis to filter on. By default this is the info axis, ‘index’ for Series, ‘columns’ for DataFrame."
},
{
"code": null,
"e": 913,
"s": 877,
"text": "Returns : same type as input object"
},
{
"code": null,
"e": 1036,
"s": 913,
"text": "Example #1: Use Series.filter() function to filter out some values in the given series object using a regular expressions."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([80, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 1292,
"s": 1036,
"text": null
},
{
"code": null,
"e": 1301,
"s": 1292,
"text": "Output :"
},
{
"code": null,
"e": 1442,
"s": 1301,
"text": "Now we will use Series.filter() function to filter those values from the given series object whose index label name has a space in its name."
},
{
"code": "# filter valuesresult = sr.filter(regex = '. .') # Print the resultprint(result)",
"e": 1524,
"s": 1442,
"text": null
},
{
"code": null,
"e": 1790,
"s": 1524,
"text": "Output :As we can see in the output, the Series.filter() function has successfully returned the desired values from the given series object. Example #2 : Use Series.filter() function to filter out some values in the given series object using a list of index labels."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 2067,
"s": 1790,
"text": null
},
{
"code": null,
"e": 2206,
"s": 2067,
"text": "Output :Now we will use Series.filter() function to filter the values corresponding to the passed index labels in the given series object."
},
{
"code": "# filter valuesresult = sr.filter(items = ['City 2', 'City 4']) # Print the resultprint(result)",
"e": 2303,
"s": 2206,
"text": null
},
{
"code": null,
"e": 2444,
"s": 2303,
"text": "Output :As we can see in the output, the Series.filter() function has successfully returned the desired values from the given series object."
},
{
"code": null,
"e": 2465,
"s": 2444,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2494,
"s": 2465,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2508,
"s": 2494,
"text": "Python-pandas"
},
{
"code": null,
"e": 2515,
"s": 2508,
"text": "Python"
}
] |
Modulus on Negative Numbers
|
17 Jun, 2022
What will be the output of the following C program?
C++
C
C#
#include <iostream>using namespace std; int main() { int a = 3, b = -8, c = 2; cout << a % b / c; return 0;}
#include <stdio.h>int main(){ int a = 3, b = -8, c = 2; printf("%d", a % b / c); return 0;}
using System; public class GFG{ static public void Main () { int a = 3; int b = -8; int c = 2; Console.WriteLine(a % b / c); }} // This code is contributed by sarajadhav12052009
1
% and / have the same precedence and left to right associativity. So % is performed first which results in 3 and / is performed next resulting in 1. The emphasis is, that a sign of a left operand is appended to result in the case of the modulus operator in C.
C++
C
C#
#include <iostream>using namespace std; int main() { int a = 3, b = -8; cout << a % b; return 0;}
#include <stdio.h>int main(){ // a positive and b negative. int a = 3, b = -8; printf("%d", a % b); return 0;}
using System; public class GFG{ static public void Main () { int a = 3; int b = -8; Console.WriteLine(a % b); }} // This code is contributed by sarajadhav12052009
Output
3
C++
C
C#
#include <iostream>using namespace std; int main(){ // a negative and b positive int a = -3, b = 8; cout << a%b; return 0;}
#include <stdio.h>int main(){ // a negative and b positive int a = -3, b = 8; printf("%d", a % b); return 0;}
using System; public class GFG{ static public void Main () { int a = -3; int b = 8; Console.WriteLine(a % b); }} // This code is contributed by sarajadhav12052009
Output
-3
But from the definition of the remainder (as stated here https://en.wikipedia.org/wiki/Remainder) it should always be a least positive integer that should be subtracted from a to make it divisible by b (mathematically if, a = QB + r then 0 ≤ r < |b|).
So, in the above example, -3 is not our real remainder because it is negative.
Therefore, in C/C++ language we always find remainder as (a%b + b)%b (add quotient to remainder and again take remainder) to avoid negative remainder.
C++
C
C#
#include <iostream>using namespace std; int main() { // a and b both negative int a = -3, b = -8; cout << a % b; return 0;}
#include <stdio.h>int main(){ // a and b both negative int a = -3, b = -8; printf("%d", a % b); return 0;}
using System; public class GFG{ static public void Main () { int a = -3; int b = -8; Console.WriteLine(a % b); }} // This code is contributed by sarajadhav12052009
Output
-3
Anyone can predict the output of a modulus operator when both operands are positive. But when it comes to the negative numbers, different languages give different outputs.
In C language, modulus is calculated as,
a % n = a – ( n * trunc( a/n ) ).
For example,8 % -3 = 8 – ( -3 * trunc(8/-3) ) = 8 – ( -3 * trunc(-2.666..) ) = 8 – ( -3 * -2 ) { rounded towards zero } = 8 – 6 = 2
Important Note:
Numerator
Denominator
X sign
Y sign
X/Y sign
X%Y sign
+
+
+
+
+
–
–
+
–
+
–
–
–
–
+
–
From the above table, we conclude that the % operator always considers a sign of a numerator
For more info, please see https://en.wikipedia.org/wiki/Modulo_operation
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
sushantgundla
surbhit7
namalashivacharan123
2019kucp1053
guptavivek0503
sarajadhav12052009
C-Operators
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Different Methods to Reverse a String in C++
Left Shift and Right Shift Operators in C/C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
What is the purpose of a function prototype?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 106,
"s": 52,
"text": "What will be the output of the following C program? "
},
{
"code": null,
"e": 110,
"s": 106,
"text": "C++"
},
{
"code": null,
"e": 112,
"s": 110,
"text": "C"
},
{
"code": null,
"e": 115,
"s": 112,
"text": "C#"
},
{
"code": "#include <iostream>using namespace std; int main() { int a = 3, b = -8, c = 2; cout << a % b / c; return 0;}",
"e": 231,
"s": 115,
"text": null
},
{
"code": "#include <stdio.h>int main(){ int a = 3, b = -8, c = 2; printf(\"%d\", a % b / c); return 0;}",
"e": 329,
"s": 231,
"text": null
},
{
"code": "using System; public class GFG{ static public void Main () { int a = 3; int b = -8; int c = 2; Console.WriteLine(a % b / c); }} // This code is contributed by sarajadhav12052009",
"e": 547,
"s": 329,
"text": null
},
{
"code": null,
"e": 549,
"s": 547,
"text": "1"
},
{
"code": null,
"e": 810,
"s": 549,
"text": "% and / have the same precedence and left to right associativity. So % is performed first which results in 3 and / is performed next resulting in 1. The emphasis is, that a sign of a left operand is appended to result in the case of the modulus operator in C. "
},
{
"code": null,
"e": 814,
"s": 810,
"text": "C++"
},
{
"code": null,
"e": 816,
"s": 814,
"text": "C"
},
{
"code": null,
"e": 819,
"s": 816,
"text": "C#"
},
{
"code": "#include <iostream>using namespace std; int main() { int a = 3, b = -8; cout << a % b; return 0;}",
"e": 928,
"s": 819,
"text": null
},
{
"code": "#include <stdio.h>int main(){ // a positive and b negative. int a = 3, b = -8; printf(\"%d\", a % b); return 0;}",
"e": 1047,
"s": 928,
"text": null
},
{
"code": "using System; public class GFG{ static public void Main () { int a = 3; int b = -8; Console.WriteLine(a % b); }} // This code is contributed by sarajadhav12052009",
"e": 1250,
"s": 1047,
"text": null
},
{
"code": null,
"e": 1258,
"s": 1250,
"text": "Output "
},
{
"code": null,
"e": 1260,
"s": 1258,
"text": "3"
},
{
"code": null,
"e": 1266,
"s": 1262,
"text": "C++"
},
{
"code": null,
"e": 1268,
"s": 1266,
"text": "C"
},
{
"code": null,
"e": 1271,
"s": 1268,
"text": "C#"
},
{
"code": "#include <iostream>using namespace std; int main(){ // a negative and b positive int a = -3, b = 8; cout << a%b; return 0;}",
"e": 1403,
"s": 1271,
"text": null
},
{
"code": "#include <stdio.h>int main(){ // a negative and b positive int a = -3, b = 8; printf(\"%d\", a % b); return 0;}",
"e": 1521,
"s": 1403,
"text": null
},
{
"code": "using System; public class GFG{ static public void Main () { int a = -3; int b = 8; Console.WriteLine(a % b); }} // This code is contributed by sarajadhav12052009",
"e": 1725,
"s": 1521,
"text": null
},
{
"code": null,
"e": 1733,
"s": 1725,
"text": "Output "
},
{
"code": null,
"e": 1736,
"s": 1733,
"text": "-3"
},
{
"code": null,
"e": 1988,
"s": 1736,
"text": "But from the definition of the remainder (as stated here https://en.wikipedia.org/wiki/Remainder) it should always be a least positive integer that should be subtracted from a to make it divisible by b (mathematically if, a = QB + r then 0 ≤ r < |b|)."
},
{
"code": null,
"e": 2068,
"s": 1988,
"text": "So, in the above example, -3 is not our real remainder because it is negative. "
},
{
"code": null,
"e": 2219,
"s": 2068,
"text": "Therefore, in C/C++ language we always find remainder as (a%b + b)%b (add quotient to remainder and again take remainder) to avoid negative remainder."
},
{
"code": null,
"e": 2225,
"s": 2221,
"text": "C++"
},
{
"code": null,
"e": 2227,
"s": 2225,
"text": "C"
},
{
"code": null,
"e": 2230,
"s": 2227,
"text": "C#"
},
{
"code": "#include <iostream>using namespace std; int main() { // a and b both negative int a = -3, b = -8; cout << a % b; return 0;}",
"e": 2362,
"s": 2230,
"text": null
},
{
"code": "#include <stdio.h>int main(){ // a and b both negative int a = -3, b = -8; printf(\"%d\", a % b); return 0;}",
"e": 2477,
"s": 2362,
"text": null
},
{
"code": "using System; public class GFG{ static public void Main () { int a = -3; int b = -8; Console.WriteLine(a % b); }} // This code is contributed by sarajadhav12052009",
"e": 2679,
"s": 2477,
"text": null
},
{
"code": null,
"e": 2687,
"s": 2679,
"text": "Output "
},
{
"code": null,
"e": 2690,
"s": 2687,
"text": "-3"
},
{
"code": null,
"e": 2862,
"s": 2690,
"text": "Anyone can predict the output of a modulus operator when both operands are positive. But when it comes to the negative numbers, different languages give different outputs."
},
{
"code": null,
"e": 2903,
"s": 2862,
"text": "In C language, modulus is calculated as,"
},
{
"code": null,
"e": 2937,
"s": 2903,
"text": "a % n = a – ( n * trunc( a/n ) )."
},
{
"code": null,
"e": 3109,
"s": 2937,
"text": "For example,8 % -3 = 8 – ( -3 * trunc(8/-3) ) = 8 – ( -3 * trunc(-2.666..) ) = 8 – ( -3 * -2 ) { rounded towards zero } = 8 – 6 = 2"
},
{
"code": null,
"e": 3125,
"s": 3109,
"text": "Important Note:"
},
{
"code": null,
"e": 3135,
"s": 3125,
"text": "Numerator"
},
{
"code": null,
"e": 3147,
"s": 3135,
"text": "Denominator"
},
{
"code": null,
"e": 3158,
"s": 3151,
"text": "X sign"
},
{
"code": null,
"e": 3165,
"s": 3158,
"text": "Y sign"
},
{
"code": null,
"e": 3174,
"s": 3165,
"text": "X/Y sign"
},
{
"code": null,
"e": 3183,
"s": 3174,
"text": "X%Y sign"
},
{
"code": null,
"e": 3185,
"s": 3183,
"text": "+"
},
{
"code": null,
"e": 3187,
"s": 3185,
"text": "+"
},
{
"code": null,
"e": 3189,
"s": 3187,
"text": "+"
},
{
"code": null,
"e": 3191,
"s": 3189,
"text": "+"
},
{
"code": null,
"e": 3193,
"s": 3191,
"text": "+"
},
{
"code": null,
"e": 3195,
"s": 3193,
"text": "–"
},
{
"code": null,
"e": 3197,
"s": 3195,
"text": "–"
},
{
"code": null,
"e": 3199,
"s": 3197,
"text": "+"
},
{
"code": null,
"e": 3201,
"s": 3199,
"text": "–"
},
{
"code": null,
"e": 3203,
"s": 3201,
"text": "+"
},
{
"code": null,
"e": 3205,
"s": 3203,
"text": "–"
},
{
"code": null,
"e": 3207,
"s": 3205,
"text": "–"
},
{
"code": null,
"e": 3209,
"s": 3207,
"text": "–"
},
{
"code": null,
"e": 3211,
"s": 3209,
"text": "–"
},
{
"code": null,
"e": 3213,
"s": 3211,
"text": "+"
},
{
"code": null,
"e": 3215,
"s": 3213,
"text": "–"
},
{
"code": null,
"e": 3308,
"s": 3215,
"text": "From the above table, we conclude that the % operator always considers a sign of a numerator"
},
{
"code": null,
"e": 3381,
"s": 3308,
"text": "For more info, please see https://en.wikipedia.org/wiki/Modulo_operation"
},
{
"code": null,
"e": 3510,
"s": 3381,
"text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3524,
"s": 3510,
"text": "sushantgundla"
},
{
"code": null,
"e": 3533,
"s": 3524,
"text": "surbhit7"
},
{
"code": null,
"e": 3554,
"s": 3533,
"text": "namalashivacharan123"
},
{
"code": null,
"e": 3567,
"s": 3554,
"text": "2019kucp1053"
},
{
"code": null,
"e": 3582,
"s": 3567,
"text": "guptavivek0503"
},
{
"code": null,
"e": 3601,
"s": 3582,
"text": "sarajadhav12052009"
},
{
"code": null,
"e": 3613,
"s": 3601,
"text": "C-Operators"
},
{
"code": null,
"e": 3624,
"s": 3613,
"text": "C Language"
},
{
"code": null,
"e": 3722,
"s": 3624,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3739,
"s": 3722,
"text": "Substring in C++"
},
{
"code": null,
"e": 3761,
"s": 3739,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 3796,
"s": 3761,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 3841,
"s": 3796,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 3887,
"s": 3841,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 3912,
"s": 3887,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3960,
"s": 3912,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3988,
"s": 3960,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 4015,
"s": 3988,
"text": "Enumeration (or enum) in C"
}
] |
dig Command in Linux with Examples
|
28 Apr, 2022
dig command stands for Domain Information Groper. It is used for retrieving information about DNS name servers. It is basically used by network administrators. It is used for verifying and troubleshooting DNS problems and to perform DNS lookups. Dig command replaces older tools such as nslookup and the host.
In case of Debian/Ubuntu
$sudo apt-get install dnsutils
In case of CentOS/RedHat
$sudo yum install bind-utils
Syntax:
dig [server] [name] [type]
1. To query domain “A” record
dig geeksforgeeks.org
This command causes dig to look up the “A” record for the domain name “geeksforgeeks.org”.
A record refers to IPV4 IP. Similarly, if record type is set as “AAAA”, this would return IPV6 IP.
2. To query domain “A” record with +short
dig geeksforgeeks.org +short
By default dig is verbose and by using “+short” option we can reduce the output drastically as shown. 3. To remove comment lines.
dig geeksforgeeks.org +nocomments
This command makes a request and excludes the comment lines. 4. To set or clear all display flags.
dig geeksforgeeks.org +noall
We use the “noall” query option, when we want to set or clear all display flags. 5. To query detailed answers.
dig geeksforgeeks.org +noall +answer
If we want to view the answers section information in detail, we first stop the display of all section using “+noall” option and then query the answers section only by using “+answer” option with the dig command. 6. To query all DNS record types.
dig geeksforgeeks.org ANY
We use “ANY” option to query all the available DNS record types associated with a domain. It will include all the available record types in the output. 7. To query MX record for the domain.
dig geeksforgeeks.org MX
If we want only the mail exchange – MX – answer section associated with a domain we use this command. 8. To trace DNS path
dig geeksforgeeks.org +trace
“+trace” command is used for tracing the DNS lookup path. This option makes iterative queries to resolve the name lookup. It will query the name servers starting from the root and subsequently traverses down the namespace tree using iterative queries following referrals along the way. 9. For specifying name servers
dig geeksforgeeks.org @8.8.8.8
By default, dig command will query the name servers listed in “/etc/resolv.conf” to perform a DNS lookup. We can change it by using @ symbol followed by a hostname or IP address of the name server. 10. To query the statistics section
dig geeksforgeeks.org +noall +answer +stats
We use “+stats” option with dig command, to see the statistics section.
Reverse DNS Lookup:
Reverse DNS lookup can be used to fetch domain name or the host name from the IP address.“-x” option is used to perform reverse DNS lookup.
ex:
[xxxxxx ~]# dig +noall +answer -x 8.8.8.88.8.8.8.in-addr.arpa. 18208 IN PTR dns.google.
Note: DNS reverse look up will work only if the entry is present PTR. PTR contents can be viewed using the command “dig -x xx.yy.zz.aa”
Batch Queries:
Instead performing dig query for each domain at a time, a list of domains can be queried at once.
To do so, enter the domain names in a file, only 1 domain name in each line and perform the dig query on file. ex: let’s say, file.txt has the list of domain names to be queried then,
dig -f file.txt +shortwill perform DNS queries and return all the resolved IPs.
rahulmittalal
linux-command
Linux-networking-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Introduction to Linux Operating System
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Apr, 2022"
},
{
"code": null,
"e": 364,
"s": 54,
"text": "dig command stands for Domain Information Groper. It is used for retrieving information about DNS name servers. It is basically used by network administrators. It is used for verifying and troubleshooting DNS problems and to perform DNS lookups. Dig command replaces older tools such as nslookup and the host."
},
{
"code": null,
"e": 389,
"s": 364,
"text": "In case of Debian/Ubuntu"
},
{
"code": null,
"e": 420,
"s": 389,
"text": "$sudo apt-get install dnsutils"
},
{
"code": null,
"e": 445,
"s": 420,
"text": "In case of CentOS/RedHat"
},
{
"code": null,
"e": 474,
"s": 445,
"text": "$sudo yum install bind-utils"
},
{
"code": null,
"e": 482,
"s": 474,
"text": "Syntax:"
},
{
"code": null,
"e": 509,
"s": 482,
"text": "dig [server] [name] [type]"
},
{
"code": null,
"e": 539,
"s": 509,
"text": "1. To query domain “A” record"
},
{
"code": null,
"e": 561,
"s": 539,
"text": "dig geeksforgeeks.org"
},
{
"code": null,
"e": 653,
"s": 561,
"text": " This command causes dig to look up the “A” record for the domain name “geeksforgeeks.org”."
},
{
"code": null,
"e": 754,
"s": 653,
"text": "A record refers to IPV4 IP. Similarly, if record type is set as “AAAA”, this would return IPV6 IP. "
},
{
"code": null,
"e": 796,
"s": 754,
"text": "2. To query domain “A” record with +short"
},
{
"code": null,
"e": 825,
"s": 796,
"text": "dig geeksforgeeks.org +short"
},
{
"code": null,
"e": 956,
"s": 825,
"text": " By default dig is verbose and by using “+short” option we can reduce the output drastically as shown. 3. To remove comment lines."
},
{
"code": null,
"e": 990,
"s": 956,
"text": "dig geeksforgeeks.org +nocomments"
},
{
"code": null,
"e": 1090,
"s": 990,
"text": " This command makes a request and excludes the comment lines. 4. To set or clear all display flags."
},
{
"code": null,
"e": 1119,
"s": 1090,
"text": "dig geeksforgeeks.org +noall"
},
{
"code": null,
"e": 1231,
"s": 1119,
"text": " We use the “noall” query option, when we want to set or clear all display flags. 5. To query detailed answers."
},
{
"code": null,
"e": 1268,
"s": 1231,
"text": "dig geeksforgeeks.org +noall +answer"
},
{
"code": null,
"e": 1516,
"s": 1268,
"text": " If we want to view the answers section information in detail, we first stop the display of all section using “+noall” option and then query the answers section only by using “+answer” option with the dig command. 6. To query all DNS record types."
},
{
"code": null,
"e": 1542,
"s": 1516,
"text": "dig geeksforgeeks.org ANY"
},
{
"code": null,
"e": 1733,
"s": 1542,
"text": " We use “ANY” option to query all the available DNS record types associated with a domain. It will include all the available record types in the output. 7. To query MX record for the domain."
},
{
"code": null,
"e": 1758,
"s": 1733,
"text": "dig geeksforgeeks.org MX"
},
{
"code": null,
"e": 1882,
"s": 1758,
"text": " If we want only the mail exchange – MX – answer section associated with a domain we use this command. 8. To trace DNS path"
},
{
"code": null,
"e": 1911,
"s": 1882,
"text": "dig geeksforgeeks.org +trace"
},
{
"code": null,
"e": 2229,
"s": 1911,
"text": " “+trace” command is used for tracing the DNS lookup path. This option makes iterative queries to resolve the name lookup. It will query the name servers starting from the root and subsequently traverses down the namespace tree using iterative queries following referrals along the way. 9. For specifying name servers"
},
{
"code": null,
"e": 2260,
"s": 2229,
"text": "dig geeksforgeeks.org @8.8.8.8"
},
{
"code": null,
"e": 2495,
"s": 2260,
"text": " By default, dig command will query the name servers listed in “/etc/resolv.conf” to perform a DNS lookup. We can change it by using @ symbol followed by a hostname or IP address of the name server. 10. To query the statistics section"
},
{
"code": null,
"e": 2539,
"s": 2495,
"text": "dig geeksforgeeks.org +noall +answer +stats"
},
{
"code": null,
"e": 2612,
"s": 2539,
"text": " We use “+stats” option with dig command, to see the statistics section."
},
{
"code": null,
"e": 2632,
"s": 2612,
"text": "Reverse DNS Lookup:"
},
{
"code": null,
"e": 2772,
"s": 2632,
"text": "Reverse DNS lookup can be used to fetch domain name or the host name from the IP address.“-x” option is used to perform reverse DNS lookup."
},
{
"code": null,
"e": 2777,
"s": 2772,
"text": "ex: "
},
{
"code": null,
"e": 2865,
"s": 2777,
"text": "[xxxxxx ~]# dig +noall +answer -x 8.8.8.88.8.8.8.in-addr.arpa. 18208 IN PTR dns.google."
},
{
"code": null,
"e": 3002,
"s": 2865,
"text": "Note: DNS reverse look up will work only if the entry is present PTR. PTR contents can be viewed using the command “dig -x xx.yy.zz.aa” "
},
{
"code": null,
"e": 3017,
"s": 3002,
"text": "Batch Queries:"
},
{
"code": null,
"e": 3116,
"s": 3017,
"text": "Instead performing dig query for each domain at a time, a list of domains can be queried at once. "
},
{
"code": null,
"e": 3301,
"s": 3116,
"text": "To do so, enter the domain names in a file, only 1 domain name in each line and perform the dig query on file. ex: let’s say, file.txt has the list of domain names to be queried then, "
},
{
"code": null,
"e": 3381,
"s": 3301,
"text": "dig -f file.txt +shortwill perform DNS queries and return all the resolved IPs."
},
{
"code": null,
"e": 3397,
"s": 3383,
"text": "rahulmittalal"
},
{
"code": null,
"e": 3411,
"s": 3397,
"text": "linux-command"
},
{
"code": null,
"e": 3437,
"s": 3411,
"text": "Linux-networking-commands"
},
{
"code": null,
"e": 3448,
"s": 3437,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3546,
"s": 3448,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3581,
"s": 3546,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3607,
"s": 3581,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3644,
"s": 3607,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 3673,
"s": 3644,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 3710,
"s": 3673,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 3747,
"s": 3710,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 3787,
"s": 3747,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 3821,
"s": 3787,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 3860,
"s": 3821,
"text": "Introduction to Linux Operating System"
}
] |
GATE | GATE-CS-2007 | Question 77
|
28 Jun, 2021
Suppose the letters a, b, c, d, e, f have probabilities 1/2, 1/4, 1/8, 1/16, 1/32, 1/32 respectively. What is the average length of Huffman codes?(A) 3(B) 2.1875(C) 2.25(D) 1.9375Answer: (D)Explanation: We get the following Huffman Tree after applying Huffman Coding Algorithm. The idea is to keep the least probable characters as low as possible by picking them first.
The letters a, b, c, d, e, f have probabilities
1/2, 1/4, 1/8, 1/16, 1/32, 1/32 respectively.
1
/ \
/ \
1/2 a(1/2)
/ \
/ \
1/4 b(1/4)
/ \
/ \
1/8 c(1/8)
/ \
/ \
1/16 d(1/16)
/ \
e f
The average length = (1*1/2 + 2*1/4 + 3*1/8 + 4*1/16 + 5*1/32 + 5*1/32)
= 1.9375
Quiz of this Question
GATE-CS-2007
GATE-GATE-CS-2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE CS 2011 | Question 49
GATE | GATE-CS-2014-(Set-1) | Question 51
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 398,
"s": 28,
"text": "Suppose the letters a, b, c, d, e, f have probabilities 1/2, 1/4, 1/8, 1/16, 1/32, 1/32 respectively. What is the average length of Huffman codes?(A) 3(B) 2.1875(C) 2.25(D) 1.9375Answer: (D)Explanation: We get the following Huffman Tree after applying Huffman Coding Algorithm. The idea is to keep the least probable characters as low as possible by picking them first."
},
{
"code": null,
"e": 851,
"s": 398,
"text": "The letters a, b, c, d, e, f have probabilities \n1/2, 1/4, 1/8, 1/16, 1/32, 1/32 respectively. \n\n 1\n / \\\n / \\\n 1/2 a(1/2)\n / \\\n / \\\n 1/4 b(1/4) \n / \\\n / \\\n 1/8 c(1/8) \n / \\\n / \\\n 1/16 d(1/16)\n / \\\n e f\nThe average length = (1*1/2 + 2*1/4 + 3*1/8 + 4*1/16 + 5*1/32 + 5*1/32)\n = 1.9375 \n"
},
{
"code": null,
"e": 873,
"s": 851,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 886,
"s": 873,
"text": "GATE-CS-2007"
},
{
"code": null,
"e": 904,
"s": 886,
"text": "GATE-GATE-CS-2007"
},
{
"code": null,
"e": 909,
"s": 904,
"text": "GATE"
},
{
"code": null,
"e": 1007,
"s": 909,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1049,
"s": 1007,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 1111,
"s": 1049,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 1153,
"s": 1111,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 20"
},
{
"code": null,
"e": 1187,
"s": 1153,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 1229,
"s": 1187,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 1263,
"s": 1229,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 1305,
"s": 1263,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 1339,
"s": 1305,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 1373,
"s": 1339,
"text": "GATE | GATE CS 2011 | Question 49"
}
] |
Iterate over characters of a string in Python
|
19 Dec, 2018
In Python, while operating with String, one can do multiple operations on it. Let’s see how to iterate over characters of a string in Python.
Example #1: Using simple iteration and range()
# Python program to iterate over characters of a string # Code #1string_name = "geeksforgeeks" # Iterate over the stringfor element in string_name: print(element, end=' ')print("\n") # Code #2string_name = "GEEKS" # Iterate over indexfor element in range(0, len(string_name)): print(string_name[element])
g e e k s f o r g e e k s
G
E
E
K
S
Example #2: Using enumerate() function
# Python program to iterate over characters of a string string_name = "Geeks" # Iterate over the stringfor i, v in enumerate(string_name): print(v)
G
e
e
k
s
Example #3: Iterate characters in reverse order
# Python program to iterate over characters of a string # Code #1string_name = "GEEKS" # slicing the string in reverse fashion for element in string_name[ : :-1]: print(element, end =' ')print('\n') # Code #2string_name = "geeksforgeeks" # Getting length of stringran = len(string_name) # using reversed() functionfor element in reversed(range(0, ran)): print(string_name[element])
S K E E G
s
k
e
e
g
r
o
f
s
k
e
e
g
Example #4: Iteration over particular set of element.
Perform iteration over string_name by passing particular string index values.
# Python program to iterate over particular set of element.string_name = "geeksforgeeks" # string_name[start:end:step]for element in string_name[0:8:1]: print(element, end =' ')
g e e k s f o r
Picked
Python string-programs
python-string
Technical Scripter 2018
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
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": "\n19 Dec, 2018"
},
{
"code": null,
"e": 194,
"s": 52,
"text": "In Python, while operating with String, one can do multiple operations on it. Let’s see how to iterate over characters of a string in Python."
},
{
"code": null,
"e": 241,
"s": 194,
"text": "Example #1: Using simple iteration and range()"
},
{
"code": "# Python program to iterate over characters of a string # Code #1string_name = \"geeksforgeeks\" # Iterate over the stringfor element in string_name: print(element, end=' ')print(\"\\n\") # Code #2string_name = \"GEEKS\" # Iterate over indexfor element in range(0, len(string_name)): print(string_name[element])",
"e": 558,
"s": 241,
"text": null
},
{
"code": null,
"e": 597,
"s": 558,
"text": "g e e k s f o r g e e k s \n\nG\nE\nE\nK\nS\n"
},
{
"code": null,
"e": 637,
"s": 597,
"text": " Example #2: Using enumerate() function"
},
{
"code": "# Python program to iterate over characters of a string string_name = \"Geeks\" # Iterate over the stringfor i, v in enumerate(string_name): print(v)",
"e": 790,
"s": 637,
"text": null
},
{
"code": null,
"e": 801,
"s": 790,
"text": "G\ne\ne\nk\ns\n"
},
{
"code": null,
"e": 850,
"s": 801,
"text": " Example #3: Iterate characters in reverse order"
},
{
"code": "# Python program to iterate over characters of a string # Code #1string_name = \"GEEKS\" # slicing the string in reverse fashion for element in string_name[ : :-1]: print(element, end =' ')print('\\n') # Code #2string_name = \"geeksforgeeks\" # Getting length of stringran = len(string_name) # using reversed() functionfor element in reversed(range(0, ran)): print(string_name[element])",
"e": 1243,
"s": 850,
"text": null
},
{
"code": null,
"e": 1282,
"s": 1243,
"text": "S K E E G \n\ns\nk\ne\ne\ng\nr\no\nf\ns\nk\ne\ne\ng\n"
},
{
"code": null,
"e": 1337,
"s": 1282,
"text": " Example #4: Iteration over particular set of element."
},
{
"code": null,
"e": 1415,
"s": 1337,
"text": "Perform iteration over string_name by passing particular string index values."
},
{
"code": "# Python program to iterate over particular set of element.string_name = \"geeksforgeeks\" # string_name[start:end:step]for element in string_name[0:8:1]: print(element, end =' ')",
"e": 1598,
"s": 1415,
"text": null
},
{
"code": null,
"e": 1615,
"s": 1598,
"text": "g e e k s f o r\n"
},
{
"code": null,
"e": 1622,
"s": 1615,
"text": "Picked"
},
{
"code": null,
"e": 1645,
"s": 1622,
"text": "Python string-programs"
},
{
"code": null,
"e": 1659,
"s": 1645,
"text": "python-string"
},
{
"code": null,
"e": 1683,
"s": 1659,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 1690,
"s": 1683,
"text": "Python"
},
{
"code": null,
"e": 1706,
"s": 1690,
"text": "Python Programs"
},
{
"code": null,
"e": 1725,
"s": 1706,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1823,
"s": 1725,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1841,
"s": 1823,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1883,
"s": 1841,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1918,
"s": 1883,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1944,
"s": 1918,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1976,
"s": 1944,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2019,
"s": 1976,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2041,
"s": 2019,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2080,
"s": 2041,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2118,
"s": 2080,
"text": "Python | Convert a list to dictionary"
}
] |
Sort an array of strings based on the given order
|
28 Feb, 2022
Given an array of strings words[] and the sequential order of alphabets, our task is to sort the array according to the order given. Assume that the dictionary and the words only contain lowercase alphabets.
Examples:
Input: words = {“hello”, “geeksforgeeks”}, order = “hlabcdefgijkmnopqrstuvwxyz” Output: “hello”, “geeksforgeeks” Explanation: According to the given order ‘h’ occurs before ‘g’ and hence the words are considered to be sorted.
Input: words = {“word”, “world”, “row”}, order = “worldabcefghijkmnpqstuvxyz” Output: “world”, “word”, “row” Explanation: According to the given order ‘l’ occurs before ‘d’ hence the words “world” will be kept first.
Approach: To solve the problem mentioned above we need to maintain the priority of each character in the given order. For doing that use Map Data Structure.
Iterate in the given order and set the priority of a character to its index value.
Use a custom comparator function to sort the array.
In the comparator function, iterate through the minimum sized word between the two words and try to find the first different character, the word with the lesser priority value character will be the smaller word.
If the words have the same prefix, then the word with a smaller size is the smaller word.
Below is the implementation of above approach:
C++
Python3
Javascript
// C++ program to sort an array// of strings based on the given order #include <bits/stdc++.h>using namespace std; // For storing priority of each characterunordered_map<char, int> mp; // Custom comparator function for sortbool comp(string& a, string& b){ // Loop through the minimum size // between two words for (int i = 0; i < min(a.size(), b.size()); i++) { // Check if the characters // at position i are different, // then the word containing lower // valued character is smaller if (mp[a[i]] != mp[b[i]]) return mp[a[i]] < mp[b[i]]; } /* When loop breaks without returning, it means the prefix of both words were same till the execution of the loop. Now, the word with the smaller size will occur before in sorted order */ return (a.size() < b.size());} // Function to print the// new sorted array of stringsvoid printSorted(vector<string> words, string order){ // Mapping each character // to its occurrence position for (int i = 0; i < order.size(); i++) mp[order[i]] = i; // Sorting with custom sort function sort(words.begin(), words.end(), comp); // Printing the sorted order of words for (auto x : words) cout << x << " ";} // Driver codeint main(){ vector<string> words = { "word", "world", "row" }; string order = { "worldabcefghijkmnpqstuvxyz" }; printSorted(words, order); return 0;}
# Python3 program to sort an array# of strings based on the given orderfrom functools import cmp_to_key # For storing priority of each charactermp = {} # Custom comparator function for sortdef comp(a, b): # Loop through the minimum size # between two words for i in range( min(len(a), len(b))): # Check if the characters # at position i are different, # then the word containing lower # valued character is smaller if (mp[a[i]] != mp[b[i]]): if mp[a[i]] < mp[b[i]]: return -1 else: return 1 '''When loop breaks without returning, it means the prefix of both words were same till the execution of the loop. Now, the word with the smaller size will occur before in sorted order''' if (len(a) < len(b)): return -1 else: return 1 # Function to print the# new sorted array of stringsdef printSorted(words, order): # Mapping each character # to its occurrence position for i in range(len(order)): mp[order[i]] = i # Sorting with custom sort function words = sorted(words, key = cmp_to_key(comp)) # Printing the sorted order of words for x in words: print(x, end = " ") # Driver codewords = [ "word", "world", "row" ]order = "worldabcefghijkmnpqstuvxyz" printSorted(words, order) # This code is contributed by Shivani
<script> // JavaScript program to sort an array// of strings based on the given order // For storing priority of each characterlet mp = new Map(); // Custom comparator function for sortfunction comp(a, b){ // Loop through the minimum size // between two words for (let i = 0; i < Math.min(a.length, b.length);i++) { // Check if the characters // at position i are different, // then the word containing lower // valued character is smaller if (mp.get(a[i]) != mp.get(b[i])) return mp.get(b[i]) - mp.get(a[i]); } /* When loop breaks without returning, it means the prefix of both words were same till the execution of the loop. Now, the word with the smaller size will occur before in sorted order */ return (b.length - a.length);} // Function to print the// new sorted array of stringsfunction printSorted(words,order){ // Mapping each character // to its occurrence position for (let i = 0; i < order.length; i++) mp.set(order[i],i); // Sorting with custom sort function words.sort(comp); // Printing the sorted order of words for (let x of words) document.write(x +" ");} // Driver codelet words = ["word", "world", "row" ];let order = ["worldabcefghijkmnpqstuvxyz" ]; printSorted(words, order); // This code is contributed by shinjanpatra </script>
world word row
saurabh1990aror
shivanisinghss2110
shinjanpatra
Arrays
Sorting
Strings
Arrays
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 260,
"s": 52,
"text": "Given an array of strings words[] and the sequential order of alphabets, our task is to sort the array according to the order given. Assume that the dictionary and the words only contain lowercase alphabets."
},
{
"code": null,
"e": 271,
"s": 260,
"text": "Examples: "
},
{
"code": null,
"e": 497,
"s": 271,
"text": "Input: words = {“hello”, “geeksforgeeks”}, order = “hlabcdefgijkmnopqrstuvwxyz” Output: “hello”, “geeksforgeeks” Explanation: According to the given order ‘h’ occurs before ‘g’ and hence the words are considered to be sorted."
},
{
"code": null,
"e": 716,
"s": 497,
"text": "Input: words = {“word”, “world”, “row”}, order = “worldabcefghijkmnpqstuvxyz” Output: “world”, “word”, “row” Explanation: According to the given order ‘l’ occurs before ‘d’ hence the words “world” will be kept first. "
},
{
"code": null,
"e": 875,
"s": 716,
"text": "Approach: To solve the problem mentioned above we need to maintain the priority of each character in the given order. For doing that use Map Data Structure. "
},
{
"code": null,
"e": 958,
"s": 875,
"text": "Iterate in the given order and set the priority of a character to its index value."
},
{
"code": null,
"e": 1010,
"s": 958,
"text": "Use a custom comparator function to sort the array."
},
{
"code": null,
"e": 1222,
"s": 1010,
"text": "In the comparator function, iterate through the minimum sized word between the two words and try to find the first different character, the word with the lesser priority value character will be the smaller word."
},
{
"code": null,
"e": 1312,
"s": 1222,
"text": "If the words have the same prefix, then the word with a smaller size is the smaller word."
},
{
"code": null,
"e": 1360,
"s": 1312,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 1364,
"s": 1360,
"text": "C++"
},
{
"code": null,
"e": 1372,
"s": 1364,
"text": "Python3"
},
{
"code": null,
"e": 1383,
"s": 1372,
"text": "Javascript"
},
{
"code": "// C++ program to sort an array// of strings based on the given order #include <bits/stdc++.h>using namespace std; // For storing priority of each characterunordered_map<char, int> mp; // Custom comparator function for sortbool comp(string& a, string& b){ // Loop through the minimum size // between two words for (int i = 0; i < min(a.size(), b.size()); i++) { // Check if the characters // at position i are different, // then the word containing lower // valued character is smaller if (mp[a[i]] != mp[b[i]]) return mp[a[i]] < mp[b[i]]; } /* When loop breaks without returning, it means the prefix of both words were same till the execution of the loop. Now, the word with the smaller size will occur before in sorted order */ return (a.size() < b.size());} // Function to print the// new sorted array of stringsvoid printSorted(vector<string> words, string order){ // Mapping each character // to its occurrence position for (int i = 0; i < order.size(); i++) mp[order[i]] = i; // Sorting with custom sort function sort(words.begin(), words.end(), comp); // Printing the sorted order of words for (auto x : words) cout << x << \" \";} // Driver codeint main(){ vector<string> words = { \"word\", \"world\", \"row\" }; string order = { \"worldabcefghijkmnpqstuvxyz\" }; printSorted(words, order); return 0;}",
"e": 2881,
"s": 1383,
"text": null
},
{
"code": "# Python3 program to sort an array# of strings based on the given orderfrom functools import cmp_to_key # For storing priority of each charactermp = {} # Custom comparator function for sortdef comp(a, b): # Loop through the minimum size # between two words for i in range( min(len(a), len(b))): # Check if the characters # at position i are different, # then the word containing lower # valued character is smaller if (mp[a[i]] != mp[b[i]]): if mp[a[i]] < mp[b[i]]: return -1 else: return 1 '''When loop breaks without returning, it means the prefix of both words were same till the execution of the loop. Now, the word with the smaller size will occur before in sorted order''' if (len(a) < len(b)): return -1 else: return 1 # Function to print the# new sorted array of stringsdef printSorted(words, order): # Mapping each character # to its occurrence position for i in range(len(order)): mp[order[i]] = i # Sorting with custom sort function words = sorted(words, key = cmp_to_key(comp)) # Printing the sorted order of words for x in words: print(x, end = \" \") # Driver codewords = [ \"word\", \"world\", \"row\" ]order = \"worldabcefghijkmnpqstuvxyz\" printSorted(words, order) # This code is contributed by Shivani",
"e": 4292,
"s": 2881,
"text": null
},
{
"code": "<script> // JavaScript program to sort an array// of strings based on the given order // For storing priority of each characterlet mp = new Map(); // Custom comparator function for sortfunction comp(a, b){ // Loop through the minimum size // between two words for (let i = 0; i < Math.min(a.length, b.length);i++) { // Check if the characters // at position i are different, // then the word containing lower // valued character is smaller if (mp.get(a[i]) != mp.get(b[i])) return mp.get(b[i]) - mp.get(a[i]); } /* When loop breaks without returning, it means the prefix of both words were same till the execution of the loop. Now, the word with the smaller size will occur before in sorted order */ return (b.length - a.length);} // Function to print the// new sorted array of stringsfunction printSorted(words,order){ // Mapping each character // to its occurrence position for (let i = 0; i < order.length; i++) mp.set(order[i],i); // Sorting with custom sort function words.sort(comp); // Printing the sorted order of words for (let x of words) document.write(x +\" \");} // Driver codelet words = [\"word\", \"world\", \"row\" ];let order = [\"worldabcefghijkmnpqstuvxyz\" ]; printSorted(words, order); // This code is contributed by shinjanpatra </script>",
"e": 5668,
"s": 4292,
"text": null
},
{
"code": null,
"e": 5683,
"s": 5668,
"text": "world word row"
},
{
"code": null,
"e": 5701,
"s": 5685,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 5720,
"s": 5701,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 5733,
"s": 5720,
"text": "shinjanpatra"
},
{
"code": null,
"e": 5740,
"s": 5733,
"text": "Arrays"
},
{
"code": null,
"e": 5748,
"s": 5740,
"text": "Sorting"
},
{
"code": null,
"e": 5756,
"s": 5748,
"text": "Strings"
},
{
"code": null,
"e": 5763,
"s": 5756,
"text": "Arrays"
},
{
"code": null,
"e": 5771,
"s": 5763,
"text": "Strings"
},
{
"code": null,
"e": 5779,
"s": 5771,
"text": "Sorting"
}
] |
Python – Check if previous element is smaller in List
|
04 Sep, 2021
Sometimes, while working with Python lists, we can have a problem in which we need to check for each element if its preceding element is smaller. This type of problem can have its use in data preprocessing domains. Let’s discuss certain problems in which this task can be performed.
Input : test_list = [1, 3, 5, 6, 8] Output : [True, True, True, True]Input : test_list = [3, 1] Output : [False]
Method #1 : Using loop This is one of the ways in which this task can be performed. In this, we perform the task of checking for elements using brute for in loop.
Python3
# Python3 code to demonstrate working of# Check if previous element is smaller in List# Using loop # initializing listtest_list = [6, 3, 7, 3, 6, 7, 8, 3] # printing original listprint("The original list is : " + str(test_list)) # Check if previous element is smaller in List# Using loopres = []for idx in range(1, len(test_list)): if test_list[idx - 1] < test_list[idx]: res.append(True) else: res.append(False) # printing resultprint("List after filtering : " + str(res))
The original list is : [6, 3, 7, 3, 6, 7, 8, 3]
List after filtering : [False, True, False, True, True, True, False]
Method #2 : Using zip() + list comprehension This is one-liner approach to solve this problem. In this, we first, zip the list and its next element list, and then check for comparisons for result.
Python3
# Python3 code to demonstrate working of# Check if previous element is smaller in List# Using zip() + list comprehension # initializing listtest_list = [6, 3, 7, 3, 6, 7, 8, 3] # printing original listprint("The original list is : " + str(test_list)) # Check if previous element is smaller in List# Using zip() + list comprehensionres = [int(sub1) < int(sub2) for sub1, sub2 in zip(test_list, test_list[1:])] # printing resultprint("List after filtering : " + str(res))
The original list is : [6, 3, 7, 3, 6, 7, 8, 3]
List after filtering : [False, True, False, True, True, True, False]
ruhelaa48
Python list-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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Sep, 2021"
},
{
"code": null,
"e": 336,
"s": 52,
"text": "Sometimes, while working with Python lists, we can have a problem in which we need to check for each element if its preceding element is smaller. This type of problem can have its use in data preprocessing domains. Let’s discuss certain problems in which this task can be performed. "
},
{
"code": null,
"e": 451,
"s": 336,
"text": "Input : test_list = [1, 3, 5, 6, 8] Output : [True, True, True, True]Input : test_list = [3, 1] Output : [False] "
},
{
"code": null,
"e": 615,
"s": 451,
"text": "Method #1 : Using loop This is one of the ways in which this task can be performed. In this, we perform the task of checking for elements using brute for in loop. "
},
{
"code": null,
"e": 623,
"s": 615,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Check if previous element is smaller in List# Using loop # initializing listtest_list = [6, 3, 7, 3, 6, 7, 8, 3] # printing original listprint(\"The original list is : \" + str(test_list)) # Check if previous element is smaller in List# Using loopres = []for idx in range(1, len(test_list)): if test_list[idx - 1] < test_list[idx]: res.append(True) else: res.append(False) # printing resultprint(\"List after filtering : \" + str(res))",
"e": 1117,
"s": 623,
"text": null
},
{
"code": null,
"e": 1234,
"s": 1117,
"text": "The original list is : [6, 3, 7, 3, 6, 7, 8, 3]\nList after filtering : [False, True, False, True, True, True, False]"
},
{
"code": null,
"e": 1435,
"s": 1236,
"text": " Method #2 : Using zip() + list comprehension This is one-liner approach to solve this problem. In this, we first, zip the list and its next element list, and then check for comparisons for result. "
},
{
"code": null,
"e": 1443,
"s": 1435,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Check if previous element is smaller in List# Using zip() + list comprehension # initializing listtest_list = [6, 3, 7, 3, 6, 7, 8, 3] # printing original listprint(\"The original list is : \" + str(test_list)) # Check if previous element is smaller in List# Using zip() + list comprehensionres = [int(sub1) < int(sub2) for sub1, sub2 in zip(test_list, test_list[1:])] # printing resultprint(\"List after filtering : \" + str(res))",
"e": 1913,
"s": 1443,
"text": null
},
{
"code": null,
"e": 2030,
"s": 1913,
"text": "The original list is : [6, 3, 7, 3, 6, 7, 8, 3]\nList after filtering : [False, True, False, True, True, True, False]"
},
{
"code": null,
"e": 2042,
"s": 2032,
"text": "ruhelaa48"
},
{
"code": null,
"e": 2063,
"s": 2042,
"text": "Python list-programs"
},
{
"code": null,
"e": 2070,
"s": 2063,
"text": "Python"
},
{
"code": null,
"e": 2086,
"s": 2070,
"text": "Python Programs"
},
{
"code": null,
"e": 2184,
"s": 2086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2202,
"s": 2184,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2244,
"s": 2202,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2279,
"s": 2244,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2305,
"s": 2279,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2337,
"s": 2305,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2380,
"s": 2337,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2402,
"s": 2380,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2441,
"s": 2402,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2479,
"s": 2441,
"text": "Python | Convert a list to dictionary"
}
] |
How to override the CSS properties of a class using another CSS class ?
|
27 Sep, 2019
To override the CSS properties of a class using another class, we can use the !important directive. In CSS, !important means “this is important”, and the property:value pair that has this directive is always applied even if the other element has higher specificity.
Syntax:
element1 {
property-x: value_y !important; /* This will be applied. */
}
element2 {
property-x: value_z; /* This will not be applied. */
}
Example:
<!DOCTYPE html><html> <head> <title>!important</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.3.1/css/bootstrap.min.css"> <link href="https://fonts.googleapis.com/css?family=Indie+Flower&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Mansalva&display=swap" rel="stylesheet"> <style> h1 { text-align: center; color: green; } .my_fav_font { font-family: 'Indie Flower', cursive !important; /* This will be applied. */ } .my_para { font-family: 'Mansalva', cursive; /* This will not be applied. */ text-align: justify; background-color: powderblue; font-size: 130%; } </style></head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <hr/> <p class="my_fav_font my_para">Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. More importantly, CSS enables you to do this independent of the HTML that makes up each web page.</p> </div></body> </html>
Output:
CSS-Misc
Picked
CSS
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Sep, 2019"
},
{
"code": null,
"e": 318,
"s": 52,
"text": "To override the CSS properties of a class using another class, we can use the !important directive. In CSS, !important means “this is important”, and the property:value pair that has this directive is always applied even if the other element has higher specificity."
},
{
"code": null,
"e": 326,
"s": 318,
"text": "Syntax:"
},
{
"code": null,
"e": 475,
"s": 326,
"text": "element1 {\n property-x: value_y !important; /* This will be applied. */\n}\nelement2 {\n property-x: value_z; /* This will not be applied. */\n}\n"
},
{
"code": null,
"e": 484,
"s": 475,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>!important</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.3.1/css/bootstrap.min.css\"> <link href=\"https://fonts.googleapis.com/css?family=Indie+Flower&display=swap\" rel=\"stylesheet\"> <link href=\"https://fonts.googleapis.com/css?family=Mansalva&display=swap\" rel=\"stylesheet\"> <style> h1 { text-align: center; color: green; } .my_fav_font { font-family: 'Indie Flower', cursive !important; /* This will be applied. */ } .my_para { font-family: 'Mansalva', cursive; /* This will not be applied. */ text-align: justify; background-color: powderblue; font-size: 130%; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <hr/> <p class=\"my_fav_font my_para\">Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. More importantly, CSS enables you to do this independent of the HTML that makes up each web page.</p> </div></body> </html>",
"e": 1925,
"s": 484,
"text": null
},
{
"code": null,
"e": 1933,
"s": 1925,
"text": "Output:"
},
{
"code": null,
"e": 1942,
"s": 1933,
"text": "CSS-Misc"
},
{
"code": null,
"e": 1949,
"s": 1942,
"text": "Picked"
},
{
"code": null,
"e": 1953,
"s": 1949,
"text": "CSS"
},
{
"code": null,
"e": 1972,
"s": 1953,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1989,
"s": 1972,
"text": "Web Technologies"
},
{
"code": null,
"e": 2016,
"s": 1989,
"text": "Web technologies Questions"
}
] |
On/Off Toggle Button Switch in Tkinter
|
19 Oct, 2021
Prerequisite: Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications.
In this article, we will learn how to make an on/off switch using Tkinter.
Approach:
Make a global variable named as is_on; the default value is True, which indicates the switch is ON.
Make two Image Objects; one object has “on image” and another one has “off image”.
Create a button that has “on image” as default; set the border width to be zero.
Make a function that will change the button image, using the config() method.
The function will check, whether the is_on value is True or False
Image link:
Switch On
Switch Off
Below is the Implementation:
Python3
# Import Modulefrom tkinter import * # Create Objectroot = Tk() # Add Titleroot.title('On/Off Switch!') # Add Geometryroot.geometry("500x300") # Keep track of the button state on/off#global is_onis_on = True # Create Labelmy_label = Label(root, text = "The Switch Is On!", fg = "green", font = ("Helvetica", 32)) my_label.pack(pady = 20) # Define our switch functiondef switch(): global is_on # Determine is on or off if is_on: on_button.config(image = off) my_label.config(text = "The Switch is Off", fg = "grey") is_on = False else: on_button.config(image = on) my_label.config(text = "The Switch is On", fg = "green") is_on = True # Define Our Imageson = PhotoImage(file = "on.png")off = PhotoImage(file = "off.png") # Create A Buttonon_button = Button(root, image = on, bd = 0, command = switch)on_button.pack(pady = 50) # Execute Tkinterroot.mainloop()
Output:
adnanirshad158
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 75,
"s": 53,
"text": "Prerequisite: Tkinter"
},
{
"code": null,
"e": 381,
"s": 75,
"text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications."
},
{
"code": null,
"e": 456,
"s": 381,
"text": "In this article, we will learn how to make an on/off switch using Tkinter."
},
{
"code": null,
"e": 466,
"s": 456,
"text": "Approach:"
},
{
"code": null,
"e": 566,
"s": 466,
"text": "Make a global variable named as is_on; the default value is True, which indicates the switch is ON."
},
{
"code": null,
"e": 649,
"s": 566,
"text": "Make two Image Objects; one object has “on image” and another one has “off image”."
},
{
"code": null,
"e": 730,
"s": 649,
"text": "Create a button that has “on image” as default; set the border width to be zero."
},
{
"code": null,
"e": 808,
"s": 730,
"text": "Make a function that will change the button image, using the config() method."
},
{
"code": null,
"e": 874,
"s": 808,
"text": "The function will check, whether the is_on value is True or False"
},
{
"code": null,
"e": 886,
"s": 874,
"text": "Image link:"
},
{
"code": null,
"e": 896,
"s": 886,
"text": "Switch On"
},
{
"code": null,
"e": 907,
"s": 896,
"text": "Switch Off"
},
{
"code": null,
"e": 936,
"s": 907,
"text": "Below is the Implementation:"
},
{
"code": null,
"e": 944,
"s": 936,
"text": "Python3"
},
{
"code": "# Import Modulefrom tkinter import * # Create Objectroot = Tk() # Add Titleroot.title('On/Off Switch!') # Add Geometryroot.geometry(\"500x300\") # Keep track of the button state on/off#global is_onis_on = True # Create Labelmy_label = Label(root, text = \"The Switch Is On!\", fg = \"green\", font = (\"Helvetica\", 32)) my_label.pack(pady = 20) # Define our switch functiondef switch(): global is_on # Determine is on or off if is_on: on_button.config(image = off) my_label.config(text = \"The Switch is Off\", fg = \"grey\") is_on = False else: on_button.config(image = on) my_label.config(text = \"The Switch is On\", fg = \"green\") is_on = True # Define Our Imageson = PhotoImage(file = \"on.png\")off = PhotoImage(file = \"off.png\") # Create A Buttonon_button = Button(root, image = on, bd = 0, command = switch)on_button.pack(pady = 50) # Execute Tkinterroot.mainloop()",
"e": 1918,
"s": 944,
"text": null
},
{
"code": null,
"e": 1926,
"s": 1918,
"text": "Output:"
},
{
"code": null,
"e": 1941,
"s": 1926,
"text": "adnanirshad158"
},
{
"code": null,
"e": 1966,
"s": 1941,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 1981,
"s": 1966,
"text": "Python-tkinter"
},
{
"code": null,
"e": 1988,
"s": 1981,
"text": "Python"
},
{
"code": null,
"e": 2086,
"s": 1988,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2118,
"s": 2086,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2145,
"s": 2118,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2166,
"s": 2145,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2189,
"s": 2166,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2220,
"s": 2189,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2276,
"s": 2220,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2318,
"s": 2276,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2360,
"s": 2318,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2399,
"s": 2360,
"text": "Python | Get unique values from a list"
}
] |
How to set Maximum Value in NumericUpDown in C#?
|
26 Jul, 2019
In Windows Forms, NumericUpDown control is used to provide a Windows spin box or an up-down control which displays the numeric values. Or in other words, NumericUpDown control provides an interface which moves using up and down arrow and holds some pre-defined numeric value. In NumericUpDown control, you can set the maximum value for the up-down control using Maximum Property. The default value of this property is 100. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the maximum value for the NumericUpDown as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Next, drag and drop the NumericUpDown control from the toolbox on the form as shown in the below image:
Step 3: After drag and drop you will go to the properties of the NumericUpDown and set the maximum value for the NumericUpDown as shown in the below image;Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the maximum value for the NumericUpDown control programmatically with the help of given syntax:
public decimal Maximum { get; set; }
Here, the value of this property represents the maximum value of the NumericUpDown. The following steps show how to set the maximum value for the NumericUpDown dynamically:
Step 1: Create a NumericUpDown using the NumericUpDown() constructor is provided by the NumericUpDown class.// Creating a NumericUpDown
NumericUpDown n = new NumericUpDown();
// Creating a NumericUpDown
NumericUpDown n = new NumericUpDown();
Step 2: After creating NumericUpDown, set the Maximum property of the NumericUpDown provided by the NumericUpDown class.// Setting the maximum value
n.Maximum = 30;
// Setting the maximum value
n.Maximum = 30;
Step 3: And last add this NumericUpDown control to the form using the following statement:// Adding NumericUpDown control on the form
this.Controls.Add(n);
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 WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = "Form"; l1.Font = new Font("Bodoni MT", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = "Enter Age"; l2.Font = new Font("Bodoni MT", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font("Bodoni MT", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = "MySpinBox"; // Adding this control // to the form this.Controls.Add(n); }}}Output:
// Adding NumericUpDown control on the form
this.Controls.Add(n);
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 WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = "Form"; l1.Font = new Font("Bodoni MT", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = "Enter Age"; l2.Font = new Font("Bodoni MT", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font("Bodoni MT", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = "MySpinBox"; // Adding this control // to the form this.Controls.Add(n); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 500,
"s": 28,
"text": "In Windows Forms, NumericUpDown control is used to provide a Windows spin box or an up-down control which displays the numeric values. Or in other words, NumericUpDown control provides an interface which moves using up and down arrow and holds some pre-defined numeric value. In NumericUpDown control, you can set the maximum value for the up-down control using Maximum Property. The default value of this property is 100. You can set this property in two different ways:"
},
{
"code": null,
"e": 618,
"s": 500,
"text": "1. Design-Time: It is the easiest way to set the maximum value for the NumericUpDown as shown in the following steps:"
},
{
"code": null,
"e": 734,
"s": 618,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 792,
"s": 734,
"text": "Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 904,
"s": 792,
"text": "Step 2: Next, drag and drop the NumericUpDown control from the toolbox on the form as shown in the below image:"
},
{
"code": null,
"e": 1067,
"s": 904,
"text": "Step 3: After drag and drop you will go to the properties of the NumericUpDown and set the maximum value for the NumericUpDown as shown in the below image;Output:"
},
{
"code": null,
"e": 1075,
"s": 1067,
"text": "Output:"
},
{
"code": null,
"e": 1263,
"s": 1075,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the maximum value for the NumericUpDown control programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1300,
"s": 1263,
"text": "public decimal Maximum { get; set; }"
},
{
"code": null,
"e": 1473,
"s": 1300,
"text": "Here, the value of this property represents the maximum value of the NumericUpDown. The following steps show how to set the maximum value for the NumericUpDown dynamically:"
},
{
"code": null,
"e": 1649,
"s": 1473,
"text": "Step 1: Create a NumericUpDown using the NumericUpDown() constructor is provided by the NumericUpDown class.// Creating a NumericUpDown\nNumericUpDown n = new NumericUpDown();\n"
},
{
"code": null,
"e": 1717,
"s": 1649,
"text": "// Creating a NumericUpDown\nNumericUpDown n = new NumericUpDown();\n"
},
{
"code": null,
"e": 1883,
"s": 1717,
"text": "Step 2: After creating NumericUpDown, set the Maximum property of the NumericUpDown provided by the NumericUpDown class.// Setting the maximum value\nn.Maximum = 30;\n"
},
{
"code": null,
"e": 1929,
"s": 1883,
"text": "// Setting the maximum value\nn.Maximum = 30;\n"
},
{
"code": null,
"e": 3519,
"s": 1929,
"text": "Step 3: And last add this NumericUpDown control to the form using the following statement:// Adding NumericUpDown control on the form\nthis.Controls.Add(n);\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 WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = \"Form\"; l1.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = \"Enter Age\"; l2.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font(\"Bodoni MT\", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = \"MySpinBox\"; // Adding this control // to the form this.Controls.Add(n); }}}Output:"
},
{
"code": null,
"e": 3586,
"s": 3519,
"text": "// Adding NumericUpDown control on the form\nthis.Controls.Add(n);\n"
},
{
"code": null,
"e": 3595,
"s": 3586,
"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 WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = \"Form\"; l1.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = \"Enter Age\"; l2.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font(\"Bodoni MT\", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = \"MySpinBox\"; // Adding this control // to the form this.Controls.Add(n); }}}",
"e": 5014,
"s": 3595,
"text": null
},
{
"code": null,
"e": 5022,
"s": 5014,
"text": "Output:"
},
{
"code": null,
"e": 5053,
"s": 5022,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 5056,
"s": 5053,
"text": "C#"
}
] |
Java String Class lines() Method with Examples
|
03 Feb, 2022
lines() method is a static method which returns out stream of lines extracted from a given multi-line string, separated by line terminators which are as follows:
Syntax:
public Stream<String> lines()
Return Type: Stream of string in order as present in multi-line
Illustration:
Input : "Geek \n For \n Geeks \n 2021"
Output :
Geek
For
Geeks
2021
Implementation:
Here we will be discussing out three examples to get better understanding of working of String class lines() method with data structures.
forEach
Converting stream of lines to ArrayList
Converting stream of lines to array
Let’s discuss them one by one:
Example 1: forEach
Java
// Importing Stream class from// java.util packageimport java.util.stream.Stream; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String str = " Geeks \n For \n Geeks \r Technical \r\n content \r writer \n Internship"; // Generating stream of lines from string // using line method Stream<String> lines = str.lines(); // print and display the output string // using forEach and scope resolution operator lines.forEach(System.out::println); }}
Geeks
For
Geeks
Technical
content
writer
Internship
Example 2: Stream of lines to ArrayList using forEach
Java
// Java Program to illustrate String class lines() method// by converting stream of lines to ArrayList // Importing ArrayList and Stream class// from java.util packageimport java.util.ArrayList;import java.util.stream.Stream; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String str = " Geeks \n For \n Geeks \r Technical \r\n content \r writer \n Internship"; // Generating stream of lines from string // using lines() method Stream<String> lines = str.lines(); // Creating an ArrayList object of String type ArrayList<String> arrayList = new ArrayList<>(); // Now, adding elements to arrayList using forEach lines.forEach(arrayList::add); // Print and display the ArrayList System.out.println(arrayList); }}
[ Geeks , For , Geeks , Technical , content , writer , Internship]
Example 3: Stream of lines to array
Java
// Java Program to illustrate String class lines() method// by converting stream of lines to array // Importing Arrays and Stream class from// java.util packageimport java.util.Arrays;import java.util.stream.Stream; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String str = " Geeks \n For \n Geeks \r Technical \r\n content \r writer \n Internship"; // Generating stream of lines from // string using line() method Stream<String> lines = str.lines(); // Converting into array // using toArray() method Object[] array = lines.toArray(); // Print and display the array // using standard toString() method System.out.println(Arrays.toString(array)); }}
[ Geeks , For , Geeks , Technical , content , writer , Internship]
sumitgumber28
Java-Strings
Picked
Technical Scripter 2020
Java
Technical Scripter
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Feb, 2022"
},
{
"code": null,
"e": 190,
"s": 28,
"text": "lines() method is a static method which returns out stream of lines extracted from a given multi-line string, separated by line terminators which are as follows:"
},
{
"code": null,
"e": 198,
"s": 190,
"text": "Syntax:"
},
{
"code": null,
"e": 228,
"s": 198,
"text": "public Stream<String> lines()"
},
{
"code": null,
"e": 292,
"s": 228,
"text": "Return Type: Stream of string in order as present in multi-line"
},
{
"code": null,
"e": 306,
"s": 292,
"text": "Illustration:"
},
{
"code": null,
"e": 395,
"s": 306,
"text": "Input : \"Geek \\n For \\n Geeks \\n 2021\"\nOutput :\n Geek\n For\n Geeks\n 2021"
},
{
"code": null,
"e": 411,
"s": 395,
"text": "Implementation:"
},
{
"code": null,
"e": 549,
"s": 411,
"text": "Here we will be discussing out three examples to get better understanding of working of String class lines() method with data structures."
},
{
"code": null,
"e": 557,
"s": 549,
"text": "forEach"
},
{
"code": null,
"e": 597,
"s": 557,
"text": "Converting stream of lines to ArrayList"
},
{
"code": null,
"e": 633,
"s": 597,
"text": "Converting stream of lines to array"
},
{
"code": null,
"e": 664,
"s": 633,
"text": "Let’s discuss them one by one:"
},
{
"code": null,
"e": 684,
"s": 664,
"text": "Example 1: forEach "
},
{
"code": null,
"e": 689,
"s": 684,
"text": "Java"
},
{
"code": "// Importing Stream class from// java.util packageimport java.util.stream.Stream; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String str = \" Geeks \\n For \\n Geeks \\r Technical \\r\\n content \\r writer \\n Internship\"; // Generating stream of lines from string // using line method Stream<String> lines = str.lines(); // print and display the output string // using forEach and scope resolution operator lines.forEach(System.out::println); }}",
"e": 1280,
"s": 689,
"text": null
},
{
"code": null,
"e": 1345,
"s": 1280,
"text": " Geeks \n For \n Geeks \n Technical \n content \n writer \n Internship"
},
{
"code": null,
"e": 1399,
"s": 1345,
"text": "Example 2: Stream of lines to ArrayList using forEach"
},
{
"code": null,
"e": 1404,
"s": 1399,
"text": "Java"
},
{
"code": "// Java Program to illustrate String class lines() method// by converting stream of lines to ArrayList // Importing ArrayList and Stream class// from java.util packageimport java.util.ArrayList;import java.util.stream.Stream; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String str = \" Geeks \\n For \\n Geeks \\r Technical \\r\\n content \\r writer \\n Internship\"; // Generating stream of lines from string // using lines() method Stream<String> lines = str.lines(); // Creating an ArrayList object of String type ArrayList<String> arrayList = new ArrayList<>(); // Now, adding elements to arrayList using forEach lines.forEach(arrayList::add); // Print and display the ArrayList System.out.println(arrayList); }}",
"e": 2287,
"s": 1404,
"text": null
},
{
"code": null,
"e": 2360,
"s": 2287,
"text": "[ Geeks , For , Geeks , Technical , content , writer , Internship]"
},
{
"code": null,
"e": 2396,
"s": 2360,
"text": "Example 3: Stream of lines to array"
},
{
"code": null,
"e": 2401,
"s": 2396,
"text": "Java"
},
{
"code": "// Java Program to illustrate String class lines() method// by converting stream of lines to array // Importing Arrays and Stream class from// java.util packageimport java.util.Arrays;import java.util.stream.Stream; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String str = \" Geeks \\n For \\n Geeks \\r Technical \\r\\n content \\r writer \\n Internship\"; // Generating stream of lines from // string using line() method Stream<String> lines = str.lines(); // Converting into array // using toArray() method Object[] array = lines.toArray(); // Print and display the array // using standard toString() method System.out.println(Arrays.toString(array)); }}",
"e": 3224,
"s": 2401,
"text": null
},
{
"code": null,
"e": 3297,
"s": 3224,
"text": "[ Geeks , For , Geeks , Technical , content , writer , Internship]"
},
{
"code": null,
"e": 3311,
"s": 3297,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3324,
"s": 3311,
"text": "Java-Strings"
},
{
"code": null,
"e": 3331,
"s": 3324,
"text": "Picked"
},
{
"code": null,
"e": 3355,
"s": 3331,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3360,
"s": 3355,
"text": "Java"
},
{
"code": null,
"e": 3379,
"s": 3360,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3392,
"s": 3379,
"text": "Java-Strings"
},
{
"code": null,
"e": 3397,
"s": 3392,
"text": "Java"
}
] |
Program to swap upper diagonal elements with lower diagonal elements of matrix.
|
22 Mar, 2022
Given a square matrix, swap upper diagonal elements of matrix with lower diagonal elements of matrix.Examples :
Input: 2 3 5 6
4 5 7 9
8 6 4 9
1 3 5 6
Output: 2 4 8 1
3 5 6 3
5 7 4 5
6 9 9 6
Input: 1 2 3
4 5 6
7 8 9
Output: 1 4 7
2 5 8
3 6 9
Below is the implementation of above idea :
C++
Java
Python 3
C#
PHP
Javascript
Javascript
// CPP Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix.#include <bits/stdc++.h>#define n 4using namespace std; // Function to swap the diagonal// elements in a matrix.void swapUpperToLower(int arr[n][n]){ // Loop for swap the elements of matrix. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Loop for print the matrix elements. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << arr[i][j] << " "; cout << endl; }} // Driver function to run the programint main(){ int arr[n][n] = { { 2, 3, 5, 6 }, { 4, 5, 7, 9 }, { 8, 6, 4, 9 }, { 1, 3, 5, 6 } }; // Function call swapUpperToLower(arr); return 0;} }
// java Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix.import java.io.*; class GFG{ static int n = 4; // Function to swap the diagonal // elements in a matrix. static void swapUpperToLower(int arr[][]) { // Loop for swap the elements of matrix. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Loop for print the matrix elements. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print( arr[i][j] +" "); System.out.println(); } } // Driver code public static void main (String[] args) { int arr[][] = { { 2, 3, 5, 6 }, { 4, 5, 7, 9 }, { 8, 6, 4, 9 }, { 1, 3, 5, 6 } }; // Function call swapUpperToLower(arr); }} // This code is contributed by vt_m.
# Python Program to implement matrix# for swapping the upper diagonal# elements with lower diagonal# elements of matrix. # Function to swap the diagonal# elements in a matrix.def swapUpperToLower(arr): n = 4; # Loop for swap the elements # of matrix. for i in range(0, n): for j in range(i + 1, n): temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; # Loop for print the matrix elements. for i in range(0, n): for j in range(0, n): print(arr[i][j], end = " "); print(" "); # Driver Code arr = [[2, 3, 5, 6 ],[ 4, 5, 7, 9 ], [8, 6, 4, 9 ],[ 1, 3, 5, 6 ]]; # Function callswapUpperToLower(arr); # This code is contributed# by Shivi_Aggarwal
// C# Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix.using System; class GFG{ static int n = 4; // Function to swap the diagonal // elements in a matrix. static void swapUpperToLower(int [,]arr) { // Loop for swap the elements of matrix. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int temp = arr[i, j]; arr[i, j] = arr[j, i]; arr[j, i] = temp; } } // Loop for print the matrix elements. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) Console.Write(arr[i, j] +" "); Console.WriteLine(); } } // Driver code public static void Main () { int [,]arr = {{ 2, 3, 5, 6 }, { 4, 5, 7, 9 }, { 8, 6, 4, 9 }, { 1, 3, 5, 6 }}; // Function call swapUpperToLower(arr); }} // This code is contributed by vt_m.
<?php// PHP Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix. $n = 4;// Function to swap the diagonal// elements in a matrix.function swapUpperToLower($arr){ global $n; // Loop for swap the elements of matrix. for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { $temp = $arr[$i][$j]; $arr[$i][$j] = $arr[$j][$i]; $arr[$j][$i] = $temp; } } // Loop for print the matrix elements. for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) echo($arr[$i][$j] . " "); echo("\n"); }} // Driver Code$arr = array(array(2, 3, 5, 6), array(4, 5, 7, 9), array(8, 6, 4, 9), array(1, 3, 5, 6)); // Function callswapUpperToLower($arr); // This code is contributed by Ajit.?>
<script>// JavaScript Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix.var arr = [ [ 2, 3, 5, 6 ], [ 4, 5, 7, 9 ], [ 8, 6, 4, 9 ], [ 1, 3, 5, 6 ] ]; var n = arr.length; // Loop for swap the elements of matrix. for (var i = 0; i < n; i++) { for ( var j = i + 1; j < n; j++) { var temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Loop for print the matrix elements. for (var i = 0; i < n; i++) { for ( var j = 0; j < n; j++) { document.write( arr[i][j] + " "); } document.write("<br>"); } // This code is contributed by SoumikMondal</script>
<script>// java script Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix. let n = 4; // Function to swap the diagonal // elements in a matrix. function swapUpperToLower(arr) { // Loop for swap the elements of matrix. for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { let temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Loop for print the matrix elements. for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) document.write( arr[i][j] +" "); document.write("<br>"); } } // Driver code let arr = [[2, 3, 5, 6 ], [ 4, 5, 7, 9 ], [ 8, 6, 4, 9 ], [ 1, 3, 5, 6 ]]; // Function call swapUpperToLower(arr); // contributed by sravan kumar</script>
Output :
2 4 8 1
3 5 6 3
5 7 4 5
6 9 9 6
Time Complexity: O(N2)
Auxiliary Space: O(1)
vt_m
jit_t
Shivi_Aggarwal
SoumikMondal
sravankumar8128
rohitkumarsinghcna
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Mar, 2022"
},
{
"code": null,
"e": 166,
"s": 52,
"text": "Given a square matrix, swap upper diagonal elements of matrix with lower diagonal elements of matrix.Examples : "
},
{
"code": null,
"e": 432,
"s": 166,
"text": "Input: 2 3 5 6\n 4 5 7 9\n 8 6 4 9\n 1 3 5 6\n\nOutput: 2 4 8 1\n 3 5 6 3\n 5 7 4 5\n 6 9 9 6\n\nInput: 1 2 3 \n 4 5 6\n 7 8 9\n\nOutput: 1 4 7\n 2 5 8\n 3 6 9"
},
{
"code": null,
"e": 480,
"s": 434,
"text": "Below is the implementation of above idea : "
},
{
"code": null,
"e": 484,
"s": 480,
"text": "C++"
},
{
"code": null,
"e": 489,
"s": 484,
"text": "Java"
},
{
"code": null,
"e": 498,
"s": 489,
"text": "Python 3"
},
{
"code": null,
"e": 501,
"s": 498,
"text": "C#"
},
{
"code": null,
"e": 505,
"s": 501,
"text": "PHP"
},
{
"code": null,
"e": 516,
"s": 505,
"text": "Javascript"
},
{
"code": null,
"e": 527,
"s": 516,
"text": "Javascript"
},
{
"code": "// CPP Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix.#include <bits/stdc++.h>#define n 4using namespace std; // Function to swap the diagonal// elements in a matrix.void swapUpperToLower(int arr[n][n]){ // Loop for swap the elements of matrix. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Loop for print the matrix elements. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << arr[i][j] << \" \"; cout << endl; }} // Driver function to run the programint main(){ int arr[n][n] = { { 2, 3, 5, 6 }, { 4, 5, 7, 9 }, { 8, 6, 4, 9 }, { 1, 3, 5, 6 } }; // Function call swapUpperToLower(arr); return 0;} }",
"e": 1461,
"s": 527,
"text": null
},
{
"code": "// java Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix.import java.io.*; class GFG{ static int n = 4; // Function to swap the diagonal // elements in a matrix. static void swapUpperToLower(int arr[][]) { // Loop for swap the elements of matrix. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Loop for print the matrix elements. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print( arr[i][j] +\" \"); System.out.println(); } } // Driver code public static void main (String[] args) { int arr[][] = { { 2, 3, 5, 6 }, { 4, 5, 7, 9 }, { 8, 6, 4, 9 }, { 1, 3, 5, 6 } }; // Function call swapUpperToLower(arr); }} // This code is contributed by vt_m.",
"e": 2618,
"s": 1461,
"text": null
},
{
"code": "# Python Program to implement matrix# for swapping the upper diagonal# elements with lower diagonal# elements of matrix. # Function to swap the diagonal# elements in a matrix.def swapUpperToLower(arr): n = 4; # Loop for swap the elements # of matrix. for i in range(0, n): for j in range(i + 1, n): temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; # Loop for print the matrix elements. for i in range(0, n): for j in range(0, n): print(arr[i][j], end = \" \"); print(\" \"); # Driver Code arr = [[2, 3, 5, 6 ],[ 4, 5, 7, 9 ], [8, 6, 4, 9 ],[ 1, 3, 5, 6 ]]; # Function callswapUpperToLower(arr); # This code is contributed# by Shivi_Aggarwal",
"e": 3372,
"s": 2618,
"text": null
},
{
"code": "// C# Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix.using System; class GFG{ static int n = 4; // Function to swap the diagonal // elements in a matrix. static void swapUpperToLower(int [,]arr) { // Loop for swap the elements of matrix. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int temp = arr[i, j]; arr[i, j] = arr[j, i]; arr[j, i] = temp; } } // Loop for print the matrix elements. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) Console.Write(arr[i, j] +\" \"); Console.WriteLine(); } } // Driver code public static void Main () { int [,]arr = {{ 2, 3, 5, 6 }, { 4, 5, 7, 9 }, { 8, 6, 4, 9 }, { 1, 3, 5, 6 }}; // Function call swapUpperToLower(arr); }} // This code is contributed by vt_m.",
"e": 4495,
"s": 3372,
"text": null
},
{
"code": "<?php// PHP Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix. $n = 4;// Function to swap the diagonal// elements in a matrix.function swapUpperToLower($arr){ global $n; // Loop for swap the elements of matrix. for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { $temp = $arr[$i][$j]; $arr[$i][$j] = $arr[$j][$i]; $arr[$j][$i] = $temp; } } // Loop for print the matrix elements. for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) echo($arr[$i][$j] . \" \"); echo(\"\\n\"); }} // Driver Code$arr = array(array(2, 3, 5, 6), array(4, 5, 7, 9), array(8, 6, 4, 9), array(1, 3, 5, 6)); // Function callswapUpperToLower($arr); // This code is contributed by Ajit.?>",
"e": 5385,
"s": 4495,
"text": null
},
{
"code": "<script>// JavaScript Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix.var arr = [ [ 2, 3, 5, 6 ], [ 4, 5, 7, 9 ], [ 8, 6, 4, 9 ], [ 1, 3, 5, 6 ] ]; var n = arr.length; // Loop for swap the elements of matrix. for (var i = 0; i < n; i++) { for ( var j = i + 1; j < n; j++) { var temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Loop for print the matrix elements. for (var i = 0; i < n; i++) { for ( var j = 0; j < n; j++) { document.write( arr[i][j] + \" \"); } document.write(\"<br>\"); } // This code is contributed by SoumikMondal</script>",
"e": 6213,
"s": 5385,
"text": null
},
{
"code": "<script>// java script Program to implement matrix// for swapping the upper diagonal// elements with lower diagonal// elements of matrix. let n = 4; // Function to swap the diagonal // elements in a matrix. function swapUpperToLower(arr) { // Loop for swap the elements of matrix. for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { let temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Loop for print the matrix elements. for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) document.write( arr[i][j] +\" \"); document.write(\"<br>\"); } } // Driver code let arr = [[2, 3, 5, 6 ], [ 4, 5, 7, 9 ], [ 8, 6, 4, 9 ], [ 1, 3, 5, 6 ]]; // Function call swapUpperToLower(arr); // contributed by sravan kumar</script>",
"e": 7282,
"s": 6213,
"text": null
},
{
"code": null,
"e": 7293,
"s": 7282,
"text": "Output : "
},
{
"code": null,
"e": 7329,
"s": 7293,
"text": "2 4 8 1 \n3 5 6 3 \n5 7 4 5 \n6 9 9 6 "
},
{
"code": null,
"e": 7352,
"s": 7329,
"text": "Time Complexity: O(N2)"
},
{
"code": null,
"e": 7375,
"s": 7352,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 7380,
"s": 7375,
"text": "vt_m"
},
{
"code": null,
"e": 7386,
"s": 7380,
"text": "jit_t"
},
{
"code": null,
"e": 7401,
"s": 7386,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 7414,
"s": 7401,
"text": "SoumikMondal"
},
{
"code": null,
"e": 7430,
"s": 7414,
"text": "sravankumar8128"
},
{
"code": null,
"e": 7449,
"s": 7430,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 7456,
"s": 7449,
"text": "Matrix"
},
{
"code": null,
"e": 7463,
"s": 7456,
"text": "Matrix"
}
] |
Number of indices pair such that element pair sum from first Array is greater than second Array - GeeksforGeeks
|
24 Dec, 2021
Given two integer arrays A[] and B[] of equal sizes, the task is to find the number of pairs of indices {i, j} in the arrays such that A[i] + A[j] > B[i] + B[j] and i < j.Examples:
Input: A[] = {4, 8, 2, 6, 2}, B[] = {4, 5, 4, 1, 3} Output: 7 Explanation: There are a total of 7 pairs of indices {i, j} in the array following the condition. They are: {0, 1}: A[0] + A[1] > B[0] + B[1] {0, 3}: A[0] + A[3] > B[0] + B[3] {1, 2}: A[1] + A[2] > B[1] + B[2] {1, 3}: A[1] + A[3] > B[1] + B[3] {1, 4}: A[1] + A[4] > B[1] + B[4] {2, 3}: A[2] + A[3] > B[2] + B[3] {3, 4}: A[3] + A[4] > B[3] + B[4]Input: A[] = {1, 3, 2, 4}, B[] = {1, 3, 2, 4} Output: 0 Explanation: No such possible pairs of {i, j} can be found that satisfies the given condition
Naive Approach: The naive approach is to consider all the possible pairs of {i, j} in the given arrays and check if A[i] + A[j] > B[i] + B[j]. This can be done by using the concept of nested loops.Time Complexity: O(N2)Efficient Approach: The key observation from the problem is that the given condition can also be visualised as (ai-bi) + (aj-bj)> 0 so we can make another array to store the difference of both arrays. let this array be D . Therefore, the problem reduces to finding pairs with Di+Dj>0. Now we can sort D array and for each corresponding element Di we will find the no of good pairs that Di can make and add this no of pairs to a count variable.For each element Di to find the no of good pairs it can make we can use the upper_bound function of the standard template library to find the upper bound of -Di. since the array is sorted so all elements present after -Di will also make good pair with Di .thus,if upper bound of -Di is x and n be the total size of array then total pairs corresponding to Di will be n-x. This approach takes O(NlogN) time.
The given condition in the question can be rewritten as:
A[i] + A[j] > B[i] + B[j]
A[i] + A[j] - B[i] - B[j] > 0
(A[i] - B[i]) + (A[j] - B[j]) > 0
Create another array, say D, to store the difference between elements at the corresponding index in both array, i.e.
D[i] = A[i] - B[i]
Now to make sure that the constraint i < j is satisfied, sort the difference array D, so that each element i is smaller than elements to its right.
If at some index i, the value in the difference array D is negative, then we only need to find the nearest position ‘j’ at which the value is just greater than -D[i], so that on summation the value becomes > 0.Inorder to find such index ‘j’, upper_bound() function or Binary Search can be used, since the array is sorted.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the number of indices pair// such that pair sum from first Array// is greater than second Array #include <bits/stdc++.h>using namespace std; // Function to get the number of pairs of indices// {i, j} in the given two arrays A and B such that// A[i] + A[j] > B[i] + B[j]int getPairs(vector<int> A, vector<int> B, int n){ // Initializing the difference array D vector<int> D(n); // Computing the difference between the // elements at every index and storing // it in the array D for (int i = 0; i < n; i++) { D[i] = A[i] - B[i]; } // Sort the array D sort(D.begin(), D.end()); // Variable to store the total // number of pairs that satisfy // the given condition long long total = 0; // Loop to iterate through the difference // array D and find the total number // of pairs of indices that follow the // given condition for (int i = n - 1; i >= 0; i--) { // If the value at the index i is positive, // then it remains positive for any pairs // with j such that j > i. if (D[i] > 0) { total += n - i - 1; } // If the value at that index is negative // then we need to find the index of the // value just greater than -D[i] else { int k = upper_bound(D.begin(), D.end(), -D[i]) - D.begin(); total += n - k; } } return total;} // Driver codeint main(){ int n = 5; vector<int> A; vector<int> B; A.push_back(4); A.push_back(8); A.push_back(2); A.push_back(6); A.push_back(2); B.push_back(4); B.push_back(5); B.push_back(4); B.push_back(1); B.push_back(3); cout << getPairs(A, B, n);}
// Java program to find the number of indices pair// such that pair sum from first Array// is greater than second Arrayimport java.util.*; class GFG{ // Function to get the number of pairs of indices// {i, j} in the given two arrays A and B such that// A[i] + A[j] > B[i] + B[j]static long getPairs(Vector<Integer> A, Vector<Integer> B, int n){ // Initializing the difference array D int []D = new int[n]; // Computing the difference between the // elements at every index and storing // it in the array D for (int i = 0; i < n; i++) { D[i] = A.get(i) - B.get(i); } // Sort the array D Arrays.sort(D); // Variable to store the total // number of pairs that satisfy // the given condition long total = 0; // Loop to iterate through the difference // array D and find the total number // of pairs of indices that follow the // given condition for (int i = n - 1; i >= 0; i--) { // If the value at the index i is positive, // then it remains positive for any pairs // with j such that j > i. if (D[i] > 0) { total += n - i - 1; } // If the value at that index is negative // then we need to find the index of the // value just greater than -D[i] else { int k = upper_bound(D,0, D.length, -D[i]); total += n - k; } } return total;}static int upper_bound(int[] a, int low, int high, int element){ while(low < high){ int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver codepublic static void main(String[] args){ int n = 5; Vector<Integer> A = new Vector<Integer>(); Vector<Integer> B= new Vector<Integer>(); A.add(4); A.add(8); A.add(2); A.add(6); A.add(2); B.add(4); B.add(5); B.add(4); B.add(1); B.add(3); System.out.print(getPairs(A, B, n));}} // This code is contributed by 29AjayKumar
# Python 3 program to find the number of indices pair# such that pair sum from first Array# is greater than second Arrayimport bisect # Function to get the number of pairs of indices# {i, j} in the given two arrays A and B such that# A[i] + A[j] > B[i] + B[j]def getPairs(A, B, n): # Initializing the difference array D D = [0]*(n) # Computing the difference between the # elements at every index and storing # it in the array D for i in range(n): D[i] = A[i] - B[i] # Sort the array D D.sort() # Variable to store the total # number of pairs that satisfy # the given condition total = 0 # Loop to iterate through the difference # array D and find the total number # of pairs of indices that follow the # given condition for i in range(n - 1, -1, -1): # If the value at the index i is positive, # then it remains positive for any pairs # with j such that j > i. if (D[i] > 0): total += n - i - 1 # If the value at that index is negative # then we need to find the index of the # value just greater than -D[i] else: k = bisect.bisect_right(D, -D[i], 0, len(D)) total += n - k return total # Driver codeif __name__ == "__main__": n = 5 A = [] B = [] A.append(4); A.append(8); A.append(2); A.append(6); A.append(2); B.append(4); B.append(5); B.append(4); B.append(1); B.append(3); print(getPairs(A, B, n)) # This code is contributed by chitranayal
// C# program to find the number of indices pair// such that pair sum from first Array// is greater than second Arrayusing System;using System.Collections.Generic; class GFG{ // Function to get the number of pairs of indices// {i, j} in the given two arrays A and B such that// A[i] + A[j] > B[i] + B[j]static long getPairs(List<int> A, List<int> B, int n){ // Initializing the difference array D int []D = new int[n]; // Computing the difference between the // elements at every index and storing // it in the array D for (int i = 0; i < n; i++) { D[i] = A[i] - B[i]; } // Sort the array D Array.Sort(D); // Variable to store the total // number of pairs that satisfy // the given condition long total = 0; // Loop to iterate through the difference // array D and find the total number // of pairs of indices that follow the // given condition for (int i = n - 1; i >= 0; i--) { // If the value at the index i is positive, // then it remains positive for any pairs // with j such that j > i. if (D[i] > 0) { total += n - i - 1; } // If the value at that index is negative // then we need to find the index of the // value just greater than -D[i] else { int k = upper_bound(D,0, D.Length, -D[i]); total += n - k; } } return total;}static int upper_bound(int[] a, int low, int high, int element){ while(low < high){ int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver codepublic static void Main(String[] args){ int n = 5; List<int> A = new List<int>(); List<int> B= new List<int>(); A.Add(4); A.Add(8); A.Add(2); A.Add(6); A.Add(2); B.Add(4); B.Add(5); B.Add(4); B.Add(1); B.Add(3); Console.Write(getPairs(A, B, n));}} // This code is contributed by sapnasingh4991
<script>// Javascript program to find the number of indices pair// such that pair sum from first Array// is greater than second Array // Function to get the number of pairs of indices// {i, j} in the given two arrays A and B such that// A[i] + A[j] > B[i] + B[j]function getPairs(A, B, n){ // Initializing the difference array D let D = new Array(n); // Computing the difference between the // elements at every index and storing // it in the array D for (let i = 0; i < n; i++) { D[i] = A[i] - B[i]; } // Sort the array D D.sort((a, b) => a - b); // Variable to store the total // number of pairs that satisfy // the given condition let total = 0; // Loop to iterate through the difference // array D and find the total number // of pairs of indices that follow the // given condition for (let i = n - 1; i >= 0; i--) { // If the value at the index i is positive, // then it remains positive for any pairs // with j such that j > i. if (D[i] > 0) { total += n - i - 1; } // If the value at that index is negative // then we need to find the index of the // value just greater than -D[i] else { let k = upper_bound(D, 0, D.length, -D[i]) total += n - k; } } return total;} function upper_bound(a, low, high, element){ while(low < high){ let middle = low + Math.floor((high - low)/2); if(a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver code let n = 5; let A = new Array(); let B = new Array(); A.push(4); A.push(8); A.push(2); A.push(6); A.push(2); B.push(4); B.push(5); B.push(4); B.push(1); B.push(3); document.write(getPairs(A, B, n)) // This code is contributed by gfgking</script>
7
Time Complexity Analysis:
The sorting of the array takes O(N * log(N)) time.
The time taken to find the index which is just greater than a specific value is O(Log(N)). Since in the worst case, this can be executed for N elements in the array, the overall time complexity for this is O(N * log(N)).
Therefore, the overall time complexity is O(N * log(N)).
29AjayKumar
sapnasingh4991
ukasp
gfgking
simranarora5sos
Arrays
Greedy
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 26675,
"s": 26647,
"text": "\n24 Dec, 2021"
},
{
"code": null,
"e": 26858,
"s": 26675,
"text": "Given two integer arrays A[] and B[] of equal sizes, the task is to find the number of pairs of indices {i, j} in the arrays such that A[i] + A[j] > B[i] + B[j] and i < j.Examples: "
},
{
"code": null,
"e": 27417,
"s": 26858,
"text": "Input: A[] = {4, 8, 2, 6, 2}, B[] = {4, 5, 4, 1, 3} Output: 7 Explanation: There are a total of 7 pairs of indices {i, j} in the array following the condition. They are: {0, 1}: A[0] + A[1] > B[0] + B[1] {0, 3}: A[0] + A[3] > B[0] + B[3] {1, 2}: A[1] + A[2] > B[1] + B[2] {1, 3}: A[1] + A[3] > B[1] + B[3] {1, 4}: A[1] + A[4] > B[1] + B[4] {2, 3}: A[2] + A[3] > B[2] + B[3] {3, 4}: A[3] + A[4] > B[3] + B[4]Input: A[] = {1, 3, 2, 4}, B[] = {1, 3, 2, 4} Output: 0 Explanation: No such possible pairs of {i, j} can be found that satisfies the given condition "
},
{
"code": null,
"e": 28486,
"s": 27417,
"text": "Naive Approach: The naive approach is to consider all the possible pairs of {i, j} in the given arrays and check if A[i] + A[j] > B[i] + B[j]. This can be done by using the concept of nested loops.Time Complexity: O(N2)Efficient Approach: The key observation from the problem is that the given condition can also be visualised as (ai-bi) + (aj-bj)> 0 so we can make another array to store the difference of both arrays. let this array be D . Therefore, the problem reduces to finding pairs with Di+Dj>0. Now we can sort D array and for each corresponding element Di we will find the no of good pairs that Di can make and add this no of pairs to a count variable.For each element Di to find the no of good pairs it can make we can use the upper_bound function of the standard template library to find the upper bound of -Di. since the array is sorted so all elements present after -Di will also make good pair with Di .thus,if upper bound of -Di is x and n be the total size of array then total pairs corresponding to Di will be n-x. This approach takes O(NlogN) time. "
},
{
"code": null,
"e": 28545,
"s": 28486,
"text": "The given condition in the question can be rewritten as: "
},
{
"code": null,
"e": 28635,
"s": 28545,
"text": "A[i] + A[j] > B[i] + B[j]\nA[i] + A[j] - B[i] - B[j] > 0\n(A[i] - B[i]) + (A[j] - B[j]) > 0"
},
{
"code": null,
"e": 28754,
"s": 28635,
"text": "Create another array, say D, to store the difference between elements at the corresponding index in both array, i.e. "
},
{
"code": null,
"e": 28773,
"s": 28754,
"text": "D[i] = A[i] - B[i]"
},
{
"code": null,
"e": 28921,
"s": 28773,
"text": "Now to make sure that the constraint i < j is satisfied, sort the difference array D, so that each element i is smaller than elements to its right."
},
{
"code": null,
"e": 29243,
"s": 28921,
"text": "If at some index i, the value in the difference array D is negative, then we only need to find the nearest position ‘j’ at which the value is just greater than -D[i], so that on summation the value becomes > 0.Inorder to find such index ‘j’, upper_bound() function or Binary Search can be used, since the array is sorted."
},
{
"code": null,
"e": 29294,
"s": 29243,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 29298,
"s": 29294,
"text": "C++"
},
{
"code": null,
"e": 29303,
"s": 29298,
"text": "Java"
},
{
"code": null,
"e": 29311,
"s": 29303,
"text": "Python3"
},
{
"code": null,
"e": 29314,
"s": 29311,
"text": "C#"
},
{
"code": null,
"e": 29325,
"s": 29314,
"text": "Javascript"
},
{
"code": "// C++ program to find the number of indices pair// such that pair sum from first Array// is greater than second Array #include <bits/stdc++.h>using namespace std; // Function to get the number of pairs of indices// {i, j} in the given two arrays A and B such that// A[i] + A[j] > B[i] + B[j]int getPairs(vector<int> A, vector<int> B, int n){ // Initializing the difference array D vector<int> D(n); // Computing the difference between the // elements at every index and storing // it in the array D for (int i = 0; i < n; i++) { D[i] = A[i] - B[i]; } // Sort the array D sort(D.begin(), D.end()); // Variable to store the total // number of pairs that satisfy // the given condition long long total = 0; // Loop to iterate through the difference // array D and find the total number // of pairs of indices that follow the // given condition for (int i = n - 1; i >= 0; i--) { // If the value at the index i is positive, // then it remains positive for any pairs // with j such that j > i. if (D[i] > 0) { total += n - i - 1; } // If the value at that index is negative // then we need to find the index of the // value just greater than -D[i] else { int k = upper_bound(D.begin(), D.end(), -D[i]) - D.begin(); total += n - k; } } return total;} // Driver codeint main(){ int n = 5; vector<int> A; vector<int> B; A.push_back(4); A.push_back(8); A.push_back(2); A.push_back(6); A.push_back(2); B.push_back(4); B.push_back(5); B.push_back(4); B.push_back(1); B.push_back(3); cout << getPairs(A, B, n);}",
"e": 31097,
"s": 29325,
"text": null
},
{
"code": "// Java program to find the number of indices pair// such that pair sum from first Array// is greater than second Arrayimport java.util.*; class GFG{ // Function to get the number of pairs of indices// {i, j} in the given two arrays A and B such that// A[i] + A[j] > B[i] + B[j]static long getPairs(Vector<Integer> A, Vector<Integer> B, int n){ // Initializing the difference array D int []D = new int[n]; // Computing the difference between the // elements at every index and storing // it in the array D for (int i = 0; i < n; i++) { D[i] = A.get(i) - B.get(i); } // Sort the array D Arrays.sort(D); // Variable to store the total // number of pairs that satisfy // the given condition long total = 0; // Loop to iterate through the difference // array D and find the total number // of pairs of indices that follow the // given condition for (int i = n - 1; i >= 0; i--) { // If the value at the index i is positive, // then it remains positive for any pairs // with j such that j > i. if (D[i] > 0) { total += n - i - 1; } // If the value at that index is negative // then we need to find the index of the // value just greater than -D[i] else { int k = upper_bound(D,0, D.length, -D[i]); total += n - k; } } return total;}static int upper_bound(int[] a, int low, int high, int element){ while(low < high){ int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver codepublic static void main(String[] args){ int n = 5; Vector<Integer> A = new Vector<Integer>(); Vector<Integer> B= new Vector<Integer>(); A.add(4); A.add(8); A.add(2); A.add(6); A.add(2); B.add(4); B.add(5); B.add(4); B.add(1); B.add(3); System.out.print(getPairs(A, B, n));}} // This code is contributed by 29AjayKumar",
"e": 33151,
"s": 31097,
"text": null
},
{
"code": "# Python 3 program to find the number of indices pair# such that pair sum from first Array# is greater than second Arrayimport bisect # Function to get the number of pairs of indices# {i, j} in the given two arrays A and B such that# A[i] + A[j] > B[i] + B[j]def getPairs(A, B, n): # Initializing the difference array D D = [0]*(n) # Computing the difference between the # elements at every index and storing # it in the array D for i in range(n): D[i] = A[i] - B[i] # Sort the array D D.sort() # Variable to store the total # number of pairs that satisfy # the given condition total = 0 # Loop to iterate through the difference # array D and find the total number # of pairs of indices that follow the # given condition for i in range(n - 1, -1, -1): # If the value at the index i is positive, # then it remains positive for any pairs # with j such that j > i. if (D[i] > 0): total += n - i - 1 # If the value at that index is negative # then we need to find the index of the # value just greater than -D[i] else: k = bisect.bisect_right(D, -D[i], 0, len(D)) total += n - k return total # Driver codeif __name__ == \"__main__\": n = 5 A = [] B = [] A.append(4); A.append(8); A.append(2); A.append(6); A.append(2); B.append(4); B.append(5); B.append(4); B.append(1); B.append(3); print(getPairs(A, B, n)) # This code is contributed by chitranayal",
"e": 34714,
"s": 33151,
"text": null
},
{
"code": "// C# program to find the number of indices pair// such that pair sum from first Array// is greater than second Arrayusing System;using System.Collections.Generic; class GFG{ // Function to get the number of pairs of indices// {i, j} in the given two arrays A and B such that// A[i] + A[j] > B[i] + B[j]static long getPairs(List<int> A, List<int> B, int n){ // Initializing the difference array D int []D = new int[n]; // Computing the difference between the // elements at every index and storing // it in the array D for (int i = 0; i < n; i++) { D[i] = A[i] - B[i]; } // Sort the array D Array.Sort(D); // Variable to store the total // number of pairs that satisfy // the given condition long total = 0; // Loop to iterate through the difference // array D and find the total number // of pairs of indices that follow the // given condition for (int i = n - 1; i >= 0; i--) { // If the value at the index i is positive, // then it remains positive for any pairs // with j such that j > i. if (D[i] > 0) { total += n - i - 1; } // If the value at that index is negative // then we need to find the index of the // value just greater than -D[i] else { int k = upper_bound(D,0, D.Length, -D[i]); total += n - k; } } return total;}static int upper_bound(int[] a, int low, int high, int element){ while(low < high){ int middle = low + (high - low)/2; if(a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver codepublic static void Main(String[] args){ int n = 5; List<int> A = new List<int>(); List<int> B= new List<int>(); A.Add(4); A.Add(8); A.Add(2); A.Add(6); A.Add(2); B.Add(4); B.Add(5); B.Add(4); B.Add(1); B.Add(3); Console.Write(getPairs(A, B, n));}} // This code is contributed by sapnasingh4991",
"e": 36759,
"s": 34714,
"text": null
},
{
"code": "<script>// Javascript program to find the number of indices pair// such that pair sum from first Array// is greater than second Array // Function to get the number of pairs of indices// {i, j} in the given two arrays A and B such that// A[i] + A[j] > B[i] + B[j]function getPairs(A, B, n){ // Initializing the difference array D let D = new Array(n); // Computing the difference between the // elements at every index and storing // it in the array D for (let i = 0; i < n; i++) { D[i] = A[i] - B[i]; } // Sort the array D D.sort((a, b) => a - b); // Variable to store the total // number of pairs that satisfy // the given condition let total = 0; // Loop to iterate through the difference // array D and find the total number // of pairs of indices that follow the // given condition for (let i = n - 1; i >= 0; i--) { // If the value at the index i is positive, // then it remains positive for any pairs // with j such that j > i. if (D[i] > 0) { total += n - i - 1; } // If the value at that index is negative // then we need to find the index of the // value just greater than -D[i] else { let k = upper_bound(D, 0, D.length, -D[i]) total += n - k; } } return total;} function upper_bound(a, low, high, element){ while(low < high){ let middle = low + Math.floor((high - low)/2); if(a[middle] > element) high = middle; else low = middle + 1; } return low;} // Driver code let n = 5; let A = new Array(); let B = new Array(); A.push(4); A.push(8); A.push(2); A.push(6); A.push(2); B.push(4); B.push(5); B.push(4); B.push(1); B.push(3); document.write(getPairs(A, B, n)) // This code is contributed by gfgking</script>",
"e": 38657,
"s": 36759,
"text": null
},
{
"code": null,
"e": 38659,
"s": 38657,
"text": "7"
},
{
"code": null,
"e": 38688,
"s": 38661,
"text": "Time Complexity Analysis: "
},
{
"code": null,
"e": 38739,
"s": 38688,
"text": "The sorting of the array takes O(N * log(N)) time."
},
{
"code": null,
"e": 38960,
"s": 38739,
"text": "The time taken to find the index which is just greater than a specific value is O(Log(N)). Since in the worst case, this can be executed for N elements in the array, the overall time complexity for this is O(N * log(N))."
},
{
"code": null,
"e": 39017,
"s": 38960,
"text": "Therefore, the overall time complexity is O(N * log(N))."
},
{
"code": null,
"e": 39029,
"s": 39017,
"text": "29AjayKumar"
},
{
"code": null,
"e": 39044,
"s": 39029,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 39050,
"s": 39044,
"text": "ukasp"
},
{
"code": null,
"e": 39058,
"s": 39050,
"text": "gfgking"
},
{
"code": null,
"e": 39074,
"s": 39058,
"text": "simranarora5sos"
},
{
"code": null,
"e": 39081,
"s": 39074,
"text": "Arrays"
},
{
"code": null,
"e": 39088,
"s": 39081,
"text": "Greedy"
},
{
"code": null,
"e": 39095,
"s": 39088,
"text": "Arrays"
},
{
"code": null,
"e": 39102,
"s": 39095,
"text": "Greedy"
},
{
"code": null,
"e": 39200,
"s": 39102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39268,
"s": 39200,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 39312,
"s": 39268,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 39360,
"s": 39312,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 39383,
"s": 39360,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 39415,
"s": 39383,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 39466,
"s": 39415,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 39524,
"s": 39466,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 39575,
"s": 39524,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 39635,
"s": 39575,
"text": "Write a program to print all permutations of a given string"
}
] |
PyQt5 - Finding the item through text in ComboBox - GeeksforGeeks
|
22 Apr, 2020
In this article we will see how we can find the item index with the help of text in it. We know we can add items with the help of addItem and addItems method, in order to find the item with the help of findText method.
Syntax : combo_box.findText(text)
Argument : It takes string as argument.
Return : It return integer i.e index of text if text doesn’t exist it return -1
Below is the implementation –
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"] # adding list of items to combo box self.combo_box.addItems(geek_list) # text text = "Legend Geek" # finding index of text index = self.combo_box.findText(text) # label to show index label = QLabel(text + " index : " + str(index), self) # setting geometry of label label.setGeometry(200, 200, 200, 30) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
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": "\n22 Apr, 2020"
},
{
"code": null,
"e": 25756,
"s": 25537,
"text": "In this article we will see how we can find the item index with the help of text in it. We know we can add items with the help of addItem and addItems method, in order to find the item with the help of findText method."
},
{
"code": null,
"e": 25790,
"s": 25756,
"text": "Syntax : combo_box.findText(text)"
},
{
"code": null,
"e": 25830,
"s": 25790,
"text": "Argument : It takes string as argument."
},
{
"code": null,
"e": 25910,
"s": 25830,
"text": "Return : It return integer i.e index of text if text doesn’t exist it return -1"
},
{
"code": null,
"e": 25940,
"s": 25910,
"text": "Below is the implementation –"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = [\"Geek\", \"Geeky Geek\", \"Legend Geek\", \"Ultra Legend Geek\"] # adding list of items to combo box self.combo_box.addItems(geek_list) # text text = \"Legend Geek\" # finding index of text index = self.combo_box.findText(text) # label to show index label = QLabel(text + \" index : \" + str(index), self) # setting geometry of label label.setGeometry(200, 200, 200, 30) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27255,
"s": 25940,
"text": null
},
{
"code": null,
"e": 27264,
"s": 27255,
"text": "Output :"
},
{
"code": null,
"e": 27286,
"s": 27264,
"text": "Python PyQt5-ComboBox"
},
{
"code": null,
"e": 27297,
"s": 27286,
"text": "Python-gui"
},
{
"code": null,
"e": 27309,
"s": 27297,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27316,
"s": 27309,
"text": "Python"
},
{
"code": null,
"e": 27414,
"s": 27316,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27446,
"s": 27414,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27488,
"s": 27446,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27530,
"s": 27488,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27557,
"s": 27530,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27613,
"s": 27557,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27635,
"s": 27613,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27674,
"s": 27635,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27705,
"s": 27674,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27734,
"s": 27705,
"text": "Create a directory in Python"
}
] |
How to use react-draggable module in ReactJS ? - GeeksforGeeks
|
21 May, 2021
We can use the react-draggable module in ReactJS for making elements draggable. Internally the draggable items are moved with the help of CSS Transforms. This module allows the items to become draggable regardless of their current position. We can use the following approach in ReactJS to use the react-draggable module.
Approach: In the following example, we have used the react-draggable module to demonstrate how we can use it in our ReactJS application. We have imported the Draggable component from the library and used it in our main App component, now whatever the content is present inside this Draggable component, it can be dragged with the mouse across the screen. Like in your below example, we have a div with the text This line can be moved now! which is draggable as shown below in the below-attached gif.
Draggable Props:
allowAnyClick: It is used to allow the dragging on non-left-button clicks if this value is set to true.
axis: It is used to determine on which axis the draggable can move.
bounds: It is used to denote the movement boundaries.
cancel: It is used to denote a selector which can be used to prevent drag initialization.
defaultClassName: It is used to denote the class name for the draggable UI.
defaultClassNameDragging: It is used to denote the default class name for the dragging movement.
defaultClassNameDragged: It is used to denote the default class name for the dragged movement.
defaultPosition: It is used to denote the default x and y coordinate where the dragging should be started.
disabled: It is used to disable the component.
grid: It is used to denote the x and y coordinate where the dragging should snap to.
handle: It is used to denote a selector which is used as a handle that initiates the drag.
offsetParent: It is used to pass our own offsetParent for drag calculations.
onMouseDown: It is a callback function that is triggered on the user mouses down event.
onStart: It is a callback function that is triggered when dragging starts.
onDrag: It is a callback function that is triggered while dragging.
onStop: It is a callback function that is triggered when dragging stops.
nodeRef: It is used to pass the node ref element to the underlying component.
position: It is used when the user wants to have direct control of the element. It makes the item controlled.
positionOffset: It is used to denote a position offset to start with.
scale: It is used to denote the scale of the canvas where the dragging is performed.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-draggable
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install react-draggable
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import Draggable from 'react-draggable'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Draggable Module</h4> <div style={{ width: 660, height: 'auto' }}> <Draggable> <div>This line can be moved now!</div> </Draggable> </div> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://www.npmjs.com/package/react-draggable
React-Modules
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 26392,
"s": 26071,
"text": "We can use the react-draggable module in ReactJS for making elements draggable. Internally the draggable items are moved with the help of CSS Transforms. This module allows the items to become draggable regardless of their current position. We can use the following approach in ReactJS to use the react-draggable module."
},
{
"code": null,
"e": 26892,
"s": 26392,
"text": "Approach: In the following example, we have used the react-draggable module to demonstrate how we can use it in our ReactJS application. We have imported the Draggable component from the library and used it in our main App component, now whatever the content is present inside this Draggable component, it can be dragged with the mouse across the screen. Like in your below example, we have a div with the text This line can be moved now! which is draggable as shown below in the below-attached gif."
},
{
"code": null,
"e": 26909,
"s": 26892,
"text": "Draggable Props:"
},
{
"code": null,
"e": 27013,
"s": 26909,
"text": "allowAnyClick: It is used to allow the dragging on non-left-button clicks if this value is set to true."
},
{
"code": null,
"e": 27081,
"s": 27013,
"text": "axis: It is used to determine on which axis the draggable can move."
},
{
"code": null,
"e": 27135,
"s": 27081,
"text": "bounds: It is used to denote the movement boundaries."
},
{
"code": null,
"e": 27225,
"s": 27135,
"text": "cancel: It is used to denote a selector which can be used to prevent drag initialization."
},
{
"code": null,
"e": 27301,
"s": 27225,
"text": "defaultClassName: It is used to denote the class name for the draggable UI."
},
{
"code": null,
"e": 27398,
"s": 27301,
"text": "defaultClassNameDragging: It is used to denote the default class name for the dragging movement."
},
{
"code": null,
"e": 27493,
"s": 27398,
"text": "defaultClassNameDragged: It is used to denote the default class name for the dragged movement."
},
{
"code": null,
"e": 27600,
"s": 27493,
"text": "defaultPosition: It is used to denote the default x and y coordinate where the dragging should be started."
},
{
"code": null,
"e": 27647,
"s": 27600,
"text": "disabled: It is used to disable the component."
},
{
"code": null,
"e": 27732,
"s": 27647,
"text": "grid: It is used to denote the x and y coordinate where the dragging should snap to."
},
{
"code": null,
"e": 27823,
"s": 27732,
"text": "handle: It is used to denote a selector which is used as a handle that initiates the drag."
},
{
"code": null,
"e": 27900,
"s": 27823,
"text": "offsetParent: It is used to pass our own offsetParent for drag calculations."
},
{
"code": null,
"e": 27988,
"s": 27900,
"text": "onMouseDown: It is a callback function that is triggered on the user mouses down event."
},
{
"code": null,
"e": 28063,
"s": 27988,
"text": "onStart: It is a callback function that is triggered when dragging starts."
},
{
"code": null,
"e": 28131,
"s": 28063,
"text": "onDrag: It is a callback function that is triggered while dragging."
},
{
"code": null,
"e": 28204,
"s": 28131,
"text": "onStop: It is a callback function that is triggered when dragging stops."
},
{
"code": null,
"e": 28282,
"s": 28204,
"text": "nodeRef: It is used to pass the node ref element to the underlying component."
},
{
"code": null,
"e": 28392,
"s": 28282,
"text": "position: It is used when the user wants to have direct control of the element. It makes the item controlled."
},
{
"code": null,
"e": 28463,
"s": 28392,
"text": "positionOffset: It is used to denote a position offset to start with. "
},
{
"code": null,
"e": 28548,
"s": 28463,
"text": "scale: It is used to denote the scale of the canvas where the dragging is performed."
},
{
"code": null,
"e": 28598,
"s": 28548,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 28693,
"s": 28598,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 28757,
"s": 28693,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 28789,
"s": 28757,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 28902,
"s": 28789,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 29002,
"s": 28902,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 29016,
"s": 29002,
"text": "cd foldername"
},
{
"code": null,
"e": 29148,
"s": 29016,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-draggable"
},
{
"code": null,
"e": 29253,
"s": 29148,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 29281,
"s": 29253,
"text": "npm install react-draggable"
},
{
"code": null,
"e": 29333,
"s": 29281,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 29351,
"s": 29333,
"text": "Project Structure"
},
{
"code": null,
"e": 29481,
"s": 29351,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 29488,
"s": 29481,
"text": "App.js"
},
{
"code": "import React from 'react';import Draggable from 'react-draggable'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Draggable Module</h4> <div style={{ width: 660, height: 'auto' }}> <Draggable> <div>This line can be moved now!</div> </Draggable> </div> </div> );}",
"e": 29862,
"s": 29488,
"text": null
},
{
"code": null,
"e": 29975,
"s": 29862,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 29985,
"s": 29975,
"text": "npm start"
},
{
"code": null,
"e": 30084,
"s": 29985,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 30141,
"s": 30084,
"text": "Reference: https://www.npmjs.com/package/react-draggable"
},
{
"code": null,
"e": 30155,
"s": 30141,
"text": "React-Modules"
},
{
"code": null,
"e": 30171,
"s": 30155,
"text": "React-Questions"
},
{
"code": null,
"e": 30179,
"s": 30171,
"text": "ReactJS"
},
{
"code": null,
"e": 30196,
"s": 30179,
"text": "Web Technologies"
},
{
"code": null,
"e": 30294,
"s": 30196,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30321,
"s": 30294,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 30363,
"s": 30321,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 30401,
"s": 30363,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 30436,
"s": 30401,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 30494,
"s": 30436,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 30534,
"s": 30494,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30567,
"s": 30534,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30612,
"s": 30567,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30662,
"s": 30612,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
JavaScript Sum function on the click of a button
|
Let’s say the following is our button −
<button type="button" onclick="addTheValue(10)">Sum </button>
</body>
We are calling the function addTheValue(10) with parameter 10 on button click. On clicking the
button, we are adding the value 10 as in the below code −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=
1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/ 4.7.0/css/font-awesome.min.css">
</head>
<body>
<p>
<h1> Adding 10 each time whenever you click the Sum
Button......</h1>
</p>
<b id="firstValue">10</b>
<button type="button" onclick="addTheValue(10)">Sum </button>
<script>
function addTheValue(secondValue) {
var fValue = document.getElementById("firstValue");
firstValue.innerHTML = parseInt(fValue.innerHTML) +
parseInt(secondValue);
}
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Now, I am going click the “Sum” button for the first time.
This will produce the following output −
|
[
{
"code": null,
"e": 1102,
"s": 1062,
"text": "Let’s say the following is our button −"
},
{
"code": null,
"e": 1172,
"s": 1102,
"text": "<button type=\"button\" onclick=\"addTheValue(10)\">Sum </button>\n</body>"
},
{
"code": null,
"e": 1325,
"s": 1172,
"text": "We are calling the function addTheValue(10) with parameter 10 on button click. On clicking the\nbutton, we are adding the value 10 as in the below code −"
},
{
"code": null,
"e": 1336,
"s": 1325,
"text": " Live Demo"
},
{
"code": null,
"e": 2235,
"s": 1336,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=\n1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/fontawesome/ 4.7.0/css/font-awesome.min.css\">\n</head>\n<body>\n<p>\n<h1> Adding 10 each time whenever you click the Sum\nButton......</h1>\n</p>\n<b id=\"firstValue\">10</b>\n<button type=\"button\" onclick=\"addTheValue(10)\">Sum </button>\n<script>\n function addTheValue(secondValue) {\n var fValue = document.getElementById(\"firstValue\");\n firstValue.innerHTML = parseInt(fValue.innerHTML) +\n parseInt(secondValue);\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2397,
"s": 2235,
"text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 2438,
"s": 2397,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2497,
"s": 2438,
"text": "Now, I am going click the “Sum” button for the first time."
},
{
"code": null,
"e": 2538,
"s": 2497,
"text": "This will produce the following output −"
}
] |
Ext.js - Localization
|
It is always best to communicate with the users in the language they understand and prefer. Extjs localization package supports over 40 languages such as German, French, Korean, Chinese, etc. It is very simple to implement the locale in ExtJs. You’ll find all of the bundled locale files in the override folder of the ext-locale package. Locale files just overrides that tells Ext JS to replace the default English values of certain components.
The following program is to show the month in different locale to see the effect. Try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-fr.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
var monthArray = Ext.Array.map(Ext.Date.monthNames, function (e) { return [e]; });
var ds = Ext.create('Ext.data.Store', {
fields: ['month'],
remoteSort: true,
pageSize: 6,
proxy: {
type: 'memory',
enablePaging: true,
data: monthArray,
reader: {type: 'array'}
}
});
Ext.create('Ext.grid.Panel', {
renderTo: 'grid',
id : 'gridId',
width: 600,
height: 200,
title:'Month Browser',
columns:[{
text: 'Month of the year',
dataIndex: 'month',
width: 300
}],
store: ds,
bbar: Ext.create('Ext.toolbar.Paging', {
pageSize: 6,
store: ds,
displayInfo: true
})
});
Ext.getCmp('gridId').getStore().load();
});
</script>
</head>
<body>
<div id = "grid" />
</body>
</html>
The above program will produce the following result
For using different locale other than English, we would need to add the locale specific file in our program. Here we are using https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/localefr.js for French. You can use different locale for different languages such as https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-ko.js for korean, etc.
The following program is to show the date picker in Korean locale to see the effect. Try the following program.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-ko.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.picker.Date', {
renderTo: 'datePicker'
});
});
</script>
</head>
<body>
<div id = "datePicker" />
</body>
</html>
The above program will produce the following result −
Following table lists the few locales available in ExtJS and the main file locale URL to be changed.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2468,
"s": 2023,
"text": "It is always best to communicate with the users in the language they understand and prefer. Extjs localization package supports over 40 languages such as German, French, Korean, Chinese, etc. It is very simple to implement the locale in ExtJs. You’ll find all of the bundled locale files in the override folder of the ext-locale package. Locale files just overrides that tells Ext JS to replace the default English values of certain components."
},
{
"code": null,
"e": 2577,
"s": 2468,
"text": "The following program is to show the month in different locale to see the effect. Try the following program."
},
{
"code": null,
"e": 4325,
"s": 2577,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-fr.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n var monthArray = Ext.Array.map(Ext.Date.monthNames, function (e) { return [e]; });\n var ds = Ext.create('Ext.data.Store', {\n fields: ['month'],\n remoteSort: true,\n pageSize: 6,\n \n proxy: {\n type: 'memory',\n enablePaging: true,\n data: monthArray,\n reader: {type: 'array'}\n }\n });\n Ext.create('Ext.grid.Panel', {\n renderTo: 'grid',\n id : 'gridId',\n width: 600,\n height: 200,\n title:'Month Browser',\n \n columns:[{\n text: 'Month of the year',\n dataIndex: 'month',\n width: 300\n }],\n store: ds,\n bbar: Ext.create('Ext.toolbar.Paging', {\n pageSize: 6,\n store: ds,\n displayInfo: true\n })\n }); \n Ext.getCmp('gridId').getStore().load();\n });\n </script>\n </head>\n \n <body>\n <div id = \"grid\" />\n </body>\n</html>"
},
{
"code": null,
"e": 4377,
"s": 4325,
"text": "The above program will produce the following result"
},
{
"code": null,
"e": 4751,
"s": 4377,
"text": "For using different locale other than English, we would need to add the locale specific file in our program. Here we are using https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/localefr.js for French. You can use different locale for different languages such as https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-ko.js for korean, etc."
},
{
"code": null,
"e": 4863,
"s": 4751,
"text": "The following program is to show the date picker in Korean locale to see the effect. Try the following program."
},
{
"code": null,
"e": 5613,
"s": 4863,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/locale/locale-ko.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.picker.Date', {\n renderTo: 'datePicker'\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"datePicker\" />\n </body>\n</html>"
},
{
"code": null,
"e": 5667,
"s": 5613,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 5768,
"s": 5667,
"text": "Following table lists the few locales available in ExtJS and the main file locale URL to be changed."
},
{
"code": null,
"e": 5775,
"s": 5768,
"text": " Print"
},
{
"code": null,
"e": 5786,
"s": 5775,
"text": " Add Notes"
}
] |
A Guide to Python Good Practices. Revisiting some of the best practices... | by Mohit Mayank | Towards Data Science
|
This article is a chapter taken from my ongoing (and still only partially complete) book on Data science titled, “A Lazy Guide to Data Science”. To read similar articles, refer to my blog or my medium page. Don't forget to say hi on LinkedIn and/or Twitter. 🖖
Writing code that works now is easy. Writing code that will work tomorrow is hard. Writing code that will work tomorrow and is intuitive enough for anyone to understand and follow — well now we have hit the super hard stuff 😀. Observing several ML engineers and Data scientists working with me, I have noticed nearly all of them have their own unique style of coding. Well, don't get me wrong, subjectively is a good thing and I think it is what leads to innovations. That said while working in a team or even in open source collaboration, it helps to agree to a certain set of rules. And that's the idea behind this article, to provide python practitioners with a set of curated guidelines, from which they can pick and choose. With that, let’s cover some of the good practices, which will not only help us to create a working but also a beautiful piece of code 😄. To cover this topic, we will go through three parts,
Project structuring: ideas on how to organize your codeCode formatting: ideas on how to make your code easy to followAdditional tips: a few things which will help you in the longer run
Project structuring: ideas on how to organize your code
Code formatting: ideas on how to make your code easy to follow
Additional tips: a few things which will help you in the longer run
In this part, we will basically talk about some good practices on how the complete python project can be structured. For this, we will look at two different possibilities, which anyone can choose based on how simple or complex their project is going to be.
This is the most basic format and yet gives the hint of organized structuring. This can be followed when our project consists of only a few modules/scripts. The directory of a sample project could look something like this:
my_project # Root directory of the project├── code # Source codes├── input # Input files├── output # Output files├── config # Configuration files├── notebooks # Project related Jupyter notebooks (for experimental code)├── requirements.txt # List of external package which are project dependency└── README.md # Project README
As obvious from the names, folder code contains the individual modules (.py files), input and output contains the input and output files respectively, and notebook contains the .ipynb notebooks files we use for experimentation. Finally, config folder could contain parameters within yaml or json or ini files and can be accessed by the code module files using [configparser](configparser — Configuration file parser — Python 3.7.11 documentation).
requirements.txt contains a list of all external python packages needed by the project. One advantage of maintaining this file is that all of these packages can be easily installed using pip install -r requirements.txt command. (No need of manually installing each and every external package!). One example requirements.txt file is shown below (with package_name==package_version format),
BeautifulSoup==3.2.0Django==1.3Fabric==1.2.0Jinja2==2.5.5PyYAML==3.09Pygments==1.4
Finally, README.MD contains the what, why and how of the project, with some dummy codes on how to run the project and sample use cases.
Kedro is not a project structuring strategy, it’s a python tool released by QuantumBlack Labs, which does project structuring for you 😎. On top of it, they provide a plethora of features to make our project organization and even code execution process super-easy, so that we can truly focus on what matters the most — the experimentations and implementations!
Their project structure is shown below. And btw, we can create a blank project by running kedro new command (don't forget to install kedro first by pip install kedro)
get-started # Parent directory of the template├── conf # Project configuration files├── data # Local project data (not committed to version control)├── docs # Project documentation├── logs # Project output logs (not committed to version control)├── notebooks # Project related Jupyter notebooks (can be used for experimental code before moving the code to src)├── README.md # Project README├── setup.cfg # Configuration options for `pytest` when doing `kedro test` and for the `isort` utility when doing `kedro lint`└── src # Project source code
While most of the directories are similar to other types, a few points should be noted. Kedro’s way of grouping different modules is by creating different ”pipelines”. These pipelines are present within src folder, which in turn contains the module files. Furthermore, they have clear segregation of individual functions which are executed - these are stored within nodes.py file, and these functions are later connected with the input and output within pipeline.py file *(all within the individual pipeline folder). Kedro also segregates the code and the parameters, by storing the parameters within conf folder.
Apart from just helping with organizing the project, they also provide options for sequential or parallel executions. We can execute individual functions (within nodes.py), or individual pipelines (which are a combination of functions), or the complete project at one go. We can also create doc of the complete project or compile and package the project as a python .whl file, with just a single command run. For more details, and believe me, we have just touched the surface, refer to their official documentation.
With a top-down approach, let’s first have a look at a neat piece of code. We will discuss individual aspects of the code in more detail later. For now, just assume if someone asks you to do some scripting, what an ideal piece of code file should look like.
The following code is taken from csv_column_operations.py module file. It was generated for the prompt: "write a function which takes CSV file as input and returns the sum of a column".
Some might argue why do such an overkill for a simple piece of code. Note, it's a dummy example. In real life, you will develop more complex pieces of codes and hence it become quite important that we understand the gist.
Now let’s take a deeper dive into the individual aspect of the above code.
A module is a python file with .py extension that contains the executable code or functions or classes, etc.
Usually, we start the module with module definition, which is an area where we provide some basic details of the module. We can do so using the following template (and it can be easily compared to a real code shown above)
"""<Short description><Long description>Author: <Name> <email>Created: <date>"""
Next, we should clearly segregate the parts of the module such as imports, code area, etc using comment lines.
Finally, at the bottom, we could include some examples on how to run the code. Including these scripts within if __name__ == '__main__': makes sure that they only run when the file is directly executed (like python csv_column_operations.py). So these pieces of code doesn't run when you say import the module in another script.
Functions are the basic block of code that performs a specific task. A module consists of several functions. To inform the user what a particular block of code does, we start the function with a function definition. A sample template is provided below,
"""DescriptionParamters---------<parameter_1>: <data_type> <parameter_1_description>Returns---------<output_1>: <data_type> <output_1_description>"""
After this, we can start adding the relevant code lines. Make sure to separate different logical blocks of code within the functions using comments.
One important thing to handle at the start of the coding section is to check the parameters and input data for some data type or data content related basic issues. A majority of code break happens due to silly mistakes like when someone provides wrong input, in which case we should print or log warning message and gracefully exit. The above same code contains two such preliminary but important checks inside the step 1 section.
There are several formatting conventions that we can follow, like Camel Case, Snake case, etc. It’s quite subjective and depends on the developer. Below are some examples of naming different entities of a python code (taken from PIP8 conventions — with some modifications) 😇,
Module name: Modules should have short, all-lowercase names (ex: csv_column_operations.py)
Function or method name: Function names should be lowercase, with words separated by underscores as necessary to improve readability. Also, don’t forget to add your verbs! (ex: perform_column_sum())
Variable name: Similar to function name but without the verbs! (ex: list_of_news)
Class name: Class names should normally use the CapWords convention. (ex: FindMax)
Constant name: Constants are usually defined on a module level and written in all capital letters with underscores separating words. (ex: MAX_OVERFLOW and TOTAL).
PEP-8 defines three types of comments,
Block comments: which is written for a single or a collection of code lines. This can be done either when you want to explain a set of lines or just want to segregate code. In the above example, you can see # Step {1, 2, 3} used as segregation comments and # run when file is directly executed used to explain a set of code lines.
Inline comments: which are added on the same line as the code. For example, see how # to handle csv files is used to justify the pandas package import. PEP-8 suggests using inline comments sparingly.
Documentation Strings: these are used for documentation for module, functions or classes. PEP-257 suggests using multiline comment for docstring (using “””). An example of module and function docstrings (short for documentation strings) is provided in the sample code above.
We should be as descriptive in our comments as possible. Try to separate functional sections of your code, provide explanations for complex code lines, provide details about the input/output of functions, etc. How do you know you have enough comments? — If you think someone with half your expertise can understand the code without calling you middle of the night! 😤
Frankly, I am only going to touch this topic with a long stick 🧹. There are already several articles, reddit threads and even tv series (Silicon valley 📺) where this topic has been discussed a lot!
Want my 2 cents? Pick any modern IDE (like VSCode, Sublime, etc), set indentations to tabs, and set 1 tab = 4 spaces. Done 😏
Till now we have discussed how to either structure the project or format the code. Next, we will cover a generic set of good practices which will save you some pain down the line 😬
Instead of printing statements in the console which is temporary (do a cls and poof it's gone💨), a better idea is to save these statements in a separate file, which you can always go back and refer to. This is logging 📜
Python provides an inbuilt function for logging. By referring to the official how to, logging to a file is super easy,
# importimport logging# config the logging behaviorlogging.basicConfig(filename='example.log',level=logging.DEBUG)# some sample log messageslogging.debug('This message should go to the log file')logging.info('So should this')logging.warning('And this, too')
Note, there is a hierarchical levelling of logs to segregate different severity of logs. In the example shown above, the level parameter denotes the minimal level that is tracked and hence saved to the file. As per the official how to, these are the different logging levels with some details about when to use which (in increasing order of severity),
Documentation of the code is an absolute must, if you are planning to maintain the code or hand it over to someone else in the foreseeable future. Just ask any developer about their excitement on finding ready-made and well-curated documentation for a package they are planning to use! On the other hand, it looks quite difficult to create one yourself, isn’t it? I mean, look at the beautiful docs of sklearn or pandas. 😮
Well, sorry for the scare there, but actually it’s quite simple 😉. Remember all the function and module docstring and the formatting we followed before? As it turns out, we can leverage many open source tools like pydoc and sphinx to create full-fledged HTML documentations! Going into practical details is out of the scope of this article, but it is fairly easy to follow the “how to” steps of both the packages and get your doc ready.
One last thing, if you are using Kedro, this process is even simpler. All you have to do is run one command — kedro build-docs --open to create the documentation and automatically open it in your default browser!
Virtual environments (VE) can be thought of as the local copy of the python environment, created specifically for a project. This local copy is like a blank slate, as any required package can be installed here separately. It is extremely important to create a new virtual environment for any new project, because,
each project has its own dependency tree (one package with a specific version needs another package to run, with its own specific version)
while developing a project we may need to downgrade or upgrade a package, which if done on the base python environment, will affect your system!
hence, a separate copy of python (VE), where you install whatever you want, seems to be the most logical solution.
Using VE basically requires two steps,
Create a VE: this can be done by running the command python3 -m venv tutorial-env at the project root directory. (note, tutorial-env is the name of the VE, you can use rename it to anything)
Activate VE: this can be done by running the command tutorial-env\Scripts\activate.bat on Windows and source tutorial-env/bin/activate on Unix or MacOS.
And that’s it! Install, uninstall, upgrade or downgrade whatever you want!
Remember to switch to another VE when you start working on another project or/and to deactivate the VE when you want to move to base VE.
PEP8 Style Guide for Python Code
Kedro
Python 3 documentation
|
[
{
"code": null,
"e": 431,
"s": 171,
"text": "This article is a chapter taken from my ongoing (and still only partially complete) book on Data science titled, “A Lazy Guide to Data Science”. To read similar articles, refer to my blog or my medium page. Don't forget to say hi on LinkedIn and/or Twitter. 🖖"
},
{
"code": null,
"e": 1350,
"s": 431,
"text": "Writing code that works now is easy. Writing code that will work tomorrow is hard. Writing code that will work tomorrow and is intuitive enough for anyone to understand and follow — well now we have hit the super hard stuff 😀. Observing several ML engineers and Data scientists working with me, I have noticed nearly all of them have their own unique style of coding. Well, don't get me wrong, subjectively is a good thing and I think it is what leads to innovations. That said while working in a team or even in open source collaboration, it helps to agree to a certain set of rules. And that's the idea behind this article, to provide python practitioners with a set of curated guidelines, from which they can pick and choose. With that, let’s cover some of the good practices, which will not only help us to create a working but also a beautiful piece of code 😄. To cover this topic, we will go through three parts,"
},
{
"code": null,
"e": 1535,
"s": 1350,
"text": "Project structuring: ideas on how to organize your codeCode formatting: ideas on how to make your code easy to followAdditional tips: a few things which will help you in the longer run"
},
{
"code": null,
"e": 1591,
"s": 1535,
"text": "Project structuring: ideas on how to organize your code"
},
{
"code": null,
"e": 1654,
"s": 1591,
"text": "Code formatting: ideas on how to make your code easy to follow"
},
{
"code": null,
"e": 1722,
"s": 1654,
"text": "Additional tips: a few things which will help you in the longer run"
},
{
"code": null,
"e": 1979,
"s": 1722,
"text": "In this part, we will basically talk about some good practices on how the complete python project can be structured. For this, we will look at two different possibilities, which anyone can choose based on how simple or complex their project is going to be."
},
{
"code": null,
"e": 2202,
"s": 1979,
"text": "This is the most basic format and yet gives the hint of organized structuring. This can be followed when our project consists of only a few modules/scripts. The directory of a sample project could look something like this:"
},
{
"code": null,
"e": 2610,
"s": 2202,
"text": "my_project # Root directory of the project├── code # Source codes├── input # Input files├── output # Output files├── config # Configuration files├── notebooks # Project related Jupyter notebooks (for experimental code)├── requirements.txt # List of external package which are project dependency└── README.md # Project README"
},
{
"code": null,
"e": 3058,
"s": 2610,
"text": "As obvious from the names, folder code contains the individual modules (.py files), input and output contains the input and output files respectively, and notebook contains the .ipynb notebooks files we use for experimentation. Finally, config folder could contain parameters within yaml or json or ini files and can be accessed by the code module files using [configparser](configparser — Configuration file parser — Python 3.7.11 documentation)."
},
{
"code": null,
"e": 3447,
"s": 3058,
"text": "requirements.txt contains a list of all external python packages needed by the project. One advantage of maintaining this file is that all of these packages can be easily installed using pip install -r requirements.txt command. (No need of manually installing each and every external package!). One example requirements.txt file is shown below (with package_name==package_version format),"
},
{
"code": null,
"e": 3530,
"s": 3447,
"text": "BeautifulSoup==3.2.0Django==1.3Fabric==1.2.0Jinja2==2.5.5PyYAML==3.09Pygments==1.4"
},
{
"code": null,
"e": 3666,
"s": 3530,
"text": "Finally, README.MD contains the what, why and how of the project, with some dummy codes on how to run the project and sample use cases."
},
{
"code": null,
"e": 4026,
"s": 3666,
"text": "Kedro is not a project structuring strategy, it’s a python tool released by QuantumBlack Labs, which does project structuring for you 😎. On top of it, they provide a plethora of features to make our project organization and even code execution process super-easy, so that we can truly focus on what matters the most — the experimentations and implementations!"
},
{
"code": null,
"e": 4193,
"s": 4026,
"text": "Their project structure is shown below. And btw, we can create a blank project by running kedro new command (don't forget to install kedro first by pip install kedro)"
},
{
"code": null,
"e": 4821,
"s": 4193,
"text": "get-started # Parent directory of the template├── conf # Project configuration files├── data # Local project data (not committed to version control)├── docs # Project documentation├── logs # Project output logs (not committed to version control)├── notebooks # Project related Jupyter notebooks (can be used for experimental code before moving the code to src)├── README.md # Project README├── setup.cfg # Configuration options for `pytest` when doing `kedro test` and for the `isort` utility when doing `kedro lint`└── src # Project source code"
},
{
"code": null,
"e": 5435,
"s": 4821,
"text": "While most of the directories are similar to other types, a few points should be noted. Kedro’s way of grouping different modules is by creating different ”pipelines”. These pipelines are present within src folder, which in turn contains the module files. Furthermore, they have clear segregation of individual functions which are executed - these are stored within nodes.py file, and these functions are later connected with the input and output within pipeline.py file *(all within the individual pipeline folder). Kedro also segregates the code and the parameters, by storing the parameters within conf folder."
},
{
"code": null,
"e": 5951,
"s": 5435,
"text": "Apart from just helping with organizing the project, they also provide options for sequential or parallel executions. We can execute individual functions (within nodes.py), or individual pipelines (which are a combination of functions), or the complete project at one go. We can also create doc of the complete project or compile and package the project as a python .whl file, with just a single command run. For more details, and believe me, we have just touched the surface, refer to their official documentation."
},
{
"code": null,
"e": 6209,
"s": 5951,
"text": "With a top-down approach, let’s first have a look at a neat piece of code. We will discuss individual aspects of the code in more detail later. For now, just assume if someone asks you to do some scripting, what an ideal piece of code file should look like."
},
{
"code": null,
"e": 6395,
"s": 6209,
"text": "The following code is taken from csv_column_operations.py module file. It was generated for the prompt: \"write a function which takes CSV file as input and returns the sum of a column\"."
},
{
"code": null,
"e": 6617,
"s": 6395,
"text": "Some might argue why do such an overkill for a simple piece of code. Note, it's a dummy example. In real life, you will develop more complex pieces of codes and hence it become quite important that we understand the gist."
},
{
"code": null,
"e": 6692,
"s": 6617,
"text": "Now let’s take a deeper dive into the individual aspect of the above code."
},
{
"code": null,
"e": 6801,
"s": 6692,
"text": "A module is a python file with .py extension that contains the executable code or functions or classes, etc."
},
{
"code": null,
"e": 7023,
"s": 6801,
"text": "Usually, we start the module with module definition, which is an area where we provide some basic details of the module. We can do so using the following template (and it can be easily compared to a real code shown above)"
},
{
"code": null,
"e": 7104,
"s": 7023,
"text": "\"\"\"<Short description><Long description>Author: <Name> <email>Created: <date>\"\"\""
},
{
"code": null,
"e": 7215,
"s": 7104,
"text": "Next, we should clearly segregate the parts of the module such as imports, code area, etc using comment lines."
},
{
"code": null,
"e": 7543,
"s": 7215,
"text": "Finally, at the bottom, we could include some examples on how to run the code. Including these scripts within if __name__ == '__main__': makes sure that they only run when the file is directly executed (like python csv_column_operations.py). So these pieces of code doesn't run when you say import the module in another script."
},
{
"code": null,
"e": 7796,
"s": 7543,
"text": "Functions are the basic block of code that performs a specific task. A module consists of several functions. To inform the user what a particular block of code does, we start the function with a function definition. A sample template is provided below,"
},
{
"code": null,
"e": 7952,
"s": 7796,
"text": "\"\"\"DescriptionParamters---------<parameter_1>: <data_type> <parameter_1_description>Returns---------<output_1>: <data_type> <output_1_description>\"\"\""
},
{
"code": null,
"e": 8101,
"s": 7952,
"text": "After this, we can start adding the relevant code lines. Make sure to separate different logical blocks of code within the functions using comments."
},
{
"code": null,
"e": 8532,
"s": 8101,
"text": "One important thing to handle at the start of the coding section is to check the parameters and input data for some data type or data content related basic issues. A majority of code break happens due to silly mistakes like when someone provides wrong input, in which case we should print or log warning message and gracefully exit. The above same code contains two such preliminary but important checks inside the step 1 section."
},
{
"code": null,
"e": 8808,
"s": 8532,
"text": "There are several formatting conventions that we can follow, like Camel Case, Snake case, etc. It’s quite subjective and depends on the developer. Below are some examples of naming different entities of a python code (taken from PIP8 conventions — with some modifications) 😇,"
},
{
"code": null,
"e": 8899,
"s": 8808,
"text": "Module name: Modules should have short, all-lowercase names (ex: csv_column_operations.py)"
},
{
"code": null,
"e": 9098,
"s": 8899,
"text": "Function or method name: Function names should be lowercase, with words separated by underscores as necessary to improve readability. Also, don’t forget to add your verbs! (ex: perform_column_sum())"
},
{
"code": null,
"e": 9180,
"s": 9098,
"text": "Variable name: Similar to function name but without the verbs! (ex: list_of_news)"
},
{
"code": null,
"e": 9263,
"s": 9180,
"text": "Class name: Class names should normally use the CapWords convention. (ex: FindMax)"
},
{
"code": null,
"e": 9426,
"s": 9263,
"text": "Constant name: Constants are usually defined on a module level and written in all capital letters with underscores separating words. (ex: MAX_OVERFLOW and TOTAL)."
},
{
"code": null,
"e": 9465,
"s": 9426,
"text": "PEP-8 defines three types of comments,"
},
{
"code": null,
"e": 9796,
"s": 9465,
"text": "Block comments: which is written for a single or a collection of code lines. This can be done either when you want to explain a set of lines or just want to segregate code. In the above example, you can see # Step {1, 2, 3} used as segregation comments and # run when file is directly executed used to explain a set of code lines."
},
{
"code": null,
"e": 9996,
"s": 9796,
"text": "Inline comments: which are added on the same line as the code. For example, see how # to handle csv files is used to justify the pandas package import. PEP-8 suggests using inline comments sparingly."
},
{
"code": null,
"e": 10271,
"s": 9996,
"text": "Documentation Strings: these are used for documentation for module, functions or classes. PEP-257 suggests using multiline comment for docstring (using “””). An example of module and function docstrings (short for documentation strings) is provided in the sample code above."
},
{
"code": null,
"e": 10638,
"s": 10271,
"text": "We should be as descriptive in our comments as possible. Try to separate functional sections of your code, provide explanations for complex code lines, provide details about the input/output of functions, etc. How do you know you have enough comments? — If you think someone with half your expertise can understand the code without calling you middle of the night! 😤"
},
{
"code": null,
"e": 10836,
"s": 10638,
"text": "Frankly, I am only going to touch this topic with a long stick 🧹. There are already several articles, reddit threads and even tv series (Silicon valley 📺) where this topic has been discussed a lot!"
},
{
"code": null,
"e": 10961,
"s": 10836,
"text": "Want my 2 cents? Pick any modern IDE (like VSCode, Sublime, etc), set indentations to tabs, and set 1 tab = 4 spaces. Done 😏"
},
{
"code": null,
"e": 11142,
"s": 10961,
"text": "Till now we have discussed how to either structure the project or format the code. Next, we will cover a generic set of good practices which will save you some pain down the line 😬"
},
{
"code": null,
"e": 11362,
"s": 11142,
"text": "Instead of printing statements in the console which is temporary (do a cls and poof it's gone💨), a better idea is to save these statements in a separate file, which you can always go back and refer to. This is logging 📜"
},
{
"code": null,
"e": 11481,
"s": 11362,
"text": "Python provides an inbuilt function for logging. By referring to the official how to, logging to a file is super easy,"
},
{
"code": null,
"e": 11739,
"s": 11481,
"text": "# importimport logging# config the logging behaviorlogging.basicConfig(filename='example.log',level=logging.DEBUG)# some sample log messageslogging.debug('This message should go to the log file')logging.info('So should this')logging.warning('And this, too')"
},
{
"code": null,
"e": 12091,
"s": 11739,
"text": "Note, there is a hierarchical levelling of logs to segregate different severity of logs. In the example shown above, the level parameter denotes the minimal level that is tracked and hence saved to the file. As per the official how to, these are the different logging levels with some details about when to use which (in increasing order of severity),"
},
{
"code": null,
"e": 12514,
"s": 12091,
"text": "Documentation of the code is an absolute must, if you are planning to maintain the code or hand it over to someone else in the foreseeable future. Just ask any developer about their excitement on finding ready-made and well-curated documentation for a package they are planning to use! On the other hand, it looks quite difficult to create one yourself, isn’t it? I mean, look at the beautiful docs of sklearn or pandas. 😮"
},
{
"code": null,
"e": 12951,
"s": 12514,
"text": "Well, sorry for the scare there, but actually it’s quite simple 😉. Remember all the function and module docstring and the formatting we followed before? As it turns out, we can leverage many open source tools like pydoc and sphinx to create full-fledged HTML documentations! Going into practical details is out of the scope of this article, but it is fairly easy to follow the “how to” steps of both the packages and get your doc ready."
},
{
"code": null,
"e": 13164,
"s": 12951,
"text": "One last thing, if you are using Kedro, this process is even simpler. All you have to do is run one command — kedro build-docs --open to create the documentation and automatically open it in your default browser!"
},
{
"code": null,
"e": 13478,
"s": 13164,
"text": "Virtual environments (VE) can be thought of as the local copy of the python environment, created specifically for a project. This local copy is like a blank slate, as any required package can be installed here separately. It is extremely important to create a new virtual environment for any new project, because,"
},
{
"code": null,
"e": 13617,
"s": 13478,
"text": "each project has its own dependency tree (one package with a specific version needs another package to run, with its own specific version)"
},
{
"code": null,
"e": 13762,
"s": 13617,
"text": "while developing a project we may need to downgrade or upgrade a package, which if done on the base python environment, will affect your system!"
},
{
"code": null,
"e": 13877,
"s": 13762,
"text": "hence, a separate copy of python (VE), where you install whatever you want, seems to be the most logical solution."
},
{
"code": null,
"e": 13916,
"s": 13877,
"text": "Using VE basically requires two steps,"
},
{
"code": null,
"e": 14107,
"s": 13916,
"text": "Create a VE: this can be done by running the command python3 -m venv tutorial-env at the project root directory. (note, tutorial-env is the name of the VE, you can use rename it to anything)"
},
{
"code": null,
"e": 14260,
"s": 14107,
"text": "Activate VE: this can be done by running the command tutorial-env\\Scripts\\activate.bat on Windows and source tutorial-env/bin/activate on Unix or MacOS."
},
{
"code": null,
"e": 14335,
"s": 14260,
"text": "And that’s it! Install, uninstall, upgrade or downgrade whatever you want!"
},
{
"code": null,
"e": 14472,
"s": 14335,
"text": "Remember to switch to another VE when you start working on another project or/and to deactivate the VE when you want to move to base VE."
},
{
"code": null,
"e": 14505,
"s": 14472,
"text": "PEP8 Style Guide for Python Code"
},
{
"code": null,
"e": 14511,
"s": 14505,
"text": "Kedro"
}
] |
IPython - IO Caching
|
The input and output cells on IPython console are numbered incrementally. In this chapter, let us look into IO caching in Python in detail.
In IPython, inputs are retrieved using up arrow key. Besides, all previous inputs are saved and can be retrieved. The variables _i, __i, and ___i always store the previous three input entries. In addition, In and _in variables provides lists of all inputs. Obviously _in[n] retrieves input from nth input cell. The following IPython session helps you to understand this phenomenon −
In [1]: print ("Hello")
Hello
In [2]: 2+2
Out[2]: 4
In [3]: x = 10
In [4]: y = 2
In [5]: pow(x,y)
Out[5]: 100
In [6]: _iii, _ii, _i
Out[6]: ('x = 10', 'y = 2', 'pow(x,y)')
In [7]: In
Out[7]:
['',
'print ("Hello")',
'2+2',
'x = 10',
'y = 2',
'pow(x,y)',
'_iii, _ii, _i',
'In'
]
In [8]: In[5] 9. IPython — IO
Out[8]: 'pow(x,y)'
In [9]: _ih
Out[9]:
['',
'print ("Hello")',
'2+2',
'x = 10',
'y = 2',
'pow(x,y)',
'_iii, _ii, _i',
'In',
'In[5]',
'_ih'
]
In [11]: _ih[4]
Out[11]: 'y = 2'
In [12]: In[1:4]
Out[12]: ['print ("Hello")', '2+2', 'x=10']
Similarly, single, double and triple underscores act as variables to store previous three outputs. Also Out and _oh form a dictionary object of cell number and output of cells performing action (not including assignment statements). To retrieve contents of specific output cell, use Out[n] or _oh[n]. You can also use slicing to get output cells within a range.
In [1]: print ("Hello")
Hello
In [2]: 2+2
Out[2]: 4
In [3]: x = 10
In [4]: y = 3
In [5]: pow(x,y)
Out[5]: 1000
In [6]: ___, __, _
Out[6]: ('', 4, 1000)
In [7]: Out
Out[7]: {2: 4, 5: 1000, 6: ('', 4, 1000)}
In [8]: _oh
Out[8]: {2: 4, 5: 1000, 6: ('', 4, 1000)}
In [9]: _5
Out[9]: 1000
In [10]: Out[6]
Out[10]: ('', 4, 1000)
22 Lectures
49 mins
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2800,
"s": 2660,
"text": "The input and output cells on IPython console are numbered incrementally. In this chapter, let us look into IO caching in Python in detail."
},
{
"code": null,
"e": 3183,
"s": 2800,
"text": "In IPython, inputs are retrieved using up arrow key. Besides, all previous inputs are saved and can be retrieved. The variables _i, __i, and ___i always store the previous three input entries. In addition, In and _in variables provides lists of all inputs. Obviously _in[n] retrieves input from nth input cell. The following IPython session helps you to understand this phenomenon −"
},
{
"code": null,
"e": 3789,
"s": 3183,
"text": "In [1]: print (\"Hello\")\nHello\n\nIn [2]: 2+2\nOut[2]: 4\n\nIn [3]: x = 10\n\nIn [4]: y = 2\n\nIn [5]: pow(x,y)\nOut[5]: 100\n\nIn [6]: _iii, _ii, _i\nOut[6]: ('x = 10', 'y = 2', 'pow(x,y)')\n\nIn [7]: In\nOut[7]:\n['',\n 'print (\"Hello\")',\n '2+2',\n 'x = 10',\n 'y = 2',\n 'pow(x,y)',\n '_iii, _ii, _i',\n 'In'\n]\n \nIn [8]: In[5] 9. IPython — IO\nOut[8]: 'pow(x,y)'\n\nIn [9]: _ih\nOut[9]:\n['',\n 'print (\"Hello\")',\n '2+2',\n 'x = 10',\n 'y = 2',\n 'pow(x,y)',\n '_iii, _ii, _i',\n 'In',\n 'In[5]',\n '_ih'\n]\n \nIn [11]: _ih[4]\nOut[11]: 'y = 2'\n\nIn [12]: In[1:4]\nOut[12]: ['print (\"Hello\")', '2+2', 'x=10']"
},
{
"code": null,
"e": 4151,
"s": 3789,
"text": "Similarly, single, double and triple underscores act as variables to store previous three outputs. Also Out and _oh form a dictionary object of cell number and output of cells performing action (not including assignment statements). To retrieve contents of specific output cell, use Out[n] or _oh[n]. You can also use slicing to get output cells within a range."
},
{
"code": null,
"e": 4483,
"s": 4151,
"text": "In [1]: print (\"Hello\")\nHello\n\nIn [2]: 2+2\nOut[2]: 4\n\nIn [3]: x = 10\n\nIn [4]: y = 3\n\nIn [5]: pow(x,y)\nOut[5]: 1000\n\nIn [6]: ___, __, _\nOut[6]: ('', 4, 1000)\n\nIn [7]: Out\nOut[7]: {2: 4, 5: 1000, 6: ('', 4, 1000)}\n\nIn [8]: _oh\nOut[8]: {2: 4, 5: 1000, 6: ('', 4, 1000)}\n\nIn [9]: _5\nOut[9]: 1000\n\nIn [10]: Out[6]\nOut[10]: ('', 4, 1000)"
},
{
"code": null,
"e": 4515,
"s": 4483,
"text": "\n 22 Lectures \n 49 mins\n"
},
{
"code": null,
"e": 4533,
"s": 4515,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4540,
"s": 4533,
"text": " Print"
},
{
"code": null,
"e": 4551,
"s": 4540,
"text": " Add Notes"
}
] |
Python – Negative index of Element in List
|
When it is required to get the negative index of an element in a list, the ‘len’ method and the ‘index’ method are used.
Below is a demonstration of the same −
Live Demo
my_list = [52, 47, 18, 22, 23, 57, 13]
print("The list is :")
print(my_list)
my_key = 22
print("The value of key is ")
print(my_key)
my_result = len(my_list) - my_list.index(my_key)
print("The result is :")
print(my_result)
The list is :
[52, 47, 18, 22, 23, 57, 13]
The value of key is
22
The result is :
4
A list of integers is defined and is displayed on the console.
A list of integers is defined and is displayed on the console.
A key is defined and is displayed on the console.
A key is defined and is displayed on the console.
The difference between the length of the list and element present at specific key is determined.
The difference between the length of the list and element present at specific key is determined.
This is assigned to a variable.
This is assigned to a variable.
This is displayed as output on the console.
This is displayed as output on the console.
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "When it is required to get the negative index of an element in a list, the ‘len’ method and the ‘index’ method are used."
},
{
"code": null,
"e": 1222,
"s": 1183,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1233,
"s": 1222,
"text": " Live Demo"
},
{
"code": null,
"e": 1461,
"s": 1233,
"text": "my_list = [52, 47, 18, 22, 23, 57, 13]\n\nprint(\"The list is :\")\nprint(my_list)\n\nmy_key = 22\nprint(\"The value of key is \")\nprint(my_key)\n\nmy_result = len(my_list) - my_list.index(my_key)\n\nprint(\"The result is :\")\nprint(my_result)"
},
{
"code": null,
"e": 1545,
"s": 1461,
"text": "The list is :\n[52, 47, 18, 22, 23, 57, 13]\nThe value of key is\n22\nThe result is :\n4"
},
{
"code": null,
"e": 1608,
"s": 1545,
"text": "A list of integers is defined and is displayed on the console."
},
{
"code": null,
"e": 1671,
"s": 1608,
"text": "A list of integers is defined and is displayed on the console."
},
{
"code": null,
"e": 1721,
"s": 1671,
"text": "A key is defined and is displayed on the console."
},
{
"code": null,
"e": 1771,
"s": 1721,
"text": "A key is defined and is displayed on the console."
},
{
"code": null,
"e": 1868,
"s": 1771,
"text": "The difference between the length of the list and element present at specific key is determined."
},
{
"code": null,
"e": 1965,
"s": 1868,
"text": "The difference between the length of the list and element present at specific key is determined."
},
{
"code": null,
"e": 1997,
"s": 1965,
"text": "This is assigned to a variable."
},
{
"code": null,
"e": 2029,
"s": 1997,
"text": "This is assigned to a variable."
},
{
"code": null,
"e": 2073,
"s": 2029,
"text": "This is displayed as output on the console."
},
{
"code": null,
"e": 2117,
"s": 2073,
"text": "This is displayed as output on the console."
}
] |
Apache Solr - Updating Data
|
Following is the XML file used to update a field in the existing document. Save this in a file with the name update.xml.
<add>
<doc>
<field name = "id">001</field>
<field name = "first name" update = "set">Raj</field>
<field name = "last name" update = "add">Malhotra</field>
<field name = "phone" update = "add">9000000000</field>
<field name = "city" update = "add">Delhi</field>
</doc>
</add>
As you can observe, the XML file written to update data is just like the one which we use to add documents. But the only difference is we use the update attribute of the field.
In our example, we will use the above document and try to update the fields of the document with the id 001.
Suppose the XML document exists in the bin directory of Solr. Since we are updating the index which exists in the core named my_core, you can update using the post tool as follows −
[Hadoop@localhost bin]$ ./post -c my_core update.xml
On executing the above command, you will get the following output.
/home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core
6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files
org.apache.Solr.util.SimplePostTool update.xml
SimplePostTool version 5.0.0
Posting files to [base] url http://localhost:8983/Solr/my_core/update...
Entering auto mode. File endings considered are
xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,
htm,html,txt,log
POSTing file update.xml (application/xml) to [base]
1 files indexed.
COMMITting Solr index changes to http://localhost:8983/Solr/my_core/update...
Time spent: 0:00:00.159
Visit the homepage of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the document is updated.
Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name UpdatingDocument.java.
import java.io.IOException;
import org.apache.Solr.client.Solrj.SolrClient;
import org.apache.Solr.client.Solrj.SolrServerException;
import org.apache.Solr.client.Solrj.impl.HttpSolrClient;
import org.apache.Solr.client.Solrj.request.UpdateRequest;
import org.apache.Solr.client.Solrj.response.UpdateResponse;
import org.apache.Solr.common.SolrInputDocument;
public class UpdatingDocument {
public static void main(String args[]) throws SolrServerException, IOException {
//Preparing the Solr client
String urlString = "http://localhost:8983/Solr/my_core";
SolrClient Solr = new HttpSolrClient.Builder(urlString).build();
//Preparing the Solr document
SolrInputDocument doc = new SolrInputDocument();
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.setAction( UpdateRequest.ACTION.COMMIT, false, false);
SolrInputDocument myDocumentInstantlycommited = new SolrInputDocument();
myDocumentInstantlycommited.addField("id", "002");
myDocumentInstantlycommited.addField("name", "Rahman");
myDocumentInstantlycommited.addField("age","27");
myDocumentInstantlycommited.addField("addr","hyderabad");
updateRequest.add( myDocumentInstantlycommited);
UpdateResponse rsp = updateRequest.process(Solr);
System.out.println("Documents Updated");
}
}
Compile the above code by executing the following commands in the terminal −
[Hadoop@localhost bin]$ javac UpdatingDocument
[Hadoop@localhost bin]$ java UpdatingDocument
On executing the above command, you will get the following output.
Documents updated
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": 2145,
"s": 2024,
"text": "Following is the XML file used to update a field in the existing document. Save this in a file with the name update.xml."
},
{
"code": null,
"e": 2487,
"s": 2145,
"text": "<add> \n <doc> \n <field name = \"id\">001</field> \n <field name = \"first name\" update = \"set\">Raj</field> \n <field name = \"last name\" update = \"add\">Malhotra</field> \n <field name = \"phone\" update = \"add\">9000000000</field> \n <field name = \"city\" update = \"add\">Delhi</field> \n </doc> \n</add>"
},
{
"code": null,
"e": 2664,
"s": 2487,
"text": "As you can observe, the XML file written to update data is just like the one which we use to add documents. But the only difference is we use the update attribute of the field."
},
{
"code": null,
"e": 2773,
"s": 2664,
"text": "In our example, we will use the above document and try to update the fields of the document with the id 001."
},
{
"code": null,
"e": 2955,
"s": 2773,
"text": "Suppose the XML document exists in the bin directory of Solr. Since we are updating the index which exists in the core named my_core, you can update using the post tool as follows −"
},
{
"code": null,
"e": 3010,
"s": 2955,
"text": "[Hadoop@localhost bin]$ ./post -c my_core update.xml \n"
},
{
"code": null,
"e": 3077,
"s": 3010,
"text": "On executing the above command, you will get the following output."
},
{
"code": null,
"e": 3675,
"s": 3077,
"text": "/home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core\n6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files \norg.apache.Solr.util.SimplePostTool update.xml \nSimplePostTool version 5.0.0 \nPosting files to [base] url http://localhost:8983/Solr/my_core/update... \nEntering auto mode. File endings considered are \nxml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,\nhtm,html,txt,log \nPOSTing file update.xml (application/xml) to [base] \n1 files indexed. \nCOMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... \nTime spent: 0:00:00.159 \n"
},
{
"code": null,
"e": 3916,
"s": 3675,
"text": "Visit the homepage of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the document is updated."
},
{
"code": null,
"e": 4047,
"s": 3916,
"text": "Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name UpdatingDocument.java."
},
{
"code": null,
"e": 5457,
"s": 4047,
"text": "import java.io.IOException; \n\nimport org.apache.Solr.client.Solrj.SolrClient; \nimport org.apache.Solr.client.Solrj.SolrServerException; \nimport org.apache.Solr.client.Solrj.impl.HttpSolrClient; \nimport org.apache.Solr.client.Solrj.request.UpdateRequest; \nimport org.apache.Solr.client.Solrj.response.UpdateResponse;\nimport org.apache.Solr.common.SolrInputDocument; \n\npublic class UpdatingDocument { \n public static void main(String args[]) throws SolrServerException, IOException { \n //Preparing the Solr client \n String urlString = \"http://localhost:8983/Solr/my_core\"; \n SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); \n \n //Preparing the Solr document \n SolrInputDocument doc = new SolrInputDocument(); \n \n UpdateRequest updateRequest = new UpdateRequest(); \n updateRequest.setAction( UpdateRequest.ACTION.COMMIT, false, false); \n SolrInputDocument myDocumentInstantlycommited = new SolrInputDocument(); \n \n myDocumentInstantlycommited.addField(\"id\", \"002\"); \n myDocumentInstantlycommited.addField(\"name\", \"Rahman\"); \n myDocumentInstantlycommited.addField(\"age\",\"27\"); \n myDocumentInstantlycommited.addField(\"addr\",\"hyderabad\"); \n \n updateRequest.add( myDocumentInstantlycommited); \n UpdateResponse rsp = updateRequest.process(Solr); \n System.out.println(\"Documents Updated\"); \n } \n}"
},
{
"code": null,
"e": 5534,
"s": 5457,
"text": "Compile the above code by executing the following commands in the terminal −"
},
{
"code": null,
"e": 5630,
"s": 5534,
"text": "[Hadoop@localhost bin]$ javac UpdatingDocument \n[Hadoop@localhost bin]$ java UpdatingDocument \n"
},
{
"code": null,
"e": 5697,
"s": 5630,
"text": "On executing the above command, you will get the following output."
},
{
"code": null,
"e": 5717,
"s": 5697,
"text": "Documents updated \n"
},
{
"code": null,
"e": 5752,
"s": 5717,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5771,
"s": 5752,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5806,
"s": 5771,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5827,
"s": 5806,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5860,
"s": 5827,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5873,
"s": 5860,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5908,
"s": 5873,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5926,
"s": 5908,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5959,
"s": 5926,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5977,
"s": 5959,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6010,
"s": 5977,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6028,
"s": 6010,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6035,
"s": 6028,
"text": " Print"
},
{
"code": null,
"e": 6046,
"s": 6035,
"text": " Add Notes"
}
] |
Tryit Editor v3.7
|
Tryit: Transition + transform
|
[] |
C++ Program to Implement Stack using array
|
A stack is an abstract data structure that contains a collection of elements. Stack implements the LIFO mechanism i.e. the element that is pushed at the end is popped out first. Some of the principle operations in the stack are −
Push - This adds a data value to the top of the stack.
Push - This adds a data value to the top of the stack.
Pop - This removes the data value on top of the stack
Pop - This removes the data value on top of the stack
Peek - This returns the top data value of the stack
Peek - This returns the top data value of the stack
A program that implements a stack using array is given as follows.
#include <iostream>
using namespace std;
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}
1) Push in stack
2) Pop from stack
3) Display stack
4) Exit
Enter choice: 1
Enter value to be pushed: 2
Enter choice: 1
Enter value to be pushed: 6
Enter choice: 1
Enter value to be pushed: 8
Enter choice: 1
Enter value to be pushed: 7
Enter choice: 2
The popped element is 7
Enter choice: 3
Stack elements are:8 6 2
Enter choice: 5
Invalid Choice
Enter choice: 4
Exit
In the above program, the push() function takes argument val i.e. value to be pushed into the stack. If a top is greater than or equal to n, there is no space in a stack and overflow is printed. Otherwise, val is pushed into the stack. The code snippet for this is as follows.
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
The pop() function pops the topmost value of the stack, if there is any value. If the stack is empty then underflow is printed. This is given as follows.
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
The display() function displays all the elements in the stack. It uses a for loop to do so. If there are no elements in the stack, then Stack is empty is printed. This is given below.
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
}else
cout<<"Stack is empty";
}
The function main() provides a choice to the user if they want to push, pop or display the stack. According to the user response, the appropriate function is called using switch. If the user enters an invalid response, then that is printed. The code snippet for this is given below.
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}
|
[
{
"code": null,
"e": 1292,
"s": 1062,
"text": "A stack is an abstract data structure that contains a collection of elements. Stack implements the LIFO mechanism i.e. the element that is pushed at the end is popped out first. Some of the principle operations in the stack are −"
},
{
"code": null,
"e": 1347,
"s": 1292,
"text": "Push - This adds a data value to the top of the stack."
},
{
"code": null,
"e": 1402,
"s": 1347,
"text": "Push - This adds a data value to the top of the stack."
},
{
"code": null,
"e": 1456,
"s": 1402,
"text": "Pop - This removes the data value on top of the stack"
},
{
"code": null,
"e": 1510,
"s": 1456,
"text": "Pop - This removes the data value on top of the stack"
},
{
"code": null,
"e": 1562,
"s": 1510,
"text": "Peek - This returns the top data value of the stack"
},
{
"code": null,
"e": 1614,
"s": 1562,
"text": "Peek - This returns the top data value of the stack"
},
{
"code": null,
"e": 1681,
"s": 1614,
"text": "A program that implements a stack using array is given as follows."
},
{
"code": null,
"e": 2930,
"s": 1681,
"text": "#include <iostream>\nusing namespace std;\nint stack[100], n=100, top=-1;\nvoid push(int val) {\n if(top>=n-1)\n cout<<\"Stack Overflow\"<<endl;\n else {\n top++;\n stack[top]=val;\n }\n}\nvoid pop() {\n if(top<=-1)\n cout<<\"Stack Underflow\"<<endl;\n else {\n cout<<\"The popped element is \"<< stack[top] <<endl;\n top--;\n }\n}\nvoid display() {\n if(top>=0) {\n cout<<\"Stack elements are:\";\n for(int i=top; i>=0; i--)\n cout<<stack[i]<<\" \";\n cout<<endl;\n } else\n cout<<\"Stack is empty\";\n}\nint main() {\n int ch, val;\n cout<<\"1) Push in stack\"<<endl;\n cout<<\"2) Pop from stack\"<<endl;\n cout<<\"3) Display stack\"<<endl;\n cout<<\"4) Exit\"<<endl;\n do {\n cout<<\"Enter choice: \"<<endl;\n cin>>ch;\n switch(ch) {\n case 1: {\n cout<<\"Enter value to be pushed:\"<<endl;\n cin>>val;\n push(val);\n break;\n }\n case 2: {\n pop();\n break;\n }\n case 3: {\n display();\n break;\n }\n case 4: {\n cout<<\"Exit\"<<endl;\n break;\n }\n default: {\n cout<<\"Invalid Choice\"<<endl;\n }\n }\n }while(ch!=4);\n return 0;\n}"
},
{
"code": null,
"e": 3300,
"s": 2930,
"text": "1) Push in stack\n2) Pop from stack\n3) Display stack\n4) Exit\n\nEnter choice: 1\nEnter value to be pushed: 2\nEnter choice: 1\nEnter value to be pushed: 6\nEnter choice: 1\nEnter value to be pushed: 8\nEnter choice: 1\nEnter value to be pushed: 7\nEnter choice: 2\nThe popped element is 7\nEnter choice: 3\nStack elements are:8 6 2\nEnter choice: 5\nInvalid Choice\nEnter choice: 4\nExit"
},
{
"code": null,
"e": 3577,
"s": 3300,
"text": "In the above program, the push() function takes argument val i.e. value to be pushed into the stack. If a top is greater than or equal to n, there is no space in a stack and overflow is printed. Otherwise, val is pushed into the stack. The code snippet for this is as follows."
},
{
"code": null,
"e": 3699,
"s": 3577,
"text": "void push(int val) {\n if(top>=n-1)\n cout<<\"Stack Overflow\"<<endl;\n else {\n top++;\n stack[top]=val;\n }\n}"
},
{
"code": null,
"e": 3853,
"s": 3699,
"text": "The pop() function pops the topmost value of the stack, if there is any value. If the stack is empty then underflow is printed. This is given as follows."
},
{
"code": null,
"e": 4003,
"s": 3853,
"text": "void pop() {\n if(top<=-1)\n cout<<\"Stack Underflow\"<<endl;\n else {\n cout<<\"The popped element is \"<< stack[top] <<endl;\n top--;\n }\n}"
},
{
"code": null,
"e": 4187,
"s": 4003,
"text": "The display() function displays all the elements in the stack. It uses a for loop to do so. If there are no elements in the stack, then Stack is empty is printed. This is given below."
},
{
"code": null,
"e": 4370,
"s": 4187,
"text": "void display() {\n if(top>=0) {\n cout<<\"Stack elements are:\";\n for(int i=top; i>=0; i--)\n cout<<stack[i]<<\" \";\n cout<<endl;\n }else\n cout<<\"Stack is empty\";\n}"
},
{
"code": null,
"e": 4653,
"s": 4370,
"text": "The function main() provides a choice to the user if they want to push, pop or display the stack. According to the user response, the appropriate function is called using switch. If the user enters an invalid response, then that is printed. The code snippet for this is given below."
},
{
"code": null,
"e": 5374,
"s": 4653,
"text": "int main() {\n int ch, val;\n cout<<\"1) Push in stack\"<<endl;\n cout<<\"2) Pop from stack\"<<endl;\n cout<<\"3) Display stack\"<<endl;\n cout<<\"4) Exit\"<<endl;\n do {\n cout<<\"Enter choice: \"<<endl;\n cin>>ch;\n switch(ch) {\n case 1: {\n cout<<\"Enter value to be pushed:\"<<endl;\n cin>>val;\n push(val);\n break;\n }\n case 2: {\n pop();\n break;\n }\n case 3: {\n display();\n break;\n }\n case 4: {\n cout<<\"Exit\"<<endl;\n break;\n }\n default: {\n cout<<\"Invalid Choice\"<<endl;\n }\n }\n }while(ch!=4);\n return 0;\n}"
}
] |
Knapsack with large Weights - GeeksforGeeks
|
26 Nov, 2021
Given a knapsack with capacity C and two arrays w[] and val[] representing the weights and values of N distinct items, the task is to find the maximum value you can put into the knapsack. Items cannot be broken and an item with weight X takes X capacity of the knapsack.
Examples:
Input: w[] = {3, 4, 5}, val[] = {30, 50, 60}, C = 8 Output: 90 We take objects ‘1’ and ‘3’. The total value we get is (30 + 60) = 90. Total weight is 8, thus it fits in the given capacity
Input: w[] = {10000}, val[] = {10}, C = 100000 Output: 10
Approach: The traditional famous 0-1 knapsack problem can be solved in O(N*C) time but if the capacity of the knapsack is huge then a 2D N*C array can’t make be made. Luckily, it can be solved by redefining the states of the dp. Let’s have a look at the states of the DP first.dp[V][i] represents the minimum weight subset of the subarray arr[i...N-1] required to get a value of at least V. The recurrence relation will be:
dp[V][i] = min(dp[V][i+1], w[i] + dp[V – val[i]][i + 1])
So, for each V from 0 to the maximum value of V possible, try to find if the given V can be represented with the given array. The largest such V that can be represented becomes the required answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define V_SUM_MAX 1000#define N_MAX 100#define W_MAX 10000000 // To store the states of DPint dp[V_SUM_MAX + 1][N_MAX];bool v[V_SUM_MAX + 1][N_MAX]; // Function to solve the recurrence relationint solveDp(int r, int i, vector<int>& w, vector<int>& val, int n){ // Base cases if (r <= 0) return 0; if (i == n) return W_MAX; if (v[r][i]) return dp[r][i]; // Marking state as solved v[r][i] = 1; // Recurrence relation dp[r][i] = min(solveDp(r, i + 1, w, val, n), w[i] + solveDp(r - val[i], i + 1, w, val, n)); return dp[r][i];} // Function to return the maximum weightint maxWeight(vector<int>& w, vector<int>& val, int n, int c){ // Iterating through all possible values // to find the the largest value that can // be represented by the given weights for (int i = V_SUM_MAX; i >= 0; i--) { if (solveDp(i, 0, w, val, n) <= c) { return i; } } return 0;} // Driver codeint main(){ vector<int> w = { 3, 4, 5 }; vector<int> val = { 30, 50, 60 }; int n = (int)w.size(); int C = 8; cout << maxWeight(w, val, n, C); return 0;}
// Java implementation of the approachclass GFG{ static final int V_SUM_MAX = 1000; static final int N_MAX = 100; static final int W_MAX = 10000000; // To store the states of DP static int dp[][] = new int[V_SUM_MAX + 1][N_MAX]; static boolean v[][] = new boolean [V_SUM_MAX + 1][N_MAX]; // Function to solve the recurrence relation static int solveDp(int r, int i, int w[], int val[], int n) { // Base cases if (r <= 0) return 0; if (i == n) return W_MAX; if (v[r][i]) return dp[r][i]; // Marking state as solved v[r][i] = true; // Recurrence relation dp[r][i] = Math.min(solveDp(r, i + 1, w, val, n), w[i] + solveDp(r - val[i], i + 1, w, val, n)); return dp[r][i]; } // Function to return the maximum weight static int maxWeight(int w[], int val[], int n, int c) { // Iterating through all possible values // to find the the largest value that can // be represented by the given weights for (int i = V_SUM_MAX; i >= 0; i--) { if (solveDp(i, 0, w, val, n) <= c) { return i; } } return 0; } // Driver code public static void main (String[] args) { int w[] = { 3, 4, 5 }; int val[] = { 30, 50, 60 }; int n = w.length; int C = 8; System.out.println(maxWeight(w, val, n, C)); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approachV_SUM_MAX = 1000N_MAX = 100W_MAX = 10000000 # To store the states of DPdp = [[ 0 for i in range(N_MAX)] for i in range(V_SUM_MAX + 1)]v = [[ 0 for i in range(N_MAX)] for i in range(V_SUM_MAX + 1)] # Function to solve the recurrence relationdef solveDp(r, i, w, val, n): # Base cases if (r <= 0): return 0 if (i == n): return W_MAX if (v[r][i]): return dp[r][i] # Marking state as solved v[r][i] = 1 # Recurrence relation dp[r][i] = min(solveDp(r, i + 1, w, val, n), w[i] + solveDp(r - val[i], i + 1, w, val, n)) return dp[r][i] # Function to return the maximum weightdef maxWeight( w, val, n, c): # Iterating through all possible values # to find the the largest value that can # be represented by the given weights for i in range(V_SUM_MAX, -1, -1): if (solveDp(i, 0, w, val, n) <= c): return i return 0 # Driver codeif __name__ == '__main__': w = [3, 4, 5] val = [30, 50, 60] n = len(w) C = 8 print(maxWeight(w, val, n, C)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG{ static readonly int V_SUM_MAX = 1000; static readonly int N_MAX = 100; static readonly int W_MAX = 10000000; // To store the states of DP static int [,]dp = new int[V_SUM_MAX + 1, N_MAX]; static bool [,]v = new bool [V_SUM_MAX + 1, N_MAX]; // Function to solve the recurrence relation static int solveDp(int r, int i, int []w, int []val, int n) { // Base cases if (r <= 0) return 0; if (i == n) return W_MAX; if (v[r, i]) return dp[r, i]; // Marking state as solved v[r, i] = true; // Recurrence relation dp[r, i] = Math.Min(solveDp(r, i + 1, w, val, n), w[i] + solveDp(r - val[i], i + 1, w, val, n)); return dp[r, i]; } // Function to return the maximum weight static int maxWeight(int []w, int []val, int n, int c) { // Iterating through all possible values // to find the the largest value that can // be represented by the given weights for (int i = V_SUM_MAX; i >= 0; i--) { if (solveDp(i, 0, w, val, n) <= c) { return i; } } return 0; } // Driver code public static void Main(String[] args) { int []w = { 3, 4, 5 }; int []val = { 30, 50, 60 }; int n = w.Length; int C = 8; Console.WriteLine(maxWeight(w, val, n, C)); }} // This code is contributed by 29AjayKumar
<script> // Javascript implementation of the approach var V_SUM_MAX = 1000var N_MAX = 100var W_MAX = 10000000 // To store the states of DPvar dp = Array.from(Array(V_SUM_MAX+1), ()=> Array(N_MAX));var v = Array.from(Array(V_SUM_MAX+1), ()=> Array(N_MAX)); // Function to solve the recurrence relationfunction solveDp(r, i, w, val, n){ // Base cases if (r <= 0) return 0; if (i == n) return W_MAX; if (v[r][i]) return dp[r][i]; // Marking state as solved v[r][i] = 1; // Recurrence relation dp[r][i] = Math.min(solveDp(r, i + 1, w, val, n), w[i] + solveDp(r - val[i], i + 1, w, val, n)); return dp[r][i];} // Function to return the maximum weightfunction maxWeight(w, val, n, c){ // Iterating through all possible values // to find the the largest value that can // be represented by the given weights for (var i = V_SUM_MAX; i >= 0; i--) { if (solveDp(i, 0, w, val, n) <= c) { return i; } } return 0;} // Driver codevar w = [3, 4, 5];var val = [30, 50, 60];var n = w.length;var C = 8;document.write( maxWeight(w, val, n, C)); </script>
90
Time Complexity: O(V_sum * N) where V_sum is the sum of all the values in the array val[].
Auxiliary Space : O(V_sum * N) where V_sum is the sum of all the values in the array val[].
mohit kumar 29
ankthon
29AjayKumar
kshitizsrivastava
itsok
ashutoshsinghgeeksforgeeks
knapsack
Algorithms
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
K means Clustering - Introduction
Quadratic Probing in Hashing
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation
|
[
{
"code": null,
"e": 26053,
"s": 26025,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 26324,
"s": 26053,
"text": "Given a knapsack with capacity C and two arrays w[] and val[] representing the weights and values of N distinct items, the task is to find the maximum value you can put into the knapsack. Items cannot be broken and an item with weight X takes X capacity of the knapsack."
},
{
"code": null,
"e": 26335,
"s": 26324,
"text": "Examples: "
},
{
"code": null,
"e": 26523,
"s": 26335,
"text": "Input: w[] = {3, 4, 5}, val[] = {30, 50, 60}, C = 8 Output: 90 We take objects ‘1’ and ‘3’. The total value we get is (30 + 60) = 90. Total weight is 8, thus it fits in the given capacity"
},
{
"code": null,
"e": 26583,
"s": 26523,
"text": "Input: w[] = {10000}, val[] = {10}, C = 100000 Output: 10 "
},
{
"code": null,
"e": 27008,
"s": 26583,
"text": "Approach: The traditional famous 0-1 knapsack problem can be solved in O(N*C) time but if the capacity of the knapsack is huge then a 2D N*C array can’t make be made. Luckily, it can be solved by redefining the states of the dp. Let’s have a look at the states of the DP first.dp[V][i] represents the minimum weight subset of the subarray arr[i...N-1] required to get a value of at least V. The recurrence relation will be: "
},
{
"code": null,
"e": 27067,
"s": 27008,
"text": "dp[V][i] = min(dp[V][i+1], w[i] + dp[V – val[i]][i + 1]) "
},
{
"code": null,
"e": 27265,
"s": 27067,
"text": "So, for each V from 0 to the maximum value of V possible, try to find if the given V can be represented with the given array. The largest such V that can be represented becomes the required answer."
},
{
"code": null,
"e": 27317,
"s": 27265,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27321,
"s": 27317,
"text": "C++"
},
{
"code": null,
"e": 27326,
"s": 27321,
"text": "Java"
},
{
"code": null,
"e": 27334,
"s": 27326,
"text": "Python3"
},
{
"code": null,
"e": 27337,
"s": 27334,
"text": "C#"
},
{
"code": null,
"e": 27348,
"s": 27337,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define V_SUM_MAX 1000#define N_MAX 100#define W_MAX 10000000 // To store the states of DPint dp[V_SUM_MAX + 1][N_MAX];bool v[V_SUM_MAX + 1][N_MAX]; // Function to solve the recurrence relationint solveDp(int r, int i, vector<int>& w, vector<int>& val, int n){ // Base cases if (r <= 0) return 0; if (i == n) return W_MAX; if (v[r][i]) return dp[r][i]; // Marking state as solved v[r][i] = 1; // Recurrence relation dp[r][i] = min(solveDp(r, i + 1, w, val, n), w[i] + solveDp(r - val[i], i + 1, w, val, n)); return dp[r][i];} // Function to return the maximum weightint maxWeight(vector<int>& w, vector<int>& val, int n, int c){ // Iterating through all possible values // to find the the largest value that can // be represented by the given weights for (int i = V_SUM_MAX; i >= 0; i--) { if (solveDp(i, 0, w, val, n) <= c) { return i; } } return 0;} // Driver codeint main(){ vector<int> w = { 3, 4, 5 }; vector<int> val = { 30, 50, 60 }; int n = (int)w.size(); int C = 8; cout << maxWeight(w, val, n, C); return 0;}",
"e": 28611,
"s": 27348,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ static final int V_SUM_MAX = 1000; static final int N_MAX = 100; static final int W_MAX = 10000000; // To store the states of DP static int dp[][] = new int[V_SUM_MAX + 1][N_MAX]; static boolean v[][] = new boolean [V_SUM_MAX + 1][N_MAX]; // Function to solve the recurrence relation static int solveDp(int r, int i, int w[], int val[], int n) { // Base cases if (r <= 0) return 0; if (i == n) return W_MAX; if (v[r][i]) return dp[r][i]; // Marking state as solved v[r][i] = true; // Recurrence relation dp[r][i] = Math.min(solveDp(r, i + 1, w, val, n), w[i] + solveDp(r - val[i], i + 1, w, val, n)); return dp[r][i]; } // Function to return the maximum weight static int maxWeight(int w[], int val[], int n, int c) { // Iterating through all possible values // to find the the largest value that can // be represented by the given weights for (int i = V_SUM_MAX; i >= 0; i--) { if (solveDp(i, 0, w, val, n) <= c) { return i; } } return 0; } // Driver code public static void main (String[] args) { int w[] = { 3, 4, 5 }; int val[] = { 30, 50, 60 }; int n = w.length; int C = 8; System.out.println(maxWeight(w, val, n, C)); }} // This code is contributed by AnkitRai01",
"e": 30296,
"s": 28611,
"text": null
},
{
"code": "# Python3 implementation of the approachV_SUM_MAX = 1000N_MAX = 100W_MAX = 10000000 # To store the states of DPdp = [[ 0 for i in range(N_MAX)] for i in range(V_SUM_MAX + 1)]v = [[ 0 for i in range(N_MAX)] for i in range(V_SUM_MAX + 1)] # Function to solve the recurrence relationdef solveDp(r, i, w, val, n): # Base cases if (r <= 0): return 0 if (i == n): return W_MAX if (v[r][i]): return dp[r][i] # Marking state as solved v[r][i] = 1 # Recurrence relation dp[r][i] = min(solveDp(r, i + 1, w, val, n), w[i] + solveDp(r - val[i], i + 1, w, val, n)) return dp[r][i] # Function to return the maximum weightdef maxWeight( w, val, n, c): # Iterating through all possible values # to find the the largest value that can # be represented by the given weights for i in range(V_SUM_MAX, -1, -1): if (solveDp(i, 0, w, val, n) <= c): return i return 0 # Driver codeif __name__ == '__main__': w = [3, 4, 5] val = [30, 50, 60] n = len(w) C = 8 print(maxWeight(w, val, n, C)) # This code is contributed by Mohit Kumar",
"e": 31465,
"s": 30296,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static readonly int V_SUM_MAX = 1000; static readonly int N_MAX = 100; static readonly int W_MAX = 10000000; // To store the states of DP static int [,]dp = new int[V_SUM_MAX + 1, N_MAX]; static bool [,]v = new bool [V_SUM_MAX + 1, N_MAX]; // Function to solve the recurrence relation static int solveDp(int r, int i, int []w, int []val, int n) { // Base cases if (r <= 0) return 0; if (i == n) return W_MAX; if (v[r, i]) return dp[r, i]; // Marking state as solved v[r, i] = true; // Recurrence relation dp[r, i] = Math.Min(solveDp(r, i + 1, w, val, n), w[i] + solveDp(r - val[i], i + 1, w, val, n)); return dp[r, i]; } // Function to return the maximum weight static int maxWeight(int []w, int []val, int n, int c) { // Iterating through all possible values // to find the the largest value that can // be represented by the given weights for (int i = V_SUM_MAX; i >= 0; i--) { if (solveDp(i, 0, w, val, n) <= c) { return i; } } return 0; } // Driver code public static void Main(String[] args) { int []w = { 3, 4, 5 }; int []val = { 30, 50, 60 }; int n = w.Length; int C = 8; Console.WriteLine(maxWeight(w, val, n, C)); }} // This code is contributed by 29AjayKumar",
"e": 33157,
"s": 31465,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach var V_SUM_MAX = 1000var N_MAX = 100var W_MAX = 10000000 // To store the states of DPvar dp = Array.from(Array(V_SUM_MAX+1), ()=> Array(N_MAX));var v = Array.from(Array(V_SUM_MAX+1), ()=> Array(N_MAX)); // Function to solve the recurrence relationfunction solveDp(r, i, w, val, n){ // Base cases if (r <= 0) return 0; if (i == n) return W_MAX; if (v[r][i]) return dp[r][i]; // Marking state as solved v[r][i] = 1; // Recurrence relation dp[r][i] = Math.min(solveDp(r, i + 1, w, val, n), w[i] + solveDp(r - val[i], i + 1, w, val, n)); return dp[r][i];} // Function to return the maximum weightfunction maxWeight(w, val, n, c){ // Iterating through all possible values // to find the the largest value that can // be represented by the given weights for (var i = V_SUM_MAX; i >= 0; i--) { if (solveDp(i, 0, w, val, n) <= c) { return i; } } return 0;} // Driver codevar w = [3, 4, 5];var val = [30, 50, 60];var n = w.length;var C = 8;document.write( maxWeight(w, val, n, C)); </script>",
"e": 34335,
"s": 33157,
"text": null
},
{
"code": null,
"e": 34338,
"s": 34335,
"text": "90"
},
{
"code": null,
"e": 34431,
"s": 34340,
"text": "Time Complexity: O(V_sum * N) where V_sum is the sum of all the values in the array val[]."
},
{
"code": null,
"e": 34524,
"s": 34431,
"text": "Auxiliary Space : O(V_sum * N) where V_sum is the sum of all the values in the array val[]. "
},
{
"code": null,
"e": 34539,
"s": 34524,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34547,
"s": 34539,
"text": "ankthon"
},
{
"code": null,
"e": 34559,
"s": 34547,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34577,
"s": 34559,
"text": "kshitizsrivastava"
},
{
"code": null,
"e": 34583,
"s": 34577,
"text": "itsok"
},
{
"code": null,
"e": 34610,
"s": 34583,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 34619,
"s": 34610,
"text": "knapsack"
},
{
"code": null,
"e": 34630,
"s": 34619,
"text": "Algorithms"
},
{
"code": null,
"e": 34637,
"s": 34630,
"text": "Arrays"
},
{
"code": null,
"e": 34657,
"s": 34637,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34664,
"s": 34657,
"text": "Arrays"
},
{
"code": null,
"e": 34684,
"s": 34664,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34695,
"s": 34684,
"text": "Algorithms"
},
{
"code": null,
"e": 34793,
"s": 34695,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34818,
"s": 34793,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 34845,
"s": 34818,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 34879,
"s": 34845,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 34908,
"s": 34879,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 34975,
"s": 34908,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 34990,
"s": 34975,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35006,
"s": 34990,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 35074,
"s": 35006,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 35120,
"s": 35074,
"text": "Write a program to reverse an array or string"
}
] |
Array set() method in Java - GeeksforGeeks
|
30 Nov, 2018
The java.lang.reflect.Array.set() is an inbuilt method in Java and is used to set a specified value to a specified index of a given object array.
Syntax
Array.set(Object []array, int index, Object value)
Parameter :
array : This is an array of type Object which is to be updated.
index : This is the index of the array which is to be updated.
value : This is the value that is to be set at the given index of the given array
Return type : This is a void type method this doesn’t returns any value. The update reflects upon the Object array passed as the argument.
Exception : This method throws following exception.
NullPointerException – when the array is null.
IllegalArgumentException – when the given object array is not an Array.
ArrayIndexOutOfBoundsException – if the given index is not in the range of the size of the array.Below programs illustrate the Array.set() method:Program 1 :// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = { "Geeks", "is", "Geeks" }; System.out.print("Befor Set : "); // printing the array for (String x : s) { System.out.print(x); } // set method of class Array Array.set(s, 1, "for"); System.out.print("\nAfter Set : "); // printing array for (String x : s) { System.out.print(x); } }}Output:Befor Set : GeeksisGeeks
After Set : GeeksforGeeks
Program 2 : to demonstrate java.lang.NullPointerException// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = null; try { // set method of class Array Array.set(s, 1, "for"); } catch (Exception e) { System.out.println("Exception : " + e); } }}Output:Exception : java.lang.NullPointerException
Program 3 : to demonstrate java.lang.ArrayIndexOutOfBoundsException// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = { "Geeks", "for", "Geeks" }; try { // set method of class Array Array.set(s, 4, "for"); } catch (Exception e) { System.out.println("Exception : " + e); } }}Output:Exception : java.lang.ArrayIndexOutOfBoundsException
Program 4 : to demonstrate java.lang.IllegalArgumentException// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s = "GeeksforGeeks"; try { // set method of class Array Array.set(s, 4, "for"); } catch (Exception e) { System.out.println("Exception : " + e); } }}Output:Exception : java.lang.IllegalArgumentException: Argument is not an array
My Personal Notes
arrow_drop_upSave
Below programs illustrate the Array.set() method:
Program 1 :
// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = { "Geeks", "is", "Geeks" }; System.out.print("Befor Set : "); // printing the array for (String x : s) { System.out.print(x); } // set method of class Array Array.set(s, 1, "for"); System.out.print("\nAfter Set : "); // printing array for (String x : s) { System.out.print(x); } }}
Befor Set : GeeksisGeeks
After Set : GeeksforGeeks
Program 2 : to demonstrate java.lang.NullPointerException
// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = null; try { // set method of class Array Array.set(s, 1, "for"); } catch (Exception e) { System.out.println("Exception : " + e); } }}
Exception : java.lang.NullPointerException
Program 3 : to demonstrate java.lang.ArrayIndexOutOfBoundsException
// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = { "Geeks", "for", "Geeks" }; try { // set method of class Array Array.set(s, 4, "for"); } catch (Exception e) { System.out.println("Exception : " + e); } }}
Exception : java.lang.ArrayIndexOutOfBoundsException
Program 4 : to demonstrate java.lang.IllegalArgumentException
// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s = "GeeksforGeeks"; try { // set method of class Array Array.set(s, 4, "for"); } catch (Exception e) { System.out.println("Exception : " + e); } }}
Exception : java.lang.IllegalArgumentException: Argument is not an array
Java-Arrays
Java-Collections
Java-Functions
java-lang-reflect-package
java-reflection-array
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
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
Multithreading in Java
|
[
{
"code": null,
"e": 26341,
"s": 26313,
"text": "\n30 Nov, 2018"
},
{
"code": null,
"e": 26487,
"s": 26341,
"text": "The java.lang.reflect.Array.set() is an inbuilt method in Java and is used to set a specified value to a specified index of a given object array."
},
{
"code": null,
"e": 26494,
"s": 26487,
"text": "Syntax"
},
{
"code": null,
"e": 26546,
"s": 26494,
"text": "Array.set(Object []array, int index, Object value)\n"
},
{
"code": null,
"e": 26558,
"s": 26546,
"text": "Parameter :"
},
{
"code": null,
"e": 26622,
"s": 26558,
"text": "array : This is an array of type Object which is to be updated."
},
{
"code": null,
"e": 26685,
"s": 26622,
"text": "index : This is the index of the array which is to be updated."
},
{
"code": null,
"e": 26767,
"s": 26685,
"text": "value : This is the value that is to be set at the given index of the given array"
},
{
"code": null,
"e": 26906,
"s": 26767,
"text": "Return type : This is a void type method this doesn’t returns any value. The update reflects upon the Object array passed as the argument."
},
{
"code": null,
"e": 26958,
"s": 26906,
"text": "Exception : This method throws following exception."
},
{
"code": null,
"e": 27005,
"s": 26958,
"text": "NullPointerException – when the array is null."
},
{
"code": null,
"e": 27077,
"s": 27005,
"text": "IllegalArgumentException – when the given object array is not an Array."
},
{
"code": null,
"e": 29674,
"s": 27077,
"text": "ArrayIndexOutOfBoundsException – if the given index is not in the range of the size of the array.Below programs illustrate the Array.set() method:Program 1 :// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = { \"Geeks\", \"is\", \"Geeks\" }; System.out.print(\"Befor Set : \"); // printing the array for (String x : s) { System.out.print(x); } // set method of class Array Array.set(s, 1, \"for\"); System.out.print(\"\\nAfter Set : \"); // printing array for (String x : s) { System.out.print(x); } }}Output:Befor Set : GeeksisGeeks\nAfter Set : GeeksforGeeks\nProgram 2 : to demonstrate java.lang.NullPointerException// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = null; try { // set method of class Array Array.set(s, 1, \"for\"); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}Output:Exception : java.lang.NullPointerException\nProgram 3 : to demonstrate java.lang.ArrayIndexOutOfBoundsException// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = { \"Geeks\", \"for\", \"Geeks\" }; try { // set method of class Array Array.set(s, 4, \"for\"); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}Output:Exception : java.lang.ArrayIndexOutOfBoundsException\nProgram 4 : to demonstrate java.lang.IllegalArgumentException// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s = \"GeeksforGeeks\"; try { // set method of class Array Array.set(s, 4, \"for\"); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}Output:Exception : java.lang.IllegalArgumentException: Argument is not an array\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 29724,
"s": 29674,
"text": "Below programs illustrate the Array.set() method:"
},
{
"code": null,
"e": 29736,
"s": 29724,
"text": "Program 1 :"
},
{
"code": "// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = { \"Geeks\", \"is\", \"Geeks\" }; System.out.print(\"Befor Set : \"); // printing the array for (String x : s) { System.out.print(x); } // set method of class Array Array.set(s, 1, \"for\"); System.out.print(\"\\nAfter Set : \"); // printing array for (String x : s) { System.out.print(x); } }}",
"e": 30359,
"s": 29736,
"text": null
},
{
"code": null,
"e": 30411,
"s": 30359,
"text": "Befor Set : GeeksisGeeks\nAfter Set : GeeksforGeeks\n"
},
{
"code": null,
"e": 30469,
"s": 30411,
"text": "Program 2 : to demonstrate java.lang.NullPointerException"
},
{
"code": "// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = null; try { // set method of class Array Array.set(s, 1, \"for\"); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}",
"e": 30909,
"s": 30469,
"text": null
},
{
"code": null,
"e": 30953,
"s": 30909,
"text": "Exception : java.lang.NullPointerException\n"
},
{
"code": null,
"e": 31021,
"s": 30953,
"text": "Program 3 : to demonstrate java.lang.ArrayIndexOutOfBoundsException"
},
{
"code": "// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = { \"Geeks\", \"for\", \"Geeks\" }; try { // set method of class Array Array.set(s, 4, \"for\"); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}",
"e": 31484,
"s": 31021,
"text": null
},
{
"code": null,
"e": 31538,
"s": 31484,
"text": "Exception : java.lang.ArrayIndexOutOfBoundsException\n"
},
{
"code": null,
"e": 31600,
"s": 31538,
"text": "Program 4 : to demonstrate java.lang.IllegalArgumentException"
},
{
"code": "// Java code to demonstrate set() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s = \"GeeksforGeeks\"; try { // set method of class Array Array.set(s, 4, \"for\"); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}",
"e": 32049,
"s": 31600,
"text": null
},
{
"code": null,
"e": 32123,
"s": 32049,
"text": "Exception : java.lang.IllegalArgumentException: Argument is not an array\n"
},
{
"code": null,
"e": 32135,
"s": 32123,
"text": "Java-Arrays"
},
{
"code": null,
"e": 32152,
"s": 32135,
"text": "Java-Collections"
},
{
"code": null,
"e": 32167,
"s": 32152,
"text": "Java-Functions"
},
{
"code": null,
"e": 32193,
"s": 32167,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 32215,
"s": 32193,
"text": "java-reflection-array"
},
{
"code": null,
"e": 32220,
"s": 32215,
"text": "Java"
},
{
"code": null,
"e": 32225,
"s": 32220,
"text": "Java"
},
{
"code": null,
"e": 32242,
"s": 32225,
"text": "Java-Collections"
},
{
"code": null,
"e": 32340,
"s": 32242,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32355,
"s": 32340,
"text": "Stream In Java"
},
{
"code": null,
"e": 32406,
"s": 32355,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 32436,
"s": 32406,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 32455,
"s": 32436,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 32486,
"s": 32455,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 32504,
"s": 32486,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 32536,
"s": 32504,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 32556,
"s": 32536,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 32580,
"s": 32556,
"text": "Singleton Class in Java"
}
] |
NEXTMONTH function
|
Returns a table that contains a column of all dates from the next month, based on the first date in the dates column in the current context.
NEXTMONTH (<dates>)
dates
A column that contains dates.
A table containing a single column of date values.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
= CALCULATE (
SUM (Sales [Sales Amount]), NEXTMONTH (Sales [Date])
)
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2142,
"s": 2001,
"text": "Returns a table that contains a column of all dates from the next month, based on the first date in the dates column in the current context."
},
{
"code": null,
"e": 2164,
"s": 2142,
"text": "NEXTMONTH (<dates>) \n"
},
{
"code": null,
"e": 2170,
"s": 2164,
"text": "dates"
},
{
"code": null,
"e": 2200,
"s": 2170,
"text": "A column that contains dates."
},
{
"code": null,
"e": 2251,
"s": 2200,
"text": "A table containing a single column of date values."
},
{
"code": null,
"e": 2301,
"s": 2251,
"text": "The dates parameter can be any of the following −"
},
{
"code": null,
"e": 2336,
"s": 2301,
"text": "A reference to a date/time column."
},
{
"code": null,
"e": 2371,
"s": 2336,
"text": "A reference to a date/time column."
},
{
"code": null,
"e": 2440,
"s": 2371,
"text": "A table expression that returns a single column of date/time values."
},
{
"code": null,
"e": 2509,
"s": 2440,
"text": "A table expression that returns a single column of date/time values."
},
{
"code": null,
"e": 2586,
"s": 2509,
"text": "A Boolean expression that defines a single-column table of date/time values."
},
{
"code": null,
"e": 2663,
"s": 2586,
"text": "A Boolean expression that defines a single-column table of date/time values."
},
{
"code": null,
"e": 2700,
"s": 2663,
"text": "Constraints on Boolean expressions −"
},
{
"code": null,
"e": 2752,
"s": 2700,
"text": "The expression cannot reference a calculated field."
},
{
"code": null,
"e": 2804,
"s": 2752,
"text": "The expression cannot reference a calculated field."
},
{
"code": null,
"e": 2850,
"s": 2804,
"text": "The expression cannot use CALCULATE function."
},
{
"code": null,
"e": 2896,
"s": 2850,
"text": "The expression cannot use CALCULATE function."
},
{
"code": null,
"e": 3007,
"s": 2896,
"text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions."
},
{
"code": null,
"e": 3118,
"s": 3007,
"text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions."
},
{
"code": null,
"e": 3234,
"s": 3118,
"text": "However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value."
},
{
"code": null,
"e": 3306,
"s": 3234,
"text": "= CALCULATE (\n SUM (Sales [Sales Amount]), NEXTMONTH (Sales [Date])\n)"
},
{
"code": null,
"e": 3341,
"s": 3306,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3355,
"s": 3341,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3388,
"s": 3355,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3402,
"s": 3388,
"text": " Randy Minder"
},
{
"code": null,
"e": 3437,
"s": 3402,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3451,
"s": 3437,
"text": " Randy Minder"
},
{
"code": null,
"e": 3458,
"s": 3451,
"text": " Print"
},
{
"code": null,
"e": 3469,
"s": 3458,
"text": " Add Notes"
}
] |
Rearrange a string according to the given indices
|
15 Jun, 2021
Given a string S and an array index[], the task is to rearrange the string S by placing every character S[i] to position index[i].Example
Input: S = “geeksforgeeks”, index[] = {5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12} Output: ksfeegeeorgksInput: S = “math”, index[] = {0, 1, 2, 3} Output: math
Approach: To solve the problem, follow the steps given below:
Convert the string S to a list of characters, since strings are immutable in nature.
Copy the list. Rearrange the characters in this list according the values from index[i].
Convert the list to string and print the final string.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to convert the strings// to propervoid Convertstrings(string s, int index[], int n){ char a[s.length()]; char b[s.length()]; // Convert string to array for(int ii = 0; ii < s.length(); ii++) { a[ii] = s[ii]; b[ii] = s[ii]; } int i = 0, j = 0; // Move characters to specified indices while(j < s.length() && i < n) { int k = index[i]; int temp = a[j]; b[k] = temp; j += 1; i += 1; } string tmp = ""; // Convert the list to string for(i = 0; i < s.length(); i++) { tmp += b[i]; } // Print the answer cout << tmp << endl;} // Driver Codeint main(){ string s = "geeksforgeeks"; int index[] = { 5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12}; int n = sizeof(index) / sizeof(index[0]); Convertstrings(s, index, n); return 0;} // This code is contributed by rutvik_56
// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to convert the Strings// to properstatic void ConvertStrings(char []s, int index[], int n){ char []a = new char[s.length]; char []b = new char[s.length]; // Convert String to array for(int ii = 0; ii < s.length; ii++) { a[ii] = s[ii]; b[ii] = s[ii]; } int i = 0, j = 0; // Move characters to specified indices while(j < s.length && i < n) { int k = index[i]; int temp = a[j]; b[k] = (char) temp; j += 1; i += 1; } String tmp = ""; // Convert the list to String for(i = 0; i < s.length; i++) { tmp += b[i]; } // Print the answer System.out.print(tmp +"\n");} // Driver Codepublic static void main(String[] args){ String s = "geeksforgeeks"; int index[] = { 5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12}; int n = index.length; ConvertStrings(s.toCharArray(), index, n);}} // This code is contributed by Rohit_ranjan
# Python3 Program to implement# the above approach # Function to convert the strings# to properdef Convertstrings(s, index): a = [] j = 0 i = 0 # Convert string to list for ii in str(s): a.append(ii) # Copy the list to another list b = a[:] # Move characters to specified indices while j < len(a) and i < len(index): k = index[i] temp = a[j] b[k] = temp j += 1 i += 1 s = '' # Convert the list to string for i in range(len(b)): s += b[i] # Print the answer print(s) # Driver Codes = "geeksforgeeks"index = [5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12]Convertstrings(s, index)
// C# program to implement// the above approachusing System;class GFG{ // Function to convert the Strings// to properstatic void ConvertStrings(char []s, int []index, int n){ char []a = new char[s.Length]; char []b = new char[s.Length]; // Convert String to array for(int ii = 0; ii < s.Length; ii++) { a[ii] = s[ii]; b[ii] = s[ii]; } int i = 0, j = 0; // Move characters to specified indices while(j < s.Length && i < n) { int k = index[i]; int temp = a[j]; b[k] = (char) temp; j += 1; i += 1; } String tmp = ""; // Convert the list to String for(i = 0; i < s.Length; i++) { tmp += b[i]; } // Print the answer Console.Write(tmp +"\n");} // Driver Codepublic static void Main(String[] args){ String s = "geeksforgeeks"; int []index = { 5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12}; int n = index.Length; ConvertStrings(s.ToCharArray(), index, n);}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to implement the above approach // Function to convert the Strings to proper function ConvertStrings(s, index, n) { let a = new Array(s.length); a.fill('0'); let b = new Array(s.length); b.fill('0'); // Convert String to array for(let ii = 0; ii < s.length; ii++) { a[ii] = s[ii]; b[ii] = s[ii]; } let i = 0, j = 0; // Move characters to specified indices while(j < s.length && i < n) { let k = index[i]; let temp = a[j].charCodeAt(); b[k] = String.fromCharCode(temp); j += 1; i += 1; } let tmp = ""; // Convert the list to String for(i = 0; i < s.length; i++) { tmp = tmp + b[i]; } // Print the answer document.write(tmp +"</br>"); } let s = "geeksforgeeks"; let index = [ 5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12]; let n = index.length; ConvertStrings(s.split(''), index, n); </script>
ksfeegeeorgks
Time Complexity: O(N) Auxiliary Space: O(N)
rutvik_56
Rohit_ranjan
Rajput-Ji
mukesh07
array-rearrange
python-list
Arrays
Strings
python-list
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jun, 2021"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "Given a string S and an array index[], the task is to rearrange the string S by placing every character S[i] to position index[i].Example "
},
{
"code": null,
"e": 327,
"s": 168,
"text": "Input: S = “geeksforgeeks”, index[] = {5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12} Output: ksfeegeeorgksInput: S = “math”, index[] = {0, 1, 2, 3} Output: math "
},
{
"code": null,
"e": 393,
"s": 329,
"text": "Approach: To solve the problem, follow the steps given below: "
},
{
"code": null,
"e": 478,
"s": 393,
"text": "Convert the string S to a list of characters, since strings are immutable in nature."
},
{
"code": null,
"e": 567,
"s": 478,
"text": "Copy the list. Rearrange the characters in this list according the values from index[i]."
},
{
"code": null,
"e": 622,
"s": 567,
"text": "Convert the list to string and print the final string."
},
{
"code": null,
"e": 674,
"s": 622,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 678,
"s": 674,
"text": "C++"
},
{
"code": null,
"e": 683,
"s": 678,
"text": "Java"
},
{
"code": null,
"e": 691,
"s": 683,
"text": "Python3"
},
{
"code": null,
"e": 694,
"s": 691,
"text": "C#"
},
{
"code": null,
"e": 705,
"s": 694,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to convert the strings// to propervoid Convertstrings(string s, int index[], int n){ char a[s.length()]; char b[s.length()]; // Convert string to array for(int ii = 0; ii < s.length(); ii++) { a[ii] = s[ii]; b[ii] = s[ii]; } int i = 0, j = 0; // Move characters to specified indices while(j < s.length() && i < n) { int k = index[i]; int temp = a[j]; b[k] = temp; j += 1; i += 1; } string tmp = \"\"; // Convert the list to string for(i = 0; i < s.length(); i++) { tmp += b[i]; } // Print the answer cout << tmp << endl;} // Driver Codeint main(){ string s = \"geeksforgeeks\"; int index[] = { 5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12}; int n = sizeof(index) / sizeof(index[0]); Convertstrings(s, index, n); return 0;} // This code is contributed by rutvik_56 ",
"e": 1787,
"s": 705,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to convert the Strings// to properstatic void ConvertStrings(char []s, int index[], int n){ char []a = new char[s.length]; char []b = new char[s.length]; // Convert String to array for(int ii = 0; ii < s.length; ii++) { a[ii] = s[ii]; b[ii] = s[ii]; } int i = 0, j = 0; // Move characters to specified indices while(j < s.length && i < n) { int k = index[i]; int temp = a[j]; b[k] = (char) temp; j += 1; i += 1; } String tmp = \"\"; // Convert the list to String for(i = 0; i < s.length; i++) { tmp += b[i]; } // Print the answer System.out.print(tmp +\"\\n\");} // Driver Codepublic static void main(String[] args){ String s = \"geeksforgeeks\"; int index[] = { 5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12}; int n = index.length; ConvertStrings(s.toCharArray(), index, n);}} // This code is contributed by Rohit_ranjan",
"e": 2926,
"s": 1787,
"text": null
},
{
"code": "# Python3 Program to implement# the above approach # Function to convert the strings# to properdef Convertstrings(s, index): a = [] j = 0 i = 0 # Convert string to list for ii in str(s): a.append(ii) # Copy the list to another list b = a[:] # Move characters to specified indices while j < len(a) and i < len(index): k = index[i] temp = a[j] b[k] = temp j += 1 i += 1 s = '' # Convert the list to string for i in range(len(b)): s += b[i] # Print the answer print(s) # Driver Codes = \"geeksforgeeks\"index = [5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12]Convertstrings(s, index)",
"e": 3596,
"s": 2926,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ // Function to convert the Strings// to properstatic void ConvertStrings(char []s, int []index, int n){ char []a = new char[s.Length]; char []b = new char[s.Length]; // Convert String to array for(int ii = 0; ii < s.Length; ii++) { a[ii] = s[ii]; b[ii] = s[ii]; } int i = 0, j = 0; // Move characters to specified indices while(j < s.Length && i < n) { int k = index[i]; int temp = a[j]; b[k] = (char) temp; j += 1; i += 1; } String tmp = \"\"; // Convert the list to String for(i = 0; i < s.Length; i++) { tmp += b[i]; } // Print the answer Console.Write(tmp +\"\\n\");} // Driver Codepublic static void Main(String[] args){ String s = \"geeksforgeeks\"; int []index = { 5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12}; int n = index.Length; ConvertStrings(s.ToCharArray(), index, n);}} // This code is contributed by Rajput-Ji",
"e": 4721,
"s": 3596,
"text": null
},
{
"code": "<script> // JavaScript program to implement the above approach // Function to convert the Strings to proper function ConvertStrings(s, index, n) { let a = new Array(s.length); a.fill('0'); let b = new Array(s.length); b.fill('0'); // Convert String to array for(let ii = 0; ii < s.length; ii++) { a[ii] = s[ii]; b[ii] = s[ii]; } let i = 0, j = 0; // Move characters to specified indices while(j < s.length && i < n) { let k = index[i]; let temp = a[j].charCodeAt(); b[k] = String.fromCharCode(temp); j += 1; i += 1; } let tmp = \"\"; // Convert the list to String for(i = 0; i < s.length; i++) { tmp = tmp + b[i]; } // Print the answer document.write(tmp +\"</br>\"); } let s = \"geeksforgeeks\"; let index = [ 5, 6, 7, 0, 1, 2, 8, 9, 10, 3, 4, 11, 12]; let n = index.length; ConvertStrings(s.split(''), index, n); </script>",
"e": 5825,
"s": 4721,
"text": null
},
{
"code": null,
"e": 5839,
"s": 5825,
"text": "ksfeegeeorgks"
},
{
"code": null,
"e": 5886,
"s": 5841,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 5896,
"s": 5886,
"text": "rutvik_56"
},
{
"code": null,
"e": 5909,
"s": 5896,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 5919,
"s": 5909,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 5928,
"s": 5919,
"text": "mukesh07"
},
{
"code": null,
"e": 5944,
"s": 5928,
"text": "array-rearrange"
},
{
"code": null,
"e": 5956,
"s": 5944,
"text": "python-list"
},
{
"code": null,
"e": 5963,
"s": 5956,
"text": "Arrays"
},
{
"code": null,
"e": 5971,
"s": 5963,
"text": "Strings"
},
{
"code": null,
"e": 5983,
"s": 5971,
"text": "python-list"
},
{
"code": null,
"e": 5990,
"s": 5983,
"text": "Arrays"
},
{
"code": null,
"e": 5998,
"s": 5990,
"text": "Strings"
}
] |
Implementing Associate Array in Java
|
27 Nov, 2020
An associative array stores the set of elements in the form of (key, value) pairs. An associative array is a collection of unique keys and collections of values where each key is associated with one value.
An associate array is an abstract datatype like a map that is composed of a (key, value) pair, such that each key-value appears at most once in the collection. Basically, an array with named indexes is known as an associative array or hashes.
In Java, it is difficult to form the associative array however this could easily be achieved using a HashMap:
Syntax:
Map<String, String> map = new HashMap<String, String>();
// method to add the key,value pair in hashmap
map.put("geeks", "course");
map.put("name", "geeks");
// method to get the value
map.get("name"); // returns "geeks"
Steps to implement the Associative array or associative the List Array using the Map Function :
1. First initialize the map
Map<String ,String> map = new HashMap<>();
2. Then Put the Key, Value to the map using put method
map.put("geeks","Course");
3. After putting all Key Value to the map Convert the map to set using the entrySet() Method
Set<Map.Entry<String ,String> > set = map.entrySet();
4. Then Now convert the set to the List Array using the function ;
List<Map.Entry<String ,String>> list=new ArrayList<>(set);
Implementation of associate array:
Java
// Java program to implement the associate array import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Forming the map Map<String, String> map = new HashMap<>(); // method to store the value and // key into the map map.put("name", "rohit"); map.put("geeks", "course"); map.put("India Capital", "Delhi"); System.out.println(map.size()); Set<Map.Entry<String, String> > set = map.entrySet(); List<Map.Entry<String, String> > list = new ArrayList<>(set); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).getKey() + ": " + list.get(i).getValue()); } }}
3
India Capital: Delhi
geeks: course
name: rohit
Time Complexity: O(n)
Space Complexity: O(n)
We can iterate through the array using the iterator() method
Syntax:
Iterator it = map.entrySet().iterator();
Java
// Java program to implement the associate array// and iterate it using iterator() method import java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // Forming the map Map<String, Integer> map = new HashMap<>(); // method to store the put the value and // key into the map map.put("Roll no", 45); map.put("Total Question", 113); map.put("Marks ", 400); // method to access the value based on // the key System.out.println(map.size()); Set<Map.Entry<String, Integer> > set = map.entrySet(); List<Map.Entry<String, Integer> > list = new ArrayList<>(set); // using the iterator Iterator it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); } }}
3
Total Question=113
Roll no=45
Marks =400
Time Complexity: O(n)
Space Complexity: O(n)
Java-Array-Programs
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Nov, 2020"
},
{
"code": null,
"e": 234,
"s": 28,
"text": "An associative array stores the set of elements in the form of (key, value) pairs. An associative array is a collection of unique keys and collections of values where each key is associated with one value."
},
{
"code": null,
"e": 477,
"s": 234,
"text": "An associate array is an abstract datatype like a map that is composed of a (key, value) pair, such that each key-value appears at most once in the collection. Basically, an array with named indexes is known as an associative array or hashes."
},
{
"code": null,
"e": 587,
"s": 477,
"text": "In Java, it is difficult to form the associative array however this could easily be achieved using a HashMap:"
},
{
"code": null,
"e": 595,
"s": 587,
"text": "Syntax:"
},
{
"code": null,
"e": 819,
"s": 595,
"text": "Map<String, String> map = new HashMap<String, String>();\n\n// method to add the key,value pair in hashmap\nmap.put(\"geeks\", \"course\");\nmap.put(\"name\", \"geeks\");\n\n\n// method to get the value\nmap.get(\"name\"); // returns \"geeks\""
},
{
"code": null,
"e": 915,
"s": 819,
"text": "Steps to implement the Associative array or associative the List Array using the Map Function :"
},
{
"code": null,
"e": 943,
"s": 915,
"text": "1. First initialize the map"
},
{
"code": null,
"e": 986,
"s": 943,
"text": "Map<String ,String> map = new HashMap<>();"
},
{
"code": null,
"e": 1041,
"s": 986,
"text": "2. Then Put the Key, Value to the map using put method"
},
{
"code": null,
"e": 1068,
"s": 1041,
"text": "map.put(\"geeks\",\"Course\");"
},
{
"code": null,
"e": 1161,
"s": 1068,
"text": "3. After putting all Key Value to the map Convert the map to set using the entrySet() Method"
},
{
"code": null,
"e": 1215,
"s": 1161,
"text": "Set<Map.Entry<String ,String> > set = map.entrySet();"
},
{
"code": null,
"e": 1282,
"s": 1215,
"text": "4. Then Now convert the set to the List Array using the function ;"
},
{
"code": null,
"e": 1341,
"s": 1282,
"text": "List<Map.Entry<String ,String>> list=new ArrayList<>(set);"
},
{
"code": null,
"e": 1376,
"s": 1341,
"text": "Implementation of associate array:"
},
{
"code": null,
"e": 1381,
"s": 1376,
"text": "Java"
},
{
"code": "// Java program to implement the associate array import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // Forming the map Map<String, String> map = new HashMap<>(); // method to store the value and // key into the map map.put(\"name\", \"rohit\"); map.put(\"geeks\", \"course\"); map.put(\"India Capital\", \"Delhi\"); System.out.println(map.size()); Set<Map.Entry<String, String> > set = map.entrySet(); List<Map.Entry<String, String> > list = new ArrayList<>(set); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).getKey() + \": \" + list.get(i).getValue()); } }}",
"e": 2215,
"s": 1381,
"text": null
},
{
"code": null,
"e": 2264,
"s": 2215,
"text": "3\nIndia Capital: Delhi\ngeeks: course\nname: rohit"
},
{
"code": null,
"e": 2286,
"s": 2264,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 2309,
"s": 2286,
"text": "Space Complexity: O(n)"
},
{
"code": null,
"e": 2370,
"s": 2309,
"text": "We can iterate through the array using the iterator() method"
},
{
"code": null,
"e": 2378,
"s": 2370,
"text": "Syntax:"
},
{
"code": null,
"e": 2419,
"s": 2378,
"text": "Iterator it = map.entrySet().iterator();"
},
{
"code": null,
"e": 2424,
"s": 2419,
"text": "Java"
},
{
"code": "// Java program to implement the associate array// and iterate it using iterator() method import java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // Forming the map Map<String, Integer> map = new HashMap<>(); // method to store the put the value and // key into the map map.put(\"Roll no\", 45); map.put(\"Total Question\", 113); map.put(\"Marks \", 400); // method to access the value based on // the key System.out.println(map.size()); Set<Map.Entry<String, Integer> > set = map.entrySet(); List<Map.Entry<String, Integer> > list = new ArrayList<>(set); // using the iterator Iterator it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); } }}",
"e": 3303,
"s": 2424,
"text": null
},
{
"code": null,
"e": 3346,
"s": 3303,
"text": "3\nTotal Question=113\nRoll no=45\nMarks =400"
},
{
"code": null,
"e": 3368,
"s": 3346,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 3391,
"s": 3368,
"text": "Space Complexity: O(n)"
},
{
"code": null,
"e": 3411,
"s": 3391,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 3418,
"s": 3411,
"text": "Picked"
},
{
"code": null,
"e": 3442,
"s": 3418,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3447,
"s": 3442,
"text": "Java"
},
{
"code": null,
"e": 3461,
"s": 3447,
"text": "Java Programs"
},
{
"code": null,
"e": 3480,
"s": 3461,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3485,
"s": 3480,
"text": "Java"
}
] |
Vieta’s Formulas
|
10 Apr, 2022
Vieta’s formula relates the coefficients of polynomial to the sum and product of their roots, as well as the products of the roots taken in groups. Vieta’s formula describes the relationship of the roots of a polynomial with its coefficients. Consider the following example to find a polynomial with given roots. (Only discuss real-valued polynomials, i.e. the coefficients of polynomials are real numbers). Let’s take a quadratic polynomial. Given two real roots and , then find a polynomial. Consider the polynomial . Given the roots, we can also write it as .Since both equation represents the same polynomial, so equate both polynomialSimplifying the above equation, we getComparing the coefficients of both sides, we getFor , ,For , , For constant term, ,Which gives, ,Equation (1) and (2) are known as Vieta’s Formulas for a second degree polynomial. In general, for an degree polynomial, there are n different Vieta’s Formulas. They can be written in a condensed form as For The following examples illustrate the use of Vieta’s formula to solve a problem.Examples:
Input : n = 2
roots = {-3, 2}
Output : Polynomial coefficients: 1, 1, -6
Input : n = 4
roots = {-1, 2, -3, 7}
Output : Polynomial coefficients: 1, -5, -19, 29, 42
C++
Java
Python3
C#
PHP
Javascript
// C++ program to implement vieta formula// to calculate polynomial coefficients.#include <bits/stdc++.h>using namespace std; // Function to calculate polynomial// coefficients.void vietaFormula(int roots[], int n){ // Declare an array for // polynomial coefficient. int coeff[n + 1]; // Set all coefficients as zero initially memset(coeff, 0, sizeof(coeff)); // Set highest order coefficient as 1 coeff[n] = 1; for (int i = 1; i <= n; i++) { for (int j = n - i - 1; j < n; j++) { coeff[j] = coeff[j] + (-1) * roots[i - 1] * coeff[j + 1]; } } cout << "Polynomial Coefficients: "; for (int i = n; i >= 0; i--) { cout << coeff[i] << " "; }} // Driver codeint main(){ // Degree of required polynomial int n = 4; // Initialise an array by // root of polynomial int roots[] = { -1, 2, -3, 7 }; // Function call vietaFormula(roots, n); return 0;}
// Java program to implement vieta formula// to calculate polynomial coefficients.import java.util.Arrays; class GFG{ // Function to calculate polynomial// coefficients.static void vietaFormula(int roots[], int n){ // Declare an array for // polynomial coefficient. int coeff[] = new int[++n + 1]; Arrays.fill(coeff, 0); // Set highest order coefficient as 1 coeff[n] = 1; for (int i = 1; i <n; i++) { for (int j = n - i - 1; j < n; j++) { coeff[j] = coeff[j] + (-1) * roots[i - 1] * coeff[j + 1]; } } System.out.print("Polynomial Coefficients: "); for (int i = n; i > 0; i--) { System.out.print(coeff[i] + " "); }} // Driver codepublic static void main(String[] args){ // Degree of required polynomial int n = 4; // Initialise an array by // root of polynomial int roots[] = { -1, 2, -3, 7 }; // Function call vietaFormula(roots, n); }} /* This code contributed by PrinciRaj1992 */
# Python3 program to implement# Vieta's formula to calculate# polynomial coefficients.def vietaFormula(roots, n): # Declare an array for # polynomial coefficient. coeff = [0] * (n + 1) # Set Highest Order # Coefficient as 1 coeff[n] = 1 for i in range(1, n + 1): for j in range(n - i - 1, n): coeff[j] += ((-1) * roots[i - 1] * coeff[j + 1]) # Reverse Array coeff = coeff[::-1] print("Polynomial Coefficients : ", end = "") # Print Coefficients for i in coeff: print(i, end = " ") print() # Driver Codeif __name__ == "__main__": # Degree of Polynomial n = 4 # Initialise an array by # root of polynomial roots = [-1, 2, -3, 7] # Function call vietaFormula(roots, n) # This code is contributed# by Arihant Joshi
// C# program to implement vieta formula// to calculate polynomial coefficients.using System; class GFG{ // Function to calculate polynomial// coefficients.static void vietaFormula(int []roots, int n){ // Declare an array for // polynomial coefficient. int []coeff = new int[++n + 1]; // Set highest order coefficient as 1 coeff[n] = 1; for (int i = 1; i <n; i++) { for (int j = n - i - 1; j < n; j++) { coeff[j] = coeff[j] + (-1) * roots[i - 1] * coeff[j + 1]; } } Console.Write("Polynomial Coefficients: "); for (int i = n; i > 0; i--) { Console.Write(coeff[i] + " "); }} // Driver codepublic static void Main(String[] args){ // Degree of required polynomial int n = 4; // Initialise an array by // root of polynomial int []roots = { -1, 2, -3, 7 }; // Function call vietaFormula(roots, n);}} // This code has been contributed by 29AjayKumar
<?php// PHP program to implement vieta formula// to calculate polynomial coefficients. // Function to calculate polynomial// coefficients.function vietaFormula($roots, $n){ // Declare an array for // polynomial coefficient. $coeff = array_fill(0, $n + 1, 0); // Set all coefficients as zero initially // Set highest order coefficient as 1 $coeff[$n] = 1; for ($i = 1; $i <= $n; $i++) { for ($j = $n - $i; $j < $n; $j++) { $coeff[$j] = $coeff[$j] + (-1) * $roots[$i - 1] * $coeff[$j + 1]; } } echo "polynomial coefficients: "; for ($i = $n; $i >= 0; $i--) { echo $coeff[$i]. " "; }} // Driver code // Degree of required polynomial$n = 4; // Initialise an array by// root of polynomial$roots = array(-1, 2, -3, 7); // Function callvietaFormula($roots, $n); // This code is contributed by mits?>
<script>// Javascript program to implement vieta formula// to calculate polynomial coefficients. // Function to calculate polynomial// coefficients.function vietaFormula(roots, n){ // Declare an array for // polynomial coefficient. let coeff = new Array(++n + 1); for(let i = 0; i < coeff.length; i++) coeff[i] = 0; // Set highest order coefficient as 1 coeff[n] = 1; for (let i = 1; i <n; i++) { for (let j = n - i - 1; j < n; j++) { coeff[j] = coeff[j] + (-1) * roots[i - 1] * coeff[j + 1]; } } document.write("Polynomial Coefficients: "); for (let i = n; i > 0; i--) { document.write(coeff[i] + " "); }} // Driver code// Degree of required polynomiallet n = 4; // Initialise an array by// root of polynomiallet roots = [ -1, 2, -3, 7 ]; // Function callvietaFormula(roots, n); // This code is contributed by rag2127</script>
Polynomial Coefficients: 1 -5 -19 29 42
Time Complexity : .
joshi_arihant
Mithun Kumar
princiraj1992
29AjayKumar
rag2127
ysfbensadik
expression-evaluation
maths-polynomial
Engineering Mathematics Questions
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": "\n10 Apr, 2022"
},
{
"code": null,
"e": 1128,
"s": 54,
"text": "Vieta’s formula relates the coefficients of polynomial to the sum and product of their roots, as well as the products of the roots taken in groups. Vieta’s formula describes the relationship of the roots of a polynomial with its coefficients. Consider the following example to find a polynomial with given roots. (Only discuss real-valued polynomials, i.e. the coefficients of polynomials are real numbers). Let’s take a quadratic polynomial. Given two real roots and , then find a polynomial. Consider the polynomial . Given the roots, we can also write it as .Since both equation represents the same polynomial, so equate both polynomialSimplifying the above equation, we getComparing the coefficients of both sides, we getFor , ,For , , For constant term, ,Which gives, ,Equation (1) and (2) are known as Vieta’s Formulas for a second degree polynomial. In general, for an degree polynomial, there are n different Vieta’s Formulas. They can be written in a condensed form as For The following examples illustrate the use of Vieta’s formula to solve a problem.Examples: "
},
{
"code": null,
"e": 1308,
"s": 1128,
"text": "Input : n = 2\n roots = {-3, 2}\nOutput : Polynomial coefficients: 1, 1, -6\n\nInput : n = 4\n roots = {-1, 2, -3, 7}\nOutput : Polynomial coefficients: 1, -5, -19, 29, 42"
},
{
"code": null,
"e": 1314,
"s": 1310,
"text": "C++"
},
{
"code": null,
"e": 1319,
"s": 1314,
"text": "Java"
},
{
"code": null,
"e": 1327,
"s": 1319,
"text": "Python3"
},
{
"code": null,
"e": 1330,
"s": 1327,
"text": "C#"
},
{
"code": null,
"e": 1334,
"s": 1330,
"text": "PHP"
},
{
"code": null,
"e": 1345,
"s": 1334,
"text": "Javascript"
},
{
"code": "// C++ program to implement vieta formula// to calculate polynomial coefficients.#include <bits/stdc++.h>using namespace std; // Function to calculate polynomial// coefficients.void vietaFormula(int roots[], int n){ // Declare an array for // polynomial coefficient. int coeff[n + 1]; // Set all coefficients as zero initially memset(coeff, 0, sizeof(coeff)); // Set highest order coefficient as 1 coeff[n] = 1; for (int i = 1; i <= n; i++) { for (int j = n - i - 1; j < n; j++) { coeff[j] = coeff[j] + (-1) * roots[i - 1] * coeff[j + 1]; } } cout << \"Polynomial Coefficients: \"; for (int i = n; i >= 0; i--) { cout << coeff[i] << \" \"; }} // Driver codeint main(){ // Degree of required polynomial int n = 4; // Initialise an array by // root of polynomial int roots[] = { -1, 2, -3, 7 }; // Function call vietaFormula(roots, n); return 0;}",
"e": 2316,
"s": 1345,
"text": null
},
{
"code": "// Java program to implement vieta formula// to calculate polynomial coefficients.import java.util.Arrays; class GFG{ // Function to calculate polynomial// coefficients.static void vietaFormula(int roots[], int n){ // Declare an array for // polynomial coefficient. int coeff[] = new int[++n + 1]; Arrays.fill(coeff, 0); // Set highest order coefficient as 1 coeff[n] = 1; for (int i = 1; i <n; i++) { for (int j = n - i - 1; j < n; j++) { coeff[j] = coeff[j] + (-1) * roots[i - 1] * coeff[j + 1]; } } System.out.print(\"Polynomial Coefficients: \"); for (int i = n; i > 0; i--) { System.out.print(coeff[i] + \" \"); }} // Driver codepublic static void main(String[] args){ // Degree of required polynomial int n = 4; // Initialise an array by // root of polynomial int roots[] = { -1, 2, -3, 7 }; // Function call vietaFormula(roots, n); }} /* This code contributed by PrinciRaj1992 */",
"e": 3333,
"s": 2316,
"text": null
},
{
"code": "# Python3 program to implement# Vieta's formula to calculate# polynomial coefficients.def vietaFormula(roots, n): # Declare an array for # polynomial coefficient. coeff = [0] * (n + 1) # Set Highest Order # Coefficient as 1 coeff[n] = 1 for i in range(1, n + 1): for j in range(n - i - 1, n): coeff[j] += ((-1) * roots[i - 1] * coeff[j + 1]) # Reverse Array coeff = coeff[::-1] print(\"Polynomial Coefficients : \", end = \"\") # Print Coefficients for i in coeff: print(i, end = \" \") print() # Driver Codeif __name__ == \"__main__\": # Degree of Polynomial n = 4 # Initialise an array by # root of polynomial roots = [-1, 2, -3, 7] # Function call vietaFormula(roots, n) # This code is contributed# by Arihant Joshi",
"e": 4204,
"s": 3333,
"text": null
},
{
"code": "// C# program to implement vieta formula// to calculate polynomial coefficients.using System; class GFG{ // Function to calculate polynomial// coefficients.static void vietaFormula(int []roots, int n){ // Declare an array for // polynomial coefficient. int []coeff = new int[++n + 1]; // Set highest order coefficient as 1 coeff[n] = 1; for (int i = 1; i <n; i++) { for (int j = n - i - 1; j < n; j++) { coeff[j] = coeff[j] + (-1) * roots[i - 1] * coeff[j + 1]; } } Console.Write(\"Polynomial Coefficients: \"); for (int i = n; i > 0; i--) { Console.Write(coeff[i] + \" \"); }} // Driver codepublic static void Main(String[] args){ // Degree of required polynomial int n = 4; // Initialise an array by // root of polynomial int []roots = { -1, 2, -3, 7 }; // Function call vietaFormula(roots, n);}} // This code has been contributed by 29AjayKumar",
"e": 5180,
"s": 4204,
"text": null
},
{
"code": "<?php// PHP program to implement vieta formula// to calculate polynomial coefficients. // Function to calculate polynomial// coefficients.function vietaFormula($roots, $n){ // Declare an array for // polynomial coefficient. $coeff = array_fill(0, $n + 1, 0); // Set all coefficients as zero initially // Set highest order coefficient as 1 $coeff[$n] = 1; for ($i = 1; $i <= $n; $i++) { for ($j = $n - $i; $j < $n; $j++) { $coeff[$j] = $coeff[$j] + (-1) * $roots[$i - 1] * $coeff[$j + 1]; } } echo \"polynomial coefficients: \"; for ($i = $n; $i >= 0; $i--) { echo $coeff[$i]. \" \"; }} // Driver code // Degree of required polynomial$n = 4; // Initialise an array by// root of polynomial$roots = array(-1, 2, -3, 7); // Function callvietaFormula($roots, $n); // This code is contributed by mits?>",
"e": 6107,
"s": 5180,
"text": null
},
{
"code": "<script>// Javascript program to implement vieta formula// to calculate polynomial coefficients. // Function to calculate polynomial// coefficients.function vietaFormula(roots, n){ // Declare an array for // polynomial coefficient. let coeff = new Array(++n + 1); for(let i = 0; i < coeff.length; i++) coeff[i] = 0; // Set highest order coefficient as 1 coeff[n] = 1; for (let i = 1; i <n; i++) { for (let j = n - i - 1; j < n; j++) { coeff[j] = coeff[j] + (-1) * roots[i - 1] * coeff[j + 1]; } } document.write(\"Polynomial Coefficients: \"); for (let i = n; i > 0; i--) { document.write(coeff[i] + \" \"); }} // Driver code// Degree of required polynomiallet n = 4; // Initialise an array by// root of polynomiallet roots = [ -1, 2, -3, 7 ]; // Function callvietaFormula(roots, n); // This code is contributed by rag2127</script>",
"e": 7049,
"s": 6107,
"text": null
},
{
"code": null,
"e": 7090,
"s": 7049,
"text": "Polynomial Coefficients: 1 -5 -19 29 42 "
},
{
"code": null,
"e": 7113,
"s": 7092,
"text": "Time Complexity : . "
},
{
"code": null,
"e": 7127,
"s": 7113,
"text": "joshi_arihant"
},
{
"code": null,
"e": 7140,
"s": 7127,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 7154,
"s": 7140,
"text": "princiraj1992"
},
{
"code": null,
"e": 7166,
"s": 7154,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7174,
"s": 7166,
"text": "rag2127"
},
{
"code": null,
"e": 7186,
"s": 7174,
"text": "ysfbensadik"
},
{
"code": null,
"e": 7208,
"s": 7186,
"text": "expression-evaluation"
},
{
"code": null,
"e": 7225,
"s": 7208,
"text": "maths-polynomial"
},
{
"code": null,
"e": 7259,
"s": 7225,
"text": "Engineering Mathematics Questions"
},
{
"code": null,
"e": 7272,
"s": 7259,
"text": "Mathematical"
},
{
"code": null,
"e": 7285,
"s": 7272,
"text": "Mathematical"
}
] |
SIN() and COS() Function in SQL Server
|
29 Sep, 2020
1. SIN() Function :The SIN() function returns the sine of a number.
Syntax :
SIN(number)
Parameter : Required. A numeric value.number : It is a numeric value.Returns : It returns the float_expression of the sine of a number.
Example-1 :When the argument holds a positive number.
SELECT SIN(5);
Output :
-0.95892427466313845
Example-2 :When the argument holds a negative number.
SELECT SIN(-5);
Output :
0.95892427466313845
Example-3 :When the PI() function is the argument.
SELECT SIN(PI());
Output :
1.2246467991473532E-16
Example-4 :When the argument passed is an expression.
SELECT SIN(4 * 3);
Output :
-0.53657291800043494
2. COS() FunctionThe COS() function returns the cosine of a number.
Syntax :
COS(number)
Parameter : Required. A numeric value.number : It is a numeric value.Returns : It returns the cosine of a number.
Example-1 :When the argument holds a positive number.
SELECT COS(4);
Output :
-0.65364362086361194
Example-2 :When the argument is a fractional component.
SELECT COS(2.53);
Output :
-0.81873459927738157
Example-3 :When the PI() function is the argument.
SELECT COS(PI());
Output :
-1
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Sep, 2020"
},
{
"code": null,
"e": 96,
"s": 28,
"text": "1. SIN() Function :The SIN() function returns the sine of a number."
},
{
"code": null,
"e": 105,
"s": 96,
"text": "Syntax :"
},
{
"code": null,
"e": 117,
"s": 105,
"text": "SIN(number)"
},
{
"code": null,
"e": 253,
"s": 117,
"text": "Parameter : Required. A numeric value.number : It is a numeric value.Returns : It returns the float_expression of the sine of a number."
},
{
"code": null,
"e": 307,
"s": 253,
"text": "Example-1 :When the argument holds a positive number."
},
{
"code": null,
"e": 322,
"s": 307,
"text": "SELECT SIN(5);"
},
{
"code": null,
"e": 331,
"s": 322,
"text": "Output :"
},
{
"code": null,
"e": 352,
"s": 331,
"text": "-0.95892427466313845"
},
{
"code": null,
"e": 406,
"s": 352,
"text": "Example-2 :When the argument holds a negative number."
},
{
"code": null,
"e": 422,
"s": 406,
"text": "SELECT SIN(-5);"
},
{
"code": null,
"e": 431,
"s": 422,
"text": "Output :"
},
{
"code": null,
"e": 451,
"s": 431,
"text": "0.95892427466313845"
},
{
"code": null,
"e": 502,
"s": 451,
"text": "Example-3 :When the PI() function is the argument."
},
{
"code": null,
"e": 520,
"s": 502,
"text": "SELECT SIN(PI());"
},
{
"code": null,
"e": 529,
"s": 520,
"text": "Output :"
},
{
"code": null,
"e": 552,
"s": 529,
"text": "1.2246467991473532E-16"
},
{
"code": null,
"e": 606,
"s": 552,
"text": "Example-4 :When the argument passed is an expression."
},
{
"code": null,
"e": 625,
"s": 606,
"text": "SELECT SIN(4 * 3);"
},
{
"code": null,
"e": 634,
"s": 625,
"text": "Output :"
},
{
"code": null,
"e": 655,
"s": 634,
"text": "-0.53657291800043494"
},
{
"code": null,
"e": 723,
"s": 655,
"text": "2. COS() FunctionThe COS() function returns the cosine of a number."
},
{
"code": null,
"e": 732,
"s": 723,
"text": "Syntax :"
},
{
"code": null,
"e": 744,
"s": 732,
"text": "COS(number)"
},
{
"code": null,
"e": 858,
"s": 744,
"text": "Parameter : Required. A numeric value.number : It is a numeric value.Returns : It returns the cosine of a number."
},
{
"code": null,
"e": 912,
"s": 858,
"text": "Example-1 :When the argument holds a positive number."
},
{
"code": null,
"e": 927,
"s": 912,
"text": "SELECT COS(4);"
},
{
"code": null,
"e": 936,
"s": 927,
"text": "Output :"
},
{
"code": null,
"e": 957,
"s": 936,
"text": "-0.65364362086361194"
},
{
"code": null,
"e": 1013,
"s": 957,
"text": "Example-2 :When the argument is a fractional component."
},
{
"code": null,
"e": 1031,
"s": 1013,
"text": "SELECT COS(2.53);"
},
{
"code": null,
"e": 1040,
"s": 1031,
"text": "Output :"
},
{
"code": null,
"e": 1061,
"s": 1040,
"text": "-0.81873459927738157"
},
{
"code": null,
"e": 1112,
"s": 1061,
"text": "Example-3 :When the PI() function is the argument."
},
{
"code": null,
"e": 1130,
"s": 1112,
"text": "SELECT COS(PI());"
},
{
"code": null,
"e": 1139,
"s": 1130,
"text": "Output :"
},
{
"code": null,
"e": 1142,
"s": 1139,
"text": "-1"
},
{
"code": null,
"e": 1151,
"s": 1142,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1162,
"s": 1151,
"text": "SQL-Server"
},
{
"code": null,
"e": 1166,
"s": 1162,
"text": "SQL"
},
{
"code": null,
"e": 1170,
"s": 1166,
"text": "SQL"
},
{
"code": null,
"e": 1268,
"s": 1170,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1334,
"s": 1268,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1358,
"s": 1334,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 1390,
"s": 1358,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 1407,
"s": 1390,
"text": "SQL using Python"
},
{
"code": null,
"e": 1440,
"s": 1407,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 1518,
"s": 1440,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 1548,
"s": 1518,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 1584,
"s": 1548,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 1615,
"s": 1584,
"text": "SQL Query to Compare Two Dates"
}
] |
Implementing OR Gate using Adaline Network
|
30 Jun, 2022
Adline stands for adaptive linear neuron. It makes use of linear activation function, and it uses the delta rule for training to minimize the mean squared errors between the actual output and the desired target output. The weights and bias are adjustable. Here, we perform 10 epochs of training and calculate total mean error in each case, the total mean error decreases after certain epochs and later becomes nearly constant.
Truth table for OR gate
Below is the implementation.
Python3
# import the module numpyimport numpy as np # the features for the or model , here we have# taken the possible values for combination of# two inputsfeatures = np.array( [ [-1, -1], [-1, 1], [1, -1], [1, 1] ]) # labels for the or model, here the output for# the features is taken as an arraylabels = np.array([-1, 1, 1, 1]) # to print the features and the labels for# which the model has to be trainedprint(features, labels) # initialise weights, bias , learning rate, epochweight = [0.5, 0.5]bias = 0.1learning_rate = 0.2epoch = 10 for i in range(epoch): # epoch is the number of the model is trained # with the same data print("epoch :", i+1) # variable to check if there is no change in previous # weight and present calculated weight # initial error is kept as 0 sum_squared_error = 0.0 # for each of the possible input given in the features for j in range(features.shape[0]): # actual output to be obtained actual = labels[j] # the value of two features as given in the features # array x1 = features[j][0] x2 = features[j][1] # net unit value computation performed to obtain the # sum of features multiplied with their weights unit = (x1 * weight[0]) + (x2 * weight[1]) + bias # error is computed so as to update the weights error = actual - unit # print statement to print the actual value , predicted # value and the error print("error =", error) # summation of squared error is calculated sum_squared_error += error * error # updation of weights, summing up of product of learning rate , # sum of squared error and feature value weight[0] += learning_rate * error * x1 weight[1] += learning_rate * error * x2 # updation of bias, summing up of product of learning rate and # sum of squared error bias += learning_rate * error print("sum of squared error = ", sum_squared_error/4, "\n\n")
Output:
[[-1 -1]
[-1 1]
[ 1 -1]
[ 1 1]] [-1 1 1 1]
epoch : 1
error = -0.09999999999999998
error = 0.9199999999999999
error = 1.1039999999999999
error = -0.5247999999999999
sum of squared error = 0.5876577599999998
epoch : 2
error = -0.54976
error = 0.803712
error = 0.8172543999999999
error = -0.64406528
sum of squared error = 0.5077284689412096
epoch : 3
error = -0.6729103360000002
error = 0.7483308032
error = 0.7399630438400001
error = -0.6898669486079996
sum of squared error = 0.5090672560860652
epoch : 4
error = -0.7047962935296
error = 0.72625757847552
error = 0.7201693816586239
error = -0.7061914301759491
sum of squared error = 0.5103845399996764
epoch : 5
error = -0.7124421954738586
error = 0.7182636328518943
error = 0.7154472043637898
error = -0.7117071786082882
sum of squared error = 0.5104670846209363
epoch : 6
error = -0.714060481354338
error = 0.715548426006041
error = 0.7144420989392495
error = -0.7134930727032405
sum of squared error = 0.5103479496309858
epoch : 7
error = -0.7143209120714415
error = 0.7146705871452027
error = 0.7142737539596766
error = -0.7140502797165604
sum of squared error = 0.5102658027779979
epoch : 8
error = -0.7143272889928647
error = 0.7143984993919014
error = 0.7142647152041359
error = -0.7142182126044045
sum of squared error = 0.510227607583693
epoch : 9
error = -0.7143072010372341
error = 0.7143174255259156
error = 0.7142744539151652
error = -0.7142671011374249
sum of squared error = 0.5102124122866718
epoch : 10
error = -0.7142946765305948
error = 0.7142942165270032
error = 0.7142809804050706
error = -0.7142808151475037
sum of squared error = 0.5102068786350209
prachisoda1234
simmytarika5
Neural Network
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Support Vector Machine Algorithm
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 481,
"s": 54,
"text": "Adline stands for adaptive linear neuron. It makes use of linear activation function, and it uses the delta rule for training to minimize the mean squared errors between the actual output and the desired target output. The weights and bias are adjustable. Here, we perform 10 epochs of training and calculate total mean error in each case, the total mean error decreases after certain epochs and later becomes nearly constant."
},
{
"code": null,
"e": 505,
"s": 481,
"text": "Truth table for OR gate"
},
{
"code": null,
"e": 534,
"s": 505,
"text": "Below is the implementation."
},
{
"code": null,
"e": 542,
"s": 534,
"text": "Python3"
},
{
"code": "# import the module numpyimport numpy as np # the features for the or model , here we have# taken the possible values for combination of# two inputsfeatures = np.array( [ [-1, -1], [-1, 1], [1, -1], [1, 1] ]) # labels for the or model, here the output for# the features is taken as an arraylabels = np.array([-1, 1, 1, 1]) # to print the features and the labels for# which the model has to be trainedprint(features, labels) # initialise weights, bias , learning rate, epochweight = [0.5, 0.5]bias = 0.1learning_rate = 0.2epoch = 10 for i in range(epoch): # epoch is the number of the model is trained # with the same data print(\"epoch :\", i+1) # variable to check if there is no change in previous # weight and present calculated weight # initial error is kept as 0 sum_squared_error = 0.0 # for each of the possible input given in the features for j in range(features.shape[0]): # actual output to be obtained actual = labels[j] # the value of two features as given in the features # array x1 = features[j][0] x2 = features[j][1] # net unit value computation performed to obtain the # sum of features multiplied with their weights unit = (x1 * weight[0]) + (x2 * weight[1]) + bias # error is computed so as to update the weights error = actual - unit # print statement to print the actual value , predicted # value and the error print(\"error =\", error) # summation of squared error is calculated sum_squared_error += error * error # updation of weights, summing up of product of learning rate , # sum of squared error and feature value weight[0] += learning_rate * error * x1 weight[1] += learning_rate * error * x2 # updation of bias, summing up of product of learning rate and # sum of squared error bias += learning_rate * error print(\"sum of squared error = \", sum_squared_error/4, \"\\n\\n\")",
"e": 2578,
"s": 542,
"text": null
},
{
"code": null,
"e": 2586,
"s": 2578,
"text": "Output:"
},
{
"code": null,
"e": 4253,
"s": 2586,
"text": "[[-1 -1]\n [-1 1]\n [ 1 -1]\n [ 1 1]] [-1 1 1 1]\nepoch : 1\nerror = -0.09999999999999998\nerror = 0.9199999999999999\nerror = 1.1039999999999999\nerror = -0.5247999999999999\nsum of squared error = 0.5876577599999998 \n\n\nepoch : 2\nerror = -0.54976\nerror = 0.803712\nerror = 0.8172543999999999\nerror = -0.64406528\nsum of squared error = 0.5077284689412096 \n\n\nepoch : 3\nerror = -0.6729103360000002\nerror = 0.7483308032\nerror = 0.7399630438400001\nerror = -0.6898669486079996\nsum of squared error = 0.5090672560860652 \n\n\nepoch : 4\nerror = -0.7047962935296\nerror = 0.72625757847552\nerror = 0.7201693816586239\nerror = -0.7061914301759491\nsum of squared error = 0.5103845399996764 \n\n\nepoch : 5\nerror = -0.7124421954738586\nerror = 0.7182636328518943\nerror = 0.7154472043637898\nerror = -0.7117071786082882\nsum of squared error = 0.5104670846209363 \n\n\nepoch : 6\nerror = -0.714060481354338\nerror = 0.715548426006041\nerror = 0.7144420989392495\nerror = -0.7134930727032405\nsum of squared error = 0.5103479496309858 \n\n\nepoch : 7\nerror = -0.7143209120714415\nerror = 0.7146705871452027\nerror = 0.7142737539596766\nerror = -0.7140502797165604\nsum of squared error = 0.5102658027779979 \n\n\nepoch : 8\nerror = -0.7143272889928647\nerror = 0.7143984993919014\nerror = 0.7142647152041359\nerror = -0.7142182126044045\nsum of squared error = 0.510227607583693 \n\n\nepoch : 9\nerror = -0.7143072010372341\nerror = 0.7143174255259156\nerror = 0.7142744539151652\nerror = -0.7142671011374249\nsum of squared error = 0.5102124122866718 \n\n\nepoch : 10\nerror = -0.7142946765305948\nerror = 0.7142942165270032\nerror = 0.7142809804050706\nerror = -0.7142808151475037\nsum of squared error = 0.5102068786350209"
},
{
"code": null,
"e": 4268,
"s": 4253,
"text": "prachisoda1234"
},
{
"code": null,
"e": 4281,
"s": 4268,
"text": "simmytarika5"
},
{
"code": null,
"e": 4296,
"s": 4281,
"text": "Neural Network"
},
{
"code": null,
"e": 4313,
"s": 4296,
"text": "Machine Learning"
},
{
"code": null,
"e": 4320,
"s": 4313,
"text": "Python"
},
{
"code": null,
"e": 4337,
"s": 4320,
"text": "Machine Learning"
},
{
"code": null,
"e": 4435,
"s": 4337,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4476,
"s": 4435,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 4512,
"s": 4476,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 4545,
"s": 4512,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 4569,
"s": 4545,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 4620,
"s": 4569,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 4648,
"s": 4620,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4698,
"s": 4648,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4720,
"s": 4698,
"text": "Python map() function"
}
] |
Python Program to generate one-time password (OTP)
|
21 Aug, 2021
One-time Passwords (OTP) is a password that is valid for only one login session or transaction in a computer or a digital device. Now a days OTP’s are used in almost every service like Internet Banking, online transactions, etc. They are generally combination of 4 or 6 numeric digits or a 6-digit alphanumeric.
random() function can be used to generate random OTP which is predefined in random library. Let’s see how to generate OTP using Python.
Used Function:random.random(): This function returns any random number between 0 to 1. math.floor(): It returns floor of any floating number to a integer value.Using the above function pick random index of string array which contains all the possible candidates of a particular digit of the OTP.
Example #1 : Generate 4 digit Numeric OTP
Python3
# import libraryimport math, random # function to generate OTPdef generateOTP() : # Declare a digits variable # which stores all digits digits = "0123456789" OTP = "" # length of password can be changed # by changing value in range for i in range(4) : OTP += digits[math.floor(random.random() * 10)] return OTP # Driver codeif __name__ == "__main__" : print("OTP of 4 digits:", generateOTP())
Output:
OTP of 4 digits: 3211
Example #2: Generate alphanumeric OTP of length 6
Python3
# import libraryimport math, random # function to generate OTPdef generateOTP() : # Declare a string variable # which stores all string string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' OTP = "" length = len(string) for i in range(6) : OTP += string[math.floor(random.random() * length)] return OTP # Driver codeif __name__ == "__main__" : print("OTP of length 6:", generateOTP())
Output:
OTP of length 6: pyelJl
Example #3: Using String constants
Python3
# Importing random to generate# random string sequenceimport random # Importing string library functionimport string def rand_pass(size): # Takes random choices from # ascii_letters and digits generate_pass = ''.join([random.choice( string.ascii_uppercase + string.ascii_lowercase + string.digits) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10)print(password)
Output:
2R8gaoDKqn
simmytarika5
ruhelaa48
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Aug, 2021"
},
{
"code": null,
"e": 365,
"s": 52,
"text": "One-time Passwords (OTP) is a password that is valid for only one login session or transaction in a computer or a digital device. Now a days OTP’s are used in almost every service like Internet Banking, online transactions, etc. They are generally combination of 4 or 6 numeric digits or a 6-digit alphanumeric. "
},
{
"code": null,
"e": 501,
"s": 365,
"text": "random() function can be used to generate random OTP which is predefined in random library. Let’s see how to generate OTP using Python."
},
{
"code": null,
"e": 797,
"s": 501,
"text": "Used Function:random.random(): This function returns any random number between 0 to 1. math.floor(): It returns floor of any floating number to a integer value.Using the above function pick random index of string array which contains all the possible candidates of a particular digit of the OTP."
},
{
"code": null,
"e": 841,
"s": 797,
"text": "Example #1 : Generate 4 digit Numeric OTP "
},
{
"code": null,
"e": 849,
"s": 841,
"text": "Python3"
},
{
"code": "# import libraryimport math, random # function to generate OTPdef generateOTP() : # Declare a digits variable # which stores all digits digits = \"0123456789\" OTP = \"\" # length of password can be changed # by changing value in range for i in range(4) : OTP += digits[math.floor(random.random() * 10)] return OTP # Driver codeif __name__ == \"__main__\" : print(\"OTP of 4 digits:\", generateOTP())",
"e": 1283,
"s": 849,
"text": null
},
{
"code": null,
"e": 1292,
"s": 1283,
"text": "Output: "
},
{
"code": null,
"e": 1314,
"s": 1292,
"text": "OTP of 4 digits: 3211"
},
{
"code": null,
"e": 1366,
"s": 1314,
"text": "Example #2: Generate alphanumeric OTP of length 6 "
},
{
"code": null,
"e": 1374,
"s": 1366,
"text": "Python3"
},
{
"code": "# import libraryimport math, random # function to generate OTPdef generateOTP() : # Declare a string variable # which stores all string string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' OTP = \"\" length = len(string) for i in range(6) : OTP += string[math.floor(random.random() * length)] return OTP # Driver codeif __name__ == \"__main__\" : print(\"OTP of length 6:\", generateOTP())",
"e": 1818,
"s": 1374,
"text": null
},
{
"code": null,
"e": 1827,
"s": 1818,
"text": "Output: "
},
{
"code": null,
"e": 1851,
"s": 1827,
"text": "OTP of length 6: pyelJl"
},
{
"code": null,
"e": 1886,
"s": 1851,
"text": "Example #3: Using String constants"
},
{
"code": null,
"e": 1894,
"s": 1886,
"text": "Python3"
},
{
"code": "# Importing random to generate# random string sequenceimport random # Importing string library functionimport string def rand_pass(size): # Takes random choices from # ascii_letters and digits generate_pass = ''.join([random.choice( string.ascii_uppercase + string.ascii_lowercase + string.digits) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10)print(password)",
"e": 2476,
"s": 1894,
"text": null
},
{
"code": null,
"e": 2485,
"s": 2476,
"text": "Output: "
},
{
"code": null,
"e": 2496,
"s": 2485,
"text": "2R8gaoDKqn"
},
{
"code": null,
"e": 2511,
"s": 2498,
"text": "simmytarika5"
},
{
"code": null,
"e": 2521,
"s": 2511,
"text": "ruhelaa48"
},
{
"code": null,
"e": 2528,
"s": 2521,
"text": "Python"
},
{
"code": null,
"e": 2544,
"s": 2528,
"text": "Python Programs"
}
] |
How to replace values of select return in MySQL?
|
You can use select case statement for this. The syntax is as follows.
select yourColumnName1,yourColumnName2,...N,
case when yourColumnName=1 then 'true'
else 'false'
end as anyVariableName
from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows.
mysql> create table selectReturnDemo
-> (
-> Id int,
-> Name varchar(100),
-> isGreaterthan18 tinyint(1)
-> );
Query OK, 0 rows affected (0.62 sec)
Now you can insert some records in the table using insert command. The query is as follows.
mysql> insert into selectReturnDemo values(1,'Carol',0);
Query OK, 1 row affected (0.23 sec)
mysql> insert into selectReturnDemo values(2,'Bob',1);
Query OK, 1 row affected (0.21 sec)
mysql> insert into selectReturnDemo values(3,'Mike',1);
Query OK, 1 row affected (0.18 sec)
mysql> insert into selectReturnDemo values(4,'David',0);
Query OK, 1 row affected (0.21 sec)
mysql> insert into selectReturnDemo values(5,'Adam',1);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement. The query is as follows.
mysql> select *from selectReturnDemo;
The following is the output.
+------+-------+-----------------+
| Id | Name | isGreaterthan18 |
+------+-------+-----------------+
| 1 | Carol | 0 |
| 2 | Bob | 1 |
| 3 | Mike | 1 |
| 4 | David | 0 |
| 5 | Adam | 1 |
+------+-------+-----------------+
5 rows in set (0.00 sec)
Here is the query to replace value with select return. The query is as follows.
mysql> select Id,Name,
-> case when isGreaterthan18=1 then 'true'
-> else 'false'
-> end as AgeIsGreaterthan18
-> from selectReturnDemo;
The following is the output.
+------+-------+--------------------+
| Id | Name | AgeIsGreaterthan18 |
+------+-------+--------------------+
| 1 | Carol | false |
| 2 | Bob | true |
| 3 | Mike | true |
| 4 | David | false |
| 5 | Adam | true |
+------+-------+--------------------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1257,
"s": 1187,
"text": "You can use select case statement for this. The syntax is as follows."
},
{
"code": null,
"e": 1397,
"s": 1257,
"text": "select yourColumnName1,yourColumnName2,...N,\ncase when yourColumnName=1 then 'true'\nelse 'false'\nend as anyVariableName\nfrom yourTableName;"
},
{
"code": null,
"e": 1495,
"s": 1397,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows."
},
{
"code": null,
"e": 1643,
"s": 1495,
"text": "mysql> create table selectReturnDemo\n-> (\n-> Id int,\n-> Name varchar(100),\n-> isGreaterthan18 tinyint(1)\n-> );\nQuery OK, 0 rows affected (0.62 sec)"
},
{
"code": null,
"e": 1735,
"s": 1643,
"text": "Now you can insert some records in the table using insert command. The query is as follows."
},
{
"code": null,
"e": 2200,
"s": 1735,
"text": "mysql> insert into selectReturnDemo values(1,'Carol',0);\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into selectReturnDemo values(2,'Bob',1);\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into selectReturnDemo values(3,'Mike',1);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into selectReturnDemo values(4,'David',0);\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into selectReturnDemo values(5,'Adam',1);\nQuery OK, 1 row affected (0.10 sec)"
},
{
"code": null,
"e": 2284,
"s": 2200,
"text": "Display all records from the table using select statement. The query is as follows."
},
{
"code": null,
"e": 2322,
"s": 2284,
"text": "mysql> select *from selectReturnDemo;"
},
{
"code": null,
"e": 2351,
"s": 2322,
"text": "The following is the output."
},
{
"code": null,
"e": 2691,
"s": 2351,
"text": "+------+-------+-----------------+\n| Id | Name | isGreaterthan18 |\n+------+-------+-----------------+\n| 1 | Carol | 0 |\n| 2 | Bob | 1 |\n| 3 | Mike | 1 |\n| 4 | David | 0 |\n| 5 | Adam | 1 |\n+------+-------+-----------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2771,
"s": 2691,
"text": "Here is the query to replace value with select return. The query is as follows."
},
{
"code": null,
"e": 2908,
"s": 2771,
"text": "mysql> select Id,Name,\n-> case when isGreaterthan18=1 then 'true'\n-> else 'false'\n-> end as AgeIsGreaterthan18\n-> from selectReturnDemo;"
},
{
"code": null,
"e": 2937,
"s": 2908,
"text": "The following is the output."
},
{
"code": null,
"e": 3304,
"s": 2937,
"text": "+------+-------+--------------------+\n| Id | Name | AgeIsGreaterthan18 |\n+------+-------+--------------------+\n| 1 | Carol | false |\n| 2 | Bob | true |\n| 3 | Mike | true |\n| 4 | David | false |\n| 5 | Adam | true |\n+------+-------+--------------------+\n5 rows in set (0.00 sec)"
}
] |
How to sort an array of object by two fields in JavaScript ?
|
13 Dec, 2019
Given an array of objects and the task is to sort the array elements by 2 fields of the object. There are two methods to solve this problem which are discussed below:
Approach 1:
First compare the first property, if both are unequal then sort accordingly.
If they are equal then do the same for the second property.
Example: This example implements the above approach.
<!DOCTYPE HTML> <html> <head> <title> How to sort an array of object by two fields in JavaScript ? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> Click Here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = [ {first: 3, second: 4}, {first: 3, second: 1}, {first: 1, second: 10} ]; el_up.innerHTML = "Click on the button to sort " + "the array accordingly.<br>Array = '" + JSON.stringify(arr[0]) + ", " + JSON.stringify(arr[1]) +", " + JSON.stringify(arr[2]) + "'"; arr.sort(function (a, b) { var af = a.first; var bf = b.first; var as = a.second; var bs = b.second; if(af == bf) { return (as < bs) ? -1 : (as > bs) ? 1 : 0; } else { return (af < bf) ? -1 : 1; } }); function gfg_Run() { el_down.innerHTML = "'" + JSON.stringify(arr[0]) + ", " + JSON.stringify(arr[1]) + ", " + JSON.stringify(arr[2]) + "'"; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
First compare the first property, If both are unequal then sort accordingly.
If they are equal then do the same for the second property, this example is following the same approach but using OR Gate to reduce the code.
Example: This example implements the above approach.
<!DOCTYPE HTML> <html> <head> <title> How to sort an array of object by two fields in JavaScript ? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> Click Here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = [ {first: 3, second: 4}, {first: 3, second: 1}, {first: 1, second: 10} ]; el_up.innerHTML = "Click on the button to sort " + "the array accordingly.<br>Array = '" + JSON.stringify(arr[0]) + ", " + JSON.stringify(arr[1]) +", " + JSON.stringify(arr[2]) + "'"; arr.sort(function (a, b) { return a.first - b.first || a.second - b.second; }); function gfg_Run() { el_down.innerHTML = "'" + JSON.stringify(arr[0]) + ", " + JSON.stringify(arr[1]) + ", " + JSON.stringify(arr[2]) + "'"; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-array
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Dec, 2019"
},
{
"code": null,
"e": 195,
"s": 28,
"text": "Given an array of objects and the task is to sort the array elements by 2 fields of the object. There are two methods to solve this problem which are discussed below:"
},
{
"code": null,
"e": 207,
"s": 195,
"text": "Approach 1:"
},
{
"code": null,
"e": 284,
"s": 207,
"text": "First compare the first property, if both are unequal then sort accordingly."
},
{
"code": null,
"e": 344,
"s": 284,
"text": "If they are equal then do the same for the second property."
},
{
"code": null,
"e": 397,
"s": 344,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to sort an array of object by two fields in JavaScript ? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> Click Here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [ {first: 3, second: 4}, {first: 3, second: 1}, {first: 1, second: 10} ]; el_up.innerHTML = \"Click on the button to sort \" + \"the array accordingly.<br>Array = '\" + JSON.stringify(arr[0]) + \", \" + JSON.stringify(arr[1]) +\", \" + JSON.stringify(arr[2]) + \"'\"; arr.sort(function (a, b) { var af = a.first; var bf = b.first; var as = a.second; var bs = b.second; if(af == bf) { return (as < bs) ? -1 : (as > bs) ? 1 : 0; } else { return (af < bf) ? -1 : 1; } }); function gfg_Run() { el_down.innerHTML = \"'\" + JSON.stringify(arr[0]) + \", \" + JSON.stringify(arr[1]) + \", \" + JSON.stringify(arr[2]) + \"'\"; } </script> </body> </html>",
"e": 2024,
"s": 397,
"text": null
},
{
"code": null,
"e": 2032,
"s": 2024,
"text": "Output:"
},
{
"code": null,
"e": 2063,
"s": 2032,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 2093,
"s": 2063,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 2105,
"s": 2093,
"text": "Approach 2:"
},
{
"code": null,
"e": 2182,
"s": 2105,
"text": "First compare the first property, If both are unequal then sort accordingly."
},
{
"code": null,
"e": 2324,
"s": 2182,
"text": "If they are equal then do the same for the second property, this example is following the same approach but using OR Gate to reduce the code."
},
{
"code": null,
"e": 2377,
"s": 2324,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to sort an array of object by two fields in JavaScript ? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> Click Here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [ {first: 3, second: 4}, {first: 3, second: 1}, {first: 1, second: 10} ]; el_up.innerHTML = \"Click on the button to sort \" + \"the array accordingly.<br>Array = '\" + JSON.stringify(arr[0]) + \", \" + JSON.stringify(arr[1]) +\", \" + JSON.stringify(arr[2]) + \"'\"; arr.sort(function (a, b) { return a.first - b.first || a.second - b.second; }); function gfg_Run() { el_down.innerHTML = \"'\" + JSON.stringify(arr[0]) + \", \" + JSON.stringify(arr[1]) + \", \" + JSON.stringify(arr[2]) + \"'\"; } </script> </body> </html>",
"e": 3784,
"s": 2377,
"text": null
},
{
"code": null,
"e": 3792,
"s": 3784,
"text": "Output:"
},
{
"code": null,
"e": 3823,
"s": 3792,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 3853,
"s": 3823,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3870,
"s": 3853,
"text": "javascript-array"
},
{
"code": null,
"e": 3881,
"s": 3870,
"text": "JavaScript"
},
{
"code": null,
"e": 3898,
"s": 3881,
"text": "Web Technologies"
},
{
"code": null,
"e": 3925,
"s": 3898,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4023,
"s": 3925,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4084,
"s": 4023,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4156,
"s": 4084,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4196,
"s": 4156,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4248,
"s": 4196,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 4289,
"s": 4248,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4351,
"s": 4289,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4384,
"s": 4351,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4445,
"s": 4384,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4495,
"s": 4445,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python List count() method
|
03 Aug, 2021
Python List count() is an inbuilt function in Python that returns the count of how many times a given object occurs in a List. The count() function is used to count elements on a list as well as a string.
Syntax:
list_name.count(object)
Parameters:
The object is the things whose count is to be returned.
Returns:
count() method returns the count of how many times object occurs in the list.
Exception:
If more then 1 parameter is passed in count() method, it returns a TypeError.
Python3
# Python3 program to count the number of times# an object appears in a list using count() method list1 = [1, 1, 1, 2, 3, 2, 1] # Counts the number of times 1 appears in list1print(list1.count(1)) list2 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b'] # Counts the number of times 'b' appears in list2print(list2.count('b')) list3 = ['Cat', 'Bat', 'Sat', 'Cat', 'cat', 'Mat'] # Counts the number of times 'Cat' appears in list3print(list3.count('Cat'))
Output:
4
3
2
Python3
# Python3 program to demonstrate# the error in count() method list1 = [1, 1, 1, 2, 3, 2, 1] # Error when two parameters is passed.print(list1.count(1, 2))
Output:
Traceback (most recent call last):
File "/home/41d2d7646b4b549b399b0dfe29e38c53.py", line 7, in
print(list1.count(1, 2))
TypeError: count() takes exactly one argument (2 given)
Python3
# Python3 program to count the number of times# an object appears in a list using count() method list1 = [ ('Cat', 'Bat'), ('Sat', 'Cat'), ('Cat', 'Bat'), ('Cat', 'Bat', 'Sat'), [1, 2], [1, 2, 3], [1, 2] ] # Counts the number of times 'Cat' appears in list1print(list1.count(('Cat', 'Bat'))) # Count the number of times sublist# '[1, 2]' appears in list1print(list1.count([1, 2]))
Output:
2
2
Let’s say we want to count each element in a list and store it in another list or say dictionary.
Python3
# Python3 program to count the number of times# an object appears in a list using count() method lst = ['Cat', 'Bat', 'Sat', 'Cat', 'Mat', 'Cat', 'Sat'] # To get the number of occurrences# of each item in a listprint ([ [l, lst.count(l)] for l in set(lst)]) # To get the number of occurrences# of each item in a dictionaryprint (dict( (l, lst.count(l) ) for l in set(lst)))
Output:
[['Mat', 1], ['Cat', 3], ['Sat', 2], ['Bat', 1]]
{'Bat': 1, 'Cat': 3, 'Sat': 2, 'Mat': 1}
AmiyaRanjanRout
Python-Built-in-functions
python-list
python-list-functions
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 257,
"s": 52,
"text": "Python List count() is an inbuilt function in Python that returns the count of how many times a given object occurs in a List. The count() function is used to count elements on a list as well as a string."
},
{
"code": null,
"e": 266,
"s": 257,
"text": "Syntax: "
},
{
"code": null,
"e": 291,
"s": 266,
"text": "list_name.count(object) "
},
{
"code": null,
"e": 304,
"s": 291,
"text": "Parameters: "
},
{
"code": null,
"e": 361,
"s": 304,
"text": "The object is the things whose count is to be returned. "
},
{
"code": null,
"e": 371,
"s": 361,
"text": "Returns: "
},
{
"code": null,
"e": 449,
"s": 371,
"text": "count() method returns the count of how many times object occurs in the list."
},
{
"code": null,
"e": 461,
"s": 449,
"text": "Exception: "
},
{
"code": null,
"e": 539,
"s": 461,
"text": "If more then 1 parameter is passed in count() method, it returns a TypeError."
},
{
"code": null,
"e": 547,
"s": 539,
"text": "Python3"
},
{
"code": "# Python3 program to count the number of times# an object appears in a list using count() method list1 = [1, 1, 1, 2, 3, 2, 1] # Counts the number of times 1 appears in list1print(list1.count(1)) list2 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b'] # Counts the number of times 'b' appears in list2print(list2.count('b')) list3 = ['Cat', 'Bat', 'Sat', 'Cat', 'cat', 'Mat'] # Counts the number of times 'Cat' appears in list3print(list3.count('Cat'))",
"e": 993,
"s": 547,
"text": null
},
{
"code": null,
"e": 1001,
"s": 993,
"text": "Output:"
},
{
"code": null,
"e": 1007,
"s": 1001,
"text": "4\n3\n2"
},
{
"code": null,
"e": 1015,
"s": 1007,
"text": "Python3"
},
{
"code": "# Python3 program to demonstrate# the error in count() method list1 = [1, 1, 1, 2, 3, 2, 1] # Error when two parameters is passed.print(list1.count(1, 2))",
"e": 1170,
"s": 1015,
"text": null
},
{
"code": null,
"e": 1178,
"s": 1170,
"text": "Output:"
},
{
"code": null,
"e": 1364,
"s": 1178,
"text": "Traceback (most recent call last):\n File \"/home/41d2d7646b4b549b399b0dfe29e38c53.py\", line 7, in \n print(list1.count(1, 2)) \nTypeError: count() takes exactly one argument (2 given)"
},
{
"code": null,
"e": 1372,
"s": 1364,
"text": "Python3"
},
{
"code": "# Python3 program to count the number of times# an object appears in a list using count() method list1 = [ ('Cat', 'Bat'), ('Sat', 'Cat'), ('Cat', 'Bat'), ('Cat', 'Bat', 'Sat'), [1, 2], [1, 2, 3], [1, 2] ] # Counts the number of times 'Cat' appears in list1print(list1.count(('Cat', 'Bat'))) # Count the number of times sublist# '[1, 2]' appears in list1print(list1.count([1, 2]))",
"e": 1762,
"s": 1372,
"text": null
},
{
"code": null,
"e": 1771,
"s": 1762,
"text": "Output: "
},
{
"code": null,
"e": 1775,
"s": 1771,
"text": "2\n2"
},
{
"code": null,
"e": 1875,
"s": 1775,
"text": " Let’s say we want to count each element in a list and store it in another list or say dictionary. "
},
{
"code": null,
"e": 1883,
"s": 1875,
"text": "Python3"
},
{
"code": "# Python3 program to count the number of times# an object appears in a list using count() method lst = ['Cat', 'Bat', 'Sat', 'Cat', 'Mat', 'Cat', 'Sat'] # To get the number of occurrences# of each item in a listprint ([ [l, lst.count(l)] for l in set(lst)]) # To get the number of occurrences# of each item in a dictionaryprint (dict( (l, lst.count(l) ) for l in set(lst)))",
"e": 2257,
"s": 1883,
"text": null
},
{
"code": null,
"e": 2265,
"s": 2257,
"text": "Output:"
},
{
"code": null,
"e": 2355,
"s": 2265,
"text": "[['Mat', 1], ['Cat', 3], ['Sat', 2], ['Bat', 1]]\n{'Bat': 1, 'Cat': 3, 'Sat': 2, 'Mat': 1}"
},
{
"code": null,
"e": 2371,
"s": 2355,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 2397,
"s": 2371,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2409,
"s": 2397,
"text": "python-list"
},
{
"code": null,
"e": 2431,
"s": 2409,
"text": "python-list-functions"
},
{
"code": null,
"e": 2438,
"s": 2431,
"text": "Python"
},
{
"code": null,
"e": 2450,
"s": 2438,
"text": "python-list"
},
{
"code": null,
"e": 2548,
"s": 2450,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2566,
"s": 2548,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2608,
"s": 2566,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2630,
"s": 2608,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2656,
"s": 2630,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2688,
"s": 2656,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2717,
"s": 2688,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2744,
"s": 2717,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2765,
"s": 2744,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2801,
"s": 2765,
"text": "Convert integer to string in Python"
}
] |
Program to match vowels in a string using regular expression in Java
|
You can group all the required characters to match within the square braces “[ ]” i.e. The metacharacter/sub-expression “[ ]” matches all the specified characters. Therefore, to match all the letters specify the vowel letters within these as shown below −
[aeiouAEIOU]
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchVowels {
public static void main( String args[] ) {
String regex = "[aeiouAEIOU]";
System.out.println("Enter input string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Compiling the regular expression
Pattern.compile(regex);
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("The input string contains vowels");
} else {
System.out.println("The input string does not contain vowels");
}
}
}
Enter input string:
hello how are you welcome
The input string contains vowels
import java.util.Scanner;
public class Test {
public static void main( String args[] ) {
String regex = "[aeiouAEIOU]";
System.out.println("Enter input string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
boolean result = input.matches(regex);
if(result) {
System.out.println("The input string contains vowels");
} else {
System.out.println("The input string does not contain vowels");
}
}
}
Enter input string:
hello how are you welcome
The input string does not contain vowels
|
[
{
"code": null,
"e": 1443,
"s": 1187,
"text": "You can group all the required characters to match within the square braces “[ ]” i.e. The metacharacter/sub-expression “[ ]” matches all the specified characters. Therefore, to match all the letters specify the vowel letters within these as shown below −"
},
{
"code": null,
"e": 1456,
"s": 1443,
"text": "[aeiouAEIOU]"
},
{
"code": null,
"e": 2188,
"s": 1456,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class MatchVowels {\n public static void main( String args[] ) {\n String regex = \"[aeiouAEIOU]\";\n System.out.println(\"Enter input string: \");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n //Compiling the regular expression\n Pattern.compile(regex);\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(input);\n if(matcher.find()) {\n System.out.println(\"The input string contains vowels\");\n } else {\n System.out.println(\"The input string does not contain vowels\");\n }\n }\n}"
},
{
"code": null,
"e": 2267,
"s": 2188,
"text": "Enter input string:\nhello how are you welcome\nThe input string contains vowels"
},
{
"code": null,
"e": 2757,
"s": 2267,
"text": "import java.util.Scanner;\npublic class Test {\n public static void main( String args[] ) {\n String regex = \"[aeiouAEIOU]\";\n System.out.println(\"Enter input string: \");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n boolean result = input.matches(regex);\n if(result) {\n System.out.println(\"The input string contains vowels\");\n } else {\n System.out.println(\"The input string does not contain vowels\");\n }\n }\n}"
},
{
"code": null,
"e": 2844,
"s": 2757,
"text": "Enter input string:\nhello how are you welcome\nThe input string does not contain vowels"
}
] |
p5.js | pow() function
|
08 Apr, 2019
The pow() function in p5.js is used to calculate the power of a number to the given number. It is an efficient way of multiplying numbers by themselves (or their reciprocals) in large quantities.
Syntax
pow( n, e )
Parameters: The function accepts two parameters as mentioned above and described below:
n: This parameter stores the base of the exponential expression.
e: This parameter stores the power by which to raise the base.
Below program illustrates the pow() function in p5.js:
Example: This example uses pow() function to calculate power of a number.
function setup() { // Create Canvas of size 270*80 createCanvas(350, 80);} function draw() { // Set the background color background(220); // Initialize the parameter let n = 3; let e = 4; // Call to pow() function let y = pow(n, e); // Set the size of text textSize(16); // Set the text color fill(color('red')); text("Given number is " + n + " and exponent is " + e + " ", 50, 30); text("Computed Number is : " + y, 50, 50);}
Output:
Reference: https://p5js.org/reference/#/p5/pow
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2019"
},
{
"code": null,
"e": 224,
"s": 28,
"text": "The pow() function in p5.js is used to calculate the power of a number to the given number. It is an efficient way of multiplying numbers by themselves (or their reciprocals) in large quantities."
},
{
"code": null,
"e": 231,
"s": 224,
"text": "Syntax"
},
{
"code": null,
"e": 244,
"s": 231,
"text": "pow( n, e )\n"
},
{
"code": null,
"e": 332,
"s": 244,
"text": "Parameters: The function accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 397,
"s": 332,
"text": "n: This parameter stores the base of the exponential expression."
},
{
"code": null,
"e": 460,
"s": 397,
"text": "e: This parameter stores the power by which to raise the base."
},
{
"code": null,
"e": 515,
"s": 460,
"text": "Below program illustrates the pow() function in p5.js:"
},
{
"code": null,
"e": 589,
"s": 515,
"text": "Example: This example uses pow() function to calculate power of a number."
},
{
"code": "function setup() { // Create Canvas of size 270*80 createCanvas(350, 80);} function draw() { // Set the background color background(220); // Initialize the parameter let n = 3; let e = 4; // Call to pow() function let y = pow(n, e); // Set the size of text textSize(16); // Set the text color fill(color('red')); text(\"Given number is \" + n + \" and exponent is \" + e + \" \", 50, 30); text(\"Computed Number is : \" + y, 50, 50);}",
"e": 1118,
"s": 589,
"text": null
},
{
"code": null,
"e": 1126,
"s": 1118,
"text": "Output:"
},
{
"code": null,
"e": 1173,
"s": 1126,
"text": "Reference: https://p5js.org/reference/#/p5/pow"
},
{
"code": null,
"e": 1190,
"s": 1173,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1201,
"s": 1190,
"text": "JavaScript"
},
{
"code": null,
"e": 1218,
"s": 1201,
"text": "Web Technologies"
}
] |
How to Interpret Models: PDP and ICE | by Zachary Warnes | Towards Data Science
|
Model interpretability is becoming increasingly valuable. However, when handling large models with complex relationships, interpretation is not always an easy task.
Partial Dependence Plots (PDP) plots show the marginal contribution of different features on the output. They are used to display either the contribution of a single feature or two features.
Partial dependence plots are also highly related to Individual Conditional Expectation (ICE) plots. ICE plots show the prediction changes for each data instance.
These plots are model agnostic, meaning that regardless of the underlying model, they can show how changing one or two features affects the model’s output.
For tasks such as price prediction, knowing the PDP trends of each feature is vital to understanding how your models would make predictions with new data. Ideally, these PDP plots should be explainable and understandable to drive decision making.
Both plots use the same mechanism to model the prediction changes. However, where PDP observe the overall trends of one or two features, ICE plots show a variation on a more granular level.
These plots can be used in parallel to understand the predictions’ overall trends and check problematic individual cases. Because PDPs show the output changes on an aggregate level, the more minor variations of particular instances are lost. Therefore it is best to look at both variations.
When the predictive task is a regression model, the changes show in the output are directly the change in prediction. However, during classification, the output change is the change in the predicted probability of the class.
For PDP, to estimate the partial function, the averages are calculated with the training data with a Monte Carlo method:
To showcase each of the methods and walk through the interpretation of the plots, I am using the ‘Abalone’ dataset.
This data set is licensed under the Open Data Commons Public Domain Dedication and License (PDDL).
datahub.io
The goal of this dataset is to determine the age of abalone. Usually, this is done via cutting through the cone, staining it, and counting the number of rings with a microscope. Unfortunately, measuring age in this way is very time-consuming, invasive, and laborious.
Instead, using eight features, the age can be predicted effectively. The features are sex, length, diameter, height, whole weight, shucked weight, viscera weight, and shell weight. This data has 4177 records and eight features.
Both PDP and ICE plots can be generated from the same package in sklearn.
from sklearn.inspection import plot_partial_dependence# PD Plotsplot_partial_dependence(model, X, [feature_name])
The dependence plots are based on a gradient boosting-tree regressor model.
In the plots, the behaviour of the model for both the ‘Shucked weight’ and the ‘Whole weight’ is shown. The age prediction of the abalone decreases when the Shucked weight increases. Whereas for ‘Whole weight’, an increase for this feature increases the predicted age, but for low values, the prediction doesn’t change.
Also, the percentiles of the feature values are shown at the bottom of each plot. Each significant black mark represents the percentile of the feature in increments of 10.
# ICE Plotsplot_partial_dependence(model, X, [feature_name], kind='individual')
Next are the PD plot and the ICE plot for height. In the PD plot, the trend is no longer linear as the value increases. Once the height is beyond 0.3, the height no longer contributes to the overall age prediction (specified with the partial dependence of 0).
In the ICE plot, this pattern is consistent among all of the instances. With a low height, the predicted age decreased. However, when height increases, the prediction increases until the height passes a threshold.
The distribution of height causes this strange behaviour. For reference, the maximum value is 1.13, but at the 75th percentile, the value is only 0.165.
The plots attempt to model across the range of values for each feature. But when most feature values are concentrated to a subset of values, the model does not learn this range well.
Therefore, we can not be confident when a new instance has a value for height in this range.
from sklearn.inspection import plot_partial_dependence# PD Plots, 2-dimensionalplot_partial_dependence(model, X, [(feature_1, feature_2)], kind='both')
The final partial dependence plot observes two features interacting towards the final output. Here the ‘Whole weight’ and the ‘Shucked weight’ are shown.
The change in values to the final output is shown with the colours of the contours, and the previous behaviours of each feature are still present.
An increase in the ‘Whole weight’ increases the predicted age once beyond the threshold previously defined. And for the ‘Shucked weight’, the prediction decreases as the value increases. So for these two features, there is not much more interaction.
Partial dependence plots and individual conditional expectation plots are a great way to start to understand your models. In addition, they are easy to implement and apply to every model.
Both plots allow the user to understand better the tendencies of their model and exposure inconsistencies and irregular model behaviour.
These plots are dependent on the underlying model used in the supervised learning task. However, they reveal model behaviours overall and at the individual instance level. Thus, they allow you to interpret your models effectively.
If you’re interested in reading articles about novel data science tools and understanding machine learning algorithms, consider following me on Medium.
If you’re interested in my writing and want to support me directly, please subscribe through the following link. This link ensures that I will receive a portion of your membership fees.
|
[
{
"code": null,
"e": 337,
"s": 172,
"text": "Model interpretability is becoming increasingly valuable. However, when handling large models with complex relationships, interpretation is not always an easy task."
},
{
"code": null,
"e": 528,
"s": 337,
"text": "Partial Dependence Plots (PDP) plots show the marginal contribution of different features on the output. They are used to display either the contribution of a single feature or two features."
},
{
"code": null,
"e": 690,
"s": 528,
"text": "Partial dependence plots are also highly related to Individual Conditional Expectation (ICE) plots. ICE plots show the prediction changes for each data instance."
},
{
"code": null,
"e": 846,
"s": 690,
"text": "These plots are model agnostic, meaning that regardless of the underlying model, they can show how changing one or two features affects the model’s output."
},
{
"code": null,
"e": 1093,
"s": 846,
"text": "For tasks such as price prediction, knowing the PDP trends of each feature is vital to understanding how your models would make predictions with new data. Ideally, these PDP plots should be explainable and understandable to drive decision making."
},
{
"code": null,
"e": 1283,
"s": 1093,
"text": "Both plots use the same mechanism to model the prediction changes. However, where PDP observe the overall trends of one or two features, ICE plots show a variation on a more granular level."
},
{
"code": null,
"e": 1574,
"s": 1283,
"text": "These plots can be used in parallel to understand the predictions’ overall trends and check problematic individual cases. Because PDPs show the output changes on an aggregate level, the more minor variations of particular instances are lost. Therefore it is best to look at both variations."
},
{
"code": null,
"e": 1799,
"s": 1574,
"text": "When the predictive task is a regression model, the changes show in the output are directly the change in prediction. However, during classification, the output change is the change in the predicted probability of the class."
},
{
"code": null,
"e": 1920,
"s": 1799,
"text": "For PDP, to estimate the partial function, the averages are calculated with the training data with a Monte Carlo method:"
},
{
"code": null,
"e": 2036,
"s": 1920,
"text": "To showcase each of the methods and walk through the interpretation of the plots, I am using the ‘Abalone’ dataset."
},
{
"code": null,
"e": 2135,
"s": 2036,
"text": "This data set is licensed under the Open Data Commons Public Domain Dedication and License (PDDL)."
},
{
"code": null,
"e": 2146,
"s": 2135,
"text": "datahub.io"
},
{
"code": null,
"e": 2414,
"s": 2146,
"text": "The goal of this dataset is to determine the age of abalone. Usually, this is done via cutting through the cone, staining it, and counting the number of rings with a microscope. Unfortunately, measuring age in this way is very time-consuming, invasive, and laborious."
},
{
"code": null,
"e": 2642,
"s": 2414,
"text": "Instead, using eight features, the age can be predicted effectively. The features are sex, length, diameter, height, whole weight, shucked weight, viscera weight, and shell weight. This data has 4177 records and eight features."
},
{
"code": null,
"e": 2716,
"s": 2642,
"text": "Both PDP and ICE plots can be generated from the same package in sklearn."
},
{
"code": null,
"e": 2830,
"s": 2716,
"text": "from sklearn.inspection import plot_partial_dependence# PD Plotsplot_partial_dependence(model, X, [feature_name])"
},
{
"code": null,
"e": 2906,
"s": 2830,
"text": "The dependence plots are based on a gradient boosting-tree regressor model."
},
{
"code": null,
"e": 3226,
"s": 2906,
"text": "In the plots, the behaviour of the model for both the ‘Shucked weight’ and the ‘Whole weight’ is shown. The age prediction of the abalone decreases when the Shucked weight increases. Whereas for ‘Whole weight’, an increase for this feature increases the predicted age, but for low values, the prediction doesn’t change."
},
{
"code": null,
"e": 3398,
"s": 3226,
"text": "Also, the percentiles of the feature values are shown at the bottom of each plot. Each significant black mark represents the percentile of the feature in increments of 10."
},
{
"code": null,
"e": 3478,
"s": 3398,
"text": "# ICE Plotsplot_partial_dependence(model, X, [feature_name], kind='individual')"
},
{
"code": null,
"e": 3738,
"s": 3478,
"text": "Next are the PD plot and the ICE plot for height. In the PD plot, the trend is no longer linear as the value increases. Once the height is beyond 0.3, the height no longer contributes to the overall age prediction (specified with the partial dependence of 0)."
},
{
"code": null,
"e": 3952,
"s": 3738,
"text": "In the ICE plot, this pattern is consistent among all of the instances. With a low height, the predicted age decreased. However, when height increases, the prediction increases until the height passes a threshold."
},
{
"code": null,
"e": 4105,
"s": 3952,
"text": "The distribution of height causes this strange behaviour. For reference, the maximum value is 1.13, but at the 75th percentile, the value is only 0.165."
},
{
"code": null,
"e": 4288,
"s": 4105,
"text": "The plots attempt to model across the range of values for each feature. But when most feature values are concentrated to a subset of values, the model does not learn this range well."
},
{
"code": null,
"e": 4381,
"s": 4288,
"text": "Therefore, we can not be confident when a new instance has a value for height in this range."
},
{
"code": null,
"e": 4533,
"s": 4381,
"text": "from sklearn.inspection import plot_partial_dependence# PD Plots, 2-dimensionalplot_partial_dependence(model, X, [(feature_1, feature_2)], kind='both')"
},
{
"code": null,
"e": 4687,
"s": 4533,
"text": "The final partial dependence plot observes two features interacting towards the final output. Here the ‘Whole weight’ and the ‘Shucked weight’ are shown."
},
{
"code": null,
"e": 4834,
"s": 4687,
"text": "The change in values to the final output is shown with the colours of the contours, and the previous behaviours of each feature are still present."
},
{
"code": null,
"e": 5084,
"s": 4834,
"text": "An increase in the ‘Whole weight’ increases the predicted age once beyond the threshold previously defined. And for the ‘Shucked weight’, the prediction decreases as the value increases. So for these two features, there is not much more interaction."
},
{
"code": null,
"e": 5272,
"s": 5084,
"text": "Partial dependence plots and individual conditional expectation plots are a great way to start to understand your models. In addition, they are easy to implement and apply to every model."
},
{
"code": null,
"e": 5409,
"s": 5272,
"text": "Both plots allow the user to understand better the tendencies of their model and exposure inconsistencies and irregular model behaviour."
},
{
"code": null,
"e": 5640,
"s": 5409,
"text": "These plots are dependent on the underlying model used in the supervised learning task. However, they reveal model behaviours overall and at the individual instance level. Thus, they allow you to interpret your models effectively."
},
{
"code": null,
"e": 5792,
"s": 5640,
"text": "If you’re interested in reading articles about novel data science tools and understanding machine learning algorithms, consider following me on Medium."
}
] |
How to mount usb drive in a linux system
|
Do you know “how to use USB memory sticks with Linux”, If you are not sure then this article describes “how to mount USB drive on a Linux system with command line interface”
Universal serial bus, or USB (also known as Flash drive), is an electronic communications protocol that is commonly used in computer accessories and other small devices. If you have an up-to-date Linux system and a modern Desktop environment, your device should show up on your desktop, with no need to open a console. There are few important factors which are involved in learning how to mount USB drive with Linux machine.
Following are the step by step instructions to understand further –
After you plug in your USB device to your Linux system USB port, It will add new block device into /dev/ directory. To verify it, use the following command –
$ sudo fdisk -l
The sample output should be like this –
Disk /dev/sdb: 15.7 GB, 15664676864 bytes
255 heads, 63 sectors/track, 1904 cylinders, total 30595072 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Device Boot Start End Blocks Id System
/dev/sdb1 * 32 30595071 15297520 c W95 FAT32 (LBA)
We can observe from the above result that, device boot, blocks, id and system format are displayed.
To mount the USB, use the following command –
$ mount /dev/sdb1 /mnt
To create a directory in the mounted device, use the following commands –
$ cd /mnt
/mnt$ mkdir john
The above command creates a directory called john in USB device.
To delete a directory in USB, use the following command –
/mnt$ rmdir john
You should unmount the device first to format the USB device, then use the following command to unmount the device –
$ sudo umount /dev/sdb1
Now use either of the commands as per file system based on your requirement. To format a USB drive, users generally prefer VFAT or NTFS file systems because they can be easily mounted on Windows operating systems and Linux systems.
To format USB with vFat File System, use the following command –
$ sudo mkfs.vfat /dev/sdb1
To format a USB Flash Drive with NTFS file system, use the following command –
$ sudo mkfs.ntfs /dev/sdb1
To format a USB with EXT4 file system, use the following command –
$ sudo mkfs.ext4 /dev/sdb1
Congratulations! Now, you know “How to Mount USB Drive in a Linux System?”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
|
[
{
"code": null,
"e": 1236,
"s": 1062,
"text": "Do you know “how to use USB memory sticks with Linux”, If you are not sure then this article describes “how to mount USB drive on a Linux system with command line interface”"
},
{
"code": null,
"e": 1661,
"s": 1236,
"text": "Universal serial bus, or USB (also known as Flash drive), is an electronic communications protocol that is commonly used in computer accessories and other small devices. If you have an up-to-date Linux system and a modern Desktop environment, your device should show up on your desktop, with no need to open a console. There are few important factors which are involved in learning how to mount USB drive with Linux machine."
},
{
"code": null,
"e": 1729,
"s": 1661,
"text": "Following are the step by step instructions to understand further –"
},
{
"code": null,
"e": 1887,
"s": 1729,
"text": "After you plug in your USB device to your Linux system USB port, It will add new block device into /dev/ directory. To verify it, use the following command –"
},
{
"code": null,
"e": 1903,
"s": 1887,
"text": "$ sudo fdisk -l"
},
{
"code": null,
"e": 1943,
"s": 1903,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 2314,
"s": 1943,
"text": "Disk /dev/sdb: 15.7 GB, 15664676864 bytes\n255 heads, 63 sectors/track, 1904 cylinders, total 30595072 sectors\nUnits = sectors of 1 * 512 = 512 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\nDisk identifier: 0x00000000\nDevice Boot Start End Blocks Id System\n/dev/sdb1 * 32 30595071 15297520 c W95 FAT32 (LBA)"
},
{
"code": null,
"e": 2414,
"s": 2314,
"text": "We can observe from the above result that, device boot, blocks, id and system format are displayed."
},
{
"code": null,
"e": 2460,
"s": 2414,
"text": "To mount the USB, use the following command –"
},
{
"code": null,
"e": 2483,
"s": 2460,
"text": "$ mount /dev/sdb1 /mnt"
},
{
"code": null,
"e": 2557,
"s": 2483,
"text": "To create a directory in the mounted device, use the following commands –"
},
{
"code": null,
"e": 2584,
"s": 2557,
"text": "$ cd /mnt\n/mnt$ mkdir john"
},
{
"code": null,
"e": 2649,
"s": 2584,
"text": "The above command creates a directory called john in USB device."
},
{
"code": null,
"e": 2707,
"s": 2649,
"text": "To delete a directory in USB, use the following command –"
},
{
"code": null,
"e": 2724,
"s": 2707,
"text": "/mnt$ rmdir john"
},
{
"code": null,
"e": 2841,
"s": 2724,
"text": "You should unmount the device first to format the USB device, then use the following command to unmount the device –"
},
{
"code": null,
"e": 2865,
"s": 2841,
"text": "$ sudo umount /dev/sdb1"
},
{
"code": null,
"e": 3097,
"s": 2865,
"text": "Now use either of the commands as per file system based on your requirement. To format a USB drive, users generally prefer VFAT or NTFS file systems because they can be easily mounted on Windows operating systems and Linux systems."
},
{
"code": null,
"e": 3162,
"s": 3097,
"text": "To format USB with vFat File System, use the following command –"
},
{
"code": null,
"e": 3189,
"s": 3162,
"text": "$ sudo mkfs.vfat /dev/sdb1"
},
{
"code": null,
"e": 3268,
"s": 3189,
"text": "To format a USB Flash Drive with NTFS file system, use the following command –"
},
{
"code": null,
"e": 3295,
"s": 3268,
"text": "$ sudo mkfs.ntfs /dev/sdb1"
},
{
"code": null,
"e": 3362,
"s": 3295,
"text": "To format a USB with EXT4 file system, use the following command –"
},
{
"code": null,
"e": 3389,
"s": 3362,
"text": "$ sudo mkfs.ext4 /dev/sdb1"
},
{
"code": null,
"e": 3550,
"s": 3389,
"text": "Congratulations! Now, you know “How to Mount USB Drive in a Linux System?”. We’ll learn more about these types of commands in our next Linux post. Keep reading!"
}
] |
Sum Pair closest to X | Practice | GeeksforGeeks
|
Given a sorted array arr[] of size N and a number X, find a pair in array whose sum is closest to X.
Example 1:
Input:
N = 6, X = 54
arr[] = {10, 22, 28, 29, 30, 40}
Output: 22 30
Explanation: As 22 + 30 = 52 is closest to 54.
Example 2:
Input:
N = 5, X = 10
arr[] = {1, 2, 3, 4, 5}
Output: 4 5
Explanation: As 4 + 5 = 9 is closest to 10.
Your Task:
You don't need to read input or print anything. Your task is to complete the function sumClosest() which takes arr[] of size n and x as input parameters and returns a list containing 2 integers denoting the required pair. If multiple pairs are possible return the largest sum pair.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
2 <= N <= 105
0 <= X <= 106
0 <= arr[i] <= 106
0
aniket6518gadhe1 week ago
JAVA SOLUTION
Total Time Taken:
0.62/3.02
int[] sumClosest(int[] arr, int x) { int[] ans =new int[2]; int low=0,high=arr.length-1,diff=Integer.MAX_VALUE; while(low<high){ int temp=x-(arr[low]+arr[high]); if(diff>Math.abs(temp)){ ans[0]=arr[low]; ans[1]=arr[high]; diff=Math.abs(temp); } if(temp==0) break; if(temp>0) low++; if(temp<0) high--; } return ans; }
0
manishitadey191 week ago
def sumClosest(self, arr, x): # code here # i = 0 # j = 0 dct = {} for i in range(0, len(arr)-1): for j in range(i+1, len(arr)): dct[(arr[i], arr[j])] = arr[i] +arr[j] min_diff = x res = 0 for item in dct: if abs(x - dct[item]) < min_diff: min_diff = abs(x - dct[item]) res = item return res
for input:
24 108
4 4 9 20 21 25 28 29 33 39 59 62 66 74 79 80 81 82 91 92 93 97 98 100
same code gives correct answer (28, 80) in the ide but gives (29,79) here, can someone tell what's the issue?
0
vickykr2 weeks ago
Java Code:-
int[] sumClosest(int[] arr, int x) { int n=arr.length; int i=0,s=Integer.MAX_VALUE; int r=0,l=0,k=n-1; while(i<k) { if(mod((arr[i]+arr[k]),x)<s) { r=i; l=k; s=mod((arr[i]+arr[k]),x); } if(arr[i]+arr[k]==x) { r=i; l=k; break; } else if((arr[i]+arr[k])>x) k--; else i++; } int ans[]=new int[2]; ans[0]=arr[r]; ans[1]=arr[l]; return ans; } static int mod(int a,int b) { if(a>b) return a-b; else return b-a; }
0
charansaisadla2 weeks ago
Where is the error
l=0 r=len(arr)-1 m=max(arr) while(l<r): if(arr[l]+arr[r]==x): return arr[l],arr[r] dif=abs(arr[l]+arr[r]-x) if dif<m: x=arr[l] y=arr[r] m=min(m,dif) if(arr[l]+arr[r]<x): l+=1 else: r-=1 return x,y
I am not getting answer
0
geminicode3 weeks ago
my approach in Python :
def sumClosest(self, arr, x):
# code here
l = 0
h = len(arr)-1
ans = None
diff =99999999999
while(l < h):
#print(arr[l],arr[h],ans)
if arr[l] + arr[h] == x:
return [arr[l],arr[h]]
elif arr[l] + arr[h] > x:
if (arr[h] + arr[l]) - x < diff:
ans=[arr[l],arr[h]]
diff = arr[h] + arr[l] - x
h-=1
else:
#print(arr[l],arr[h],diff,[x - (arr[h] + arr[l])])
if x - (arr[h] + arr[l]) < diff:
ans = [arr[l],arr[h]]
diff = x - (arr[h] + arr[l])
l+=1
return ans
+2
abhishektyagi12633 weeks ago
//Best Solution
vector<int> sumClosest(vector<int>arr, int x) { int s=0,e=arr.size()-1;int fir;int sec;int m=0,ans=INT_MAX,mec=0; while(s<e){ m=arr[s]+arr[e]; if(m==x){fir=s,sec=e;break;} else{ if(m<x){mec=x-m;} else{mec=m-x;} if(ans<mec){ans=mec;fir=s;sec=e;} if(m<x){s++;} else if(m>x){e--;}} } // cout<<fir<<endl; cout<<sec; vector<int> v; v.push_back(fir);v.push_back(sec); return v; }
+2
badgujarsachin833 weeks ago
vector<int> sumClosest(vector<int>arr, int x)
{
int sum,di=INT_MAX;
int first,second;
int i=0,j=arr.size()-1;
while(i<j){
sum=arr[i]+arr[j];
if(abs(sum-x)<di){
di=abs(sum-x);
first=arr[i],second=arr[j];
}
if(sum>x){
j--;
}else{
i++;
}
}
return {first,second};
}
+2
mayank20211 month ago
C++ : 0.2/1.4vector<int> sumClosest(vector<int>arr, int x) { vector<int>v; int i=0, j=arr.size()-1, diff=INT_MAX, one, two; while(i<j) { if(arr[i]+arr[j]==x) return {arr[i], arr[j]}; if(abs(x-arr[i]-arr[j]) < diff) { diff=abs(x-arr[i]-arr[j]); one=arr[i], two=arr[j]; } if(arr[i]+arr[j] > x) j--; else i++; } return {one, two}; }
0
arunvj13jun1 month ago
class Solution {
int[] sumClosest(int[] arr, int x) {
int left = 0;
int right = arr.length-1;
int diff = Integer.MAX_VALUE;
int sum = 0;
int out1 = -1;
int out2 = -1;
while(left < right) {
sum = arr[left] + arr[right];
if(Math.abs(sum-x) < diff) {
diff = Math.abs(sum-x);
out1 = left;
out2 = right;
}
if(sum < x) {
left++;
} else {
right--;
}
}
return new int[]{arr[out1],arr[out2]};
}
}
-1
sachinupreti1901 month ago
// I m very happy , coz i didnt know that i would ever solve this question, But after wasting an hour i did it
class Solution{ public: vector<int> sumClosest(vector<int>arr, int x) { // code here // may be 2 pointer will use in this int min=1000000,p,q; vector<int>v; vector<int>vec; int i,l=0,r=arr.size()-1,j=0,sum; while(l<r) { sum=arr[l]+arr[r]; if(sum==x) { v.push_back(arr[l]); v.push_back(arr[r]); break; } if(sum<x) { v.push_back(arr[l]); v.push_back(arr[r]); l++; } else { v.push_back(arr[l]); v.push_back(arr[r]); r--; } } for(i=0;i<v.size();i+=2) { if(abs(v[i]+v[i+1]-x) < min) { min=abs(v[i]+v[i+1]-x); p=v[i]; q=v[i+1]; } } vec.push_back(p); vec.push_back(q); return vec; }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 339,
"s": 238,
"text": "Given a sorted array arr[] of size N and a number X, find a pair in array whose sum is closest to X."
},
{
"code": null,
"e": 350,
"s": 339,
"text": "Example 1:"
},
{
"code": null,
"e": 466,
"s": 350,
"text": "Input:\nN = 6, X = 54\narr[] = {10, 22, 28, 29, 30, 40}\nOutput: 22 30\nExplanation: As 22 + 30 = 52 is closest to 54.\n"
},
{
"code": null,
"e": 478,
"s": 466,
"text": "\nExample 2:"
},
{
"code": null,
"e": 579,
"s": 478,
"text": "Input:\nN = 5, X = 10\narr[] = {1, 2, 3, 4, 5}\nOutput: 4 5\nExplanation: As 4 + 5 = 9 is closest to 10."
},
{
"code": null,
"e": 873,
"s": 579,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function sumClosest() which takes arr[] of size n and x as input parameters and returns a list containing 2 integers denoting the required pair. If multiple pairs are possible return the largest sum pair."
},
{
"code": null,
"e": 936,
"s": 873,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 997,
"s": 936,
"text": "\nConstraints:\n2 <= N <= 105\n0 <= X <= 106\n0 <= arr[i] <= 106"
},
{
"code": null,
"e": 1001,
"s": 999,
"text": "0"
},
{
"code": null,
"e": 1027,
"s": 1001,
"text": "aniket6518gadhe1 week ago"
},
{
"code": null,
"e": 1041,
"s": 1027,
"text": "JAVA SOLUTION"
},
{
"code": null,
"e": 1059,
"s": 1041,
"text": "Total Time Taken:"
},
{
"code": null,
"e": 1069,
"s": 1059,
"text": "0.62/3.02"
},
{
"code": null,
"e": 1564,
"s": 1071,
"text": "int[] sumClosest(int[] arr, int x) { int[] ans =new int[2]; int low=0,high=arr.length-1,diff=Integer.MAX_VALUE; while(low<high){ int temp=x-(arr[low]+arr[high]); if(diff>Math.abs(temp)){ ans[0]=arr[low]; ans[1]=arr[high]; diff=Math.abs(temp); } if(temp==0) break; if(temp>0) low++; if(temp<0) high--; } return ans; }"
},
{
"code": null,
"e": 1566,
"s": 1564,
"text": "0"
},
{
"code": null,
"e": 1591,
"s": 1566,
"text": "manishitadey191 week ago"
},
{
"code": null,
"e": 2035,
"s": 1591,
"text": "def sumClosest(self, arr, x): # code here # i = 0 # j = 0 dct = {} for i in range(0, len(arr)-1): for j in range(i+1, len(arr)): dct[(arr[i], arr[j])] = arr[i] +arr[j] min_diff = x res = 0 for item in dct: if abs(x - dct[item]) < min_diff: min_diff = abs(x - dct[item]) res = item return res"
},
{
"code": null,
"e": 2048,
"s": 2037,
"text": "for input:"
},
{
"code": null,
"e": 2056,
"s": 2048,
"text": "24 108 "
},
{
"code": null,
"e": 2126,
"s": 2056,
"text": "4 4 9 20 21 25 28 29 33 39 59 62 66 74 79 80 81 82 91 92 93 97 98 100"
},
{
"code": null,
"e": 2236,
"s": 2126,
"text": "same code gives correct answer (28, 80) in the ide but gives (29,79) here, can someone tell what's the issue?"
},
{
"code": null,
"e": 2238,
"s": 2236,
"text": "0"
},
{
"code": null,
"e": 2257,
"s": 2238,
"text": "vickykr2 weeks ago"
},
{
"code": null,
"e": 2269,
"s": 2257,
"text": "Java Code:-"
},
{
"code": null,
"e": 2980,
"s": 2269,
"text": "int[] sumClosest(int[] arr, int x) { int n=arr.length; int i=0,s=Integer.MAX_VALUE; int r=0,l=0,k=n-1; while(i<k) { if(mod((arr[i]+arr[k]),x)<s) { r=i; l=k; s=mod((arr[i]+arr[k]),x); } if(arr[i]+arr[k]==x) { r=i; l=k; break; } else if((arr[i]+arr[k])>x) k--; else i++; } int ans[]=new int[2]; ans[0]=arr[r]; ans[1]=arr[l]; return ans; } static int mod(int a,int b) { if(a>b) return a-b; else return b-a; }"
},
{
"code": null,
"e": 2982,
"s": 2980,
"text": "0"
},
{
"code": null,
"e": 3008,
"s": 2982,
"text": "charansaisadla2 weeks ago"
},
{
"code": null,
"e": 3027,
"s": 3008,
"text": "Where is the error"
},
{
"code": null,
"e": 3400,
"s": 3027,
"text": " l=0 r=len(arr)-1 m=max(arr) while(l<r): if(arr[l]+arr[r]==x): return arr[l],arr[r] dif=abs(arr[l]+arr[r]-x) if dif<m: x=arr[l] y=arr[r] m=min(m,dif) if(arr[l]+arr[r]<x): l+=1 else: r-=1 return x,y"
},
{
"code": null,
"e": 3424,
"s": 3400,
"text": "I am not getting answer"
},
{
"code": null,
"e": 3428,
"s": 3426,
"text": "0"
},
{
"code": null,
"e": 3450,
"s": 3428,
"text": "geminicode3 weeks ago"
},
{
"code": null,
"e": 3474,
"s": 3450,
"text": "my approach in Python :"
},
{
"code": null,
"e": 4232,
"s": 3474,
"text": "def sumClosest(self, arr, x):\n # code here\n \n l = 0\n h = len(arr)-1\n ans = None\n diff =99999999999\n while(l < h):\n #print(arr[l],arr[h],ans)\n if arr[l] + arr[h] == x:\n return [arr[l],arr[h]]\n elif arr[l] + arr[h] > x:\n if (arr[h] + arr[l]) - x < diff:\n ans=[arr[l],arr[h]]\n diff = arr[h] + arr[l] - x\n \n h-=1\n else:\n #print(arr[l],arr[h],diff,[x - (arr[h] + arr[l])])\n if x - (arr[h] + arr[l]) < diff:\n ans = [arr[l],arr[h]]\n diff = x - (arr[h] + arr[l])\n l+=1\n return ans"
},
{
"code": null,
"e": 4235,
"s": 4232,
"text": "+2"
},
{
"code": null,
"e": 4264,
"s": 4235,
"text": "abhishektyagi12633 weeks ago"
},
{
"code": null,
"e": 4281,
"s": 4264,
"text": "//Best Solution "
},
{
"code": null,
"e": 4791,
"s": 4281,
"text": " vector<int> sumClosest(vector<int>arr, int x) { int s=0,e=arr.size()-1;int fir;int sec;int m=0,ans=INT_MAX,mec=0; while(s<e){ m=arr[s]+arr[e]; if(m==x){fir=s,sec=e;break;} else{ if(m<x){mec=x-m;} else{mec=m-x;} if(ans<mec){ans=mec;fir=s;sec=e;} if(m<x){s++;} else if(m>x){e--;}} } // cout<<fir<<endl; cout<<sec; vector<int> v; v.push_back(fir);v.push_back(sec); return v; }"
},
{
"code": null,
"e": 4794,
"s": 4791,
"text": "+2"
},
{
"code": null,
"e": 4822,
"s": 4794,
"text": "badgujarsachin833 weeks ago"
},
{
"code": null,
"e": 5287,
"s": 4822,
"text": " vector<int> sumClosest(vector<int>arr, int x)\n {\n int sum,di=INT_MAX;\n int first,second;\n int i=0,j=arr.size()-1;\n while(i<j){\n sum=arr[i]+arr[j];\n if(abs(sum-x)<di){\n di=abs(sum-x);\n first=arr[i],second=arr[j];\n }\n if(sum>x){\n j--;\n }else{\n i++;\n }\n }\n return {first,second};\n }"
},
{
"code": null,
"e": 5290,
"s": 5287,
"text": "+2"
},
{
"code": null,
"e": 5312,
"s": 5290,
"text": "mayank20211 month ago"
},
{
"code": null,
"e": 5856,
"s": 5312,
"text": "C++ : 0.2/1.4vector<int> sumClosest(vector<int>arr, int x) { vector<int>v; int i=0, j=arr.size()-1, diff=INT_MAX, one, two; while(i<j) { if(arr[i]+arr[j]==x) return {arr[i], arr[j]}; if(abs(x-arr[i]-arr[j]) < diff) { diff=abs(x-arr[i]-arr[j]); one=arr[i], two=arr[j]; } if(arr[i]+arr[j] > x) j--; else i++; } return {one, two}; }"
},
{
"code": null,
"e": 5858,
"s": 5856,
"text": "0"
},
{
"code": null,
"e": 5881,
"s": 5858,
"text": "arunvj13jun1 month ago"
},
{
"code": null,
"e": 6528,
"s": 5881,
"text": "class Solution {\n int[] sumClosest(int[] arr, int x) {\n int left = 0;\n int right = arr.length-1;\n int diff = Integer.MAX_VALUE;\n int sum = 0;\n int out1 = -1;\n int out2 = -1;\n \n while(left < right) {\n sum = arr[left] + arr[right];\n if(Math.abs(sum-x) < diff) {\n diff = Math.abs(sum-x);\n out1 = left;\n out2 = right;\n }\n if(sum < x) {\n left++;\n } else {\n right--;\n }\n }\n \n return new int[]{arr[out1],arr[out2]};\n \n }\n}"
},
{
"code": null,
"e": 6531,
"s": 6528,
"text": "-1"
},
{
"code": null,
"e": 6558,
"s": 6531,
"text": "sachinupreti1901 month ago"
},
{
"code": null,
"e": 6669,
"s": 6558,
"text": "// I m very happy , coz i didnt know that i would ever solve this question, But after wasting an hour i did it"
},
{
"code": null,
"e": 7710,
"s": 6671,
"text": "class Solution{ public: vector<int> sumClosest(vector<int>arr, int x) { // code here // may be 2 pointer will use in this int min=1000000,p,q; vector<int>v; vector<int>vec; int i,l=0,r=arr.size()-1,j=0,sum; while(l<r) { sum=arr[l]+arr[r]; if(sum==x) { v.push_back(arr[l]); v.push_back(arr[r]); break; } if(sum<x) { v.push_back(arr[l]); v.push_back(arr[r]); l++; } else { v.push_back(arr[l]); v.push_back(arr[r]); r--; } } for(i=0;i<v.size();i+=2) { if(abs(v[i]+v[i+1]-x) < min) { min=abs(v[i]+v[i+1]-x); p=v[i]; q=v[i+1]; } } vec.push_back(p); vec.push_back(q); return vec; }};"
},
{
"code": null,
"e": 7856,
"s": 7710,
"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": 7892,
"s": 7856,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7902,
"s": 7892,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7912,
"s": 7902,
"text": "\nContest\n"
},
{
"code": null,
"e": 7975,
"s": 7912,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8123,
"s": 7975,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8331,
"s": 8123,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 8437,
"s": 8331,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Benchmarking Language Detection for NLP | by Jenny Lee | Towards Data Science
|
Most NLP applications tend to be language-specific and therefore require monolingual data. In order to build an application in your target language, you may need to apply a preprocessing technique that filters out text written in non-target languages. This requires proper identification of the language of each input example. Below I list some tools you can use as Python modules for this preprocessing requirement, and provide a performance benchmark assessing the speed and accuracy of each one.
pypi.org
langdetect is a re-implementation of Google’s language-detection library from Java to Python. Simply pass your text to the imported detect function and it will output the two-letter ISO 693 code of the language for which the model gave the highest confidence score. (Refer to this page for a full list of 693 codes and their respective languages.) If you use detect_langs instead, it will output a list of the top languages that the model has predicted, along with their probabilities.
from langdetect import DetectorFactory, detect, detect_langstext = "My lubimy mleko i chleb."detect(text) # 'cs'detect_langs(text) # [cs:0.7142840957132709, pl:0.14285810606233737, sk:0.14285779665739756]
A few embellishing points:
The library makers recommend that you set the DetectorFactory seed to some number. This is because langdetect’s algorithm is non-deterministic, which means if you try to run it on a text that’s too short or too ambiguous, you might get different results each time you run it. Setting the seed enforces consistent results during development/evaluation.You may also want to surround the detect call in a try/except block with LanguageDetectException, otherwise you will likely get a “No features in text” error, which occurs when there the language of the given input cannot be evaluated as when it contains strings like URLs, numbers, formulas, etc.
The library makers recommend that you set the DetectorFactory seed to some number. This is because langdetect’s algorithm is non-deterministic, which means if you try to run it on a text that’s too short or too ambiguous, you might get different results each time you run it. Setting the seed enforces consistent results during development/evaluation.
You may also want to surround the detect call in a try/except block with LanguageDetectException, otherwise you will likely get a “No features in text” error, which occurs when there the language of the given input cannot be evaluated as when it contains strings like URLs, numbers, formulas, etc.
from langdetect import DetectorFactory, detectfrom langdetect.lang_detect_exception import LangDetectExceptionDetectorFactory.seed = 0def is_english(text): try: if detect(text) != "en": return False except LangDetectException: return False return True
spacy.io
If you use spaCy for your NLP needs, you can add a custom language detection component to your existing spaCy pipeline, which will enable you to set an extension attribute called .language on the Doc object. This attribute can then be accessed via Doc._.language, which will return the predicted language along with its probability.
import spacyfrom spacy_langdetect import LanguageDetectortext2 = 'In 1793, Alexander Hamilton recruited Webster to move to New York City and become an editor for a Federalist Party newspaper.'nlp = spacy.load('en_core_web_sm')nlp.add_pipe(LanguageDetector(), name='language_detector', last=True)doc = nlp(text)doc._.language # {'language': 'en', 'score': 0.9999978351575265}
langid boasts of its speed in particular (more on this below). It works similarly to the above tools, but it can additionally be used as a command-line tool by running python langid.py. Check out their repo for more details and other options.
github.com
To use langid as a Python library, use the classify function:
import langidlangid.classify(text2) # ('en', -127.75649309158325)
You can calibrate the probability prediction, originally computed in the log-probability space, to what can be interpreted as confidence scores in the range of 0 to 1:
from langid.langid import LanguageIdentifier, modellang_identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)lang_identifier.classify(text2) # ('en', 0.999999999999998)
fasttext notes that its pre-trained language identification model takes less than 1MB of memory while being able to classify thousands of documents per second.
Download a model of your choice:
lid.176.bin: faster and slightly more accurate (file size=126MB).
lid.176.ftz: the compressed version of the model (file size=917kB).
import fasttextpath_to_pretrained_model = '/tmp/lid.176.bin'fmodel = fasttext.load_model(path_to_pretrained_model)fmodel.predict([text2]) # ([['__label__en']], [array([0.9331119], dtype=float32)]
If you plan to use your application requiring language identification in production, speed is likely an important consideration for you. Below is a quick benchmark of the four tools described above.
I downloaded a dataset of 10,502 tweets from Kaggle, which was randomly sampled from publicly available geotagged Twitter messages originating from 130 different countries. They were annotated for being in English or non-English, among other features.
Data source: https://www.kaggle.com/rtatman/the-umass-global-english-on-twitter-dataset.
import pandas as pddf = pd.read_csv('all_annotated.tsv', sep='\t')
The results of the speed test!
fasttext took only 129 ms to predict on 10,000+ datapoints. langid came in second and the other contenders were many orders of magnitude slower.
from sklearn.metrics import accuracy_scoreytrue = df['Definitely English'].to_list()tweets = df['Tweet'].to_list()# get the predictions of each detectorlangdetect_preds = [lang_detect(t) for t in tweets]spacy_preds = [nlp(t)._.language['language'] for t in tweets]langid_preds = [lang_identifier.classify(text)[0] for t in tweets]fasttext_preds = [p[0].replace('__label__', '') for p in fmodel.predict(tweets)[0]]# binarize the labelslangdetect_preds_binary = [1 if p == 'en' else 0 for p in langdetect_preds]spacy_preds_binary = [1 if p == 'en' else 0 for p in spacy_preds]langid_preds_binary = [1 if p == 'en' else 0 for p in langid_preds]fasttext_preds_binary = [1 if p == 'en' else 0 for p in fasttext_preds]# evaluate accuracy against the true labels (1 for English, 0 otherwise)accuracy_score(ytrue, langdetect_preds_binary) # 0.8448866882498571 accuracy_score(ytrue, spacy_preds_binary) # 0.8448866882498571accuracy_score(ytrue, langid_preds_binary) # 0.8268901161683488accuracy_score(ytrue, fasttext_preds_binary) # 0.8598362216720624
fasttext had the highest accuracy score, followed by langdetect and spacy-langdetect. Something tells me that spacy-langdetect is just langdetect under the hood. ;) (They had exactly the same accuracy score...and that would also explain the similar library names.)
And for good measure, here are the precision, recall and f1-score for each model.
from sklearn.metrics import classification_reportprint(classification_report(ytrue, langdetect_preds_binary))print(classification_report(ytrue, spacy_preds_binary))print(classification_report(ytrue, langid_preds_binary))print(classification_report(ytrue, fasttext_preds_binary))# langdetect precision recall f1-score support 0 0.80 0.94 0.86 5416 1 0.92 0.75 0.82 5086 accuracy 0.84 10502 macro avg 0.86 0.84 0.84 10502weighted avg 0.86 0.84 0.84 10502# spacy-langdetect precision recall f1-score support 0 0.80 0.94 0.86 5416 1 0.92 0.75 0.82 5086 accuracy 0.84 10502 macro avg 0.86 0.84 0.84 10502weighted avg 0.86 0.84 0.84 10502# langid precision recall f1-score support 0 0.79 0.90 0.84 5416 1 0.88 0.74 0.81 5086 accuracy 0.83 10502 macro avg 0.83 0.82 0.82 10502weighted avg 0.83 0.83 0.83 10502# fasttext precision recall f1-score support 0 0.91 0.80 0.86 5416 1 0.82 0.92 0.86 5086 accuracy 0.86 10502 macro avg 0.86 0.86 0.86 10502weighted avg 0.87 0.86 0.86 10502
I would go with fasttext if you’re dealing with a very large dataset.
|
[
{
"code": null,
"e": 671,
"s": 172,
"text": "Most NLP applications tend to be language-specific and therefore require monolingual data. In order to build an application in your target language, you may need to apply a preprocessing technique that filters out text written in non-target languages. This requires proper identification of the language of each input example. Below I list some tools you can use as Python modules for this preprocessing requirement, and provide a performance benchmark assessing the speed and accuracy of each one."
},
{
"code": null,
"e": 680,
"s": 671,
"text": "pypi.org"
},
{
"code": null,
"e": 1166,
"s": 680,
"text": "langdetect is a re-implementation of Google’s language-detection library from Java to Python. Simply pass your text to the imported detect function and it will output the two-letter ISO 693 code of the language for which the model gave the highest confidence score. (Refer to this page for a full list of 693 codes and their respective languages.) If you use detect_langs instead, it will output a list of the top languages that the model has predicted, along with their probabilities."
},
{
"code": null,
"e": 1373,
"s": 1166,
"text": "from langdetect import DetectorFactory, detect, detect_langstext = \"My lubimy mleko i chleb.\"detect(text) # 'cs'detect_langs(text) # [cs:0.7142840957132709, pl:0.14285810606233737, sk:0.14285779665739756]"
},
{
"code": null,
"e": 1400,
"s": 1373,
"text": "A few embellishing points:"
},
{
"code": null,
"e": 2049,
"s": 1400,
"text": "The library makers recommend that you set the DetectorFactory seed to some number. This is because langdetect’s algorithm is non-deterministic, which means if you try to run it on a text that’s too short or too ambiguous, you might get different results each time you run it. Setting the seed enforces consistent results during development/evaluation.You may also want to surround the detect call in a try/except block with LanguageDetectException, otherwise you will likely get a “No features in text” error, which occurs when there the language of the given input cannot be evaluated as when it contains strings like URLs, numbers, formulas, etc."
},
{
"code": null,
"e": 2401,
"s": 2049,
"text": "The library makers recommend that you set the DetectorFactory seed to some number. This is because langdetect’s algorithm is non-deterministic, which means if you try to run it on a text that’s too short or too ambiguous, you might get different results each time you run it. Setting the seed enforces consistent results during development/evaluation."
},
{
"code": null,
"e": 2699,
"s": 2401,
"text": "You may also want to surround the detect call in a try/except block with LanguageDetectException, otherwise you will likely get a “No features in text” error, which occurs when there the language of the given input cannot be evaluated as when it contains strings like URLs, numbers, formulas, etc."
},
{
"code": null,
"e": 2985,
"s": 2699,
"text": "from langdetect import DetectorFactory, detectfrom langdetect.lang_detect_exception import LangDetectExceptionDetectorFactory.seed = 0def is_english(text): try: if detect(text) != \"en\": return False except LangDetectException: return False return True"
},
{
"code": null,
"e": 2994,
"s": 2985,
"text": "spacy.io"
},
{
"code": null,
"e": 3327,
"s": 2994,
"text": "If you use spaCy for your NLP needs, you can add a custom language detection component to your existing spaCy pipeline, which will enable you to set an extension attribute called .language on the Doc object. This attribute can then be accessed via Doc._.language, which will return the predicted language along with its probability."
},
{
"code": null,
"e": 3703,
"s": 3327,
"text": "import spacyfrom spacy_langdetect import LanguageDetectortext2 = 'In 1793, Alexander Hamilton recruited Webster to move to New York City and become an editor for a Federalist Party newspaper.'nlp = spacy.load('en_core_web_sm')nlp.add_pipe(LanguageDetector(), name='language_detector', last=True)doc = nlp(text)doc._.language # {'language': 'en', 'score': 0.9999978351575265}"
},
{
"code": null,
"e": 3946,
"s": 3703,
"text": "langid boasts of its speed in particular (more on this below). It works similarly to the above tools, but it can additionally be used as a command-line tool by running python langid.py. Check out their repo for more details and other options."
},
{
"code": null,
"e": 3957,
"s": 3946,
"text": "github.com"
},
{
"code": null,
"e": 4019,
"s": 3957,
"text": "To use langid as a Python library, use the classify function:"
},
{
"code": null,
"e": 4086,
"s": 4019,
"text": "import langidlangid.classify(text2) # ('en', -127.75649309158325)"
},
{
"code": null,
"e": 4254,
"s": 4086,
"text": "You can calibrate the probability prediction, originally computed in the log-probability space, to what can be interpreted as confidence scores in the range of 0 to 1:"
},
{
"code": null,
"e": 4442,
"s": 4254,
"text": "from langid.langid import LanguageIdentifier, modellang_identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)lang_identifier.classify(text2) # ('en', 0.999999999999998)"
},
{
"code": null,
"e": 4602,
"s": 4442,
"text": "fasttext notes that its pre-trained language identification model takes less than 1MB of memory while being able to classify thousands of documents per second."
},
{
"code": null,
"e": 4635,
"s": 4602,
"text": "Download a model of your choice:"
},
{
"code": null,
"e": 4701,
"s": 4635,
"text": "lid.176.bin: faster and slightly more accurate (file size=126MB)."
},
{
"code": null,
"e": 4769,
"s": 4701,
"text": "lid.176.ftz: the compressed version of the model (file size=917kB)."
},
{
"code": null,
"e": 4966,
"s": 4769,
"text": "import fasttextpath_to_pretrained_model = '/tmp/lid.176.bin'fmodel = fasttext.load_model(path_to_pretrained_model)fmodel.predict([text2]) # ([['__label__en']], [array([0.9331119], dtype=float32)]"
},
{
"code": null,
"e": 5165,
"s": 4966,
"text": "If you plan to use your application requiring language identification in production, speed is likely an important consideration for you. Below is a quick benchmark of the four tools described above."
},
{
"code": null,
"e": 5417,
"s": 5165,
"text": "I downloaded a dataset of 10,502 tweets from Kaggle, which was randomly sampled from publicly available geotagged Twitter messages originating from 130 different countries. They were annotated for being in English or non-English, among other features."
},
{
"code": null,
"e": 5506,
"s": 5417,
"text": "Data source: https://www.kaggle.com/rtatman/the-umass-global-english-on-twitter-dataset."
},
{
"code": null,
"e": 5573,
"s": 5506,
"text": "import pandas as pddf = pd.read_csv('all_annotated.tsv', sep='\\t')"
},
{
"code": null,
"e": 5604,
"s": 5573,
"text": "The results of the speed test!"
},
{
"code": null,
"e": 5749,
"s": 5604,
"text": "fasttext took only 129 ms to predict on 10,000+ datapoints. langid came in second and the other contenders were many orders of magnitude slower."
},
{
"code": null,
"e": 6796,
"s": 5749,
"text": "from sklearn.metrics import accuracy_scoreytrue = df['Definitely English'].to_list()tweets = df['Tweet'].to_list()# get the predictions of each detectorlangdetect_preds = [lang_detect(t) for t in tweets]spacy_preds = [nlp(t)._.language['language'] for t in tweets]langid_preds = [lang_identifier.classify(text)[0] for t in tweets]fasttext_preds = [p[0].replace('__label__', '') for p in fmodel.predict(tweets)[0]]# binarize the labelslangdetect_preds_binary = [1 if p == 'en' else 0 for p in langdetect_preds]spacy_preds_binary = [1 if p == 'en' else 0 for p in spacy_preds]langid_preds_binary = [1 if p == 'en' else 0 for p in langid_preds]fasttext_preds_binary = [1 if p == 'en' else 0 for p in fasttext_preds]# evaluate accuracy against the true labels (1 for English, 0 otherwise)accuracy_score(ytrue, langdetect_preds_binary) # 0.8448866882498571 accuracy_score(ytrue, spacy_preds_binary) # 0.8448866882498571accuracy_score(ytrue, langid_preds_binary) # 0.8268901161683488accuracy_score(ytrue, fasttext_preds_binary) # 0.8598362216720624"
},
{
"code": null,
"e": 7061,
"s": 6796,
"text": "fasttext had the highest accuracy score, followed by langdetect and spacy-langdetect. Something tells me that spacy-langdetect is just langdetect under the hood. ;) (They had exactly the same accuracy score...and that would also explain the similar library names.)"
},
{
"code": null,
"e": 7143,
"s": 7061,
"text": "And for good measure, here are the precision, recall and f1-score for each model."
},
{
"code": null,
"e": 8742,
"s": 7143,
"text": "from sklearn.metrics import classification_reportprint(classification_report(ytrue, langdetect_preds_binary))print(classification_report(ytrue, spacy_preds_binary))print(classification_report(ytrue, langid_preds_binary))print(classification_report(ytrue, fasttext_preds_binary))# langdetect precision recall f1-score support 0 0.80 0.94 0.86 5416 1 0.92 0.75 0.82 5086 accuracy 0.84 10502 macro avg 0.86 0.84 0.84 10502weighted avg 0.86 0.84 0.84 10502# spacy-langdetect precision recall f1-score support 0 0.80 0.94 0.86 5416 1 0.92 0.75 0.82 5086 accuracy 0.84 10502 macro avg 0.86 0.84 0.84 10502weighted avg 0.86 0.84 0.84 10502# langid precision recall f1-score support 0 0.79 0.90 0.84 5416 1 0.88 0.74 0.81 5086 accuracy 0.83 10502 macro avg 0.83 0.82 0.82 10502weighted avg 0.83 0.83 0.83 10502# fasttext precision recall f1-score support 0 0.91 0.80 0.86 5416 1 0.82 0.92 0.86 5086 accuracy 0.86 10502 macro avg 0.86 0.86 0.86 10502weighted avg 0.87 0.86 0.86 10502"
}
] |
Creating Custom Transformers with Scikit-Learn | by KSV Muralidhar | Towards Data Science
|
Transformers are classes that enable data transformations while preprocessing the data for machine learning. Examples of transformers in Scikit-Learn are SimpleImputer, MinMaxScaler, OrdinalEncoder, PowerTransformer, to name a few. At times, we may require to perform data transformations that are not predefined in popular Python packages. In such cases, custom transformers come to the rescue. In this article, we’ll discuss two methods of defining custom transformers in Python using Scikit-Learn. We’ll use the ‘Iris dataset’ from Scikit-Learn and define a custom transformer for outlier removal using the IQR method.
This method defines a custom transformer by inheriting BaseEstimator and TransformerMixin classes of Scikit-Learn. ‘BaseEstimator’ class of Scikit-Learn enables hyperparameter tuning by adding the ‘set_params’ and ‘get_params’ methods. While, ‘TransformerMixin’ class adds the ‘fit_transform’ method without explicitly defining it. In the below code snippet, we’ll import the required packages and the dataset.
In the above code snippet, we’ve defined a class named ‘OutlierRemover’ which is our custom transformer to remove outliers i.e. replace outliers with NaN. The class has an attribute named ‘factor’ which is a hyperparameter to control the outlier removal process. Higher the ‘factor’, extreme would be the outliers removed. By default, ‘factor’ is initialized to 1.5. The class has three methods, namely, ‘outlier_removal’, ‘fit’ and ‘transform’. Inheriting BaseEstimator and TransformerMixin classes adds three more methods, namely, ‘fit_transform’, ‘get_params’ and ‘set_params’. We’ve also created an instance named ‘outlier_remover’ of the ‘OutlierRemover’ class.
‘__init__’ is the first method that’s called upon creating an instance/object of the class. This is used to initialize the class attributes. We’ll initialize the factor of the IQR method with 1.5 (default value). The ‘outlier_removal’ method replaces the outliers in a Series with NaN. The ‘fit’ method returns self always. The ‘transform’ method takes in an array/data frame as input and applies the outlier_removal method to all the columns of the data frame/array and returns it.
We’ll apply the outlier removal transform using ‘OutlierRemover’ by creating a data frame named ‘test’ with three columns and four records.
We can see that ‘col1’ has an outlier (999) and ‘col3' also has an outlier (-10). We’ll first fit the ‘OutlierRemover’ to the ‘test’ data frame (using the already created instance, ‘outlier_remover’) and apply the transform to it.
outlier_remover.fit(test)
outlier_remover.transform(test)
We can see that the outlier in ‘col1’ (999) is replaced with NaN and the outlier in ‘col3’ (-10) is replaced with NaN. We can apply the transform using a single ‘fit_transform’ method as shown below. This gives the same result as the one above.
outlier_remover.fit_transform(test)
We’ll create an instance named ‘outlier_remover_100’ of the ‘OutlierRemover’ class by setting the ‘factor’ to 100. As discussed earlier, higher the ‘factor’, extreme would be the outliers removed.
We can see that ‘999’ in ‘col1’ and ‘-10’ in ‘col2’ aren’t considered as outliers this time, as the ‘factor’ attribute is high. Now, we’ll apply the outlier remover transform to the iris dataset. Before that, we’ll visualize the outliers in the four columns of the Iris dataset using a box plot.
In the above box plot, we can see the column ‘SepalWidthCm’ has few outliers, four to be precise. The other three columns have no outliers. We’ll create a ColumnTransformer to apply the ‘OutlierRemover’ to all the variables of the Iris dataset and visualize the variables after outlier removal, using a boxplot.
In the above box plot, we can see that the outliers in the column ‘SepalWidthCm’ are removed i.e. replaced with NaN. We’ll find out how many and which outliers were removed from each column.
We can see that the values of ‘SepalWidthCm’ greater than 4 and less than or equal to 2 are removed, as they were outliers. The same can be seen in the earlier box plot showing outliers. Now, we’ll create a pipeline that removes the outliers, imputes the removed outliers and fits a logistic regression model. We’ll tune the hyperparameters using GridSearchCV.
The second method to create a custom transformer uses the ‘FunctionTransformer’ class of Scikit-Learn. This is a simpler approach that eliminates the need of defining a class, however, we need to define a function to perform the required transformation. Similar to method 1, we’ll create a custom transformer to remove the outliers. The below function takes an array/data frame along with ‘factor’ as inputs and replaces the outliers in each column with NaN.
In the above code snippet, we’ve also created an instance named ‘outlier_remover’ of the ‘FunctionTransformer’ class by passing the custom function (‘outlier_removal’) we defined for outlier removal, along with the argument ‘factor’. In this method, we need to pass the additional arguments (other than the input array/data frame) to the function inside the ‘FunctionTransformer’ as a dictionary using the ‘kw_args’ argument of ‘Functiontransformer’. We’ve also created the ‘test’ data frame we used in method 1.
We can see that ‘col1’ has an outlier (999) and ‘col3’ also has an outlier (-10). We’ll fit and apply the ‘OutlierRemover’ transform to the data using the already created instance ‘outlier_remover’ .
outlier_remover.fit_transform(test)
We can see that the outlier in ‘col1’ (999) is replaced with NaN and the outlier in ‘col3’ (-10) is replaced with NaN. Creating a custom transformer using ‘FunctionTransformer’ provides us with a few additional methods as shown below.
[i for i in dir(outlier_remover) if i.startswith('_') == False]
Now, we’ll create a pipeline that removes the outliers, imputes the removed outliers and fits a logistic regression model. We’ll tune the hyperparameters using GridSearchCV.
A major difference in the method 2 is, we need to tune the ‘kw_args’ hyperparameter, unlike in the other transformers (including the one discussed in method 1). In the above code snippet, we’ve tuned the ‘kw_args’ hyperparameter using the list of values [{‘factor’:0},{‘factor’:1},{‘factor’:2},{‘factor’:3},{‘factor’:4}]. This may make it difficult to tune multiple hyperparameters of a custom transformer.
These are the two methods to define a custom transformer using Scikit-Learn. Defining custom transformers and including them in a pipeline simplifies the model development and also prevents the problem of data leakage while using k-fold cross-validation.
|
[
{
"code": null,
"e": 794,
"s": 172,
"text": "Transformers are classes that enable data transformations while preprocessing the data for machine learning. Examples of transformers in Scikit-Learn are SimpleImputer, MinMaxScaler, OrdinalEncoder, PowerTransformer, to name a few. At times, we may require to perform data transformations that are not predefined in popular Python packages. In such cases, custom transformers come to the rescue. In this article, we’ll discuss two methods of defining custom transformers in Python using Scikit-Learn. We’ll use the ‘Iris dataset’ from Scikit-Learn and define a custom transformer for outlier removal using the IQR method."
},
{
"code": null,
"e": 1205,
"s": 794,
"text": "This method defines a custom transformer by inheriting BaseEstimator and TransformerMixin classes of Scikit-Learn. ‘BaseEstimator’ class of Scikit-Learn enables hyperparameter tuning by adding the ‘set_params’ and ‘get_params’ methods. While, ‘TransformerMixin’ class adds the ‘fit_transform’ method without explicitly defining it. In the below code snippet, we’ll import the required packages and the dataset."
},
{
"code": null,
"e": 1872,
"s": 1205,
"text": "In the above code snippet, we’ve defined a class named ‘OutlierRemover’ which is our custom transformer to remove outliers i.e. replace outliers with NaN. The class has an attribute named ‘factor’ which is a hyperparameter to control the outlier removal process. Higher the ‘factor’, extreme would be the outliers removed. By default, ‘factor’ is initialized to 1.5. The class has three methods, namely, ‘outlier_removal’, ‘fit’ and ‘transform’. Inheriting BaseEstimator and TransformerMixin classes adds three more methods, namely, ‘fit_transform’, ‘get_params’ and ‘set_params’. We’ve also created an instance named ‘outlier_remover’ of the ‘OutlierRemover’ class."
},
{
"code": null,
"e": 2355,
"s": 1872,
"text": "‘__init__’ is the first method that’s called upon creating an instance/object of the class. This is used to initialize the class attributes. We’ll initialize the factor of the IQR method with 1.5 (default value). The ‘outlier_removal’ method replaces the outliers in a Series with NaN. The ‘fit’ method returns self always. The ‘transform’ method takes in an array/data frame as input and applies the outlier_removal method to all the columns of the data frame/array and returns it."
},
{
"code": null,
"e": 2495,
"s": 2355,
"text": "We’ll apply the outlier removal transform using ‘OutlierRemover’ by creating a data frame named ‘test’ with three columns and four records."
},
{
"code": null,
"e": 2726,
"s": 2495,
"text": "We can see that ‘col1’ has an outlier (999) and ‘col3' also has an outlier (-10). We’ll first fit the ‘OutlierRemover’ to the ‘test’ data frame (using the already created instance, ‘outlier_remover’) and apply the transform to it."
},
{
"code": null,
"e": 2752,
"s": 2726,
"text": "outlier_remover.fit(test)"
},
{
"code": null,
"e": 2784,
"s": 2752,
"text": "outlier_remover.transform(test)"
},
{
"code": null,
"e": 3029,
"s": 2784,
"text": "We can see that the outlier in ‘col1’ (999) is replaced with NaN and the outlier in ‘col3’ (-10) is replaced with NaN. We can apply the transform using a single ‘fit_transform’ method as shown below. This gives the same result as the one above."
},
{
"code": null,
"e": 3065,
"s": 3029,
"text": "outlier_remover.fit_transform(test)"
},
{
"code": null,
"e": 3262,
"s": 3065,
"text": "We’ll create an instance named ‘outlier_remover_100’ of the ‘OutlierRemover’ class by setting the ‘factor’ to 100. As discussed earlier, higher the ‘factor’, extreme would be the outliers removed."
},
{
"code": null,
"e": 3558,
"s": 3262,
"text": "We can see that ‘999’ in ‘col1’ and ‘-10’ in ‘col2’ aren’t considered as outliers this time, as the ‘factor’ attribute is high. Now, we’ll apply the outlier remover transform to the iris dataset. Before that, we’ll visualize the outliers in the four columns of the Iris dataset using a box plot."
},
{
"code": null,
"e": 3870,
"s": 3558,
"text": "In the above box plot, we can see the column ‘SepalWidthCm’ has few outliers, four to be precise. The other three columns have no outliers. We’ll create a ColumnTransformer to apply the ‘OutlierRemover’ to all the variables of the Iris dataset and visualize the variables after outlier removal, using a boxplot."
},
{
"code": null,
"e": 4061,
"s": 3870,
"text": "In the above box plot, we can see that the outliers in the column ‘SepalWidthCm’ are removed i.e. replaced with NaN. We’ll find out how many and which outliers were removed from each column."
},
{
"code": null,
"e": 4422,
"s": 4061,
"text": "We can see that the values of ‘SepalWidthCm’ greater than 4 and less than or equal to 2 are removed, as they were outliers. The same can be seen in the earlier box plot showing outliers. Now, we’ll create a pipeline that removes the outliers, imputes the removed outliers and fits a logistic regression model. We’ll tune the hyperparameters using GridSearchCV."
},
{
"code": null,
"e": 4881,
"s": 4422,
"text": "The second method to create a custom transformer uses the ‘FunctionTransformer’ class of Scikit-Learn. This is a simpler approach that eliminates the need of defining a class, however, we need to define a function to perform the required transformation. Similar to method 1, we’ll create a custom transformer to remove the outliers. The below function takes an array/data frame along with ‘factor’ as inputs and replaces the outliers in each column with NaN."
},
{
"code": null,
"e": 5394,
"s": 4881,
"text": "In the above code snippet, we’ve also created an instance named ‘outlier_remover’ of the ‘FunctionTransformer’ class by passing the custom function (‘outlier_removal’) we defined for outlier removal, along with the argument ‘factor’. In this method, we need to pass the additional arguments (other than the input array/data frame) to the function inside the ‘FunctionTransformer’ as a dictionary using the ‘kw_args’ argument of ‘Functiontransformer’. We’ve also created the ‘test’ data frame we used in method 1."
},
{
"code": null,
"e": 5594,
"s": 5394,
"text": "We can see that ‘col1’ has an outlier (999) and ‘col3’ also has an outlier (-10). We’ll fit and apply the ‘OutlierRemover’ transform to the data using the already created instance ‘outlier_remover’ ."
},
{
"code": null,
"e": 5630,
"s": 5594,
"text": "outlier_remover.fit_transform(test)"
},
{
"code": null,
"e": 5865,
"s": 5630,
"text": "We can see that the outlier in ‘col1’ (999) is replaced with NaN and the outlier in ‘col3’ (-10) is replaced with NaN. Creating a custom transformer using ‘FunctionTransformer’ provides us with a few additional methods as shown below."
},
{
"code": null,
"e": 5929,
"s": 5865,
"text": "[i for i in dir(outlier_remover) if i.startswith('_') == False]"
},
{
"code": null,
"e": 6103,
"s": 5929,
"text": "Now, we’ll create a pipeline that removes the outliers, imputes the removed outliers and fits a logistic regression model. We’ll tune the hyperparameters using GridSearchCV."
},
{
"code": null,
"e": 6510,
"s": 6103,
"text": "A major difference in the method 2 is, we need to tune the ‘kw_args’ hyperparameter, unlike in the other transformers (including the one discussed in method 1). In the above code snippet, we’ve tuned the ‘kw_args’ hyperparameter using the list of values [{‘factor’:0},{‘factor’:1},{‘factor’:2},{‘factor’:3},{‘factor’:4}]. This may make it difficult to tune multiple hyperparameters of a custom transformer."
}
] |
How to check whether a stored procedure exist in MySQL?
|
Let us first create a stored procedure −
mysql> DELIMITER //
mysql> CREATE PROCEDURE ExtenddatesWithMonthdemo(IN date1 datetime, IN NumberOfMonth int )
-> BEGIN
-> SELECT DATE_ADD(date1,INTERVAL NumberOfMonth MONTH) AS ExtendDate;
-> END;
-> //
Query OK, 0 rows affected (0.20 sec)
mysql> DELIMITER ;
Now you check whether the stored procedure exists with the help SHOW CREATE command.
The query is as follows −
mysql> SHOW CREATE PROCEDURE ExtenddatesWithMonthdemo;
The following is the output displaying the details of the stored procedure we created above:
+--------------------------+--------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| Procedure | sql_mode | Create Procedure | character_set_client | collation_connection | Database Collation |
+--------------------------+--------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| ExtenddatesWithMonthdemo | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | CREATE DEFINER = `root`@`%` PROCEDURE `ExtenddatesWithMonthdemo`(IN date1 datetime, IN NumberOfMonth int )
BEGIN
SELECT DATE_ADD(date1,INTERVAL NumberOfMonth MONTH) AS ExtendDate;
END | utf8 | utf8_general_ci | utf8_general_ci |
+--------------------------+--------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)
Call the stored procedure with the help of the CALL command. The query is as follows −
mysql> call ExtenddatesWithMonthdemo('2019-02-13',6);
+---------------------+
| ExtendDate |
+---------------------+
| 2019-08-13 00:00:00 |
+---------------------+
1 row in set (0.10 sec)
Query OK, 0 rows affected (0.12 sec)
|
[
{
"code": null,
"e": 1103,
"s": 1062,
"text": "Let us first create a stored procedure −"
},
{
"code": null,
"e": 1375,
"s": 1103,
"text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE ExtenddatesWithMonthdemo(IN date1 datetime, IN NumberOfMonth int )\n -> BEGIN\n -> SELECT DATE_ADD(date1,INTERVAL NumberOfMonth MONTH) AS ExtendDate;\n -> END;\n -> //\nQuery OK, 0 rows affected (0.20 sec)\nmysql> DELIMITER ;"
},
{
"code": null,
"e": 1460,
"s": 1375,
"text": "Now you check whether the stored procedure exists with the help SHOW CREATE command."
},
{
"code": null,
"e": 1486,
"s": 1460,
"text": "The query is as follows −"
},
{
"code": null,
"e": 3245,
"s": 1486,
"text": "mysql> SHOW CREATE PROCEDURE ExtenddatesWithMonthdemo;\nThe following is the output displaying the details of the stored procedure we created above:\n+--------------------------+--------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+\n| Procedure | sql_mode | Create Procedure | character_set_client | collation_connection | Database Collation |\n+--------------------------+--------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+\n| ExtenddatesWithMonthdemo | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | CREATE DEFINER = `root`@`%` PROCEDURE `ExtenddatesWithMonthdemo`(IN date1 datetime, IN NumberOfMonth int )\nBEGIN\nSELECT DATE_ADD(date1,INTERVAL NumberOfMonth MONTH) AS ExtendDate;\nEND | utf8 | utf8_general_ci | utf8_general_ci |\n+--------------------------+--------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 3332,
"s": 3245,
"text": "Call the stored procedure with the help of the CALL command. The query is as follows −"
},
{
"code": null,
"e": 3386,
"s": 3332,
"text": "mysql> call ExtenddatesWithMonthdemo('2019-02-13',6);"
},
{
"code": null,
"e": 3567,
"s": 3386,
"text": "+---------------------+\n| ExtendDate |\n+---------------------+\n| 2019-08-13 00:00:00 |\n+---------------------+\n1 row in set (0.10 sec)\nQuery OK, 0 rows affected (0.12 sec)"
}
] |
Inserting random numbers into a table in MySQL?
|
To insert random numbers, use RAND() function from MySQL. Let us first create a table −
mysql> create table DemoTable
(
Value int
);
Query OK, 0 rows affected (0.46 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
| 10 |
| 20 |
| 30 |
+-------+
3 rows in set (0.00 sec)
Let us insert random numbers into a table in MySQL −
mysql> update DemoTable set Value=FLOOR(@number * rand()) + 1;
Query OK, 3 rows affected (0.17 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
| 2 |
| 2 |
| 1 |
+-------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "To insert random numbers, use RAND() function from MySQL. Let us first create a table −"
},
{
"code": null,
"e": 1235,
"s": 1150,
"text": "mysql> create table DemoTable\n(\n Value int\n);\nQuery OK, 0 rows affected (0.46 sec)"
},
{
"code": null,
"e": 1291,
"s": 1235,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1522,
"s": 1291,
"text": "mysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(20);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values(30);\nQuery OK, 1 row affected (0.08 sec)"
},
{
"code": null,
"e": 1582,
"s": 1522,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1613,
"s": 1582,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1654,
"s": 1613,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1749,
"s": 1654,
"text": "+-------+\n| Value |\n+-------+\n| 10 |\n| 20 |\n| 30 |\n+-------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1802,
"s": 1749,
"text": "Let us insert random numbers into a table in MySQL −"
},
{
"code": null,
"e": 1941,
"s": 1802,
"text": "mysql> update DemoTable set Value=FLOOR(@number * rand()) + 1;\nQuery OK, 3 rows affected (0.17 sec)\nRows matched: 3 Changed: 3 Warnings: 0"
},
{
"code": null,
"e": 1981,
"s": 1941,
"text": "Let us check table records once again −"
},
{
"code": null,
"e": 2012,
"s": 1981,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2053,
"s": 2012,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2148,
"s": 2053,
"text": "+-------+\n| Value |\n+-------+\n| 2 |\n| 2 |\n| 1 |\n+-------+\n3 rows in set (0.00 sec)"
}
] |
CSS | image-rendering Property - GeeksforGeeks
|
17 Dec, 2019
The image-rendering property is used to set the type of algorithm used for image scaling. This property can be used to modify the scaling behavior when the user scales the image above or below the original dimensions.
Syntax:
shape-rendering: auto | crisp-edges | pixelated | initial | inherit
Property Values:
auto: It is used to indicate that the scaling algorithm will be dependent on the user agent. Different browsers may have different algorithms.Example:<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-auto { image-rendering: auto; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'auto' value in Firefox </p> <div class="container"> <img class="image-crisp" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> <img class="image-auto" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> </div></body></html>Output: Comparing the crisp-edges value with the auto value
Example:
<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-auto { image-rendering: auto; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'auto' value in Firefox </p> <div class="container"> <img class="image-crisp" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> <img class="image-auto" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> </div></body></html>
Output: Comparing the crisp-edges value with the auto value
crisp-edges: It is used to indicate that the algorithm will preserve the contrast and edges in the image. It will not smooth out the colors or blur the image due to the use of anti-aliasing. Some of the algorithms used here are nearest-neighbor and other non-smoothing scaling algorithms.Example:<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-auto { image-rendering: auto; } .image-crisp { image-rendering: crisp-edges; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'auto' value with the 'crisp-edges' value in Firefox </p> <div class="container"> <img class="image-auto" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> <img class="image-crisp" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> </div></body></html>Output: Comparing the auto value with the crisp-edges value
Example:
<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-auto { image-rendering: auto; } .image-crisp { image-rendering: crisp-edges; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'auto' value with the 'crisp-edges' value in Firefox </p> <div class="container"> <img class="image-auto" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> <img class="image-crisp" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> </div></body></html>
Output: Comparing the auto value with the crisp-edges value
pixelated: It is used to indicate that the nearest-neighbor algorithm is used on the image when it is scaled up. When the image is scaled down, the behavior is the same as the auto value.Example:<!DOCTYPE html><html> <head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-pixelated { image-rendering: pixelated; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'pixelated' value in Firefox </p> <div class="container"> <img class="image-crisp" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> <img class="image-pixelated" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> </div></body></html>Output: Comparing the crisp-edges value with the pixelated value
Example:
<!DOCTYPE html><html> <head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-pixelated { image-rendering: pixelated; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'pixelated' value in Firefox </p> <div class="container"> <img class="image-crisp" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> <img class="image-pixelated" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> </div></body></html>
Output: Comparing the crisp-edges value with the pixelated value
initial: It is used to set the property to its default value.Example:<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-auto { image-rendering: initial; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'initial' value in Firefox </p> <div class="container"> <img class="image-crisp" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> <img class="image-auto" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> </div></body></html>Output: Comparing the crisp-edges value with the initial value
<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-auto { image-rendering: initial; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'initial' value in Firefox </p> <div class="container"> <img class="image-crisp" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> <img class="image-auto" src="https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png" width="250px"> </div></body></html>
Output: Comparing the crisp-edges value with the initial value
inherit: It is used to set the property to inherit from its parent element.
Supported Browsers: The browsers supported by image-rendering property are listed below:
Chrome
Firefox
Safari
Opera
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24305,
"s": 24277,
"text": "\n17 Dec, 2019"
},
{
"code": null,
"e": 24523,
"s": 24305,
"text": "The image-rendering property is used to set the type of algorithm used for image scaling. This property can be used to modify the scaling behavior when the user scales the image above or below the original dimensions."
},
{
"code": null,
"e": 24531,
"s": 24523,
"text": "Syntax:"
},
{
"code": null,
"e": 24599,
"s": 24531,
"text": "shape-rendering: auto | crisp-edges | pixelated | initial | inherit"
},
{
"code": null,
"e": 24616,
"s": 24599,
"text": "Property Values:"
},
{
"code": null,
"e": 25599,
"s": 24616,
"text": "auto: It is used to indicate that the scaling algorithm will be dependent on the user agent. Different browsers may have different algorithms.Example:<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-auto { image-rendering: auto; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'auto' value in Firefox </p> <div class=\"container\"> <img class=\"image-crisp\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> <img class=\"image-auto\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> </div></body></html>Output: Comparing the crisp-edges value with the auto value"
},
{
"code": null,
"e": 25608,
"s": 25599,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-auto { image-rendering: auto; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'auto' value in Firefox </p> <div class=\"container\"> <img class=\"image-crisp\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> <img class=\"image-auto\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> </div></body></html>",
"e": 26382,
"s": 25608,
"text": null
},
{
"code": null,
"e": 26442,
"s": 26382,
"text": "Output: Comparing the crisp-edges value with the auto value"
},
{
"code": null,
"e": 27511,
"s": 26442,
"text": "crisp-edges: It is used to indicate that the algorithm will preserve the contrast and edges in the image. It will not smooth out the colors or blur the image due to the use of anti-aliasing. Some of the algorithms used here are nearest-neighbor and other non-smoothing scaling algorithms.Example:<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-auto { image-rendering: auto; } .image-crisp { image-rendering: crisp-edges; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'auto' value with the 'crisp-edges' value in Firefox </p> <div class=\"container\"> <img class=\"image-auto\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> <img class=\"image-crisp\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> </div></body></html>Output: Comparing the auto value with the crisp-edges value"
},
{
"code": null,
"e": 27520,
"s": 27511,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-auto { image-rendering: auto; } .image-crisp { image-rendering: crisp-edges; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'auto' value with the 'crisp-edges' value in Firefox </p> <div class=\"container\"> <img class=\"image-auto\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> <img class=\"image-crisp\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> </div></body></html>",
"e": 28234,
"s": 27520,
"text": null
},
{
"code": null,
"e": 28294,
"s": 28234,
"text": "Output: Comparing the auto value with the crisp-edges value"
},
{
"code": null,
"e": 29352,
"s": 28294,
"text": "pixelated: It is used to indicate that the nearest-neighbor algorithm is used on the image when it is scaled up. When the image is scaled down, the behavior is the same as the auto value.Example:<!DOCTYPE html><html> <head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-pixelated { image-rendering: pixelated; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'pixelated' value in Firefox </p> <div class=\"container\"> <img class=\"image-crisp\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> <img class=\"image-pixelated\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> </div></body></html>Output: Comparing the crisp-edges value with the pixelated value"
},
{
"code": null,
"e": 29361,
"s": 29352,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-pixelated { image-rendering: pixelated; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'pixelated' value in Firefox </p> <div class=\"container\"> <img class=\"image-crisp\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> <img class=\"image-pixelated\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> </div></body></html>",
"e": 30160,
"s": 29361,
"text": null
},
{
"code": null,
"e": 30225,
"s": 30160,
"text": "Output: Comparing the crisp-edges value with the pixelated value"
},
{
"code": null,
"e": 31122,
"s": 30225,
"text": "initial: It is used to set the property to its default value.Example:<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-auto { image-rendering: initial; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'initial' value in Firefox </p> <div class=\"container\"> <img class=\"image-crisp\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> <img class=\"image-auto\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> </div></body></html>Output: Comparing the crisp-edges value with the initial value"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | image-rendering </title> <style> .image-crisp { /* Using the crisp-edges value for demonstration */ image-rendering: crisp-edges; } .image-auto { image-rendering: initial; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | image-rendering </b> <p> Comparing the 'crisp-edges' value with the 'initial' value in Firefox </p> <div class=\"container\"> <img class=\"image-crisp\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> <img class=\"image-auto\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191202010422/eg-image.png\" width=\"250px\"> </div></body></html>",
"e": 31888,
"s": 31122,
"text": null
},
{
"code": null,
"e": 31951,
"s": 31888,
"text": "Output: Comparing the crisp-edges value with the initial value"
},
{
"code": null,
"e": 32027,
"s": 31951,
"text": "inherit: It is used to set the property to inherit from its parent element."
},
{
"code": null,
"e": 32116,
"s": 32027,
"text": "Supported Browsers: The browsers supported by image-rendering property are listed below:"
},
{
"code": null,
"e": 32123,
"s": 32116,
"text": "Chrome"
},
{
"code": null,
"e": 32131,
"s": 32123,
"text": "Firefox"
},
{
"code": null,
"e": 32138,
"s": 32131,
"text": "Safari"
},
{
"code": null,
"e": 32144,
"s": 32138,
"text": "Opera"
},
{
"code": null,
"e": 32159,
"s": 32144,
"text": "CSS-Properties"
},
{
"code": null,
"e": 32163,
"s": 32159,
"text": "CSS"
},
{
"code": null,
"e": 32180,
"s": 32163,
"text": "Web Technologies"
},
{
"code": null,
"e": 32278,
"s": 32180,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32287,
"s": 32278,
"text": "Comments"
},
{
"code": null,
"e": 32300,
"s": 32287,
"text": "Old Comments"
},
{
"code": null,
"e": 32358,
"s": 32300,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 32395,
"s": 32358,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 32436,
"s": 32395,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 32473,
"s": 32436,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32537,
"s": 32473,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 32593,
"s": 32537,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 32626,
"s": 32593,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32669,
"s": 32626,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32730,
"s": 32669,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
How to disable close button on a JFrame in Java?
|
To disable the close button, let us first create a frame −
JFrame frame = new JFrame("Login!");
Use the setDefaultCloseOperation() to set the status of the close button. Set it to DO_NOTHING_ON_CLOSE to disable it −
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
The following is an example to disable close button on a JFrame in Java −
package my;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Login!");
JLabel label1, label2, label3;
frame.setLayout(new GridLayout(2, 2));
label1 = new JLabel("DeptId", SwingConstants.CENTER);
label2 = new JLabel("SSN", SwingConstants.CENTER);
label3 = new JLabel("Password", SwingConstants.CENTER);
JTextField deptid = new JTextField(20);
JTextField ssn = new JTextField(20);
JPasswordField passwd = new JPasswordField();
passwd.setEchoChar('*');
frame.add(label1); frame.add(label2); frame.add(label3); frame.add(deptid); frame.add(ssn); frame.add(passwd);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setSize(550, 400);
frame.setVisible(true);
}
}
The output is as follows displaying the close button but it won’t work since we disabled it above −
|
[
{
"code": null,
"e": 1121,
"s": 1062,
"text": "To disable the close button, let us first create a frame −"
},
{
"code": null,
"e": 1158,
"s": 1121,
"text": "JFrame frame = new JFrame(\"Login!\");"
},
{
"code": null,
"e": 1278,
"s": 1158,
"text": "Use the setDefaultCloseOperation() to set the status of the close button. Set it to DO_NOTHING_ON_CLOSE to disable it −"
},
{
"code": null,
"e": 1338,
"s": 1278,
"text": "frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);"
},
{
"code": null,
"e": 1412,
"s": 1338,
"text": "The following is an example to disable close button on a JFrame in Java −"
},
{
"code": null,
"e": 2414,
"s": 1412,
"text": "package my;\nimport java.awt.GridLayout;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPasswordField;\nimport javax.swing.JTextField;\nimport javax.swing.SwingConstants;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Login!\");\n JLabel label1, label2, label3;\n frame.setLayout(new GridLayout(2, 2));\n label1 = new JLabel(\"DeptId\", SwingConstants.CENTER);\n label2 = new JLabel(\"SSN\", SwingConstants.CENTER);\n label3 = new JLabel(\"Password\", SwingConstants.CENTER);\n JTextField deptid = new JTextField(20);\n JTextField ssn = new JTextField(20);\n JPasswordField passwd = new JPasswordField();\n passwd.setEchoChar('*');\n frame.add(label1); frame.add(label2); frame.add(label3); frame.add(deptid); frame.add(ssn); frame.add(passwd);\n frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2514,
"s": 2414,
"text": "The output is as follows displaying the close button but it won’t work since we disabled it above −"
}
] |
Selenium - Grid
|
Selenium Grid is a tool that distributes the tests across multiple physical or virtual machines so that we can execute scripts in parallel (simultaneously). It dramatically accelerates the testing process across browsers and across platforms by giving us quick and accurate feedback.
Selenium Grid allows us to execute multiple instances of WebDriver or Selenium Remote Control tests in parallel which uses the same code base, hence the code need NOT be present on the system they execute. The selenium-server-standalone package includes Hub, WebDriver, and Selenium RC to execute the scripts in grid.
Selenium Grid has a Hub and a Node.
Hub − The hub can also be understood as a server which acts as the central point where the tests would be triggered. A Selenium Grid has only one Hub and it is launched on a single machine once.
Hub − The hub can also be understood as a server which acts as the central point where the tests would be triggered. A Selenium Grid has only one Hub and it is launched on a single machine once.
Node − Nodes are the Selenium instances that are attached to the Hub which execute the tests. There can be one or more nodes in a grid which can be of any OS and can contain any of the Selenium supported browsers.
Node − Nodes are the Selenium instances that are attached to the Hub which execute the tests. There can be one or more nodes in a grid which can be of any OS and can contain any of the Selenium supported browsers.
The following diagram shows the architecture of Selenium Grid.
In order to work with the Grid, we need to follow certain protocols. Listen below are the major steps involved in this process −
Configuring the Hub
Configuring the Nodes
Develop the Script and Prepare the XML File
Test Execution
Result Analysis
Let us discuss each of these steps in detail.
Step 1 − Download the latest Selenium Server standalone JAR file from http://docs.seleniumhq.org/download/. Download it by clicking on the version as shown below.
Step 2 − Start the Hub by launching the Selenium Server using the following command. Now we will use the port '4444' to start the hub.
Note − Ensure that there are no other applications that are running on port# 4444.
java -jar selenium-server-standalone-2.25.0.jar -port 4444 -role hub -nodeTimeout 1000
Step 3 − Now open the browser and navigate to the URL http//localhost:4444 from the Hub (The system where you have executed Step#2).
Step 4 − Now click on the 'console' link and click 'view config'. The config of the hub would be displayed as follows. As of now, we haven't got any nodes, hence we will not be able to see the details.
Step 1 − Logon to the node (where you would like to execute the scripts) and place the 'selenium-server-standalone-2.42.2' in a folder. We need to point to the selenium-server-standalone JAR while launching the nodes.
Step 2 − Launch FireFox Node using the following below command.
java -jar D:\JAR\selenium-server-standalone-2.42.2.jar
-role node -hub http://10.30.217.157:4444/grid/register
-browser browserName = firefox -port 5555
Where,
D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)
http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub
browserName = firefox (Parameter to specify the Browser name on Nodes)
5555 = Port on which Firefox Node would be up and running.
Step 3 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the node attached to it.
Step 4 − Now let us launch the Internet Explorer Node. For launching the IE Node, we need to have the Internet Explorer driver downloaded on the node machine.
Step 5 − To download the Internet Explorer driver, navigate to http://docs.seleniumhq.org/download/ and download the appropriate file based on the architecture of your OS. After you have downloaded, unzip the exe file and place in it a folder which has to be referred while launching IE nodes.
Step 6 − Launch IE using the following command.
C:\>java -Dwebdriver.ie.driver = D:\IEDriverServer.exe
-jar D:\JAR\selenium-server-standalone-2.42.2.jar
-role webdriver -hub http://10.30.217.157:4444/grid/register
-browser browserName = ie,platform = WINDOWS -port 5558
Where,
D:\IEDriverServer.exe = The location of the downloaded the IE Driver(on the Node Machine)
D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)
http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub
browserName = ie (Parameter to specify the Browser name on Nodes)
5558 = Port on which IE Node would be up and running.
Step 7 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the IE node attached to it.
Step 8 − Let us now launch Chrome Node. For launching the Chrome Node, we need to have the Chrome driver downloaded on the node machine.
Step 9 − To download the Chrome Driver, navigate to http://docs.seleniumhq.org/download/ and then navigate to Third Party Browser Drivers area and click on the version number '2.10' as shown below.
Step 10 − Download the driver based on the type of your OS. We will execute it on Windows environment, hence we will download the Windows Chrome Driver. After you have downloaded, unzip the exe file and place it in a folder which has to be referred while launching chrome nodes.
Step 11 − Launch Chrome using the following command.
C:\>java -Dwebdriver.chrome.driver = D:\chromedriver.exe
-jar D:\JAR\selenium-server-standalone-2.42.2.jar
-role webdriver -hub http://10.30.217.157:4444/grid/register
-browser browserName = chrome, platform = WINDOWS -port 5557
Where,
D:\chromedriver.exe = The location of the downloaded the chrome Driver(on the Node Machine)
D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)
http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub
browserName = chrome (Parameter to specify the Browser name on Nodes)
5557 = Port on which chrome Node would be up and running.
Step 12 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the chrome node attached to it.
Step 1 − We will develop a test using TestNG. In the following example, we will launch each one of those browsers using remote webDriver. It can pass on their capabilities to the driver so that the driver has all information to execute on Nodes.
The Browser Parameter would be passed from the "XML" file.
package TestNG;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.net.MalformedURLException;
public class TestNGClass {
public WebDriver driver;
public String URL, Node;
protected ThreadLocal<RemoteWebDriver> threadDriver = null;
@Parameters("browser")
@BeforeTest
public void launchapp(String browser) throws MalformedURLException {
String URL = "http://www.calculator.net";
if (browser.equalsIgnoreCase("firefox")) {
System.out.println(" Executing on FireFox");
String Node = "http://10.112.66.52:5555/wd/hub";
DesiredCapabilities cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
driver = new RemoteWebDriver(new URL(Node), cap);
// Puts an Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Launch website
driver.navigate().to(URL);
driver.manage().window().maximize();
} else if (browser.equalsIgnoreCase("chrome")) {
System.out.println(" Executing on CHROME");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
String Node = "http://10.112.66.52:5557/wd/hub";
driver = new RemoteWebDriver(new URL(Node), cap);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Launch website
driver.navigate().to(URL);
driver.manage().window().maximize();
} else if (browser.equalsIgnoreCase("ie")) {
System.out.println(" Executing on IE");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setBrowserName("ie");
String Node = "http://10.112.66.52:5558/wd/hub";
driver = new RemoteWebDriver(new URL(Node), cap);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Launch website
driver.navigate().to(URL);
driver.manage().window().maximize();
} else {
throw new IllegalArgumentException("The Browser Type is Undefined");
}
}
@Test
public void calculatepercent() {
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[3]/a")).click();
// Click on Percent Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[4]/div[3]/a")).click();
// Enter value 10 in the first number of the percent Calculator
driver.findElement(By.id("cpar1")).sendKeys("10");
// Enter value 50 in the second number of the percent Calculator
driver.findElement(By.id("cpar2")).sendKeys("50");
// Click Calculate Button
// driver.findElement(By.xpath(".//*[@id = 'content']/table/tbody/tr/td[2]/input")).click();
// Get the Result Text based on its xpath
String result =
driver.findElement(By.xpath(".//*[@id = 'content']/p[2]/span/font/b")).getText();
// Print a Log In message to the screen
System.out.println(" The Result is " + result);
if(result.equals("5")) {
System.out.println(" The Result is Pass");
} else {
System.out.println(" The Result is Fail");
}
}
@AfterTest
public void closeBrowser() {
driver.quit();
}
}
Step 2 − The Browser parameter will be passed using XML. Create an XML under the project folder.
Step 3 − Select 'File' from 'General' and click 'Next'.
Step 4 − Enter the name of the file and click 'Finish'.
Step 5 − TestNg.XML is created under the project folder as shown below.
Step 6 − The contents of the XML file are shown below. We create 3 tests and put them in a suite and mention parallel="tests" so that all the tests would be executed in parallel.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "Suite" parallel = "tests">
<test name = "FirefoxTest">
<parameter name = "browser" value = "firefox" />
<classes>
<class name = "TestNG.TestNGClass" />
</classes>
</test>
<test name = "ChromeTest">
<parameter name = "browser" value = "chrome" />
<classes>
<class name = "TestNG.TestNGClass" />
</classes>
</test>
<test name = "IETest">
<parameter name = "browser" value = "ie" />
<classes>
<class name = "TestNG.TestNGClass" />
</classes>
</test>
</suite>
Step 1 − Select the created XML; right-click and choose 'Run As' >> 'TestNG Suite'.
Step 2 − Now open the Node, where we have launched all the browser nodes. You will see all the three browsers in execution simultaneously.
Step 1 − Upon completing the execution, we can analyze the result like any other execution. The result summary is printed in the console as shown in the following snapshot.
Step 2 − Navigate to the 'Results of Running Suite' Tab and TestNG would display the result summary as shown below.
Step 3 − Upon generating the HTML, we will be able to see the test results in HTML format.
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2159,
"s": 1875,
"text": "Selenium Grid is a tool that distributes the tests across multiple physical or virtual machines so that we can execute scripts in parallel (simultaneously). It dramatically accelerates the testing process across browsers and across platforms by giving us quick and accurate feedback."
},
{
"code": null,
"e": 2477,
"s": 2159,
"text": "Selenium Grid allows us to execute multiple instances of WebDriver or Selenium Remote Control tests in parallel which uses the same code base, hence the code need NOT be present on the system they execute. The selenium-server-standalone package includes Hub, WebDriver, and Selenium RC to execute the scripts in grid."
},
{
"code": null,
"e": 2513,
"s": 2477,
"text": "Selenium Grid has a Hub and a Node."
},
{
"code": null,
"e": 2708,
"s": 2513,
"text": "Hub − The hub can also be understood as a server which acts as the central point where the tests would be triggered. A Selenium Grid has only one Hub and it is launched on a single machine once."
},
{
"code": null,
"e": 2903,
"s": 2708,
"text": "Hub − The hub can also be understood as a server which acts as the central point where the tests would be triggered. A Selenium Grid has only one Hub and it is launched on a single machine once."
},
{
"code": null,
"e": 3117,
"s": 2903,
"text": "Node − Nodes are the Selenium instances that are attached to the Hub which execute the tests. There can be one or more nodes in a grid which can be of any OS and can contain any of the Selenium supported browsers."
},
{
"code": null,
"e": 3331,
"s": 3117,
"text": "Node − Nodes are the Selenium instances that are attached to the Hub which execute the tests. There can be one or more nodes in a grid which can be of any OS and can contain any of the Selenium supported browsers."
},
{
"code": null,
"e": 3394,
"s": 3331,
"text": "The following diagram shows the architecture of Selenium Grid."
},
{
"code": null,
"e": 3523,
"s": 3394,
"text": "In order to work with the Grid, we need to follow certain protocols. Listen below are the major steps involved in this process −"
},
{
"code": null,
"e": 3543,
"s": 3523,
"text": "Configuring the Hub"
},
{
"code": null,
"e": 3565,
"s": 3543,
"text": "Configuring the Nodes"
},
{
"code": null,
"e": 3609,
"s": 3565,
"text": "Develop the Script and Prepare the XML File"
},
{
"code": null,
"e": 3624,
"s": 3609,
"text": "Test Execution"
},
{
"code": null,
"e": 3640,
"s": 3624,
"text": "Result Analysis"
},
{
"code": null,
"e": 3686,
"s": 3640,
"text": "Let us discuss each of these steps in detail."
},
{
"code": null,
"e": 3849,
"s": 3686,
"text": "Step 1 − Download the latest Selenium Server standalone JAR file from http://docs.seleniumhq.org/download/. Download it by clicking on the version as shown below."
},
{
"code": null,
"e": 3984,
"s": 3849,
"text": "Step 2 − Start the Hub by launching the Selenium Server using the following command. Now we will use the port '4444' to start the hub."
},
{
"code": null,
"e": 4067,
"s": 3984,
"text": "Note − Ensure that there are no other applications that are running on port# 4444."
},
{
"code": null,
"e": 4154,
"s": 4067,
"text": "java -jar selenium-server-standalone-2.25.0.jar -port 4444 -role hub -nodeTimeout 1000"
},
{
"code": null,
"e": 4287,
"s": 4154,
"text": "Step 3 − Now open the browser and navigate to the URL http//localhost:4444 from the Hub (The system where you have executed Step#2)."
},
{
"code": null,
"e": 4489,
"s": 4287,
"text": "Step 4 − Now click on the 'console' link and click 'view config'. The config of the hub would be displayed as follows. As of now, we haven't got any nodes, hence we will not be able to see the details."
},
{
"code": null,
"e": 4707,
"s": 4489,
"text": "Step 1 − Logon to the node (where you would like to execute the scripts) and place the 'selenium-server-standalone-2.42.2' in a folder. We need to point to the selenium-server-standalone JAR while launching the nodes."
},
{
"code": null,
"e": 4771,
"s": 4707,
"text": "Step 2 − Launch FireFox Node using the following below command."
},
{
"code": null,
"e": 4931,
"s": 4771,
"text": "java -jar D:\\JAR\\selenium-server-standalone-2.42.2.jar\n -role node -hub http://10.30.217.157:4444/grid/register\n -browser browserName = firefox -port 5555\n"
},
{
"code": null,
"e": 4938,
"s": 4931,
"text": "Where,"
},
{
"code": null,
"e": 5058,
"s": 4938,
"text": "D:\\JAR\\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)"
},
{
"code": null,
"e": 5140,
"s": 5058,
"text": "http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub"
},
{
"code": null,
"e": 5211,
"s": 5140,
"text": "browserName = firefox (Parameter to specify the Browser name on Nodes)"
},
{
"code": null,
"e": 5270,
"s": 5211,
"text": "5555 = Port on which Firefox Node would be up and running."
},
{
"code": null,
"e": 5433,
"s": 5270,
"text": "Step 3 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the node attached to it."
},
{
"code": null,
"e": 5592,
"s": 5433,
"text": "Step 4 − Now let us launch the Internet Explorer Node. For launching the IE Node, we need to have the Internet Explorer driver downloaded on the node machine."
},
{
"code": null,
"e": 5886,
"s": 5592,
"text": "Step 5 − To download the Internet Explorer driver, navigate to http://docs.seleniumhq.org/download/ and download the appropriate file based on the architecture of your OS. After you have downloaded, unzip the exe file and place in it a folder which has to be referred while launching IE nodes."
},
{
"code": null,
"e": 5934,
"s": 5886,
"text": "Step 6 − Launch IE using the following command."
},
{
"code": null,
"e": 6166,
"s": 5934,
"text": "C:\\>java -Dwebdriver.ie.driver = D:\\IEDriverServer.exe\n -jar D:\\JAR\\selenium-server-standalone-2.42.2.jar\n -role webdriver -hub http://10.30.217.157:4444/grid/register\n -browser browserName = ie,platform = WINDOWS -port 5558\n"
},
{
"code": null,
"e": 6173,
"s": 6166,
"text": "Where,"
},
{
"code": null,
"e": 6263,
"s": 6173,
"text": "D:\\IEDriverServer.exe = The location of the downloaded the IE Driver(on the Node Machine)"
},
{
"code": null,
"e": 6383,
"s": 6263,
"text": "D:\\JAR\\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)"
},
{
"code": null,
"e": 6465,
"s": 6383,
"text": "http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub"
},
{
"code": null,
"e": 6531,
"s": 6465,
"text": "browserName = ie (Parameter to specify the Browser name on Nodes)"
},
{
"code": null,
"e": 6585,
"s": 6531,
"text": "5558 = Port on which IE Node would be up and running."
},
{
"code": null,
"e": 6751,
"s": 6585,
"text": "Step 7 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the IE node attached to it."
},
{
"code": null,
"e": 6888,
"s": 6751,
"text": "Step 8 − Let us now launch Chrome Node. For launching the Chrome Node, we need to have the Chrome driver downloaded on the node machine."
},
{
"code": null,
"e": 7086,
"s": 6888,
"text": "Step 9 − To download the Chrome Driver, navigate to http://docs.seleniumhq.org/download/ and then navigate to Third Party Browser Drivers area and click on the version number '2.10' as shown below."
},
{
"code": null,
"e": 7365,
"s": 7086,
"text": "Step 10 − Download the driver based on the type of your OS. We will execute it on Windows environment, hence we will download the Windows Chrome Driver. After you have downloaded, unzip the exe file and place it in a folder which has to be referred while launching chrome nodes."
},
{
"code": null,
"e": 7418,
"s": 7365,
"text": "Step 11 − Launch Chrome using the following command."
},
{
"code": null,
"e": 7661,
"s": 7418,
"text": "C:\\>java -Dwebdriver.chrome.driver = D:\\chromedriver.exe \n -jar D:\\JAR\\selenium-server-standalone-2.42.2.jar \n -role webdriver -hub http://10.30.217.157:4444/grid/register \n -browser browserName = chrome, platform = WINDOWS -port 5557\n"
},
{
"code": null,
"e": 7668,
"s": 7661,
"text": "Where,"
},
{
"code": null,
"e": 7760,
"s": 7668,
"text": "D:\\chromedriver.exe = The location of the downloaded the chrome Driver(on the Node Machine)"
},
{
"code": null,
"e": 7880,
"s": 7760,
"text": "D:\\JAR\\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)"
},
{
"code": null,
"e": 7962,
"s": 7880,
"text": "http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub"
},
{
"code": null,
"e": 8032,
"s": 7962,
"text": "browserName = chrome (Parameter to specify the Browser name on Nodes)"
},
{
"code": null,
"e": 8090,
"s": 8032,
"text": "5557 = Port on which chrome Node would be up and running."
},
{
"code": null,
"e": 8261,
"s": 8090,
"text": "Step 12 − After executing the command, come back to the Hub. Navigate to the URL - http://10.30.217.157:4444 and the Hub would now display the chrome node attached to it."
},
{
"code": null,
"e": 8507,
"s": 8261,
"text": "Step 1 − We will develop a test using TestNG. In the following example, we will launch each one of those browsers using remote webDriver. It can pass on their capabilities to the driver so that the driver has all information to execute on Nodes."
},
{
"code": null,
"e": 8566,
"s": 8507,
"text": "The Browser Parameter would be passed from the \"XML\" file."
},
{
"code": null,
"e": 12267,
"s": 8566,
"text": "package TestNG;\n\nimport org.openqa.selenium.*;\nimport org.openqa.selenium.remote.RemoteWebDriver;\nimport org.openqa.selenium.remote.DesiredCapabilities;\n\nimport org.testng.annotations.AfterTest;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Parameters;\nimport org.testng.annotations.Test;\n\nimport java.net.URL;\nimport java.util.concurrent.TimeUnit;\nimport java.net.MalformedURLException;\n\npublic class TestNGClass {\n public WebDriver driver;\n public String URL, Node;\n protected ThreadLocal<RemoteWebDriver> threadDriver = null;\n \n @Parameters(\"browser\")\n @BeforeTest\n public void launchapp(String browser) throws MalformedURLException {\n String URL = \"http://www.calculator.net\";\n \n if (browser.equalsIgnoreCase(\"firefox\")) {\n System.out.println(\" Executing on FireFox\");\n String Node = \"http://10.112.66.52:5555/wd/hub\";\n DesiredCapabilities cap = DesiredCapabilities.firefox();\n cap.setBrowserName(\"firefox\");\n \n driver = new RemoteWebDriver(new URL(Node), cap);\n // Puts an Implicit wait, Will wait for 10 seconds before throwing exception\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n // Launch website\n driver.navigate().to(URL);\n driver.manage().window().maximize();\n } else if (browser.equalsIgnoreCase(\"chrome\")) {\n System.out.println(\" Executing on CHROME\");\n DesiredCapabilities cap = DesiredCapabilities.chrome();\n cap.setBrowserName(\"chrome\");\n String Node = \"http://10.112.66.52:5557/wd/hub\";\n driver = new RemoteWebDriver(new URL(Node), cap);\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n // Launch website\n driver.navigate().to(URL);\n driver.manage().window().maximize();\n } else if (browser.equalsIgnoreCase(\"ie\")) {\n System.out.println(\" Executing on IE\");\n DesiredCapabilities cap = DesiredCapabilities.chrome();\n cap.setBrowserName(\"ie\");\n String Node = \"http://10.112.66.52:5558/wd/hub\";\n driver = new RemoteWebDriver(new URL(Node), cap);\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n // Launch website\n driver.navigate().to(URL);\n driver.manage().window().maximize();\n } else {\n throw new IllegalArgumentException(\"The Browser Type is Undefined\");\n }\n }\n \n @Test\n public void calculatepercent() {\n // Click on Math Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[3]/a\")).click(); \t\n \n // Click on Percent Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[4]/div[3]/a\")).click();\n \n // Enter value 10 in the first number of the percent Calculator\n driver.findElement(By.id(\"cpar1\")).sendKeys(\"10\");\n \n // Enter value 50 in the second number of the percent Calculator\n driver.findElement(By.id(\"cpar2\")).sendKeys(\"50\");\n \n // Click Calculate Button\n // driver.findElement(By.xpath(\".//*[@id = 'content']/table/tbody/tr/td[2]/input\")).click();\n // Get the Result Text based on its xpath\n String result =\n driver.findElement(By.xpath(\".//*[@id = 'content']/p[2]/span/font/b\")).getText();\n \n // Print a Log In message to the screen\n System.out.println(\" The Result is \" + result);\n \n if(result.equals(\"5\")) {\n System.out.println(\" The Result is Pass\");\n } else {\n System.out.println(\" The Result is Fail\");\n }\n }\n \n @AfterTest\n public void closeBrowser() {\n driver.quit();\n }\n}"
},
{
"code": null,
"e": 12364,
"s": 12267,
"text": "Step 2 − The Browser parameter will be passed using XML. Create an XML under the project folder."
},
{
"code": null,
"e": 12420,
"s": 12364,
"text": "Step 3 − Select 'File' from 'General' and click 'Next'."
},
{
"code": null,
"e": 12476,
"s": 12420,
"text": "Step 4 − Enter the name of the file and click 'Finish'."
},
{
"code": null,
"e": 12548,
"s": 12476,
"text": "Step 5 − TestNg.XML is created under the project folder as shown below."
},
{
"code": null,
"e": 12727,
"s": 12548,
"text": "Step 6 − The contents of the XML file are shown below. We create 3 tests and put them in a suite and mention parallel=\"tests\" so that all the tests would be executed in parallel."
},
{
"code": null,
"e": 13397,
"s": 12727,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\">\n<suite name = \"Suite\" parallel = \"tests\">\n\n <test name = \"FirefoxTest\">\n <parameter name = \"browser\" value = \"firefox\" />\n <classes>\n <class name = \"TestNG.TestNGClass\" />\n </classes>\n </test>\n\n <test name = \"ChromeTest\">\n <parameter name = \"browser\" value = \"chrome\" />\n <classes>\n <class name = \"TestNG.TestNGClass\" />\n </classes>\n </test>\n\n <test name = \"IETest\">\n <parameter name = \"browser\" value = \"ie\" />\n <classes>\n <class name = \"TestNG.TestNGClass\" />\n </classes>\n </test>\n \n</suite>"
},
{
"code": null,
"e": 13481,
"s": 13397,
"text": "Step 1 − Select the created XML; right-click and choose 'Run As' >> 'TestNG Suite'."
},
{
"code": null,
"e": 13620,
"s": 13481,
"text": "Step 2 − Now open the Node, where we have launched all the browser nodes. You will see all the three browsers in execution simultaneously."
},
{
"code": null,
"e": 13793,
"s": 13620,
"text": "Step 1 − Upon completing the execution, we can analyze the result like any other execution. The result summary is printed in the console as shown in the following snapshot."
},
{
"code": null,
"e": 13909,
"s": 13793,
"text": "Step 2 − Navigate to the 'Results of Running Suite' Tab and TestNG would display the result summary as shown below."
},
{
"code": null,
"e": 14000,
"s": 13909,
"text": "Step 3 − Upon generating the HTML, we will be able to see the test results in HTML format."
},
{
"code": null,
"e": 14035,
"s": 14000,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 14047,
"s": 14035,
"text": " Aditya Dua"
},
{
"code": null,
"e": 14083,
"s": 14047,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 14097,
"s": 14083,
"text": " Arun Motoori"
},
{
"code": null,
"e": 14134,
"s": 14097,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 14156,
"s": 14134,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 14189,
"s": 14156,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 14203,
"s": 14189,
"text": " Arun Motoori"
},
{
"code": null,
"e": 14238,
"s": 14203,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 14252,
"s": 14238,
"text": " Arun Motoori"
},
{
"code": null,
"e": 14289,
"s": 14252,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 14303,
"s": 14289,
"text": " Lets Kode It"
},
{
"code": null,
"e": 14310,
"s": 14303,
"text": " Print"
},
{
"code": null,
"e": 14321,
"s": 14310,
"text": " Add Notes"
}
] |
Subset Sum Problem
|
In this problem, there is a given set with some integer elements. And another some value is also provided, we have to find a subset of the given set whose sum is the same as the given sum value.
Here backtracking approach is used for trying to select a valid subset when an item is not valid, we will backtrack to get the previous subset and add another element to get the solution.
Input:
This algorithm takes a set of numbers, and a sum value.
The Set: {10, 7, 5, 18, 12, 20, 15}
The sum Value: 35
Output:
All possible subsets of the given set, where sum of each element for every subsets is same as the given sum value.
{10, 7, 18}
{10, 5, 20}
{5, 18, 12}
{20, 15}
subsetSum(set, subset, n, subSize, total, node, sum)
Input − The given set and subset, size of set and subset, a total of the subset, number of elements in the subset and the given sum.
Output − All possible subsets whose sum is the same as the given sum.
Begin
if total = sum, then
display the subset
//go for finding next subset
subsetSum(set, subset, , subSize-1, total-set[node], node+1, sum)
return
else
for all element i in the set, do
subset[subSize] := set[i]
subSetSum(set, subset, n, subSize+1, total+set[i], i+1, sum)
done
End
#include <iostream>
using namespace std;
void displaySubset(int subSet[], int size) {
for(int i = 0; i < size; i++) {
cout << subSet[i] << " ";
}
cout << endl;
}
void subsetSum(int set[], int subSet[], int n, int subSize, int total, int nodeCount ,int sum) {
if( total == sum) {
displaySubset(subSet, subSize); //print the subset
subsetSum(set,subSet,n,subSize-1,total-set[nodeCount],nodeCount+1,sum); //for other subsets
return;
}else {
for( int i = nodeCount; i < n; i++ ) { //find node along breadth
subSet[subSize] = set[i];
subsetSum(set,subSet,n,subSize+1,total+set[i],i+1,sum); //do for next node in depth
}
}
}
void findSubset(int set[], int size, int sum) {
int *subSet = new int[size]; //create subset array to pass parameter of subsetSum
subsetSum(set, subSet, size, 0, 0, 0, sum);
delete[] subSet;
}
int main() {
int weights[] = {10, 7, 5, 18, 12, 20, 15};
int size = 7;
findSubset(weights, size, 35);
}
10 7 18
10 5 20
5 18 12
20 15
|
[
{
"code": null,
"e": 1257,
"s": 1062,
"text": "In this problem, there is a given set with some integer elements. And another some value is also provided, we have to find a subset of the given set whose sum is the same as the given sum value."
},
{
"code": null,
"e": 1445,
"s": 1257,
"text": "Here backtracking approach is used for trying to select a valid subset when an item is not valid, we will backtrack to get the previous subset and add another element to get the solution."
},
{
"code": null,
"e": 1737,
"s": 1445,
"text": "Input:\nThis algorithm takes a set of numbers, and a sum value.\nThe Set: {10, 7, 5, 18, 12, 20, 15}\nThe sum Value: 35\nOutput:\nAll possible subsets of the given set, where sum of each element for every subsets is same as the given sum value.\n{10, 7, 18}\n{10, 5, 20}\n{5, 18, 12}\n{20, 15}"
},
{
"code": null,
"e": 1790,
"s": 1737,
"text": "subsetSum(set, subset, n, subSize, total, node, sum)"
},
{
"code": null,
"e": 1923,
"s": 1790,
"text": "Input − The given set and subset, size of set and subset, a total of the subset, number of elements in the subset and the given sum."
},
{
"code": null,
"e": 1993,
"s": 1923,
"text": "Output − All possible subsets whose sum is the same as the given sum."
},
{
"code": null,
"e": 2335,
"s": 1993,
"text": "Begin\n if total = sum, then\n display the subset\n //go for finding next subset\n subsetSum(set, subset, , subSize-1, total-set[node], node+1, sum)\n return\n else\n for all element i in the set, do\n subset[subSize] := set[i]\n subSetSum(set, subset, n, subSize+1, total+set[i], i+1, sum)\n done\nEnd"
},
{
"code": null,
"e": 3366,
"s": 2335,
"text": "#include <iostream>\nusing namespace std;\n\nvoid displaySubset(int subSet[], int size) {\n for(int i = 0; i < size; i++) {\n cout << subSet[i] << \" \";\n }\n cout << endl;\n}\n\nvoid subsetSum(int set[], int subSet[], int n, int subSize, int total, int nodeCount ,int sum) {\n if( total == sum) {\n displaySubset(subSet, subSize); //print the subset\n subsetSum(set,subSet,n,subSize-1,total-set[nodeCount],nodeCount+1,sum); //for other subsets\n return;\n }else {\n for( int i = nodeCount; i < n; i++ ) { //find node along breadth\n subSet[subSize] = set[i];\n subsetSum(set,subSet,n,subSize+1,total+set[i],i+1,sum); //do for next node in depth\n }\n }\n}\n\nvoid findSubset(int set[], int size, int sum) {\n int *subSet = new int[size]; //create subset array to pass parameter of subsetSum\n subsetSum(set, subSet, size, 0, 0, 0, sum);\n delete[] subSet;\n}\n\nint main() {\n int weights[] = {10, 7, 5, 18, 12, 20, 15};\n int size = 7;\n findSubset(weights, size, 35);\n}"
},
{
"code": null,
"e": 3406,
"s": 3366,
"text": "10 7 18\n10 5 20\n5 18 12\n20 15"
}
] |
Pre & post increment operator behavior in C, C++, Java, and C#
|
The Pre increment and post increment both operators are used as increment operations. The pre increment operator is used to increment the value of some variable before using it in an expression. In the pre increment the value is incremented at first, then used inside the expression.
if the expression is a = ++b; and b is holding 5 at first, then a will hold 6. Because increase b by 1, then set the value of a with it.
#include <iostream>
using namespace std;
main () {
int a, b = 15;
a = ++b;
cout << a;
}
16
#include <stdio.h>
main () {
int a, b = 15;
a = ++b;
printf(“%d”, a);
}
16
public class IncDec {
public static void main(String[] args) {
int a, b = 15;
a = ++b;
System.out.println(“” + a);
}
}
16
using System;
namespace IncDec {
class Inc {
static void Main() {
int a, b = 15;
a = ++b;
Console.WriteLine(""+a);
}
}
}
16
The post increment operator is used to increment the value of some variable after using it in an expression. In the post increment the value is used inside the expression, then incremented by one.
if the expression is a = b++; and b is holding 5 at first, then a will also hold 5. Because increase b by 1 after assigning it into a.
#include <iostream>
using namespace std;
main () {
int a, b = 15;
a = b++;
cout << a;
cout << b;
}
15
16
#include <stdio.h>
main () {
int a, b = 15;
a = ++b;
printf(“%d”, a);
printf(“%d”, b);
}
15
16
public class IncDec {
public static void main(String[] args) {
int a, b = 15;
a = ++b;
System.out.println(“” + a);
System.out.println(“” + b);
}
}
15
16
using System;
namespace IncDec {
class Inc {
static void Main() {
int a, b = 15;
a = ++b;
Console.WriteLine(""+a);
Console.WriteLine(""+b);
}
}
}
15
16
|
[
{
"code": null,
"e": 1346,
"s": 1062,
"text": "The Pre increment and post increment both operators are used as increment operations. The pre increment operator is used to increment the value of some variable before using it in an expression. In the pre increment the value is incremented at first, then used inside the expression."
},
{
"code": null,
"e": 1483,
"s": 1346,
"text": "if the expression is a = ++b; and b is holding 5 at first, then a will hold 6. Because increase b by 1, then set the value of a with it."
},
{
"code": null,
"e": 1580,
"s": 1483,
"text": "#include <iostream>\nusing namespace std;\nmain () {\n int a, b = 15;\n a = ++b;\n cout << a;\n}"
},
{
"code": null,
"e": 1583,
"s": 1580,
"text": "16"
},
{
"code": null,
"e": 1664,
"s": 1583,
"text": "#include <stdio.h>\nmain () {\n int a, b = 15;\n a = ++b;\n printf(“%d”, a);\n}"
},
{
"code": null,
"e": 1667,
"s": 1664,
"text": "16"
},
{
"code": null,
"e": 1810,
"s": 1667,
"text": "public class IncDec {\n public static void main(String[] args) {\n int a, b = 15;\n a = ++b;\n System.out.println(“” + a);\n }\n}"
},
{
"code": null,
"e": 1813,
"s": 1810,
"text": "16"
},
{
"code": null,
"e": 1982,
"s": 1813,
"text": "using System;\nnamespace IncDec {\n class Inc {\n static void Main() {\n int a, b = 15;\n a = ++b;\n Console.WriteLine(\"\"+a);\n }\n }\n}"
},
{
"code": null,
"e": 1985,
"s": 1982,
"text": "16"
},
{
"code": null,
"e": 2182,
"s": 1985,
"text": "The post increment operator is used to increment the value of some variable after using it in an expression. In the post increment the value is used inside the expression, then incremented by one."
},
{
"code": null,
"e": 2317,
"s": 2182,
"text": "if the expression is a = b++; and b is holding 5 at first, then a will also hold 5. Because increase b by 1 after assigning it into a."
},
{
"code": null,
"e": 2428,
"s": 2317,
"text": "#include <iostream>\nusing namespace std;\nmain () {\n int a, b = 15;\n a = b++;\n cout << a;\n cout << b;\n}"
},
{
"code": null,
"e": 2434,
"s": 2428,
"text": "15\n16"
},
{
"code": null,
"e": 2535,
"s": 2434,
"text": "#include <stdio.h>\nmain () {\n int a, b = 15;\n a = ++b;\n printf(“%d”, a);\n printf(“%d”, b);\n}"
},
{
"code": null,
"e": 2541,
"s": 2535,
"text": "15\n16"
},
{
"code": null,
"e": 2718,
"s": 2541,
"text": "public class IncDec {\n public static void main(String[] args) {\n int a, b = 15;\n a = ++b;\n System.out.println(“” + a);\n System.out.println(“” + b);\n }\n}"
},
{
"code": null,
"e": 2724,
"s": 2718,
"text": "15\n16"
},
{
"code": null,
"e": 2923,
"s": 2724,
"text": "using System;\nnamespace IncDec {\n class Inc {\n static void Main() {\n int a, b = 15;\n a = ++b;\n Console.WriteLine(\"\"+a);\n Console.WriteLine(\"\"+b);\n }\n }\n}"
},
{
"code": null,
"e": 2929,
"s": 2923,
"text": "15\n16"
}
] |
Creating a Pandas Series - GeeksforGeeks
|
17 Jan, 2019
Pandas Series is a one-dimensional labelled array capable of holding data of any type (integer, string, float, python objects, etc.). The axis labels are collectively called index.
Labels need not be unique but must be a hashable type. The object supports both integer and label-based indexing and provides a host of methods for performing operations involving the index.
Creating an empty Series :A basic series, which can be created is an Empty Series.
# import pandas as pdimport pandas as pd # Creating empty seriesser = pd.Series() print(ser)
Output :
Series([], dtype: float64)
Creating a series from array:In order to create a series from array, we have to import a numpy module and have to use array() function.
# import pandas as pdimport pandas as pd # import numpy as npimport numpy as np # simple arraydata = np.array(['g', 'e', 'e', 'k', 's']) ser = pd.Series(data)print(ser)
Output :
Creating a series from array with index :In order to create a series from array with index, we have to provide index with same number of element as it is in array.
# import pandas as pdimport pandas as pd # import numpy as npimport numpy as np # simple arraydata = np.array(['g', 'e', 'e', 'k', 's']) # providing an indexser = pd.Series(data, index =[10, 11, 12, 13, 14])print(ser)
Output :
Creating a series from Lists:In order to create a series from list, we have to first create a list after that we can create a series from list.
import pandas as pd # a simple listlist = ['g', 'e', 'e', 'k', 's'] # create series form a listser = pd.Series(list)print(ser)
Output :
Creating a series from Dictionary:In order to create a series from dictionary, we have to first create a dictionary after that we can make a series using dictionary. Dictionary key are used to construct a index.
import pandas as pd # a simple dictionarydict = {'Geeks' : 10, 'for' : 20, 'geeks' : 30} # create series from dictionaryser = pd.Series(dict) print(ser)
Output :
Creating a series from Scalar value:In order to create a series from scalar value, an index must be provided. The scalar value will be repeated to match the length of index.
import pandas as pd import numpy as np # giving a scalar value with indexser = pd.Series(10, index =[0, 1, 2, 3, 4, 5]) print(ser)
Output :
Creating a series using NumPy functions :In order to create a series using numpy function, we can use different function of numpy like numpy.linspace(), numpy.random.radn().
# import pandas and numpy import pandas as pd import numpy as np # series with numpy linspace() ser1 = pd.Series(np.linspace(3, 33, 3)) print(ser1) # series with numpy linspace() ser2 = pd.Series(np.linspace(1, 100, 10)) print("\n", ser2)
Output :
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
|
[
{
"code": null,
"e": 41553,
"s": 41525,
"text": "\n17 Jan, 2019"
},
{
"code": null,
"e": 41734,
"s": 41553,
"text": "Pandas Series is a one-dimensional labelled array capable of holding data of any type (integer, string, float, python objects, etc.). The axis labels are collectively called index."
},
{
"code": null,
"e": 41925,
"s": 41734,
"text": "Labels need not be unique but must be a hashable type. The object supports both integer and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 42008,
"s": 41925,
"text": "Creating an empty Series :A basic series, which can be created is an Empty Series."
},
{
"code": "# import pandas as pdimport pandas as pd # Creating empty seriesser = pd.Series() print(ser)",
"e": 42103,
"s": 42008,
"text": null
},
{
"code": null,
"e": 42112,
"s": 42103,
"text": "Output :"
},
{
"code": null,
"e": 42140,
"s": 42112,
"text": "Series([], dtype: float64)\n"
},
{
"code": null,
"e": 42277,
"s": 42140,
"text": " Creating a series from array:In order to create a series from array, we have to import a numpy module and have to use array() function."
},
{
"code": "# import pandas as pdimport pandas as pd # import numpy as npimport numpy as np # simple arraydata = np.array(['g', 'e', 'e', 'k', 's']) ser = pd.Series(data)print(ser)",
"e": 42449,
"s": 42277,
"text": null
},
{
"code": null,
"e": 42458,
"s": 42449,
"text": "Output :"
},
{
"code": null,
"e": 42623,
"s": 42458,
"text": " Creating a series from array with index :In order to create a series from array with index, we have to provide index with same number of element as it is in array."
},
{
"code": "# import pandas as pdimport pandas as pd # import numpy as npimport numpy as np # simple arraydata = np.array(['g', 'e', 'e', 'k', 's']) # providing an indexser = pd.Series(data, index =[10, 11, 12, 13, 14])print(ser)",
"e": 42844,
"s": 42623,
"text": null
},
{
"code": null,
"e": 42853,
"s": 42844,
"text": "Output :"
},
{
"code": null,
"e": 42998,
"s": 42853,
"text": " Creating a series from Lists:In order to create a series from list, we have to first create a list after that we can create a series from list."
},
{
"code": "import pandas as pd # a simple listlist = ['g', 'e', 'e', 'k', 's'] # create series form a listser = pd.Series(list)print(ser)",
"e": 43128,
"s": 42998,
"text": null
},
{
"code": null,
"e": 43137,
"s": 43128,
"text": "Output :"
},
{
"code": null,
"e": 43349,
"s": 43137,
"text": "Creating a series from Dictionary:In order to create a series from dictionary, we have to first create a dictionary after that we can make a series using dictionary. Dictionary key are used to construct a index."
},
{
"code": "import pandas as pd # a simple dictionarydict = {'Geeks' : 10, 'for' : 20, 'geeks' : 30} # create series from dictionaryser = pd.Series(dict) print(ser)",
"e": 43522,
"s": 43349,
"text": null
},
{
"code": null,
"e": 43531,
"s": 43522,
"text": "Output :"
},
{
"code": null,
"e": 43706,
"s": 43531,
"text": " Creating a series from Scalar value:In order to create a series from scalar value, an index must be provided. The scalar value will be repeated to match the length of index."
},
{
"code": "import pandas as pd import numpy as np # giving a scalar value with indexser = pd.Series(10, index =[0, 1, 2, 3, 4, 5]) print(ser)",
"e": 43840,
"s": 43706,
"text": null
},
{
"code": null,
"e": 43849,
"s": 43840,
"text": "Output :"
},
{
"code": null,
"e": 44024,
"s": 43849,
"text": " Creating a series using NumPy functions :In order to create a series using numpy function, we can use different function of numpy like numpy.linspace(), numpy.random.radn()."
},
{
"code": "# import pandas and numpy import pandas as pd import numpy as np # series with numpy linspace() ser1 = pd.Series(np.linspace(3, 33, 3)) print(ser1) # series with numpy linspace() ser2 = pd.Series(np.linspace(1, 100, 10)) print(\"\\n\", ser2) ",
"e": 44273,
"s": 44024,
"text": null
},
{
"code": null,
"e": 44282,
"s": 44273,
"text": "Output :"
},
{
"code": null,
"e": 44303,
"s": 44282,
"text": "Python pandas-series"
},
{
"code": null,
"e": 44317,
"s": 44303,
"text": "Python-pandas"
},
{
"code": null,
"e": 44324,
"s": 44317,
"text": "Python"
},
{
"code": null,
"e": 44422,
"s": 44324,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44431,
"s": 44422,
"text": "Comments"
},
{
"code": null,
"e": 44444,
"s": 44431,
"text": "Old Comments"
},
{
"code": null,
"e": 44472,
"s": 44444,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 44522,
"s": 44472,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 44544,
"s": 44522,
"text": "Python map() function"
},
{
"code": null,
"e": 44588,
"s": 44544,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 44610,
"s": 44588,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 44645,
"s": 44610,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 44677,
"s": 44645,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 44707,
"s": 44677,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 44749,
"s": 44707,
"text": "Different ways to create Pandas Dataframe"
}
] |
Interesting facts about switch statement in C - GeeksforGeeks
|
18 Sep, 2018
Prerequisite – Switch Statement in CSwitch is a control statement that allows a value to change control of execution.
// Following is a simple program to demonstrate syntax of switch.#include <stdio.h>int main(){ int x = 2; switch (x) { case 1: printf("Choice is 1"); break; case 2: printf("Choice is 2"); break; case 3: printf("Choice is 3"); break; default: printf("Choice other than 1, 2 and 3"); break; } return 0;}
Output:
Choice is 2
Following are some interesting facts about switch statement.
1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed.
// float is not allowed in switch#include <stdio.h>int main(){ float x = 1.1; switch (x) { case 1.1: printf("Choice is 1"); break; default: printf("Choice other than 1, 2 and 3"); break; } return 0;}
Output:
Compiler Error: switch quantity not an integer
In Java, String is also allowed in switch (See this)
2) All the statements following a matching case execute until a break statement is reached.
// There is no break in all cases#include <stdio.h>int main(){ int x = 2; switch (x) { case 1: printf("Choice is 1\n"); case 2: printf("Choice is 2\n"); case 3: printf("Choice is 3\n"); default: printf("Choice other than 1, 2 and 3\n"); } return 0;}
Output:
Choice is 2
Choice is 3
Choice other than 1, 2 and 3
// There is no break in some cases#include <stdio.h>int main(){ int x = 2; switch (x) { case 1: printf("Choice is 1\n"); case 2: printf("Choice is 2\n"); case 3: printf("Choice is 3\n"); case 4: printf("Choice is 4\n"); break; default: printf("Choice other than 1, 2, 3 and 4\n"); break; } printf("After Switch"); return 0;}
Output:
Choice is 2
Choice is 3
Choice is 4
After Switch
3) The default block can be placed anywhere. The position of default doesn’t matter, it is still executed if no match found.
// The default block is placed above other cases.#include <stdio.h>int main(){ int x = 4; switch (x) { default: printf("Choice other than 1 and 2"); break; case 1: printf("Choice is 1"); break; case 2: printf("Choice is 2"); break; } return 0;}
Output:
Choice other than 1 and 2
4) The integral expressions used in labels must be a constant expressions
// A program with variable expressions in labels#include <stdio.h>int main(){ int x = 2; int arr[] = {1, 2, 3}; switch (x) { case arr[0]: printf("Choice 1\n"); case arr[1]: printf("Choice 2\n"); case arr[2]: printf("Choice 3\n"); } return 0;}
Output:
Compiler Error: case label does not reduce to an integer constant
5) The statements written above cases are never executed After the switch statement, the control transfers to the matching case, the statements written before case are not executed.
// Statements before all cases are never executed#include <stdio.h>int main(){ int x = 1; switch (x) { x = x + 1; // This statement is not executed case 1: printf("Choice is 1"); break; case 2: printf("Choice is 2"); break; default: printf("Choice other than 1 and 2"); break; } return 0;}
Output:
Choice is 1
6) Two case labels cannot have same value
// Program where two case labels have same value#include <stdio.h>int main(){ int x = 1; switch (x) { case 2: printf("Choice is 1"); break; case 1+1: printf("Choice is 2"); break; } return 0;}
Output:
Compiler Error: duplicate case value
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Yuvraj Patil
C-Loops & Control Statements
cpp-switch
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
fork() in C
Left Shift and Right Shift Operators in C/C++
Command line arguments in C/C++
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n18 Sep, 2018"
},
{
"code": null,
"e": 24524,
"s": 24406,
"text": "Prerequisite – Switch Statement in CSwitch is a control statement that allows a value to change control of execution."
},
{
"code": "// Following is a simple program to demonstrate syntax of switch.#include <stdio.h>int main(){ int x = 2; switch (x) { case 1: printf(\"Choice is 1\"); break; case 2: printf(\"Choice is 2\"); break; case 3: printf(\"Choice is 3\"); break; default: printf(\"Choice other than 1, 2 and 3\"); break; } return 0;} ",
"e": 24921,
"s": 24524,
"text": null
},
{
"code": null,
"e": 24929,
"s": 24921,
"text": "Output:"
},
{
"code": null,
"e": 24941,
"s": 24929,
"text": "Choice is 2"
},
{
"code": null,
"e": 25002,
"s": 24941,
"text": "Following are some interesting facts about switch statement."
},
{
"code": null,
"e": 25125,
"s": 25002,
"text": "1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed."
},
{
"code": "// float is not allowed in switch#include <stdio.h>int main(){ float x = 1.1; switch (x) { case 1.1: printf(\"Choice is 1\"); break; default: printf(\"Choice other than 1, 2 and 3\"); break; } return 0;} ",
"e": 25381,
"s": 25125,
"text": null
},
{
"code": null,
"e": 25389,
"s": 25381,
"text": "Output:"
},
{
"code": null,
"e": 25437,
"s": 25389,
"text": " Compiler Error: switch quantity not an integer"
},
{
"code": null,
"e": 25490,
"s": 25437,
"text": "In Java, String is also allowed in switch (See this)"
},
{
"code": null,
"e": 25582,
"s": 25490,
"text": "2) All the statements following a matching case execute until a break statement is reached."
},
{
"code": "// There is no break in all cases#include <stdio.h>int main(){ int x = 2; switch (x) { case 1: printf(\"Choice is 1\\n\"); case 2: printf(\"Choice is 2\\n\"); case 3: printf(\"Choice is 3\\n\"); default: printf(\"Choice other than 1, 2 and 3\\n\"); } return 0;} ",
"e": 25867,
"s": 25582,
"text": null
},
{
"code": null,
"e": 25875,
"s": 25867,
"text": "Output:"
},
{
"code": null,
"e": 25928,
"s": 25875,
"text": "Choice is 2\nChoice is 3\nChoice other than 1, 2 and 3"
},
{
"code": "// There is no break in some cases#include <stdio.h>int main(){ int x = 2; switch (x) { case 1: printf(\"Choice is 1\\n\"); case 2: printf(\"Choice is 2\\n\"); case 3: printf(\"Choice is 3\\n\"); case 4: printf(\"Choice is 4\\n\"); break; default: printf(\"Choice other than 1, 2, 3 and 4\\n\"); break; } printf(\"After Switch\"); return 0;}",
"e": 26324,
"s": 25928,
"text": null
},
{
"code": null,
"e": 26332,
"s": 26324,
"text": "Output:"
},
{
"code": null,
"e": 26381,
"s": 26332,
"text": "Choice is 2\nChoice is 3\nChoice is 4\nAfter Switch"
},
{
"code": null,
"e": 26506,
"s": 26381,
"text": "3) The default block can be placed anywhere. The position of default doesn’t matter, it is still executed if no match found."
},
{
"code": "// The default block is placed above other cases.#include <stdio.h>int main(){ int x = 4; switch (x) { default: printf(\"Choice other than 1 and 2\"); break; case 1: printf(\"Choice is 1\"); break; case 2: printf(\"Choice is 2\"); break; } return 0;}",
"e": 26831,
"s": 26506,
"text": null
},
{
"code": null,
"e": 26839,
"s": 26831,
"text": "Output:"
},
{
"code": null,
"e": 26865,
"s": 26839,
"text": "Choice other than 1 and 2"
},
{
"code": null,
"e": 26939,
"s": 26865,
"text": "4) The integral expressions used in labels must be a constant expressions"
},
{
"code": "// A program with variable expressions in labels#include <stdio.h>int main(){ int x = 2; int arr[] = {1, 2, 3}; switch (x) { case arr[0]: printf(\"Choice 1\\n\"); case arr[1]: printf(\"Choice 2\\n\"); case arr[2]: printf(\"Choice 3\\n\"); } return 0;}",
"e": 27222,
"s": 26939,
"text": null
},
{
"code": null,
"e": 27230,
"s": 27222,
"text": "Output:"
},
{
"code": null,
"e": 27296,
"s": 27230,
"text": "Compiler Error: case label does not reduce to an integer constant"
},
{
"code": null,
"e": 27478,
"s": 27296,
"text": "5) The statements written above cases are never executed After the switch statement, the control transfers to the matching case, the statements written before case are not executed."
},
{
"code": "// Statements before all cases are never executed#include <stdio.h>int main(){ int x = 1; switch (x) { x = x + 1; // This statement is not executed case 1: printf(\"Choice is 1\"); break; case 2: printf(\"Choice is 2\"); break; default: printf(\"Choice other than 1 and 2\"); break; } return 0;} ",
"e": 27867,
"s": 27478,
"text": null
},
{
"code": null,
"e": 27875,
"s": 27867,
"text": "Output:"
},
{
"code": null,
"e": 27887,
"s": 27875,
"text": "Choice is 1"
},
{
"code": null,
"e": 27929,
"s": 27887,
"text": "6) Two case labels cannot have same value"
},
{
"code": "// Program where two case labels have same value#include <stdio.h>int main(){ int x = 1; switch (x) { case 2: printf(\"Choice is 1\"); break; case 1+1: printf(\"Choice is 2\"); break; } return 0;} ",
"e": 28174,
"s": 27929,
"text": null
},
{
"code": null,
"e": 28182,
"s": 28174,
"text": "Output:"
},
{
"code": null,
"e": 28219,
"s": 28182,
"text": "Compiler Error: duplicate case value"
},
{
"code": null,
"e": 28343,
"s": 28219,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 28356,
"s": 28343,
"text": "Yuvraj Patil"
},
{
"code": null,
"e": 28385,
"s": 28356,
"text": "C-Loops & Control Statements"
},
{
"code": null,
"e": 28396,
"s": 28385,
"text": "cpp-switch"
},
{
"code": null,
"e": 28407,
"s": 28396,
"text": "C Language"
},
{
"code": null,
"e": 28411,
"s": 28407,
"text": "C++"
},
{
"code": null,
"e": 28415,
"s": 28411,
"text": "CPP"
},
{
"code": null,
"e": 28513,
"s": 28415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28522,
"s": 28513,
"text": "Comments"
},
{
"code": null,
"e": 28535,
"s": 28522,
"text": "Old Comments"
},
{
"code": null,
"e": 28570,
"s": 28535,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 28598,
"s": 28570,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 28610,
"s": 28598,
"text": "fork() in C"
},
{
"code": null,
"e": 28656,
"s": 28610,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 28688,
"s": 28656,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 28706,
"s": 28688,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 28725,
"s": 28706,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28771,
"s": 28725,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28814,
"s": 28771,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
DAX Filter - HASONEFILTER function
|
Returns TRUE when the number of directly filtered values on columnName is one and only one. Otherwise, returns FALSE.
HASONEFILTER (<columnName>)
columnName
The name of an existing column, using standard DAX syntax. It cannot be an expression.
TRUE or FALSE.
DAX HASONEFILTER function is similar to DAX HASONEVALUE function, with the difference that HASONEFILTER works by a direct filter, while HASONEVALUE works based on crossfilters.
= HASONEFILTER (Sales[Product])
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2119,
"s": 2001,
"text": "Returns TRUE when the number of directly filtered values on columnName is one and only one. Otherwise, returns FALSE."
},
{
"code": null,
"e": 2149,
"s": 2119,
"text": "HASONEFILTER (<columnName>) \n"
},
{
"code": null,
"e": 2160,
"s": 2149,
"text": "columnName"
},
{
"code": null,
"e": 2247,
"s": 2160,
"text": "The name of an existing column, using standard DAX syntax. It cannot be an expression."
},
{
"code": null,
"e": 2262,
"s": 2247,
"text": "TRUE or FALSE."
},
{
"code": null,
"e": 2439,
"s": 2262,
"text": "DAX HASONEFILTER function is similar to DAX HASONEVALUE function, with the difference that HASONEFILTER works by a direct filter, while HASONEVALUE works based on crossfilters."
},
{
"code": null,
"e": 2472,
"s": 2439,
"text": "= HASONEFILTER (Sales[Product]) "
},
{
"code": null,
"e": 2507,
"s": 2472,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2521,
"s": 2507,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 2554,
"s": 2521,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2568,
"s": 2554,
"text": " Randy Minder"
},
{
"code": null,
"e": 2603,
"s": 2568,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2617,
"s": 2603,
"text": " Randy Minder"
},
{
"code": null,
"e": 2624,
"s": 2617,
"text": " Print"
},
{
"code": null,
"e": 2635,
"s": 2624,
"text": " Add Notes"
}
] |
JavaScript - RegExp multiline Property
|
multiline is a read-only boolean property of RegExp objects. It specifies whether a particular regular expression performs multiline matching, i.e., whether it was created with the "m" attribute.
Its syntax is as follows −
RegExpObject.multiline
Returns "TRUE" if the "m" modifier is set, "FALSE" otherwise.
Try the following example program.
<html>
<head>
<title>JavaScript RegExp multiline Property</title>
</head>
<body>
<script type = "text/javascript">
var re = new RegExp( "string" );
if ( re.multiline ) {
document.write("Test1-multiline property is set");
} else {
document.write("Test1-multiline property is not set");
}
re = new RegExp( "string", "m" );
if ( re.multiline ) {
document.write("<br/>Test2-multiline property is set");
} else {
document.write("<br/>Test2-multiline property is not set");
}
</script>
</body>
</html>
Test1 - multiline property is not set
Test2 - multiline property is set
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2662,
"s": 2466,
"text": "multiline is a read-only boolean property of RegExp objects. It specifies whether a particular regular expression performs multiline matching, i.e., whether it was created with the \"m\" attribute."
},
{
"code": null,
"e": 2689,
"s": 2662,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2713,
"s": 2689,
"text": "RegExpObject.multiline\n"
},
{
"code": null,
"e": 2775,
"s": 2713,
"text": "Returns \"TRUE\" if the \"m\" modifier is set, \"FALSE\" otherwise."
},
{
"code": null,
"e": 2810,
"s": 2775,
"text": "Try the following example program."
},
{
"code": null,
"e": 3499,
"s": 2810,
"text": "<html> \n <head>\n <title>JavaScript RegExp multiline Property</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var re = new RegExp( \"string\" );\n \n if ( re.multiline ) {\n document.write(\"Test1-multiline property is set\"); \n } else {\n document.write(\"Test1-multiline property is not set\"); \n }\n re = new RegExp( \"string\", \"m\" );\n \n if ( re.multiline ) {\n document.write(\"<br/>Test2-multiline property is set\"); \n } else {\n document.write(\"<br/>Test2-multiline property is not set\"); \n }\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3572,
"s": 3499,
"text": "Test1 - multiline property is not set\nTest2 - multiline property is set\n"
},
{
"code": null,
"e": 3607,
"s": 3572,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3621,
"s": 3607,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3655,
"s": 3621,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3669,
"s": 3655,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3704,
"s": 3669,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3721,
"s": 3704,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3756,
"s": 3721,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3773,
"s": 3756,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3806,
"s": 3773,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3834,
"s": 3806,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3868,
"s": 3834,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3896,
"s": 3868,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3903,
"s": 3896,
"text": " Print"
},
{
"code": null,
"e": 3914,
"s": 3903,
"text": " Add Notes"
}
] |
Redis - Hash Hmset Command
|
Redis HMSET command is used to set the specified fields to their respective values in the hash stored at the key. This command overwrites any existing fields in the hash. If the key does not exist, a new key holding a hash is created.
Simple string reply.
Following is the basic syntax of Redis HMSET command.
redis 127.0.0.1:6379> HMSET KEY_NAME FIELD1 VALUE1 ...FIELDN VALUEN
redis 127.0.0.1:6379> HMSET myhash field1 "foo" field2 "bar"
OK
redis 127.0.0.1:6379> HGET myhash field1
"foo"
redis 127.0.0.1:6379> HGET myhash field2
"bar"
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2280,
"s": 2045,
"text": "Redis HMSET command is used to set the specified fields to their respective values in the hash stored at the key. This command overwrites any existing fields in the hash. If the key does not exist, a new key holding a hash is created."
},
{
"code": null,
"e": 2301,
"s": 2280,
"text": "Simple string reply."
},
{
"code": null,
"e": 2355,
"s": 2301,
"text": "Following is the basic syntax of Redis HMSET command."
},
{
"code": null,
"e": 2424,
"s": 2355,
"text": "redis 127.0.0.1:6379> HMSET KEY_NAME FIELD1 VALUE1 ...FIELDN VALUEN\n"
},
{
"code": null,
"e": 2588,
"s": 2424,
"text": "redis 127.0.0.1:6379> HMSET myhash field1 \"foo\" field2 \"bar\" \nOK \nredis 127.0.0.1:6379> HGET myhash field1 \n\"foo\" \nredis 127.0.0.1:6379> HGET myhash field2 \n\"bar\"\n"
},
{
"code": null,
"e": 2620,
"s": 2588,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 2640,
"s": 2620,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2647,
"s": 2640,
"text": " Print"
},
{
"code": null,
"e": 2658,
"s": 2647,
"text": " Add Notes"
}
] |
Data Abstraction in Ruby - GeeksforGeeks
|
02 Dec, 2019
The idea of representing significant details and hiding details of functionality is called data abstraction. The interface and the implementation are isolated by this programming technique. Data abstraction is one of the object oriented programming features as well. Abstraction is trying to minimize information so that the developer can concentrate on a few ideas at a time. Abstraction is the foundation for software development.
Consider a real-life example of making a phone call. The only thing the person knows is that typing the numbers and hitting the dial button will make a phone call, they don’t know about the inner system of the phone or the dial button on the phone. That’s what we call abstraction.Another real-life example of abstraction is as users of television sets, we can switch it on or off, change the channel and set the volume without knowing the details about how its functionality has been implemented.
Data Abstraction in modules: In Ruby, Modules are defined as a set of methods, classes, and constants together.For example, consider the sqrt() method present in Math module. Whenever we need to calculate the square root of a non negative number, We simply call the sqrt() method present in the Math module and send the number as a parameter without understanding the actual algorithm that actually calculates the square root of the numbers.
Data Abstraction in Classes: we can use classes to perform data abstraction in ruby. The class allows us to group information and methods using access specifiers (private, protected, public). The Class will determine which information should be visible and which is not.
Data Abstraction using Access Control: There are three levels of access control in Ruby (private, protected, public). These are the most important implementation of data abstraction in ruby. For Example-
Members who have been declared public in a class can be accessed from anywhere in the program.
Members declared to be private in a class can only be accessed from within the class. They arenot allowed to access any part of the code outside the class.
# Ruby program to demonstrate Data Abstraction class Geeks # defining publicMethod public def publicMethod puts "In Public!" # calling privateMethod inside publicMethod privateMethod end # defining privateMethod private def privateMethod puts "In Private!" endend # creating an object of class Geeks obj = Geeks.new # calling the public method of class Geeks obj.publicMethod
Output:
In Public!
In Private!
In the above program, we are not allowed to access the privateMethod() of Geeks class directly, however, we can call the publicMethod() in the class in order to access the privateMethod().
Advantages of Data Abstraction:
Helps increase the security of a system because only crucial details are made available to the user.
It increases re-usability and prevents redundancy of code.
Could alter the internal class implementation independently without affecting the user.
Picked
Ruby-OOP
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array slice() function
Ruby | Array count() operation
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Ruby | Case Statement
Ruby | Hash delete() function
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | String gsub! Method
Ruby | Data Types
|
[
{
"code": null,
"e": 23702,
"s": 23674,
"text": "\n02 Dec, 2019"
},
{
"code": null,
"e": 24135,
"s": 23702,
"text": "The idea of representing significant details and hiding details of functionality is called data abstraction. The interface and the implementation are isolated by this programming technique. Data abstraction is one of the object oriented programming features as well. Abstraction is trying to minimize information so that the developer can concentrate on a few ideas at a time. Abstraction is the foundation for software development."
},
{
"code": null,
"e": 24633,
"s": 24135,
"text": "Consider a real-life example of making a phone call. The only thing the person knows is that typing the numbers and hitting the dial button will make a phone call, they don’t know about the inner system of the phone or the dial button on the phone. That’s what we call abstraction.Another real-life example of abstraction is as users of television sets, we can switch it on or off, change the channel and set the volume without knowing the details about how its functionality has been implemented."
},
{
"code": null,
"e": 25075,
"s": 24633,
"text": "Data Abstraction in modules: In Ruby, Modules are defined as a set of methods, classes, and constants together.For example, consider the sqrt() method present in Math module. Whenever we need to calculate the square root of a non negative number, We simply call the sqrt() method present in the Math module and send the number as a parameter without understanding the actual algorithm that actually calculates the square root of the numbers."
},
{
"code": null,
"e": 25346,
"s": 25075,
"text": "Data Abstraction in Classes: we can use classes to perform data abstraction in ruby. The class allows us to group information and methods using access specifiers (private, protected, public). The Class will determine which information should be visible and which is not."
},
{
"code": null,
"e": 25550,
"s": 25346,
"text": "Data Abstraction using Access Control: There are three levels of access control in Ruby (private, protected, public). These are the most important implementation of data abstraction in ruby. For Example-"
},
{
"code": null,
"e": 25645,
"s": 25550,
"text": "Members who have been declared public in a class can be accessed from anywhere in the program."
},
{
"code": null,
"e": 25801,
"s": 25645,
"text": "Members declared to be private in a class can only be accessed from within the class. They arenot allowed to access any part of the code outside the class."
},
{
"code": "# Ruby program to demonstrate Data Abstraction class Geeks # defining publicMethod public def publicMethod puts \"In Public!\" # calling privateMethod inside publicMethod privateMethod end # defining privateMethod private def privateMethod puts \"In Private!\" endend # creating an object of class Geeks obj = Geeks.new # calling the public method of class Geeks obj.publicMethod",
"e": 26262,
"s": 25801,
"text": null
},
{
"code": null,
"e": 26270,
"s": 26262,
"text": "Output:"
},
{
"code": null,
"e": 26293,
"s": 26270,
"text": "In Public!\nIn Private!"
},
{
"code": null,
"e": 26482,
"s": 26293,
"text": "In the above program, we are not allowed to access the privateMethod() of Geeks class directly, however, we can call the publicMethod() in the class in order to access the privateMethod()."
},
{
"code": null,
"e": 26514,
"s": 26482,
"text": "Advantages of Data Abstraction:"
},
{
"code": null,
"e": 26615,
"s": 26514,
"text": "Helps increase the security of a system because only crucial details are made available to the user."
},
{
"code": null,
"e": 26674,
"s": 26615,
"text": "It increases re-usability and prevents redundancy of code."
},
{
"code": null,
"e": 26762,
"s": 26674,
"text": "Could alter the internal class implementation independently without affecting the user."
},
{
"code": null,
"e": 26769,
"s": 26762,
"text": "Picked"
},
{
"code": null,
"e": 26778,
"s": 26769,
"text": "Ruby-OOP"
},
{
"code": null,
"e": 26783,
"s": 26778,
"text": "Ruby"
},
{
"code": null,
"e": 26881,
"s": 26783,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26911,
"s": 26881,
"text": "Ruby | Array slice() function"
},
{
"code": null,
"e": 26942,
"s": 26911,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 26966,
"s": 26942,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 27009,
"s": 26966,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 27040,
"s": 27009,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 27062,
"s": 27040,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 27092,
"s": 27062,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 27160,
"s": 27092,
"text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1"
},
{
"code": null,
"e": 27187,
"s": 27160,
"text": "Ruby | String gsub! Method"
}
] |
Designing Custom ggplot2 Themes. Give your graphs an attitude | by Nancy Organ | Towards Data Science
|
The R versus Python debate is a favorite among data scientists. When it comes to data visualization, however, yours truly has a very clear preference: ggplot2 in R all the way.
Ease of data handling and formatting aside, ggplot2 shines in its customizability. The defaults look great, albeit very distinct, but with a bit of planning you can totally transform visualizations to fit any imaginable aesthetic. In this article I’ll walk through how to create a custom ggplot2 theme that can be applied to your graphs.
Open up a new R script that will contain your customizations. You’ll run this script before building any visualizations in order to make your settings available. You can package it up into a library, too, though that’s not strictly necessary.
Make sure to load up the necessary libraries. There’s nothing surprising here, just make sure ggplot and scales are loaded in before you do anything else.
library("ggplot2")library("scales")
New font, new you. Right? There are several options for using a custom font in your graphs.
The first option involves using the fonts that are already on your machine. To access them, load the extrafont library and import all fonts to R. Warning: This is slow. Once you’ve run font_import(), comment it out and leave it alone. If you’re not sure what fonts are possible, use system_fonts() to see a list.
library("extrafont")font_import() # only run this once then comment out. It's slow!extrafont::loadfonts()library("systemfonts")system_fonts() # shows you available fonts
The second option is to add in a Google font. The showtext library will let you import a font from the Google font page using the font_add_google() function. In this example, I’m importing the Reenie Beanie font for a fun handwriting effect.
library("showtext")## Loading Google fonts (https://fonts.google.com/)graphFont = "Reenie Beanie"font_add_google(graphFont)
Under normal circumstances you might use the theme() argument to make small changes to the default settings. Because ggplot2 is layered, adding +theme() to the end of a visualization will override any preceding settings.
We can take advantage of this behavior by defining a bespoke theme that can be added at the end of any visualization. This means you could even go back to old work and apply your new theme to achieve a consistent portfolio. In this example, I’ve defined a straightforward theme that makes all the text black, specifies various background fills, and sets the font. Running theme without the parentheses in R will show you all possible theme options.
theme_custom = function(){ theme( panel.background = element_blank(), panel.grid = element_blank(), axis.ticks = element_blank(), axis.text = element_text(color = "black"), legend.box.background = element_blank(), legend.key = element_rect(fill = NA), text = element_text(graphFont), plot.title = element_text(size = 16) )}
Setting up color pre-planned color scales can be a huge time saver—say goodbye to guessing which shade of magenta you used last time. I like to use the coolors app to create color palettes, and then create a vector of hex codes.
Remember that you’ll need to set a scale for both scale_color_manual() and scale_fill_manual() to account for the different geoms.
pal_custom = c("#9e0a0a", "#115035", "#ff9e97", "#f6cb4c")### Scales custom_color_manual = function(){ scale_color_manual(values = pal_custom)}custom_fill_manual = function(){ scale_fill_manual(values = pal_custom)
If you would like specific behavior for certain types of graphs, customizing the geoms is the way to go. The update_geom_defaults() function does the trick. In these examples, I’ve requested that points be at least size 3, bars have white outlines, and lines are size 1.
update_geom_defaults("point", list(size = 3))update_geom_defaults("bar", list(color = "white"))update_geom_defaults("line", list(size = 1))
As if one theme wasn’t enough, you can actually layer themes. If, for example, you are only making small changes to an existing ggplot theme, you can run the original first, and add your changes afterward.
In this example, I used the xkcd theme by Emilio Torres-Manzanera to achieve a hand-drawn look on the axes, and then applied my custom theme at the end.
ggplot(data=iris, aes(x=Sepal.Width)) + geom_histogram(binwidth=0.1, aes(fill=Species)) + custom_fill_manual() + xlab("X-axis title") + ylab("Y-axis title") + ggtitle("Main chart title") + theme_xkcd() + xkcdaxis(range(iris$Sepal.Width),range(c(0, 30))) + theme_custom()
This particular theme might not be your cup of tea, but it’s certainly different from the default look:
Establishing a custom aesthetic for your visualizations will take some iteration and testing. I recommend building a few test visuals that you can run when you update your theme—this will let you preview the effects on different chart types. Having a handful of test figures will also allow you to conduct accessibility checks and ensure that your theme is user-friendly. I use the Sim Daltonism app to evaluate color palettes and the Accessibility Insights extension to check web elements.
A knitr (.Rnw) or R Markdown (.Rmd) script works nicely for testing because it can be easily recompiled to produce a sharable document. Something as simple as this will do the trick:
\documentclass[a4paper]{article}\begin{document}<<projections, include=FALSE, cache=FALSE>>==source("branding.R")opts_chunk$set(dev='cairo_pdf')@<<renderimage, echo = FALSE, fig.height = 3, fig.width = 5, fig.align='center'>>==ggplot(data=iris, aes(x=Sepal.Width)) + geom_histogram(binwidth=0.1, aes(fill=Species)) + custom_fill_manual() + xlab("X-axis title") + ylab("Y-axis title") + ggtitle("Main chart title") + theme_xkcd() + xkcdaxis(range(iris$Sepal.Width),range(c(0, 30))) + theme_custom()@\end{document}
And that’s it! I hope this gives you a few ideas on how you can create a custom theme for your own ggplot2 work. Start small, see what works, and build from there. Your graphs will be turning heads in no time.
Thinking about accessibility in data visualization? Great! Here are some ways to get started:
|
[
{
"code": null,
"e": 349,
"s": 172,
"text": "The R versus Python debate is a favorite among data scientists. When it comes to data visualization, however, yours truly has a very clear preference: ggplot2 in R all the way."
},
{
"code": null,
"e": 687,
"s": 349,
"text": "Ease of data handling and formatting aside, ggplot2 shines in its customizability. The defaults look great, albeit very distinct, but with a bit of planning you can totally transform visualizations to fit any imaginable aesthetic. In this article I’ll walk through how to create a custom ggplot2 theme that can be applied to your graphs."
},
{
"code": null,
"e": 930,
"s": 687,
"text": "Open up a new R script that will contain your customizations. You’ll run this script before building any visualizations in order to make your settings available. You can package it up into a library, too, though that’s not strictly necessary."
},
{
"code": null,
"e": 1085,
"s": 930,
"text": "Make sure to load up the necessary libraries. There’s nothing surprising here, just make sure ggplot and scales are loaded in before you do anything else."
},
{
"code": null,
"e": 1121,
"s": 1085,
"text": "library(\"ggplot2\")library(\"scales\")"
},
{
"code": null,
"e": 1213,
"s": 1121,
"text": "New font, new you. Right? There are several options for using a custom font in your graphs."
},
{
"code": null,
"e": 1526,
"s": 1213,
"text": "The first option involves using the fonts that are already on your machine. To access them, load the extrafont library and import all fonts to R. Warning: This is slow. Once you’ve run font_import(), comment it out and leave it alone. If you’re not sure what fonts are possible, use system_fonts() to see a list."
},
{
"code": null,
"e": 1696,
"s": 1526,
"text": "library(\"extrafont\")font_import() # only run this once then comment out. It's slow!extrafont::loadfonts()library(\"systemfonts\")system_fonts() # shows you available fonts"
},
{
"code": null,
"e": 1938,
"s": 1696,
"text": "The second option is to add in a Google font. The showtext library will let you import a font from the Google font page using the font_add_google() function. In this example, I’m importing the Reenie Beanie font for a fun handwriting effect."
},
{
"code": null,
"e": 2062,
"s": 1938,
"text": "library(\"showtext\")## Loading Google fonts (https://fonts.google.com/)graphFont = \"Reenie Beanie\"font_add_google(graphFont)"
},
{
"code": null,
"e": 2283,
"s": 2062,
"text": "Under normal circumstances you might use the theme() argument to make small changes to the default settings. Because ggplot2 is layered, adding +theme() to the end of a visualization will override any preceding settings."
},
{
"code": null,
"e": 2732,
"s": 2283,
"text": "We can take advantage of this behavior by defining a bespoke theme that can be added at the end of any visualization. This means you could even go back to old work and apply your new theme to achieve a consistent portfolio. In this example, I’ve defined a straightforward theme that makes all the text black, specifies various background fills, and sets the font. Running theme without the parentheses in R will show you all possible theme options."
},
{
"code": null,
"e": 3082,
"s": 2732,
"text": "theme_custom = function(){ theme( panel.background = element_blank(), panel.grid = element_blank(), axis.ticks = element_blank(), axis.text = element_text(color = \"black\"), legend.box.background = element_blank(), legend.key = element_rect(fill = NA), text = element_text(graphFont), plot.title = element_text(size = 16) )}"
},
{
"code": null,
"e": 3311,
"s": 3082,
"text": "Setting up color pre-planned color scales can be a huge time saver—say goodbye to guessing which shade of magenta you used last time. I like to use the coolors app to create color palettes, and then create a vector of hex codes."
},
{
"code": null,
"e": 3442,
"s": 3311,
"text": "Remember that you’ll need to set a scale for both scale_color_manual() and scale_fill_manual() to account for the different geoms."
},
{
"code": null,
"e": 3659,
"s": 3442,
"text": "pal_custom = c(\"#9e0a0a\", \"#115035\", \"#ff9e97\", \"#f6cb4c\")### Scales custom_color_manual = function(){ scale_color_manual(values = pal_custom)}custom_fill_manual = function(){ scale_fill_manual(values = pal_custom)"
},
{
"code": null,
"e": 3930,
"s": 3659,
"text": "If you would like specific behavior for certain types of graphs, customizing the geoms is the way to go. The update_geom_defaults() function does the trick. In these examples, I’ve requested that points be at least size 3, bars have white outlines, and lines are size 1."
},
{
"code": null,
"e": 4070,
"s": 3930,
"text": "update_geom_defaults(\"point\", list(size = 3))update_geom_defaults(\"bar\", list(color = \"white\"))update_geom_defaults(\"line\", list(size = 1))"
},
{
"code": null,
"e": 4276,
"s": 4070,
"text": "As if one theme wasn’t enough, you can actually layer themes. If, for example, you are only making small changes to an existing ggplot theme, you can run the original first, and add your changes afterward."
},
{
"code": null,
"e": 4429,
"s": 4276,
"text": "In this example, I used the xkcd theme by Emilio Torres-Manzanera to achieve a hand-drawn look on the axes, and then applied my custom theme at the end."
},
{
"code": null,
"e": 4717,
"s": 4429,
"text": "ggplot(data=iris, aes(x=Sepal.Width)) + geom_histogram(binwidth=0.1, aes(fill=Species)) + custom_fill_manual() + xlab(\"X-axis title\") + ylab(\"Y-axis title\") + ggtitle(\"Main chart title\") + theme_xkcd() + xkcdaxis(range(iris$Sepal.Width),range(c(0, 30))) + theme_custom()"
},
{
"code": null,
"e": 4821,
"s": 4717,
"text": "This particular theme might not be your cup of tea, but it’s certainly different from the default look:"
},
{
"code": null,
"e": 5312,
"s": 4821,
"text": "Establishing a custom aesthetic for your visualizations will take some iteration and testing. I recommend building a few test visuals that you can run when you update your theme—this will let you preview the effects on different chart types. Having a handful of test figures will also allow you to conduct accessibility checks and ensure that your theme is user-friendly. I use the Sim Daltonism app to evaluate color palettes and the Accessibility Insights extension to check web elements."
},
{
"code": null,
"e": 5495,
"s": 5312,
"text": "A knitr (.Rnw) or R Markdown (.Rmd) script works nicely for testing because it can be easily recompiled to produce a sharable document. Something as simple as this will do the trick:"
},
{
"code": null,
"e": 6025,
"s": 5495,
"text": "\\documentclass[a4paper]{article}\\begin{document}<<projections, include=FALSE, cache=FALSE>>==source(\"branding.R\")opts_chunk$set(dev='cairo_pdf')@<<renderimage, echo = FALSE, fig.height = 3, fig.width = 5, fig.align='center'>>==ggplot(data=iris, aes(x=Sepal.Width)) + geom_histogram(binwidth=0.1, aes(fill=Species)) + custom_fill_manual() + xlab(\"X-axis title\") + ylab(\"Y-axis title\") + ggtitle(\"Main chart title\") + theme_xkcd() + xkcdaxis(range(iris$Sepal.Width),range(c(0, 30))) + theme_custom()@\\end{document}"
},
{
"code": null,
"e": 6235,
"s": 6025,
"text": "And that’s it! I hope this gives you a few ideas on how you can create a custom theme for your own ggplot2 work. Start small, see what works, and build from there. Your graphs will be turning heads in no time."
}
] |
Print Adjacency List for a Directed Graph - GeeksforGeeks
|
11 Feb, 2022
An Adjacency List is used for representing graphs. Here, for every vertex in the graph, we have a list of all the other vertices which the particular vertex has an edge to.
Problem: Given the adjacency list and number of vertices and edges of a graph, the task is to represent the adjacency list for a directed graph.
Examples:
Input: V = 3, edges[][]= {{0, 1}, {1, 2} {2, 0}}
Output: 0 -> 1 1 -> 2 2 -> 0Explanation: The output represents the adjacency list for the given graph.
Input: V = 4, edges[][] = {{0, 1}, {1, 2}, {1, 3}, {2, 3}, {3, 0}}
Output: 0 -> 1 1 -> 2 3 2 -> 3 3 -> 0Explanation: The output represents the adjacency list for the given graph.
Approach (using STL): The main idea is to represent the graph as an array of vectors such that every vector represents the adjacency list of a single vertex. Using STL, the code becomes simpler and easier to understand.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to add edgesvoid addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v);} // Function to print adjacency listvoid adjacencylist(vector<int> adj[], int V){ for (int i = 0; i < V; i++) { cout << i << "->"; for (int& x : adj[i]) { cout << x << " "; } cout << endl; }} // Function to initialize the adjacency list// of the given graphvoid initGraph(int V, int edges[3][2], int noOfEdges){ // To represent graph as adjacency list vector<int> adj[V]; // Traverse edges array and make edges for (int i = 0; i < noOfEdges; i++) { // Function call to make an edge addEdge(adj, edges[i][0], edges[i][1]); } // Function Call to print adjacency list adjacencylist(adj, V);} // Driver Codeint main(){ // Given vertices int V = 3; // Given edges int edges[3][2] = { { 0, 1 }, { 1, 2 }, { 2, 0 } }; int noOfEdges = 3; // Function Call initGraph(V, edges, noOfEdges); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to add edges static void addEdge(Vector<Integer> adj[], int u, int v) { adj[u].add(v); } // Function to print adjacency list static void adjacencylist(Vector<Integer> adj[], int V) { for (int i = 0; i < V; i++) { System.out.print(i+ "->"); for (int x : adj[i]) { System.out.print(x+ " "); } System.out.println(); } } // Function to initialize the adjacency list // of the given graph static void initGraph(int V, int edges[][], int noOfEdges) { // To represent graph as adjacency list @SuppressWarnings("unchecked") Vector<Integer> adj[] = new Vector[3]; for(int i =0;i<adj.length;i++) { adj[i] = new Vector<>(); } // Traverse edges array and make edges for (int i = 0; i < noOfEdges; i++) { // Function call to make an edge addEdge(adj, edges[i][0], edges[i][1]); } // Function Call to print adjacency list adjacencylist(adj, V); } // Driver Code public static void main(String[] args) { // Given vertices int V = 3; // Given edges int edges[][] = { { 0, 1 }, { 1, 2 }, { 2, 0 } }; int noOfEdges = 3; // Function Call initGraph(V, edges, noOfEdges); }} // This code is contributed by gauravrajput1
# Python program for the above approach # Function to add edgesdef addEdge(adj, u, v): adj[u].append(v) # Function to print adjacency listdef adjacencylist(adj, V): for i in range (0, V): print(i, "->", end="") for x in adj[i]: print(x , " ", end="") print() # Function to initialize the adjacency list# of the given graphdef initGraph(V, edges, noOfEdges): adj = [0]* 3 for i in range(0, len(adj)): adj[i] = [] # Traverse edges array and make edges for i in range(0, noOfEdges) : # Function call to make an edge addEdge(adj, edges[i][0], edges[i][1]) # Function Call to print adjacency list adjacencylist(adj, V) # Driver Code # Given verticesV = 3 # Given edgesedges = [[0, 1 ], [1, 2 ], [2, 0 ]] noOfEdges = 3; # Function CallinitGraph(V, edges, noOfEdges) # This code is contributed by AR_Gaurav
// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to add edges static void addEdge(List<int> []adj, int u, int v) { adj[u].Add(v); } // Function to print adjacency list static void adjacencylist(List<int> []adj, int V) { for (int i = 0; i < V; i++) { Console.Write(i+ "->"); foreach (int x in adj[i]) { Console.Write(x+ " "); } Console.WriteLine(); } } // Function to initialize the adjacency list // of the given graph static void initGraph(int V, int [,]edges, int noOfEdges) { // To represent graph as adjacency list List<int> []adj = new List<int>[3]; for(int i = 0; i < adj.Length; i++) { adj[i] = new List<int>(); } // Traverse edges array and make edges for (int i = 0; i < noOfEdges; i++) { // Function call to make an edge addEdge(adj, edges[i,0], edges[i,1]); } // Function Call to print adjacency list adjacencylist(adj, V); } // Driver Code public static void Main(String[] args) { // Given vertices int V = 3; // Given edges int [,]edges = { { 0, 1 }, { 1, 2 }, { 2, 0 } }; int noOfEdges = 3; // Function Call initGraph(V, edges, noOfEdges); }} // This code is contributed by Amit Katiyar
<script>// javascript program for the above approach // Function to add edges function addEdge( adj , u , v) { adj[u].push(v); } // Function to print adjacency list function adjacencylist(adj , V) { for (var i = 0; i < V; i++) { document.write(i + "->"); for (var x of adj[i]) { document.write(x + " "); } document.write("<br/>"); } } // Function to initialize the adjacency list // of the given graph function initGraph(V , edges , noOfEdges) { // To represent graph as adjacency list var adj = Array(3); for (var i = 0; i < adj.length; i++) { adj[i] = Array(); } // Traverse edges array and make edges for (i = 0; i < noOfEdges; i++) { // Function call to make an edge addEdge(adj, edges[i][0], edges[i][1]); } // Function Call to print adjacency list adjacencylist(adj, V); } // Driver Code // Given vertices var V = 3; // Given edges var edges = [ [ 0, 1 ], [ 1, 2 ], [ 2, 0 ]]; var noOfEdges = 3; // Function Call initGraph(V, edges, noOfEdges); // This code is contributed by gauravrajput1</script>
0->1
1->2
2->0
maitreyeepaliwal
GauravRajput1
amit143katiyar
AR_Gaurav
simranarora5sos
cpp-list
cpp-vector
Data Structures-Graph
STL
Data Structures
Graph
Data Structures
Graph
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Tree Data Structure
Program to implement Singly Linked List in C++ using class
Hash Functions and list/types of Hash functions
Insertion in a B+ tree
TCS NQT Coding Sheet
Breadth First Search or BFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Depth First Search or DFS for a Graph
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
|
[
{
"code": null,
"e": 25028,
"s": 25000,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 25201,
"s": 25028,
"text": "An Adjacency List is used for representing graphs. Here, for every vertex in the graph, we have a list of all the other vertices which the particular vertex has an edge to."
},
{
"code": null,
"e": 25346,
"s": 25201,
"text": "Problem: Given the adjacency list and number of vertices and edges of a graph, the task is to represent the adjacency list for a directed graph."
},
{
"code": null,
"e": 25356,
"s": 25346,
"text": "Examples:"
},
{
"code": null,
"e": 25406,
"s": 25356,
"text": "Input: V = 3, edges[][]= {{0, 1}, {1, 2} {2, 0}} "
},
{
"code": null,
"e": 25542,
"s": 25406,
"text": "Output: 0 -> 1 1 -> 2 2 -> 0Explanation: The output represents the adjacency list for the given graph. "
},
{
"code": null,
"e": 25610,
"s": 25542,
"text": "Input: V = 4, edges[][] = {{0, 1}, {1, 2}, {1, 3}, {2, 3}, {3, 0}} "
},
{
"code": null,
"e": 25770,
"s": 25610,
"text": "Output: 0 -> 1 1 -> 2 3 2 -> 3 3 -> 0Explanation: The output represents the adjacency list for the given graph. "
},
{
"code": null,
"e": 25991,
"s": 25770,
"text": "Approach (using STL): The main idea is to represent the graph as an array of vectors such that every vector represents the adjacency list of a single vertex. Using STL, the code becomes simpler and easier to understand. "
},
{
"code": null,
"e": 26042,
"s": 25991,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26046,
"s": 26042,
"text": "C++"
},
{
"code": null,
"e": 26051,
"s": 26046,
"text": "Java"
},
{
"code": null,
"e": 26059,
"s": 26051,
"text": "Python3"
},
{
"code": null,
"e": 26062,
"s": 26059,
"text": "C#"
},
{
"code": null,
"e": 26073,
"s": 26062,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to add edgesvoid addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v);} // Function to print adjacency listvoid adjacencylist(vector<int> adj[], int V){ for (int i = 0; i < V; i++) { cout << i << \"->\"; for (int& x : adj[i]) { cout << x << \" \"; } cout << endl; }} // Function to initialize the adjacency list// of the given graphvoid initGraph(int V, int edges[3][2], int noOfEdges){ // To represent graph as adjacency list vector<int> adj[V]; // Traverse edges array and make edges for (int i = 0; i < noOfEdges; i++) { // Function call to make an edge addEdge(adj, edges[i][0], edges[i][1]); } // Function Call to print adjacency list adjacencylist(adj, V);} // Driver Codeint main(){ // Given vertices int V = 3; // Given edges int edges[3][2] = { { 0, 1 }, { 1, 2 }, { 2, 0 } }; int noOfEdges = 3; // Function Call initGraph(V, edges, noOfEdges); return 0;}",
"e": 27152,
"s": 26073,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to add edges static void addEdge(Vector<Integer> adj[], int u, int v) { adj[u].add(v); } // Function to print adjacency list static void adjacencylist(Vector<Integer> adj[], int V) { for (int i = 0; i < V; i++) { System.out.print(i+ \"->\"); for (int x : adj[i]) { System.out.print(x+ \" \"); } System.out.println(); } } // Function to initialize the adjacency list // of the given graph static void initGraph(int V, int edges[][], int noOfEdges) { // To represent graph as adjacency list @SuppressWarnings(\"unchecked\") Vector<Integer> adj[] = new Vector[3]; for(int i =0;i<adj.length;i++) { adj[i] = new Vector<>(); } // Traverse edges array and make edges for (int i = 0; i < noOfEdges; i++) { // Function call to make an edge addEdge(adj, edges[i][0], edges[i][1]); } // Function Call to print adjacency list adjacencylist(adj, V); } // Driver Code public static void main(String[] args) { // Given vertices int V = 3; // Given edges int edges[][] = { { 0, 1 }, { 1, 2 }, { 2, 0 } }; int noOfEdges = 3; // Function Call initGraph(V, edges, noOfEdges); }} // This code is contributed by gauravrajput1",
"e": 28462,
"s": 27152,
"text": null
},
{
"code": "# Python program for the above approach # Function to add edgesdef addEdge(adj, u, v): adj[u].append(v) # Function to print adjacency listdef adjacencylist(adj, V): for i in range (0, V): print(i, \"->\", end=\"\") for x in adj[i]: print(x , \" \", end=\"\") print() # Function to initialize the adjacency list# of the given graphdef initGraph(V, edges, noOfEdges): adj = [0]* 3 for i in range(0, len(adj)): adj[i] = [] # Traverse edges array and make edges for i in range(0, noOfEdges) : # Function call to make an edge addEdge(adj, edges[i][0], edges[i][1]) # Function Call to print adjacency list adjacencylist(adj, V) # Driver Code # Given verticesV = 3 # Given edgesedges = [[0, 1 ], [1, 2 ], [2, 0 ]] noOfEdges = 3; # Function CallinitGraph(V, edges, noOfEdges) # This code is contributed by AR_Gaurav",
"e": 29391,
"s": 28462,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to add edges static void addEdge(List<int> []adj, int u, int v) { adj[u].Add(v); } // Function to print adjacency list static void adjacencylist(List<int> []adj, int V) { for (int i = 0; i < V; i++) { Console.Write(i+ \"->\"); foreach (int x in adj[i]) { Console.Write(x+ \" \"); } Console.WriteLine(); } } // Function to initialize the adjacency list // of the given graph static void initGraph(int V, int [,]edges, int noOfEdges) { // To represent graph as adjacency list List<int> []adj = new List<int>[3]; for(int i = 0; i < adj.Length; i++) { adj[i] = new List<int>(); } // Traverse edges array and make edges for (int i = 0; i < noOfEdges; i++) { // Function call to make an edge addEdge(adj, edges[i,0], edges[i,1]); } // Function Call to print adjacency list adjacencylist(adj, V); } // Driver Code public static void Main(String[] args) { // Given vertices int V = 3; // Given edges int [,]edges = { { 0, 1 }, { 1, 2 }, { 2, 0 } }; int noOfEdges = 3; // Function Call initGraph(V, edges, noOfEdges); }} // This code is contributed by Amit Katiyar",
"e": 30690,
"s": 29391,
"text": null
},
{
"code": "<script>// javascript program for the above approach // Function to add edges function addEdge( adj , u , v) { adj[u].push(v); } // Function to print adjacency list function adjacencylist(adj , V) { for (var i = 0; i < V; i++) { document.write(i + \"->\"); for (var x of adj[i]) { document.write(x + \" \"); } document.write(\"<br/>\"); } } // Function to initialize the adjacency list // of the given graph function initGraph(V , edges , noOfEdges) { // To represent graph as adjacency list var adj = Array(3); for (var i = 0; i < adj.length; i++) { adj[i] = Array(); } // Traverse edges array and make edges for (i = 0; i < noOfEdges; i++) { // Function call to make an edge addEdge(adj, edges[i][0], edges[i][1]); } // Function Call to print adjacency list adjacencylist(adj, V); } // Driver Code // Given vertices var V = 3; // Given edges var edges = [ [ 0, 1 ], [ 1, 2 ], [ 2, 0 ]]; var noOfEdges = 3; // Function Call initGraph(V, edges, noOfEdges); // This code is contributed by gauravrajput1</script>",
"e": 31970,
"s": 30690,
"text": null
},
{
"code": null,
"e": 31990,
"s": 31973,
"text": "0->1 \n1->2 \n2->0"
},
{
"code": null,
"e": 32011,
"s": 31994,
"text": "maitreyeepaliwal"
},
{
"code": null,
"e": 32025,
"s": 32011,
"text": "GauravRajput1"
},
{
"code": null,
"e": 32040,
"s": 32025,
"text": "amit143katiyar"
},
{
"code": null,
"e": 32050,
"s": 32040,
"text": "AR_Gaurav"
},
{
"code": null,
"e": 32066,
"s": 32050,
"text": "simranarora5sos"
},
{
"code": null,
"e": 32075,
"s": 32066,
"text": "cpp-list"
},
{
"code": null,
"e": 32086,
"s": 32075,
"text": "cpp-vector"
},
{
"code": null,
"e": 32108,
"s": 32086,
"text": "Data Structures-Graph"
},
{
"code": null,
"e": 32112,
"s": 32108,
"text": "STL"
},
{
"code": null,
"e": 32128,
"s": 32112,
"text": "Data Structures"
},
{
"code": null,
"e": 32134,
"s": 32128,
"text": "Graph"
},
{
"code": null,
"e": 32150,
"s": 32134,
"text": "Data Structures"
},
{
"code": null,
"e": 32156,
"s": 32150,
"text": "Graph"
},
{
"code": null,
"e": 32160,
"s": 32156,
"text": "STL"
},
{
"code": null,
"e": 32258,
"s": 32160,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32294,
"s": 32258,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 32353,
"s": 32294,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 32401,
"s": 32353,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 32424,
"s": 32401,
"text": "Insertion in a B+ tree"
},
{
"code": null,
"e": 32445,
"s": 32424,
"text": "TCS NQT Coding Sheet"
},
{
"code": null,
"e": 32485,
"s": 32445,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 32536,
"s": 32485,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 32574,
"s": 32536,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 32632,
"s": 32574,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
DeepWalk Algorithm - GeeksforGeeks
|
18 Jul, 2021
In the real world, Networks are just the collection of interconnected nodes. To represent this type of network we need a data structure that is similar to it. Fortunately, we have a data structure that is the graph.
The graph contains vertices (which represents the node in the network) that are connected by edges (which can represent interconnection b/w nodes)
The deep walk is an algorithm proposed for learning latent representations of vertices in a network. These latent representations are used to represent the social representation b/w two graphs. It uses a randomized path traversing technique to provide insights into localized structures within networks. It does so by utilizing these random paths as sequences, that are then used to train a Skip-Gram Language Model.
Skip-Gram Model is used to predict the next word in the sentence by maximizing the co-occurrence probability among the words that appear within a window, w, in a sentence. For our implementation, we will use the Word2Vec implementation which uses the cosine distance to calculate the probability.
Deepwalk process operates in few steps:
The random walk generator takes a graph G and samples uniformly a random vertex vi as the root of the random walk Wvi. A walk sample uniformly from the neighbors of the last vertex visited until the maximum length (t) is reached.
Skip-gram model iterates over all possible collocations in a random walk that appear within the window w. For each, we map each vertex vj to its current representation vector Φ(vj ) ∈ Rd.
Given the representation of vj, we would like to maximize the probability of its neighbors in the walk (line 3). We can learn such posterior distribution using several choices of classifiers
Given an undirected graph G = (V, E), with n =| V | and m =| E |, a natural random walk is a stochastic process that starts from a given vertex, and then selects one of its neighbors uniformly at random to visit.
In the above graph, from 1 we have two nodes 2 and 4. From that, we choose any of them, let’s select 2.
Now, from 2, we have two choices 4 and 5, we randomly select 5 from them. So our random walk becomes Node 1 → 2 → 5.
Repeat the above process again and again until we cover all the nodes in the graph. This process is known as a random walk. One such random walk is 1 → 2 → 5 → 6 → 7 → 8 → 3 → 4.
Word Embeddings is a way to map words into a feature vector of a fixed size to make the processing of words easier. In 2013, Google proposed word2vec, a group of related models that are used to produce word embeddings. In the skip-gram architecture of word2vec, the input is the center word and the predictions are the context words. Consider an array of words W, if W(i) is the input (center word), then W(i-2), W(i-1), W(i+1), and W(i+2) are the context words if the sliding window size is 2.
Below is the template architecture for the skip-gram model:
Deepwalk is scalable since it does process the entire graph at once. This allows deep walk to create meaningful representations of large graphs that may not run on the spectral algorithms.
Deepwalk is faster compared to the other algorithms while dealing with sparsity.
Deepwalk can be used for many purposes such as Anomaly Detection, Clustering, Link Prediction, etc.
In this implementation, we will be using networkx and karateclub API. For our purpose, we will use Graph Embedding with Self Clustering: Facebook dataset. The dataset can be downloaded from here
Python3
# Install karateclub API! pip install karateclub# imports import networkx as nximport pandas as pdfrom sklearn.decomposition import PCAimport matplotlib.pyplot as pltfrom karateclub import DeepWalk # import datasetdf = pd.read_csv("/content/politician_edges.csv")df.head() # create GraphG = nx.from_pandas_edgelist(df, "node_1", "node_2", create_using=nx.Graph())print(len(G)) # train model and generate embeddingmodel = DeepWalk(walk_length=100, dimensions=64, window_size=5)model.fit(G)embedding = model.get_embedding() # print Embedding shapeprint(embedding.shape)# take first 100 nodesnodes =list(range(100)) # plot nodes graphdef plot_nodes(node_no): X = embedding[node_no] pca = PCA(n_components=2) pca_out= pca.fit_transform(X) plt.figure(figsize=(15,10)) plt.scatter(pca_out[:, 0], pca_out[:, 1]) for i, node in enumerate(node_no): plt.annotate(node, (pca_out[i, 0], pca_out[i, 1])) plt.xlabel('Label_1') plt.ylabel('label_2') plt.show() plot_nodes(nodes)
Output:
node_1 node_2
0 0 1972
1 0 5111
2 0 138
3 0 3053
4 0 1473
-------------
# length of nodes
5908
-------------
# embedding shape
(5908, 64)
Plot of Nodes
References:
Deepwalk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Singular Value Decomposition (SVD)
Principal Component Analysis with Python
ML | Stochastic Gradient Descent (SGD)
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": 24290,
"s": 24262,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 24506,
"s": 24290,
"text": "In the real world, Networks are just the collection of interconnected nodes. To represent this type of network we need a data structure that is similar to it. Fortunately, we have a data structure that is the graph."
},
{
"code": null,
"e": 24653,
"s": 24506,
"text": "The graph contains vertices (which represents the node in the network) that are connected by edges (which can represent interconnection b/w nodes)"
},
{
"code": null,
"e": 25070,
"s": 24653,
"text": "The deep walk is an algorithm proposed for learning latent representations of vertices in a network. These latent representations are used to represent the social representation b/w two graphs. It uses a randomized path traversing technique to provide insights into localized structures within networks. It does so by utilizing these random paths as sequences, that are then used to train a Skip-Gram Language Model."
},
{
"code": null,
"e": 25367,
"s": 25070,
"text": "Skip-Gram Model is used to predict the next word in the sentence by maximizing the co-occurrence probability among the words that appear within a window, w, in a sentence. For our implementation, we will use the Word2Vec implementation which uses the cosine distance to calculate the probability."
},
{
"code": null,
"e": 25407,
"s": 25367,
"text": "Deepwalk process operates in few steps:"
},
{
"code": null,
"e": 25637,
"s": 25407,
"text": "The random walk generator takes a graph G and samples uniformly a random vertex vi as the root of the random walk Wvi. A walk sample uniformly from the neighbors of the last vertex visited until the maximum length (t) is reached."
},
{
"code": null,
"e": 25825,
"s": 25637,
"text": "Skip-gram model iterates over all possible collocations in a random walk that appear within the window w. For each, we map each vertex vj to its current representation vector Φ(vj ) ∈ Rd."
},
{
"code": null,
"e": 26016,
"s": 25825,
"text": "Given the representation of vj, we would like to maximize the probability of its neighbors in the walk (line 3). We can learn such posterior distribution using several choices of classifiers"
},
{
"code": null,
"e": 26230,
"s": 26016,
"text": "Given an undirected graph G = (V, E), with n =| V | and m =| E |, a natural random walk is a stochastic process that starts from a given vertex, and then selects one of its neighbors uniformly at random to visit. "
},
{
"code": null,
"e": 26334,
"s": 26230,
"text": "In the above graph, from 1 we have two nodes 2 and 4. From that, we choose any of them, let’s select 2."
},
{
"code": null,
"e": 26451,
"s": 26334,
"text": "Now, from 2, we have two choices 4 and 5, we randomly select 5 from them. So our random walk becomes Node 1 → 2 → 5."
},
{
"code": null,
"e": 26630,
"s": 26451,
"text": "Repeat the above process again and again until we cover all the nodes in the graph. This process is known as a random walk. One such random walk is 1 → 2 → 5 → 6 → 7 → 8 → 3 → 4."
},
{
"code": null,
"e": 27125,
"s": 26630,
"text": "Word Embeddings is a way to map words into a feature vector of a fixed size to make the processing of words easier. In 2013, Google proposed word2vec, a group of related models that are used to produce word embeddings. In the skip-gram architecture of word2vec, the input is the center word and the predictions are the context words. Consider an array of words W, if W(i) is the input (center word), then W(i-2), W(i-1), W(i+1), and W(i+2) are the context words if the sliding window size is 2."
},
{
"code": null,
"e": 27185,
"s": 27125,
"text": "Below is the template architecture for the skip-gram model:"
},
{
"code": null,
"e": 27374,
"s": 27185,
"text": "Deepwalk is scalable since it does process the entire graph at once. This allows deep walk to create meaningful representations of large graphs that may not run on the spectral algorithms."
},
{
"code": null,
"e": 27455,
"s": 27374,
"text": "Deepwalk is faster compared to the other algorithms while dealing with sparsity."
},
{
"code": null,
"e": 27555,
"s": 27455,
"text": "Deepwalk can be used for many purposes such as Anomaly Detection, Clustering, Link Prediction, etc."
},
{
"code": null,
"e": 27750,
"s": 27555,
"text": "In this implementation, we will be using networkx and karateclub API. For our purpose, we will use Graph Embedding with Self Clustering: Facebook dataset. The dataset can be downloaded from here"
},
{
"code": null,
"e": 27758,
"s": 27750,
"text": "Python3"
},
{
"code": "# Install karateclub API! pip install karateclub# imports import networkx as nximport pandas as pdfrom sklearn.decomposition import PCAimport matplotlib.pyplot as pltfrom karateclub import DeepWalk # import datasetdf = pd.read_csv(\"/content/politician_edges.csv\")df.head() # create GraphG = nx.from_pandas_edgelist(df, \"node_1\", \"node_2\", create_using=nx.Graph())print(len(G)) # train model and generate embeddingmodel = DeepWalk(walk_length=100, dimensions=64, window_size=5)model.fit(G)embedding = model.get_embedding() # print Embedding shapeprint(embedding.shape)# take first 100 nodesnodes =list(range(100)) # plot nodes graphdef plot_nodes(node_no): X = embedding[node_no] pca = PCA(n_components=2) pca_out= pca.fit_transform(X) plt.figure(figsize=(15,10)) plt.scatter(pca_out[:, 0], pca_out[:, 1]) for i, node in enumerate(node_no): plt.annotate(node, (pca_out[i, 0], pca_out[i, 1])) plt.xlabel('Label_1') plt.ylabel('label_2') plt.show() plot_nodes(nodes)",
"e": 28781,
"s": 27758,
"text": null
},
{
"code": null,
"e": 28790,
"s": 28781,
"text": "Output: "
},
{
"code": null,
"e": 28961,
"s": 28790,
"text": "node_1 node_2\n0 0 1972\n1 0 5111\n2 0 138\n3 0 3053\n4 0 1473\n-------------\n# length of nodes\n5908\n-------------\n# embedding shape\n(5908, 64)"
},
{
"code": null,
"e": 28975,
"s": 28961,
"text": "Plot of Nodes"
},
{
"code": null,
"e": 28987,
"s": 28975,
"text": "References:"
},
{
"code": null,
"e": 28996,
"s": 28987,
"text": "Deepwalk"
},
{
"code": null,
"e": 29013,
"s": 28996,
"text": "Machine Learning"
},
{
"code": null,
"e": 29020,
"s": 29013,
"text": "Python"
},
{
"code": null,
"e": 29037,
"s": 29020,
"text": "Machine Learning"
},
{
"code": null,
"e": 29135,
"s": 29037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29144,
"s": 29135,
"text": "Comments"
},
{
"code": null,
"e": 29157,
"s": 29144,
"text": "Old Comments"
},
{
"code": null,
"e": 29190,
"s": 29157,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 29229,
"s": 29190,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 29264,
"s": 29229,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 29305,
"s": 29264,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 29344,
"s": 29305,
"text": "ML | Stochastic Gradient Descent (SGD)"
},
{
"code": null,
"e": 29372,
"s": 29344,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29422,
"s": 29372,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29444,
"s": 29422,
"text": "Python map() function"
}
] |
Changing CSS styling with React onClick() Event - GeeksforGeeks
|
19 Oct, 2021
Working on styling is one of the major tasks while creating websites. Time and again we have to manipulate the CSS styling to provide a better appearance to the application we are building. So, In this article, we will see how we can change the CSS styling using React. Specifically, we will see how an event(onClick) can change the CSS styling. Here, we will be using React hooks to implement the problem statement. React hooks helps in managing the state of functional components.
Approach: The introduction of React hooks is significant while working with functional components. It makes the management of the state much easier in React Lifecycle. Additionally, it’s much easier and uses less code while building components. So, we will leverage the functionality of React hooks in order to implement our problem statement. Here, we will be creating a small app to understand the concept. So, basically, we will change the background color of a container by making use of the onClick() event. We will initially define the CSS for our app. Once a user clicks the button then the background color gets changed by changing the state. The principle of React hooks will make things easier for us.
Now, let’s get started with the file structure and coding part.
Creating React App:
Step 1: Create a React application using the following command:
npx create-react-app appname
Make sure that the app name is starting with lower-case letters.
Step 2: After creating your project folder. Now, jump into the respective folder by making use of the following command:
cd appname
Project Structure: Now, the file structure will look like the following:
Our app file Structure
Step 3: In the above file structure, we will only use App.js and App.css files. Let’s first provide the CSS styling for our app. All the CSS code must be written inside the App.css file. Copy the code mentioned below in the App.css file.
App.css
.App { font-family: sans-serif; text-align: center; background-color: aqua;}.cont { width: 250px; height: 250px; margin-top: 50px; margin-left: 150px; background-color: violet;}.button { border-radius: 8px; font-size: 20px; background-color: red; color: white; margin-left: 70px; margin-top: 100px;}.cont2 { width: 250px; height: 250px; margin-top: 50px; margin-left: 150px; background-color: yellow;}
Step 4: Now, Let’s start implementing the React hooks approach in the App.js file. In the above code, we set initial state(style) value as the string. This value is the className that we will be using inside the Button. Initially, the value is defined as cont for which the CSS styling is defined in our App.css file. We provide this state value to the className of the button.
Now, the next step is to define the onClick handler for the button. So, changeStyle is the button handler. In order to change the state value, we define our setState value which is setStyle in our case. This is triggered inside the changeStyle. So, once we click the button then changeStyle gets executed which further executes the setStyle to change the state i.e cont2.
App.js
import React, { useState } from "react";import "./App.css";const App = () => { const [style, setStyle] = useState("cont"); const changeStyle = () => { console.log("you just clicked"); setStyle("cont2"); }; return ( <> <div className="App">CHANGE CSS STYLING WITH ONCLICK EVENT</div> <div className={style}> <button className="button" onClick={changeStyle}> Click me! </button> </div> </> );};export default App;
Step 5: Run the code by making use of the following command:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output. After, Click the background color changes to yellow.
The Background color changed on clicking the Button.
saketprag322
Blogathon-2021
CSS-Properties
React Events
React-Questions
Blogathon
CSS
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Import JSON Data into SQL Server?
How to Install Tkinter in Windows?
SQL - Multiple Column Ordering
How to pass data into table from a form using React Components
How to Create a Table With Multiple Foreign Keys in SQL?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 24363,
"s": 24335,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 24846,
"s": 24363,
"text": "Working on styling is one of the major tasks while creating websites. Time and again we have to manipulate the CSS styling to provide a better appearance to the application we are building. So, In this article, we will see how we can change the CSS styling using React. Specifically, we will see how an event(onClick) can change the CSS styling. Here, we will be using React hooks to implement the problem statement. React hooks helps in managing the state of functional components."
},
{
"code": null,
"e": 25558,
"s": 24846,
"text": "Approach: The introduction of React hooks is significant while working with functional components. It makes the management of the state much easier in React Lifecycle. Additionally, it’s much easier and uses less code while building components. So, we will leverage the functionality of React hooks in order to implement our problem statement. Here, we will be creating a small app to understand the concept. So, basically, we will change the background color of a container by making use of the onClick() event. We will initially define the CSS for our app. Once a user clicks the button then the background color gets changed by changing the state. The principle of React hooks will make things easier for us."
},
{
"code": null,
"e": 25622,
"s": 25558,
"text": "Now, let’s get started with the file structure and coding part."
},
{
"code": null,
"e": 25644,
"s": 25624,
"text": "Creating React App:"
},
{
"code": null,
"e": 25708,
"s": 25644,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 25737,
"s": 25708,
"text": "npx create-react-app appname"
},
{
"code": null,
"e": 25802,
"s": 25737,
"text": "Make sure that the app name is starting with lower-case letters."
},
{
"code": null,
"e": 25923,
"s": 25802,
"text": "Step 2: After creating your project folder. Now, jump into the respective folder by making use of the following command:"
},
{
"code": null,
"e": 25934,
"s": 25923,
"text": "cd appname"
},
{
"code": null,
"e": 26007,
"s": 25934,
"text": "Project Structure: Now, the file structure will look like the following:"
},
{
"code": null,
"e": 26030,
"s": 26007,
"text": "Our app file Structure"
},
{
"code": null,
"e": 26268,
"s": 26030,
"text": "Step 3: In the above file structure, we will only use App.js and App.css files. Let’s first provide the CSS styling for our app. All the CSS code must be written inside the App.css file. Copy the code mentioned below in the App.css file."
},
{
"code": null,
"e": 26276,
"s": 26268,
"text": "App.css"
},
{
"code": ".App { font-family: sans-serif; text-align: center; background-color: aqua;}.cont { width: 250px; height: 250px; margin-top: 50px; margin-left: 150px; background-color: violet;}.button { border-radius: 8px; font-size: 20px; background-color: red; color: white; margin-left: 70px; margin-top: 100px;}.cont2 { width: 250px; height: 250px; margin-top: 50px; margin-left: 150px; background-color: yellow;}",
"e": 26697,
"s": 26276,
"text": null
},
{
"code": null,
"e": 27075,
"s": 26697,
"text": "Step 4: Now, Let’s start implementing the React hooks approach in the App.js file. In the above code, we set initial state(style) value as the string. This value is the className that we will be using inside the Button. Initially, the value is defined as cont for which the CSS styling is defined in our App.css file. We provide this state value to the className of the button."
},
{
"code": null,
"e": 27447,
"s": 27075,
"text": "Now, the next step is to define the onClick handler for the button. So, changeStyle is the button handler. In order to change the state value, we define our setState value which is setStyle in our case. This is triggered inside the changeStyle. So, once we click the button then changeStyle gets executed which further executes the setStyle to change the state i.e cont2."
},
{
"code": null,
"e": 27454,
"s": 27447,
"text": "App.js"
},
{
"code": "import React, { useState } from \"react\";import \"./App.css\";const App = () => { const [style, setStyle] = useState(\"cont\"); const changeStyle = () => { console.log(\"you just clicked\"); setStyle(\"cont2\"); }; return ( <> <div className=\"App\">CHANGE CSS STYLING WITH ONCLICK EVENT</div> <div className={style}> <button className=\"button\" onClick={changeStyle}> Click me! </button> </div> </> );};export default App;",
"e": 27925,
"s": 27454,
"text": null
},
{
"code": null,
"e": 27986,
"s": 27925,
"text": "Step 5: Run the code by making use of the following command:"
},
{
"code": null,
"e": 27996,
"s": 27986,
"text": "npm start"
},
{
"code": null,
"e": 28148,
"s": 27996,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output. After, Click the background color changes to yellow."
},
{
"code": null,
"e": 28201,
"s": 28148,
"text": "The Background color changed on clicking the Button."
},
{
"code": null,
"e": 28214,
"s": 28201,
"text": "saketprag322"
},
{
"code": null,
"e": 28229,
"s": 28214,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 28244,
"s": 28229,
"text": "CSS-Properties"
},
{
"code": null,
"e": 28257,
"s": 28244,
"text": "React Events"
},
{
"code": null,
"e": 28273,
"s": 28257,
"text": "React-Questions"
},
{
"code": null,
"e": 28283,
"s": 28273,
"text": "Blogathon"
},
{
"code": null,
"e": 28287,
"s": 28283,
"text": "CSS"
},
{
"code": null,
"e": 28295,
"s": 28287,
"text": "ReactJS"
},
{
"code": null,
"e": 28312,
"s": 28295,
"text": "Web Technologies"
},
{
"code": null,
"e": 28410,
"s": 28312,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28419,
"s": 28410,
"text": "Comments"
},
{
"code": null,
"e": 28432,
"s": 28419,
"text": "Old Comments"
},
{
"code": null,
"e": 28473,
"s": 28432,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 28508,
"s": 28473,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 28539,
"s": 28508,
"text": "SQL - Multiple Column Ordering"
},
{
"code": null,
"e": 28602,
"s": 28539,
"text": "How to pass data into table from a form using React Components"
},
{
"code": null,
"e": 28659,
"s": 28602,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 28721,
"s": 28659,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28771,
"s": 28721,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28829,
"s": 28771,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 28877,
"s": 28829,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Bioinformatics on the cloud. Aligning RNAseq with STAR on Google... | by Hylke C. Donker | Towards Data Science
|
The price of analysing a person’s DNA, as well as its transcribed instructions (RNA), are rapidly getting cheaper. As a result, uptake of sequencing technology is growing, not only in scientific labs, but also in routine healthcare. But the data that is generated for a single individual can easily exceed several GBs in size. So this truly is a big data problem! Since the cloud is specifically designed to address problems of large scale, we can leverage its tools and infrastructure to boost our bioinformatics analyses. By running your bioinformatics tools on the cloud, you can do the analysis in a fraction of the time.
This tutorial will walk you through the steps of aligning human RNA sequencing data (RNAseq, for short) on Google Cloud Platform (GCP).
Objectives:
Store genomic data on the cloud.
Align RNA sequencing data using STAR.
Sequence machines, that read nucleotide bases off a strand, can only read small portions of a fragment. The machine therefore generates a large collection of small chunks of bases, called reads. Usually, reads come in two flavours: left and right reads. These reads, generated by paired-end sequencing machines, are the two sides of a fragment from where the machine started reading the bases. After finishing the measurement, the sequencing machine typically generates two files (one for each flavour) containing all these chunks of bases with corresponding quality estimates in FASTQ format. All these small pieces of the puzzle, that are now in FASTQ format, have to be put back together. This is the process of alignment against a reference genome, where the reads are assigned to a location on the genome. When successful, this will result in a SAM file indicating the genomic location of the reads. Our task for today is to carry out the alignment of bases that originate from RNA material. Or put differently, combine and transform the FASTQ files to SAM files.
Open the Google Cloud Platform dashboard and click on the cloud shell icon (Fig. 2) in the top right corner to launch the terminal.
We will make use of dsub to distribute our bioinformatics workload on Google Cloud Platform. To install dsub, execute:
sudo pip3 install dsub
in your cloud shell, or on your local machine, if you have installed and configured gcloud locally.
Next, choose a name for storing your data, e.g., gs://rna-seq-tutorial, and make a bucket (mb):
export BUCKET=gs://rna-seq-tutorialexport REFDATA=${BUCKET}/refdataexport INPUT=${BUCKET}/inputexport GENOME_INDEX=${BUCKET}/genome_indexgsutil mb -l europe-west4 ${BUCKET}
And download the annotation file to the newly created bucket:
wget -O - \ ftp://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_36/gencode.v36.chr_patch_hapl_scaff.annotation.gff3.gz \ | zcat \ | gsutil cp - ${REFDATA}/gencode.v36.chr_patch_hapl_scaff.annotation.gff3
This command downloads the file (wget), unpacks it (zcat) and copies the data to the bucket (gsutil cp). Next, copy the FASTQ files (the RNAseq data in raw format) that are to be aligned to the bucket. If you are not using your own files, use the following example files [1]:
wget http://genomedata.org/rnaseq-tutorial/practical.tartar -xf practical.tar# Sample 1.gsutil cp \ hcc1395_normal_rep1_r1.fastq.gz \ ${INPUT}/sample1_R1.fastq.gzgsutil cp\ hcc1395_normal_rep1_r2.fastq.gz \ ${INPUT}/sample1_R2.fastq.gz# Sample 2.gsutil cp \ hcc1395_tumor_rep1_r1.fastq.gz \ ${INPUT}/sample2_R1.fastq.gzgsutil cp\ hcc1395_tumor_rep1_r2.fastq.gz \ ${INPUT}/sample2_R2.fastq.gz
And finally, enable the Cloud Life Sciences API, to use dsub.
To align the RNA transcripts to the reference genome, we will make use of STAR [2]. Alignment with STAR is a two-step process:
Generate a genome index using genome reference information.Align sequencing data using the genome index.
Generate a genome index using genome reference information.
Align sequencing data using the genome index.
STAR uses both the reference genome and the annotation file to generate the index files. Create a bash script called step1.sh with the following content:
#!/bin/bashSTAR --runThreadN 8 \ --runMode genomeGenerate \ --sjdbOverhang 100 \ --genomeFastaFiles ${FASTA_FILE} \ --sjdbGTFfile ${GTF_FILE} \ --genomeDir ${GENOME_INDEX}
This will use 8 cores to generate the index files, and write them to $GENOME_INDEX (the location will be specified below). We passed the reference genome using the --genomeFastaFiles flag, while the gene annotation file can be specified with --sjdbGTFfile. For more details on the command line argument, please refer to the STAR manual. Next, use dsub to execute the workload on a worker with 8 virtual cores (--min-cores 8) and 48 GBs of memory (--min-ram 48), since STAR requires loads of memory for this step:
dsub \ --provider google-cls-v2 \ --project <my-project> \ --location europe-west4 \ --zones europe-west4-a \ --preemptible \ --min-ram 48 \ --min-cores 8 \ --logging "${BUCKET}/logging/" \ --input FASTA_FILE=gs://gcp-public-data--broad-references/hg38/v0/GRCh38.primary_assembly.genome.fa \ --input GTF_FILE=${REFDATA}/gencode.v36.chr_patch_hapl_scaff.annotation.gff3 \ --output-recursive GENOME_INDEX=${GENOME_INDEX} \ --image registry.gitlab.com/hylkedonker/rna-seq \ --script step1.sh
Decide if you want to go for the cheaper pre-emptible compute (--preemptible) at the risk of job termination, and replace <my-project> with your Google Cloud Platform project ID. You can adjust the location as desired, but you are advised to adjust your bucket location accordingly. Notice that there was no need to spin up a virtual machine, and install our bioinformatics tools. Instead we used a Docker image (--image registry.gitlab.com/hylkedonker/rna-seq) that contains everything we need, and dsub takes care of the rest. While our workload is being executed on the cloud, we can prep for the next step.
To do the actual alignment, create a file step2.sh with the following contents:
#!/bin/bashSTAR \ --runThreadN 4 \ --readFilesCommand zcat \ --genomeDir ${GENOME_INDEX} \ --readFilesIn ${R1} ${R2} \ --outFileNamePrefix "${OUTPUT}/"
This script invokes STAR to do the actual alignment on four cores (--runThreadN 4) using the index that was generated in the previous step (--genomeDir ${GENOME_INDEX}). Notice that the alignment of each sample is (computationally) a self contained problem. This means all samples can be aligned in parallel! Executing arrays of jobs is easy with dsub. Simply create a tab-separated file (a .tsv file) with the arguments to be passed to dsub. For this tutorial, create a file called job2.tsv with the following contents:
--input R1 --input R2 --output-recursive OUTPUTgs://rna-seq-tutorial/input/sample1_R1.fastq.gz gs://rna-seq-tutorial/input/sample1_R2.fastq.gz gs://rna-seq-tutorial/output/step2/sample1gs://rna-seq-tutorial/input/sample2_R1.fastq.gz gs://rna-seq-tutorial/input/sample2_R2.fastq.gz gs://rna-seq-tutorial/output/step2/sample2
Replacing <my-bucket> with the appropriate value. Also, notice that the columns are tab separated (no white spaces). Before executing the alignment workloads, make sure that STAR finished generating the genome index. The status can be queried using dstat. After verifying the job was successfully carried out, submit the alignment workloads to the cloud using:
dsub \ --provider google-cls-v2 \ --project <my-project> \ --location europe-west4 \ --zones europe-west4-a \ --preemptible \ --min-ram 32 \ --min-cores 4 \ --logging "${BUCKET}/logging/" \ --input-recursive GENOME_INDEX=${GENOME_INDEX} \ --image registry.gitlab.com/hylkedonker/rna-seq \ --tasks ./job2.tsv \ --script step2.sh
Here, we used --tasks ./job2.tsv to refer to input and output arguments, one line per sample. Finally, wait for the workers to finish (use dstat to poll the status) and don't forget to remove your resources after finishing your computation to prevent additional storage costs.
gsutil rm -r ${BUCKET}
That’s it, you have just aligned your first RNAseq data on the cloud using STAR! Notice how easy it is to scale up our analysis: aligning 1000 instead of 2 samples is simply a matter of extending the tab-separated file.
Of course, alignment by itself is usually a pre-processing step required for downstream analysis. In part II, we will continue our cloud adventure by computing gene expression from our aligned RNAseq.
Drop a comment if you have helpful STAR tips or interesting cloud tricks to share, or any improvements to the code.
[1]: Malachi Griffith*, Jason R. Walker, Nicholas C. Spies, Benjamin J. Ainscough, Obi L. Griffith*. 2015. Informatics for RNA-seq: A web resource for analysis on the cloud. PLoS Comp Biol. 11(8):e1004393.
[2]: Dobin, Alexander, et al. “STAR: ultrafast universal RNA-seq aligner.” Bioinformatics 29.1 (2013): 15–21.
|
[
{
"code": null,
"e": 797,
"s": 171,
"text": "The price of analysing a person’s DNA, as well as its transcribed instructions (RNA), are rapidly getting cheaper. As a result, uptake of sequencing technology is growing, not only in scientific labs, but also in routine healthcare. But the data that is generated for a single individual can easily exceed several GBs in size. So this truly is a big data problem! Since the cloud is specifically designed to address problems of large scale, we can leverage its tools and infrastructure to boost our bioinformatics analyses. By running your bioinformatics tools on the cloud, you can do the analysis in a fraction of the time."
},
{
"code": null,
"e": 933,
"s": 797,
"text": "This tutorial will walk you through the steps of aligning human RNA sequencing data (RNAseq, for short) on Google Cloud Platform (GCP)."
},
{
"code": null,
"e": 945,
"s": 933,
"text": "Objectives:"
},
{
"code": null,
"e": 978,
"s": 945,
"text": "Store genomic data on the cloud."
},
{
"code": null,
"e": 1016,
"s": 978,
"text": "Align RNA sequencing data using STAR."
},
{
"code": null,
"e": 2085,
"s": 1016,
"text": "Sequence machines, that read nucleotide bases off a strand, can only read small portions of a fragment. The machine therefore generates a large collection of small chunks of bases, called reads. Usually, reads come in two flavours: left and right reads. These reads, generated by paired-end sequencing machines, are the two sides of a fragment from where the machine started reading the bases. After finishing the measurement, the sequencing machine typically generates two files (one for each flavour) containing all these chunks of bases with corresponding quality estimates in FASTQ format. All these small pieces of the puzzle, that are now in FASTQ format, have to be put back together. This is the process of alignment against a reference genome, where the reads are assigned to a location on the genome. When successful, this will result in a SAM file indicating the genomic location of the reads. Our task for today is to carry out the alignment of bases that originate from RNA material. Or put differently, combine and transform the FASTQ files to SAM files."
},
{
"code": null,
"e": 2217,
"s": 2085,
"text": "Open the Google Cloud Platform dashboard and click on the cloud shell icon (Fig. 2) in the top right corner to launch the terminal."
},
{
"code": null,
"e": 2336,
"s": 2217,
"text": "We will make use of dsub to distribute our bioinformatics workload on Google Cloud Platform. To install dsub, execute:"
},
{
"code": null,
"e": 2359,
"s": 2336,
"text": "sudo pip3 install dsub"
},
{
"code": null,
"e": 2459,
"s": 2359,
"text": "in your cloud shell, or on your local machine, if you have installed and configured gcloud locally."
},
{
"code": null,
"e": 2555,
"s": 2459,
"text": "Next, choose a name for storing your data, e.g., gs://rna-seq-tutorial, and make a bucket (mb):"
},
{
"code": null,
"e": 2728,
"s": 2555,
"text": "export BUCKET=gs://rna-seq-tutorialexport REFDATA=${BUCKET}/refdataexport INPUT=${BUCKET}/inputexport GENOME_INDEX=${BUCKET}/genome_indexgsutil mb -l europe-west4 ${BUCKET}"
},
{
"code": null,
"e": 2790,
"s": 2728,
"text": "And download the annotation file to the newly created bucket:"
},
{
"code": null,
"e": 3015,
"s": 2790,
"text": "wget -O - \\ ftp://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_36/gencode.v36.chr_patch_hapl_scaff.annotation.gff3.gz \\ | zcat \\ | gsutil cp - ${REFDATA}/gencode.v36.chr_patch_hapl_scaff.annotation.gff3"
},
{
"code": null,
"e": 3291,
"s": 3015,
"text": "This command downloads the file (wget), unpacks it (zcat) and copies the data to the bucket (gsutil cp). Next, copy the FASTQ files (the RNAseq data in raw format) that are to be aligned to the bucket. If you are not using your own files, use the following example files [1]:"
},
{
"code": null,
"e": 3704,
"s": 3291,
"text": "wget http://genomedata.org/rnaseq-tutorial/practical.tartar -xf practical.tar# Sample 1.gsutil cp \\ hcc1395_normal_rep1_r1.fastq.gz \\ ${INPUT}/sample1_R1.fastq.gzgsutil cp\\ hcc1395_normal_rep1_r2.fastq.gz \\ ${INPUT}/sample1_R2.fastq.gz# Sample 2.gsutil cp \\ hcc1395_tumor_rep1_r1.fastq.gz \\ ${INPUT}/sample2_R1.fastq.gzgsutil cp\\ hcc1395_tumor_rep1_r2.fastq.gz \\ ${INPUT}/sample2_R2.fastq.gz"
},
{
"code": null,
"e": 3766,
"s": 3704,
"text": "And finally, enable the Cloud Life Sciences API, to use dsub."
},
{
"code": null,
"e": 3893,
"s": 3766,
"text": "To align the RNA transcripts to the reference genome, we will make use of STAR [2]. Alignment with STAR is a two-step process:"
},
{
"code": null,
"e": 3998,
"s": 3893,
"text": "Generate a genome index using genome reference information.Align sequencing data using the genome index."
},
{
"code": null,
"e": 4058,
"s": 3998,
"text": "Generate a genome index using genome reference information."
},
{
"code": null,
"e": 4104,
"s": 4058,
"text": "Align sequencing data using the genome index."
},
{
"code": null,
"e": 4258,
"s": 4104,
"text": "STAR uses both the reference genome and the annotation file to generate the index files. Create a bash script called step1.sh with the following content:"
},
{
"code": null,
"e": 4445,
"s": 4258,
"text": "#!/bin/bashSTAR --runThreadN 8 \\ --runMode genomeGenerate \\ --sjdbOverhang 100 \\ --genomeFastaFiles ${FASTA_FILE} \\ --sjdbGTFfile ${GTF_FILE} \\ --genomeDir ${GENOME_INDEX}"
},
{
"code": null,
"e": 4958,
"s": 4445,
"text": "This will use 8 cores to generate the index files, and write them to $GENOME_INDEX (the location will be specified below). We passed the reference genome using the --genomeFastaFiles flag, while the gene annotation file can be specified with --sjdbGTFfile. For more details on the command line argument, please refer to the STAR manual. Next, use dsub to execute the workload on a worker with 8 virtual cores (--min-cores 8) and 48 GBs of memory (--min-ram 48), since STAR requires loads of memory for this step:"
},
{
"code": null,
"e": 5486,
"s": 4958,
"text": "dsub \\ --provider google-cls-v2 \\ --project <my-project> \\ --location europe-west4 \\ --zones europe-west4-a \\ --preemptible \\ --min-ram 48 \\ --min-cores 8 \\ --logging \"${BUCKET}/logging/\" \\ --input FASTA_FILE=gs://gcp-public-data--broad-references/hg38/v0/GRCh38.primary_assembly.genome.fa \\ --input GTF_FILE=${REFDATA}/gencode.v36.chr_patch_hapl_scaff.annotation.gff3 \\ --output-recursive GENOME_INDEX=${GENOME_INDEX} \\ --image registry.gitlab.com/hylkedonker/rna-seq \\ --script step1.sh"
},
{
"code": null,
"e": 6097,
"s": 5486,
"text": "Decide if you want to go for the cheaper pre-emptible compute (--preemptible) at the risk of job termination, and replace <my-project> with your Google Cloud Platform project ID. You can adjust the location as desired, but you are advised to adjust your bucket location accordingly. Notice that there was no need to spin up a virtual machine, and install our bioinformatics tools. Instead we used a Docker image (--image registry.gitlab.com/hylkedonker/rna-seq) that contains everything we need, and dsub takes care of the rest. While our workload is being executed on the cloud, we can prep for the next step."
},
{
"code": null,
"e": 6177,
"s": 6097,
"text": "To do the actual alignment, create a file step2.sh with the following contents:"
},
{
"code": null,
"e": 6344,
"s": 6177,
"text": "#!/bin/bashSTAR \\ --runThreadN 4 \\ --readFilesCommand zcat \\ --genomeDir ${GENOME_INDEX} \\ --readFilesIn ${R1} ${R2} \\ --outFileNamePrefix \"${OUTPUT}/\""
},
{
"code": null,
"e": 6865,
"s": 6344,
"text": "This script invokes STAR to do the actual alignment on four cores (--runThreadN 4) using the index that was generated in the previous step (--genomeDir ${GENOME_INDEX}). Notice that the alignment of each sample is (computationally) a self contained problem. This means all samples can be aligned in parallel! Executing arrays of jobs is easy with dsub. Simply create a tab-separated file (a .tsv file) with the arguments to be passed to dsub. For this tutorial, create a file called job2.tsv with the following contents:"
},
{
"code": null,
"e": 7189,
"s": 6865,
"text": "--input R1 --input R2 --output-recursive OUTPUTgs://rna-seq-tutorial/input/sample1_R1.fastq.gz gs://rna-seq-tutorial/input/sample1_R2.fastq.gz gs://rna-seq-tutorial/output/step2/sample1gs://rna-seq-tutorial/input/sample2_R1.fastq.gz gs://rna-seq-tutorial/input/sample2_R2.fastq.gz gs://rna-seq-tutorial/output/step2/sample2"
},
{
"code": null,
"e": 7550,
"s": 7189,
"text": "Replacing <my-bucket> with the appropriate value. Also, notice that the columns are tab separated (no white spaces). Before executing the alignment workloads, make sure that STAR finished generating the genome index. The status can be queried using dstat. After verifying the job was successfully carried out, submit the alignment workloads to the cloud using:"
},
{
"code": null,
"e": 7914,
"s": 7550,
"text": "dsub \\ --provider google-cls-v2 \\ --project <my-project> \\ --location europe-west4 \\ --zones europe-west4-a \\ --preemptible \\ --min-ram 32 \\ --min-cores 4 \\ --logging \"${BUCKET}/logging/\" \\ --input-recursive GENOME_INDEX=${GENOME_INDEX} \\ --image registry.gitlab.com/hylkedonker/rna-seq \\ --tasks ./job2.tsv \\ --script step2.sh"
},
{
"code": null,
"e": 8191,
"s": 7914,
"text": "Here, we used --tasks ./job2.tsv to refer to input and output arguments, one line per sample. Finally, wait for the workers to finish (use dstat to poll the status) and don't forget to remove your resources after finishing your computation to prevent additional storage costs."
},
{
"code": null,
"e": 8214,
"s": 8191,
"text": "gsutil rm -r ${BUCKET}"
},
{
"code": null,
"e": 8434,
"s": 8214,
"text": "That’s it, you have just aligned your first RNAseq data on the cloud using STAR! Notice how easy it is to scale up our analysis: aligning 1000 instead of 2 samples is simply a matter of extending the tab-separated file."
},
{
"code": null,
"e": 8635,
"s": 8434,
"text": "Of course, alignment by itself is usually a pre-processing step required for downstream analysis. In part II, we will continue our cloud adventure by computing gene expression from our aligned RNAseq."
},
{
"code": null,
"e": 8751,
"s": 8635,
"text": "Drop a comment if you have helpful STAR tips or interesting cloud tricks to share, or any improvements to the code."
},
{
"code": null,
"e": 8957,
"s": 8751,
"text": "[1]: Malachi Griffith*, Jason R. Walker, Nicholas C. Spies, Benjamin J. Ainscough, Obi L. Griffith*. 2015. Informatics for RNA-seq: A web resource for analysis on the cloud. PLoS Comp Biol. 11(8):e1004393."
}
] |
How to: Automate live data to your website with Python | by Truett Bloxsom | Towards Data Science
|
This tutorial will be helpful for people who have a website that hosts live data on a cloud service but are unsure how to completely automate the updating of the live data so the website becomes hassle free. For example: I host a website that shows Texas COVID case counts by county in an interactive dashboard, but everyday I had to run a script to download the excel file from the Texas COVID website, clean the data, update the pandas data frame that was used to create the dashboard, upload the updated data to the cloud service I was using, and reload my website. This was annoying, so I used the steps in this tutorial to show how my live data website is now totally automated.
I will only be going over how to do this using the cloud service pythonanywhere, but these steps can be transferred to other cloud services. Another thing to note is that I am new to building and maintaining websites so please feel free to correct me or give me constructive feedback on this tutorial. I will be assuming that you have basic knowledge of python, selenium for web scraping, bash commands, and you have your own website. Lets go through the steps of automating live data to your website:
web scraping with selenium using a cloud serviceconverting downloaded data in a .part file to .xlsx filere-loading your website using the os python packagescheduling a python script to run every day in pythonanywhere
web scraping with selenium using a cloud service
converting downloaded data in a .part file to .xlsx file
re-loading your website using the os python package
scheduling a python script to run every day in pythonanywhere
I will not be going through some of the code I will be showing because I use much of the same code from my last tutorial on how to create and automate an interactive dashboard using python found here. Lets get started!
web scraping with selenium using a cloud service
web scraping with selenium using a cloud service
So in your cloud service of choice (mine being pythonanywhere), open up a python3.7 console. I will be showing the code in chunks but all the code can be combined into one script which is what I have done. Also, all the file paths in the code you will have to change to your own for the code to work.
from pyvirtualdisplay import Displayfrom selenium import webdriverimport timefrom selenium.webdriver.chrome.options import Optionswith Display(): # we can now start Firefox and it will run inside the virtual display browser = webdriver.Firefox()# these options allow selenium to download files options = Options() options.add_experimental_option("browser.download.folderList",2) options.add_experimental_option("browser.download.manager.showWhenStarting", False) options.add_experimental_option("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream,application/vnd.ms-excel")# put the rest of our selenium code in a try/finally # to make sure we always clean up at the end try: browser.get('https://www.dshs.texas.gov/coronavirus/additionaldata/')# initialize an object to the location on the html page and click on it to download link = browser.find_element_by_xpath('/html/body/form/div[4]/div/div[3]/div[2]/div/div/ul[1]/li[1]/a') link.click()# Wait for 30 seconds to allow chrome to download file time.sleep(30)print(browser.title) finally: browser.quit()
In the chunk of code above, I open up a Firefox browser within pythonanywhere using their pyvirtualdisplay library. No new browser will pop on your computer since its running on the cloud. This means you should test out the script on your own computer without the display() function because error handling will be difficult within the cloud server. Then I download an .xlsx file from the Texas COVID website and it saves it in my /tmp file within pythonanywhere. To access the /tmp file, just click on the first “/” of the files tab that proceeds the home file button. This is all done within a try/finally blocks, so after the script runs, we close the browser so we do not use any more cpu time on the server. Another thing to note is that pythonanywhere only supports one version of selenium: 2.53.6. You can downgrade to this version of selenium using the following bash command:
pip3.7 install --user selenium==2.53.6
2. converting downloaded data in a .part file to .xlsx file
import shutilimport globimport os# locating most recent .xlsx downloaded filelist_of_files = glob.glob('/tmp/*.xlsx.part')latest_file = max(list_of_files, key=os.path.getmtime)print(latest_file)# we need to locate the old .xlsx file(s) in the dir we want to store the new xlsx file inlist_of_files = glob.glob('/home/tsbloxsom/mysite/get_data/*.xlsx')print(list_of_files)# need to delete old xlsx file(s) so if we download new xlsx file with same name we do not get an error while moving itfor file in list_of_files: print("deleting old xlsx file:", file) os.remove(file)# move new data into data dirshutil.move("{}".format(latest_file), "/home/tsbloxsom/mysite/get_data/covid_dirty_data.xlsx")
When you download .xlsx files in pythonanywhere, they are stored as .xlsx.part files. After some research, these .part files are caused when you stop a download from completing. These .part files cannot be opened with typical tools but there is a easy trick around this problem. In the above code, I automate moving the new data and deleting the old data in my cloud directories. The part to notice is that when I move the .xlsx.part file, I save it as a .xlsx file. This converts it magically, and when you open this new .xlsx file, it has all the live data which means that my script did download the complete .xlsx file but pythonanywhere adds a .part to the file which is weird but hey it works.
3. re-loading your website using the os python package
import pandas as pdimport relist_of_files = glob.glob('/home/tsbloxsom/mysite/get_data/*.xlsx')latest_file = max(list_of_files, key=os.path.getctime)print(latest_file)df = pd.read_excel("{}".format(latest_file),header=None)# print out latest COVID data datetime and notesdate = re.findall("- [0-9]+/[0-9]+/[0-9]+ .+", df.iloc[0, 0])print("COVID cases latest update:", date[0][2:])print(df.iloc[1, 0])#print(str(df.iloc[262:266, 0]).lstrip().rstrip())#drop non-data rowsdf2 = df.drop([0, 1, 258, 260, 261, 262, 263, 264, 265, 266, 267])# clean column namesdf2.iloc[0,:] = df2.iloc[0,:].apply(lambda x: x.replace("\r", ""))df2.iloc[0,:] = df2.iloc[0,:].apply(lambda x: x.replace("\n", ""))df2.columns = df2.iloc[0]clean_df = df2.drop(df2.index[0])clean_df = clean_df.set_index("County Name")clean_df.to_csv("/home/tsbloxsom/mysite/get_data/Texas county COVID cases data clean.csv")df = pd.read_csv("Texas county COVID cases data clean.csv")# convert df into time series where rows are each date and clean updf_t = df.Tdf_t.columns = df_t.iloc[0]df_t = df_t.iloc[1:]df_t = df_t.iloc[:,:-2]# next lets convert the index to a date time, must clean up dates firstdef clean_index(s): s = s.replace("*","") s = s[-5:] s = s + "-2020" #print(s) return sdf_t.index = df_t.index.map(clean_index)df_t.index = pd.to_datetime(df_t.index)# initalize df with three columns: Date, Case Count, and Countyanderson = df_t.T.iloc[0,:]ts = anderson.to_frame().reset_index()ts["County"] = "Anderson"ts = ts.rename(columns = {"Anderson": "Case Count", "index": "Date"})# This while loop adds all counties to the above ts so we can input it into plotlyx = 1while x < 254: new_ts = df_t.T.iloc[x,:] new_ts = new_ts.to_frame().reset_index() new_ts["County"] = new_ts.columns[1] new_ts = new_ts.rename(columns = {new_ts.columns[1]: "Case Count", "index": "Date"}) ts = pd.concat([ts, new_ts]) x += 1ts.to_csv("/home/tsbloxsom/mysite/data/time_series_plotly.csv")time.sleep(5)#reload website with updated dataos.utime('/var/www/tsbloxsom_pythonanywhere_com_wsgi.py')
Most of the above code I explained in my last post which deals with cleaning excel files using pandas for inputting into a plotly dashboard. The most important line for this tutorial is the very last one. The os.utime function shows access and modify times of a file or python script. But when you call the function on your Web Server Gateway Interface (WSGI) file it will reload your website!
4. scheduling a python script to run every day in pythonanywhere
Now for the easy part! After you combine the above code into one .py file, you can make it run every day or hour using pythonanywhere’s Task tab. All you do is copy and paste the bash command, with the full directory path, you would use to run the .py file into the bar in the image above and hit the create button! Now you should test the .py file using a bash console first to see if it runs correctly. But now you have a fully automated data scraping script that your website can use to have daily or hourly updated data displayed without you having to push one button!
If you have any questions or critiques please feel free to say so in the comments and if you want to follow me on LinkedIn you can!
|
[
{
"code": null,
"e": 856,
"s": 172,
"text": "This tutorial will be helpful for people who have a website that hosts live data on a cloud service but are unsure how to completely automate the updating of the live data so the website becomes hassle free. For example: I host a website that shows Texas COVID case counts by county in an interactive dashboard, but everyday I had to run a script to download the excel file from the Texas COVID website, clean the data, update the pandas data frame that was used to create the dashboard, upload the updated data to the cloud service I was using, and reload my website. This was annoying, so I used the steps in this tutorial to show how my live data website is now totally automated."
},
{
"code": null,
"e": 1358,
"s": 856,
"text": "I will only be going over how to do this using the cloud service pythonanywhere, but these steps can be transferred to other cloud services. Another thing to note is that I am new to building and maintaining websites so please feel free to correct me or give me constructive feedback on this tutorial. I will be assuming that you have basic knowledge of python, selenium for web scraping, bash commands, and you have your own website. Lets go through the steps of automating live data to your website:"
},
{
"code": null,
"e": 1575,
"s": 1358,
"text": "web scraping with selenium using a cloud serviceconverting downloaded data in a .part file to .xlsx filere-loading your website using the os python packagescheduling a python script to run every day in pythonanywhere"
},
{
"code": null,
"e": 1624,
"s": 1575,
"text": "web scraping with selenium using a cloud service"
},
{
"code": null,
"e": 1681,
"s": 1624,
"text": "converting downloaded data in a .part file to .xlsx file"
},
{
"code": null,
"e": 1733,
"s": 1681,
"text": "re-loading your website using the os python package"
},
{
"code": null,
"e": 1795,
"s": 1733,
"text": "scheduling a python script to run every day in pythonanywhere"
},
{
"code": null,
"e": 2014,
"s": 1795,
"text": "I will not be going through some of the code I will be showing because I use much of the same code from my last tutorial on how to create and automate an interactive dashboard using python found here. Lets get started!"
},
{
"code": null,
"e": 2063,
"s": 2014,
"text": "web scraping with selenium using a cloud service"
},
{
"code": null,
"e": 2112,
"s": 2063,
"text": "web scraping with selenium using a cloud service"
},
{
"code": null,
"e": 2413,
"s": 2112,
"text": "So in your cloud service of choice (mine being pythonanywhere), open up a python3.7 console. I will be showing the code in chunks but all the code can be combined into one script which is what I have done. Also, all the file paths in the code you will have to change to your own for the code to work."
},
{
"code": null,
"e": 3549,
"s": 2413,
"text": "from pyvirtualdisplay import Displayfrom selenium import webdriverimport timefrom selenium.webdriver.chrome.options import Optionswith Display(): # we can now start Firefox and it will run inside the virtual display browser = webdriver.Firefox()# these options allow selenium to download files options = Options() options.add_experimental_option(\"browser.download.folderList\",2) options.add_experimental_option(\"browser.download.manager.showWhenStarting\", False) options.add_experimental_option(\"browser.helperApps.neverAsk.saveToDisk\", \"application/octet-stream,application/vnd.ms-excel\")# put the rest of our selenium code in a try/finally # to make sure we always clean up at the end try: browser.get('https://www.dshs.texas.gov/coronavirus/additionaldata/')# initialize an object to the location on the html page and click on it to download link = browser.find_element_by_xpath('/html/body/form/div[4]/div/div[3]/div[2]/div/div/ul[1]/li[1]/a') link.click()# Wait for 30 seconds to allow chrome to download file time.sleep(30)print(browser.title) finally: browser.quit()"
},
{
"code": null,
"e": 4433,
"s": 3549,
"text": "In the chunk of code above, I open up a Firefox browser within pythonanywhere using their pyvirtualdisplay library. No new browser will pop on your computer since its running on the cloud. This means you should test out the script on your own computer without the display() function because error handling will be difficult within the cloud server. Then I download an .xlsx file from the Texas COVID website and it saves it in my /tmp file within pythonanywhere. To access the /tmp file, just click on the first “/” of the files tab that proceeds the home file button. This is all done within a try/finally blocks, so after the script runs, we close the browser so we do not use any more cpu time on the server. Another thing to note is that pythonanywhere only supports one version of selenium: 2.53.6. You can downgrade to this version of selenium using the following bash command:"
},
{
"code": null,
"e": 4472,
"s": 4433,
"text": "pip3.7 install --user selenium==2.53.6"
},
{
"code": null,
"e": 4532,
"s": 4472,
"text": "2. converting downloaded data in a .part file to .xlsx file"
},
{
"code": null,
"e": 5233,
"s": 4532,
"text": "import shutilimport globimport os# locating most recent .xlsx downloaded filelist_of_files = glob.glob('/tmp/*.xlsx.part')latest_file = max(list_of_files, key=os.path.getmtime)print(latest_file)# we need to locate the old .xlsx file(s) in the dir we want to store the new xlsx file inlist_of_files = glob.glob('/home/tsbloxsom/mysite/get_data/*.xlsx')print(list_of_files)# need to delete old xlsx file(s) so if we download new xlsx file with same name we do not get an error while moving itfor file in list_of_files: print(\"deleting old xlsx file:\", file) os.remove(file)# move new data into data dirshutil.move(\"{}\".format(latest_file), \"/home/tsbloxsom/mysite/get_data/covid_dirty_data.xlsx\")"
},
{
"code": null,
"e": 5933,
"s": 5233,
"text": "When you download .xlsx files in pythonanywhere, they are stored as .xlsx.part files. After some research, these .part files are caused when you stop a download from completing. These .part files cannot be opened with typical tools but there is a easy trick around this problem. In the above code, I automate moving the new data and deleting the old data in my cloud directories. The part to notice is that when I move the .xlsx.part file, I save it as a .xlsx file. This converts it magically, and when you open this new .xlsx file, it has all the live data which means that my script did download the complete .xlsx file but pythonanywhere adds a .part to the file which is weird but hey it works."
},
{
"code": null,
"e": 5988,
"s": 5933,
"text": "3. re-loading your website using the os python package"
},
{
"code": null,
"e": 8059,
"s": 5988,
"text": "import pandas as pdimport relist_of_files = glob.glob('/home/tsbloxsom/mysite/get_data/*.xlsx')latest_file = max(list_of_files, key=os.path.getctime)print(latest_file)df = pd.read_excel(\"{}\".format(latest_file),header=None)# print out latest COVID data datetime and notesdate = re.findall(\"- [0-9]+/[0-9]+/[0-9]+ .+\", df.iloc[0, 0])print(\"COVID cases latest update:\", date[0][2:])print(df.iloc[1, 0])#print(str(df.iloc[262:266, 0]).lstrip().rstrip())#drop non-data rowsdf2 = df.drop([0, 1, 258, 260, 261, 262, 263, 264, 265, 266, 267])# clean column namesdf2.iloc[0,:] = df2.iloc[0,:].apply(lambda x: x.replace(\"\\r\", \"\"))df2.iloc[0,:] = df2.iloc[0,:].apply(lambda x: x.replace(\"\\n\", \"\"))df2.columns = df2.iloc[0]clean_df = df2.drop(df2.index[0])clean_df = clean_df.set_index(\"County Name\")clean_df.to_csv(\"/home/tsbloxsom/mysite/get_data/Texas county COVID cases data clean.csv\")df = pd.read_csv(\"Texas county COVID cases data clean.csv\")# convert df into time series where rows are each date and clean updf_t = df.Tdf_t.columns = df_t.iloc[0]df_t = df_t.iloc[1:]df_t = df_t.iloc[:,:-2]# next lets convert the index to a date time, must clean up dates firstdef clean_index(s): s = s.replace(\"*\",\"\") s = s[-5:] s = s + \"-2020\" #print(s) return sdf_t.index = df_t.index.map(clean_index)df_t.index = pd.to_datetime(df_t.index)# initalize df with three columns: Date, Case Count, and Countyanderson = df_t.T.iloc[0,:]ts = anderson.to_frame().reset_index()ts[\"County\"] = \"Anderson\"ts = ts.rename(columns = {\"Anderson\": \"Case Count\", \"index\": \"Date\"})# This while loop adds all counties to the above ts so we can input it into plotlyx = 1while x < 254: new_ts = df_t.T.iloc[x,:] new_ts = new_ts.to_frame().reset_index() new_ts[\"County\"] = new_ts.columns[1] new_ts = new_ts.rename(columns = {new_ts.columns[1]: \"Case Count\", \"index\": \"Date\"}) ts = pd.concat([ts, new_ts]) x += 1ts.to_csv(\"/home/tsbloxsom/mysite/data/time_series_plotly.csv\")time.sleep(5)#reload website with updated dataos.utime('/var/www/tsbloxsom_pythonanywhere_com_wsgi.py')"
},
{
"code": null,
"e": 8453,
"s": 8059,
"text": "Most of the above code I explained in my last post which deals with cleaning excel files using pandas for inputting into a plotly dashboard. The most important line for this tutorial is the very last one. The os.utime function shows access and modify times of a file or python script. But when you call the function on your Web Server Gateway Interface (WSGI) file it will reload your website!"
},
{
"code": null,
"e": 8518,
"s": 8453,
"text": "4. scheduling a python script to run every day in pythonanywhere"
},
{
"code": null,
"e": 9091,
"s": 8518,
"text": "Now for the easy part! After you combine the above code into one .py file, you can make it run every day or hour using pythonanywhere’s Task tab. All you do is copy and paste the bash command, with the full directory path, you would use to run the .py file into the bar in the image above and hit the create button! Now you should test the .py file using a bash console first to see if it runs correctly. But now you have a fully automated data scraping script that your website can use to have daily or hourly updated data displayed without you having to push one button!"
}
] |
Program to find the shortest distance between diagonal and edge skew of a Cube - GeeksforGeeks
|
17 Mar, 2021
Given an integer A, denoting the length of a cube, the task is to find the shortest distance between the diagonal of a cube and an edge skew to it i.e. KL in the below figure.
Examples :
Input: A = 2Output: 1.4142Explanation:Length of KL = A / √2Length of KL = 2 / 1.41 = 1.4142
Input: A = 3Output: 2.1213
Approach: The idea to solve the problem is based on the following mathematical formula:
Let’s draw a perpendicular from K to down face of cube as Q.Using Pythagorean Theorem in triangle QKL,
KL2 = QK2 + QL2
l2 = (a/2)2 + (a/2)2
l2 = 2 * (a/2)2
l = a / sqrt(2)
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the shortest distance// between the diagonal of a cube and// an edge skew to itfloat diagonalLength(float a){ // Stores the required distance float L = a / sqrt(2); // Print the required distance cout << L;} // Driver Codeint main(){ // Given side of the cube float a = 2; // Function call to find the shortest // distance between the diagonal of a // cube and an edge skew to it diagonalLength(a); return 0;}
// Java program for the above approach class GFG { // Function to find the shortest // distance between the diagonal of a // cube and an edge skew to it static void diagonalLength(float a) { // Stores the required distance float L = a / (float)Math.sqrt(2); // Print the required distance System.out.println(L); } // Driver Code public static void main(String[] args) { // Given side of the cube float a = 2; // Function call to find the shortest // distance between the diagonal of a // cube and an edge skew to it diagonalLength(a); }}
# Python3 program for the above approach from math import sqrt # Function to find the shortest# distance between the diagonal of a# cube and an edge skew to itdef diagonalLength(a): # Stores the required distance L = a / sqrt(2) # Print the required distance print(L) # Given side of the cubea = 2 # Function call to find the shortest# distance between the diagonal of a# cube and an edge skew to itdiagonalLength(a)
// C# program for the above approach using System;class GFG { // Function to find the shortest // distance between the diagonal of a // cube and an edge skew to it static void diagonalLength(float a) { // Stores the required distance float L = a / (float)Math.Sqrt(2); // Print the required distance Console.Write(L); } // Driver Code public static void Main() { // Given side of the cube float a = 2; // Function call to find the shortest // distance between the diagonal of a // cube and an edge skew to it diagonalLength(a); }}
<?php// PHP program for the above approach // Function to find the shortest// distance between the diagonal of a// cube and an edge skew to itfunction diagonalLength($a){ // Stores the required distance $L = $a / sqrt(2); # Print the required distance echo $L;} // Given side of the cube$a = 2; // Function call to find the shortest// distance between the diagonal of a// cube and an edge skew to itdiagonalLength($a); ?>
<script>// javascript program for the above approach // Function to find the shortest distance// between the diagonal of a cube and// an edge skew to itfunction diagonalLength( a){ // Stores the required distance let L = a / Math.sqrt(2); // Print the required distance document.write( L.toFixed(5));} // Driver Code // Given side of the cube let a = 2; // Function call to find the shortest // distance between the diagonal of a // cube and an edge skew to it diagonalLength(a); // This code is contributed by todaysgaurav </script>
1.41421
Time Complexity: O(1)Auxiliary Space: O(1)
todaysgaurav
area-volume-programs
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Equation of circle when three points on the circle are given
Circle and Lattice Points
Convex Hull using Divide and Conquer Algorithm
Line Clipping | Set 2 (Cyrus Beck Algorithm)
Minimum Cost Polygon Triangulation
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 25476,
"s": 25300,
"text": "Given an integer A, denoting the length of a cube, the task is to find the shortest distance between the diagonal of a cube and an edge skew to it i.e. KL in the below figure."
},
{
"code": null,
"e": 25487,
"s": 25476,
"text": "Examples :"
},
{
"code": null,
"e": 25579,
"s": 25487,
"text": "Input: A = 2Output: 1.4142Explanation:Length of KL = A / √2Length of KL = 2 / 1.41 = 1.4142"
},
{
"code": null,
"e": 25606,
"s": 25579,
"text": "Input: A = 3Output: 2.1213"
},
{
"code": null,
"e": 25694,
"s": 25606,
"text": "Approach: The idea to solve the problem is based on the following mathematical formula:"
},
{
"code": null,
"e": 25797,
"s": 25694,
"text": "Let’s draw a perpendicular from K to down face of cube as Q.Using Pythagorean Theorem in triangle QKL,"
},
{
"code": null,
"e": 25813,
"s": 25797,
"text": "KL2 = QK2 + QL2"
},
{
"code": null,
"e": 25835,
"s": 25813,
"text": "l2 = (a/2)2 + (a/2)2 "
},
{
"code": null,
"e": 25851,
"s": 25835,
"text": "l2 = 2 * (a/2)2"
},
{
"code": null,
"e": 25867,
"s": 25851,
"text": "l = a / sqrt(2)"
},
{
"code": null,
"e": 25918,
"s": 25867,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25922,
"s": 25918,
"text": "C++"
},
{
"code": null,
"e": 25927,
"s": 25922,
"text": "Java"
},
{
"code": null,
"e": 25935,
"s": 25927,
"text": "Python3"
},
{
"code": null,
"e": 25938,
"s": 25935,
"text": "C#"
},
{
"code": null,
"e": 25942,
"s": 25938,
"text": "PHP"
},
{
"code": null,
"e": 25953,
"s": 25942,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the shortest distance// between the diagonal of a cube and// an edge skew to itfloat diagonalLength(float a){ // Stores the required distance float L = a / sqrt(2); // Print the required distance cout << L;} // Driver Codeint main(){ // Given side of the cube float a = 2; // Function call to find the shortest // distance between the diagonal of a // cube and an edge skew to it diagonalLength(a); return 0;}",
"e": 26502,
"s": 25953,
"text": null
},
{
"code": "// Java program for the above approach class GFG { // Function to find the shortest // distance between the diagonal of a // cube and an edge skew to it static void diagonalLength(float a) { // Stores the required distance float L = a / (float)Math.sqrt(2); // Print the required distance System.out.println(L); } // Driver Code public static void main(String[] args) { // Given side of the cube float a = 2; // Function call to find the shortest // distance between the diagonal of a // cube and an edge skew to it diagonalLength(a); }}",
"e": 27144,
"s": 26502,
"text": null
},
{
"code": "# Python3 program for the above approach from math import sqrt # Function to find the shortest# distance between the diagonal of a# cube and an edge skew to itdef diagonalLength(a): # Stores the required distance L = a / sqrt(2) # Print the required distance print(L) # Given side of the cubea = 2 # Function call to find the shortest# distance between the diagonal of a# cube and an edge skew to itdiagonalLength(a)",
"e": 27578,
"s": 27144,
"text": null
},
{
"code": "// C# program for the above approach using System;class GFG { // Function to find the shortest // distance between the diagonal of a // cube and an edge skew to it static void diagonalLength(float a) { // Stores the required distance float L = a / (float)Math.Sqrt(2); // Print the required distance Console.Write(L); } // Driver Code public static void Main() { // Given side of the cube float a = 2; // Function call to find the shortest // distance between the diagonal of a // cube and an edge skew to it diagonalLength(a); }}",
"e": 28213,
"s": 27578,
"text": null
},
{
"code": "<?php// PHP program for the above approach // Function to find the shortest// distance between the diagonal of a// cube and an edge skew to itfunction diagonalLength($a){ // Stores the required distance $L = $a / sqrt(2); # Print the required distance echo $L;} // Given side of the cube$a = 2; // Function call to find the shortest// distance between the diagonal of a// cube and an edge skew to itdiagonalLength($a); ?>",
"e": 28650,
"s": 28213,
"text": null
},
{
"code": "<script>// javascript program for the above approach // Function to find the shortest distance// between the diagonal of a cube and// an edge skew to itfunction diagonalLength( a){ // Stores the required distance let L = a / Math.sqrt(2); // Print the required distance document.write( L.toFixed(5));} // Driver Code // Given side of the cube let a = 2; // Function call to find the shortest // distance between the diagonal of a // cube and an edge skew to it diagonalLength(a); // This code is contributed by todaysgaurav </script>",
"e": 29219,
"s": 28650,
"text": null
},
{
"code": null,
"e": 29227,
"s": 29219,
"text": "1.41421"
},
{
"code": null,
"e": 29272,
"s": 29229,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 29285,
"s": 29272,
"text": "todaysgaurav"
},
{
"code": null,
"e": 29306,
"s": 29285,
"text": "area-volume-programs"
},
{
"code": null,
"e": 29316,
"s": 29306,
"text": "Geometric"
},
{
"code": null,
"e": 29329,
"s": 29316,
"text": "Mathematical"
},
{
"code": null,
"e": 29342,
"s": 29329,
"text": "Mathematical"
},
{
"code": null,
"e": 29352,
"s": 29342,
"text": "Geometric"
},
{
"code": null,
"e": 29450,
"s": 29352,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29459,
"s": 29450,
"text": "Comments"
},
{
"code": null,
"e": 29472,
"s": 29459,
"text": "Old Comments"
},
{
"code": null,
"e": 29533,
"s": 29472,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 29559,
"s": 29533,
"text": "Circle and Lattice Points"
},
{
"code": null,
"e": 29606,
"s": 29559,
"text": "Convex Hull using Divide and Conquer Algorithm"
},
{
"code": null,
"e": 29651,
"s": 29606,
"text": "Line Clipping | Set 2 (Cyrus Beck Algorithm)"
},
{
"code": null,
"e": 29686,
"s": 29651,
"text": "Minimum Cost Polygon Triangulation"
},
{
"code": null,
"e": 29716,
"s": 29686,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 29731,
"s": 29716,
"text": "C++ Data Types"
},
{
"code": null,
"e": 29791,
"s": 29731,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 29834,
"s": 29791,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Ultimate Pandas Guide — Window Functions | by Skyler Dale | Towards Data Science
|
Window functions are an efficient way to understand more about the relationship between each of the records within our data and the groups they belong to.
They also happen to be a common data science interview question so they’re a good thing to understand well.
In this post, I’ll walk through an intuitive explanation of Window functions and how to implement them in Pandas.
In a standard “groupby,” we split our data up into groups, apply an aggregation, and then combine each of the results in a new table.
This helps us answer questions about the characteristics of the groups within our data.
For example, if we have monthly customer-level sales data, we can use a groupby to understand what our total sales are for each month:
If you’re a little rusty on how this works, I recommend you check out my post on the groupby function:
towardsdatascience.com
The output above is useful if we only care about monthly sales.
But the drawback of this result is that our information is now spread across two tables — the first gives us the sales details and the second gives us aggregated information about each month.
Window functions help us bridge this gap, by bringing our group-level aggregations back to the initial table:
If it’s not immediately clear why that’s useful, let’s add a percent column to our output:
Now we can see what percentage of the total monthly sales each of our records comprises.
The window function is useful because it helps us run these types of calculations without having to perform any separate joins.
The syntax for a window function in Pandas is pleasantly simple, and very similar to the syntax we would use for a groupby aggregation.
The key difference is that to perform a window function we use the “transform” method rather than the “agg” method:
And the transform method returns a series instead of a DataFrame, so we need to add it as a column if we want it to be a part of our original DataFrame:
sales_data[“monthly_sales”] = sales_data.groupby(“month”).transform(sum)[“purchase_amount”]
And that’s it! Not too bad.
Let’s try one more example. Below we rank each transaction by state:
sales_data['state_rank'] = sales_data.sort_values(by = 'purchase_amount', ascending = False).groupby("state").transform('rank', method = 'min')["purchase_amount"]
Note a couple things here:
We use the “sort_values” function to make sure we are ranking in order of the purchase amount.We pass an argument (“min”) to the “method” parameter within our transform. This is a parameter of the rank method and gets passed to it when executed.This type of analysis tends to be useful when we want to return the “top” values within groups. For example, we could filter the result above for the top 2 transactions within each state and then pass those to sales reps that cover each state.
We use the “sort_values” function to make sure we are ranking in order of the purchase amount.
We pass an argument (“min”) to the “method” parameter within our transform. This is a parameter of the rank method and gets passed to it when executed.
This type of analysis tends to be useful when we want to return the “top” values within groups. For example, we could filter the result above for the top 2 transactions within each state and then pass those to sales reps that cover each state.
For those with a strong SQL background, this syntax might feel a bit strange.
In SQL we execute a window function by starting with an aggregation and then applying it “over” an optional “partition by” and “order by” :
select rank() over (partition by state order by purchase_amount desc)
In order to help reconcile the two approaches, I’ve converted the elements of the Pandas code from above into their SQL equivalent:
Window functions are powerful, efficient, and fairly straightforward to implement in Pandas.
It’s worth noting, however, that the “transform” method is not the correct approach for performing position-based aggregations, like summing a column’s values for the previous 5 records. In order to address this, we’ll have to look deeper at the “shift” and “expanding” functions in Pandas in a future post.
|
[
{
"code": null,
"e": 327,
"s": 172,
"text": "Window functions are an efficient way to understand more about the relationship between each of the records within our data and the groups they belong to."
},
{
"code": null,
"e": 435,
"s": 327,
"text": "They also happen to be a common data science interview question so they’re a good thing to understand well."
},
{
"code": null,
"e": 549,
"s": 435,
"text": "In this post, I’ll walk through an intuitive explanation of Window functions and how to implement them in Pandas."
},
{
"code": null,
"e": 683,
"s": 549,
"text": "In a standard “groupby,” we split our data up into groups, apply an aggregation, and then combine each of the results in a new table."
},
{
"code": null,
"e": 771,
"s": 683,
"text": "This helps us answer questions about the characteristics of the groups within our data."
},
{
"code": null,
"e": 906,
"s": 771,
"text": "For example, if we have monthly customer-level sales data, we can use a groupby to understand what our total sales are for each month:"
},
{
"code": null,
"e": 1009,
"s": 906,
"text": "If you’re a little rusty on how this works, I recommend you check out my post on the groupby function:"
},
{
"code": null,
"e": 1032,
"s": 1009,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1096,
"s": 1032,
"text": "The output above is useful if we only care about monthly sales."
},
{
"code": null,
"e": 1288,
"s": 1096,
"text": "But the drawback of this result is that our information is now spread across two tables — the first gives us the sales details and the second gives us aggregated information about each month."
},
{
"code": null,
"e": 1398,
"s": 1288,
"text": "Window functions help us bridge this gap, by bringing our group-level aggregations back to the initial table:"
},
{
"code": null,
"e": 1489,
"s": 1398,
"text": "If it’s not immediately clear why that’s useful, let’s add a percent column to our output:"
},
{
"code": null,
"e": 1578,
"s": 1489,
"text": "Now we can see what percentage of the total monthly sales each of our records comprises."
},
{
"code": null,
"e": 1706,
"s": 1578,
"text": "The window function is useful because it helps us run these types of calculations without having to perform any separate joins."
},
{
"code": null,
"e": 1842,
"s": 1706,
"text": "The syntax for a window function in Pandas is pleasantly simple, and very similar to the syntax we would use for a groupby aggregation."
},
{
"code": null,
"e": 1958,
"s": 1842,
"text": "The key difference is that to perform a window function we use the “transform” method rather than the “agg” method:"
},
{
"code": null,
"e": 2111,
"s": 1958,
"text": "And the transform method returns a series instead of a DataFrame, so we need to add it as a column if we want it to be a part of our original DataFrame:"
},
{
"code": null,
"e": 2203,
"s": 2111,
"text": "sales_data[“monthly_sales”] = sales_data.groupby(“month”).transform(sum)[“purchase_amount”]"
},
{
"code": null,
"e": 2231,
"s": 2203,
"text": "And that’s it! Not too bad."
},
{
"code": null,
"e": 2300,
"s": 2231,
"text": "Let’s try one more example. Below we rank each transaction by state:"
},
{
"code": null,
"e": 2481,
"s": 2300,
"text": "sales_data['state_rank'] = sales_data.sort_values(by = 'purchase_amount', ascending = False).groupby(\"state\").transform('rank', method = 'min')[\"purchase_amount\"]"
},
{
"code": null,
"e": 2508,
"s": 2481,
"text": "Note a couple things here:"
},
{
"code": null,
"e": 2997,
"s": 2508,
"text": "We use the “sort_values” function to make sure we are ranking in order of the purchase amount.We pass an argument (“min”) to the “method” parameter within our transform. This is a parameter of the rank method and gets passed to it when executed.This type of analysis tends to be useful when we want to return the “top” values within groups. For example, we could filter the result above for the top 2 transactions within each state and then pass those to sales reps that cover each state."
},
{
"code": null,
"e": 3092,
"s": 2997,
"text": "We use the “sort_values” function to make sure we are ranking in order of the purchase amount."
},
{
"code": null,
"e": 3244,
"s": 3092,
"text": "We pass an argument (“min”) to the “method” parameter within our transform. This is a parameter of the rank method and gets passed to it when executed."
},
{
"code": null,
"e": 3488,
"s": 3244,
"text": "This type of analysis tends to be useful when we want to return the “top” values within groups. For example, we could filter the result above for the top 2 transactions within each state and then pass those to sales reps that cover each state."
},
{
"code": null,
"e": 3566,
"s": 3488,
"text": "For those with a strong SQL background, this syntax might feel a bit strange."
},
{
"code": null,
"e": 3706,
"s": 3566,
"text": "In SQL we execute a window function by starting with an aggregation and then applying it “over” an optional “partition by” and “order by” :"
},
{
"code": null,
"e": 3776,
"s": 3706,
"text": "select rank() over (partition by state order by purchase_amount desc)"
},
{
"code": null,
"e": 3908,
"s": 3776,
"text": "In order to help reconcile the two approaches, I’ve converted the elements of the Pandas code from above into their SQL equivalent:"
},
{
"code": null,
"e": 4001,
"s": 3908,
"text": "Window functions are powerful, efficient, and fairly straightforward to implement in Pandas."
}
] |
Hello World Program in Java
|
Let us look at a simple code that will print the words Hello World.
Online Demo
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}
Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −
Open notepad and add the code as above.
Open notepad and add the code as above.
Save the file as − MyFirstJavaProgram.java.
Save the file as − MyFirstJavaProgram.java.
Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption − The path variable is set).
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption − The path variable is set).
Now, type ' java MyFirstJavaProgram ' to run your program.
Now, type ' java MyFirstJavaProgram ' to run your program.
You will be able to see ' Hello World ' printed on the window.
You will be able to see ' Hello World ' printed on the window.
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World
|
[
{
"code": null,
"e": 1130,
"s": 1062,
"text": "Let us look at a simple code that will print the words Hello World."
},
{
"code": null,
"e": 1142,
"s": 1130,
"text": "Online Demo"
},
{
"code": null,
"e": 1386,
"s": 1142,
"text": "public class MyFirstJavaProgram {\n\n /* This is my first java program.\n * This will print 'Hello World' as the output\n */\n\n public static void main(String []args) {\n System.out.println(\"Hello World\"); // prints Hello World\n }\n}"
},
{
"code": null,
"e": 1489,
"s": 1386,
"text": "Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −"
},
{
"code": null,
"e": 1529,
"s": 1489,
"text": "Open notepad and add the code as above."
},
{
"code": null,
"e": 1569,
"s": 1529,
"text": "Open notepad and add the code as above."
},
{
"code": null,
"e": 1613,
"s": 1569,
"text": "Save the file as − MyFirstJavaProgram.java."
},
{
"code": null,
"e": 1657,
"s": 1613,
"text": "Save the file as − MyFirstJavaProgram.java."
},
{
"code": null,
"e": 1754,
"s": 1657,
"text": "Open a command prompt window and go to the directory where you saved the class. Assume it's C:\\."
},
{
"code": null,
"e": 1851,
"s": 1754,
"text": "Open a command prompt window and go to the directory where you saved the class. Assume it's C:\\."
},
{
"code": null,
"e": 2054,
"s": 1851,
"text": "Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption − The path variable is set)."
},
{
"code": null,
"e": 2257,
"s": 2054,
"text": "Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption − The path variable is set)."
},
{
"code": null,
"e": 2316,
"s": 2257,
"text": "Now, type ' java MyFirstJavaProgram ' to run your program."
},
{
"code": null,
"e": 2375,
"s": 2316,
"text": "Now, type ' java MyFirstJavaProgram ' to run your program."
},
{
"code": null,
"e": 2438,
"s": 2375,
"text": "You will be able to see ' Hello World ' printed on the window."
},
{
"code": null,
"e": 2501,
"s": 2438,
"text": "You will be able to see ' Hello World ' printed on the window."
},
{
"code": null,
"e": 2577,
"s": 2501,
"text": "C:\\> javac MyFirstJavaProgram.java\nC:\\> java MyFirstJavaProgram\nHello World"
}
] |
Market-basket analysis and prediction | by Gokul S Kumar | Towards Data Science
|
We all have been shopping more from online e-commerce sites recently, probably due to the lock-down imposed in most parts of the world. You must have noticed an up-sell feature named ‘frequently bought together’ in most of these sites, for instance Amazon where it predicts what all items would go-along with the item that you have just added to the cart. Customers are given the choice of adding all the items shown under this feature to the cart or select the required ones. Amazon does it thorough what they call ‘item-to-item collaborative filtering’ where it runs recommendation algorithms based on the item-search history of the customer to improve the shopping experience. In the case of offline retailers, it works pretty much the same. Let us consider the basic example of Bread and Jam. If the retailer finds that there is an increase in the sales of bread, he can further up-sell by giving a discount in the price of jam, so that more customers are bound to buy them together.
This entire process of analyzing the shopping trends of customers is called ‘Market Basket Analysis’. It is an analyzing technique based on the idea that if we buy an item then we are bound to buy or not-buy a group (or single) items. For example, if a customer is buying bread then the chances of him/her buying jam is more. This is represented by the following equation:
This equation is called the Association Mining Rule. This can be thought of as an IF-THEN relationship. If item A is bought by a customer then the chances of item B being bought by the same user in the same transaction is found out. Here A is called the Antecedent and B the consequent. Antecedents are primary item that are found in the basket and consequents are the items that are found with an antecedent/group of antecedents. The metrics for measuring association are:
Support: It tells us about the combination of items bought together frequently. It gives the part of transactions that contain both A and B.
We can filter out the less frequently occurring items-sets using support.
Confidence: It tells us how frequently the items A and B are bought together, for the no. of times A is bought.
Lift: It indicates the strength of a rule over the randomness of A and B being bought together. It basically measures the strength of any association rule(we will talk about association rules below).
More the lift more is the strength of the rule. If the lift is 3 for A -> B then it means if we buy A, the chances of buying B is 3 times.
So the process is to make rules for each item-set to figure out the metrics of its association so as to decide whether to include it in the analysis or not. But consider a large data-set having millions of user and transactions, thereby producing a large amount of item-sets. So to make rules for all of these would be a humongous task. This is where Apriori algorithm enters the scene.
Apriori algorithm uses frequently bought item-sets to generate association rules. It is built on the idea that the subset of a frequently bought items-set is also a frequently bought item-set. Frequently bought item-sets are decided if their support value is above a minimum threshold support value.
To demonstrate the working of this algorithm consider the following transactions:
There are 5 items A,B,C,D and E in total which are bought together in different combinations in each transaction. Lets fix the minimum threshold support value of item-sets formed to be 2.
Iteration-1: Item-sets having 1 item is formed and their support is calculated.
As seen from the support values of each item-set, D has a support of 1 which is less than the threshold value. So we are going to omit that item-set.
Iteration-2: Next we make all the possible item-sets having 2 items in them. All the items in the table F1 are used in this.
Item-sets having support less than 2 are again omitted, {A,B} in this iteration.
Iteration-3: All the possible item-sets having 3 items in them are listed. Then we are going to divide these item-sets into their sub-sets and omit those having a support value less than the threshold i.e., 2. This process is called Pruning.
We will omit {A,B,C} and {A,B,E} as they both contain {A,B} which was omitted in Iteration-2. This pruning section is the key part of Apriori algorithm.
Iteration-4: Using F3 we will create item-sets having 4 items.
As we can see, the support of the only item-set having 4 items is less than 2. So we stop the iterations here and the final item-set is F3.
If I={A,C,E} then the subsets are {A,C}, {A,E}, {C,E}, {A}, {C}, {E}.
If I={B,C,E} the the subsets are {B,C}, {B,E}, {C,E}, {B}, {C}, {E}.
Rules: For filtering out the relevant item-sets we will create certain rules and apply it to the subsets. Assume a minimum confidence value of 60%.
For every subset S of I we make the rule
S →(I-S) (which means if S then I minus S) if
support(I)/support(S) ≥ minimum confidence value i.e., 60%.
Consider {A,C,E}
Rule 1: {A,C} →({A,C,E}- {A,C}) which is {A,C} → {E}
Confidence = support{A,C,E}/support{A,C} = 2/3 = 66.6% > 60%
So rule 1 i.e., {A,C} → {E} is selected.
Rule 2: {A,E} →({A,C,E}- {A,E}) which is {A,E} → {C}
Confidence = support{A,C,E}/support{A,E} = 2/2 = 100% > 60%
So rule 2 i.e., {A,E} → {C} is selected.
Rule 3: {C,E} →({A,C,E}- {C,E}) which is {C,E} → {A}
Confidence = support{A,C,E}/support{C,E} = 2/3 = 66.6% > 60%
So rule 3 i.e., {C,E} → {A} is selected.
Rule 4: {A} →({A,C,E}- {A}) which is {A} → {C,E}
Confidence = support{A,C,E}/support{A} = 2/3 = 66.6% > 60%
So rule 4 i.e., {A} → {C,E} is selected.
Rule 5: {C} →({A,C,E}- {C}) which is {C} → {A,E}
Confidence = support{A,C,E}/support{C} = 2/4 = 50% < 60%
So rule 5 i.e., {C} → {A,E} is rejected.
Rule 6: {E} →({A,C,E}- {E}) which is {E} → {A,C}
Confidence = support{A,C,E}/support{E} = 2/4 = 50% < 60%
So rule 6 i.e., {E} → {A,C} is rejected.
Same steps can be done to {B,C,E}. Lift is not being used as the size of the input data-set is small and there is no need of further filtering. But in the case of larger data set further filtering is done by imposing a minimum lift value for the rules. The values of all three of the association metrics can be tweaked as per requirement.
Lets consider an actual data-set and see how the analysis is done.
The link to the data-set being used is given below
drive.google.com
We are going to sue python and pandas. We are also going to use Mlxtend lib as it contains inbuilt functions for Apriori algorithm and Associaction rules.
Load the necessary libraries:
import pandas as pdfrom mlxtend.frequent_patterns import apriorifrom mlxtend.frequent_patterns import association_rulesimport matplotlib.pyplot as pltfrom matplotlib import styleimport numpy as np
Ingest the data into a pandas data-frame and try to know about the features.
read_df = pd.read_csv(‘transaction_data.csv’)df = read_df.copy()df.info()
Further description of the features are as follows:
UserId — Unique identifier of a user.
TransactionId — Unique identifier of a transaction. If the same TransactionId is present in multiple rows, then all those products are bought together in the same transaction.
TransactionTime — Time at which the transaction is performed
ItemCode — Unique identifier of the product purchased
ItemDescription — Simple description of the product purchased
NumberOfItemsPurchased — Quantity of the product purchased in the transaction
CostPerItem — Price per each unit of the product
Country — Country from which the purchase is made.
EDA and data cleaning is done as follows:
df = df[df.UserId>0] # usedid <=0 : 25%df = df[df.ItemCode>0]df = df[df.NumberOfItemsPurchased>0]df = df[df.CostPerItem>0]df = df[df.ItemDescription.notna()]df = df[df.TransactionTime.str[-4:] != ‘2028’]
The following data-frame is obtained:
EDA:
Lets do some exploratory data analysis now. Lets see the no. of transactions being done in each part of the year.
df.TransactionTime = pd.to_datetime(df.TransactionTime)df[‘month_year’]= pd.to_datetime(df.TransactionTime).dt.to_period(‘M’)df.sort_values(by = [‘month_year’], inplace = True)Ser = df.groupby(‘month_year’).TransactionId.nunique()x = np.arange(0,len(Ser),1)style.use(‘ggplot’)fig = plt.figure(figsize = (10,10))ax1 = fig.add_subplot(111)ax1.plot(x, Ser, color = ‘k’)ax1.fill_between(x, Ser, color = ‘r’, alpha = 0.5)ax1.set_xticks(x)ax1.set_xticklabels(Ser.index)plt.xlabel(‘Time period’)plt.ylabel(‘No. of transactions’)
Basically we are creating a column named month_year to divide the datapoints into the month in which they occurred. Then we are taking the no. of unique transaction occurring in each month and plotting it using matplotlib.
As we can see the as the time advances the online retailer is getting more and more purchases which maxed in the month of Jan’19.
Lets explore the no. of items bought in each transaction.
Ser = df.groupby(‘TransactionId’).ItemDescription.nunique()Ser.describe()
As we can see the min no. of items is 1 and the max is 540. So we need to plot our histogram as shown below:
bins = [0,50,100,150,200,250,300,350,400,450,500,550]fig = plt.figure(figsize = (10,10))plt.hist(Ser, bins, histtype = 'bar', rwidth = 0.5)plt.xlabel('No. of items')plt.ylabel('No. of transactions')plt.show()
Oops! We can see that most of the transactions include items between 0–100 and some between 100–200. The max items transactions shown above probably is an outlier or is a customer who purchases in a large scale. So we need to re-scale our histogram.
bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200]fig = plt.figure(figsize = (10,10))ax1 = fig.add_subplot(111)ax1.hist(Ser, bins, histtype = 'bar', rwidth = 0.5)ax1.set_xticks(bins)plt.xlabel('No. of items')plt.ylabel('No. of transactions')plt.show()
As we can see most transactions included less than 10 items.
Lets find out the most-selling item in the market. This can be interpreted in many way such as the item which brings in the maximum revenue, items which were found in maximum no. of transactions etc. We will be considering the items which bring in maximum revenue.
df[‘total_cost_item’] = df.NumberOfItemsPurchased*df.CostPerItemSer = df.groupby(‘ItemDescription’).total_cost_item.sum()Ser.sort_values(ascending = False, inplace = True)Ser = Ser[:10]fig = plt.figure(figsize = (10,10))ax = fig.add_subplot(111)ax.barh(Ser.index, Ser, height = 0.5)
From the above plot showing the top 10 items, we can see that the item ‘retrospot lamp’ has maximum sales value.
The no. of unique TransactionId’s is found to be 18334 and the no. of unique ItemDescription’s is found to be 3871.
Now that we have our data after all the pre-processing, lets arrange it with the TransactionId’s as the index and the ItemDescriptions as the columns with the total no. of items bought in each transaction of each item as the data-point.
df_set = df.groupby(['TransactionId', 'ItemDescription']).NumberOfItemsPurchased.sum().unstack().reset_index().fillna(0).set_index('TransactionId')
The following data-frame is obtained:
We need to make sure that any positive values are encoded to one and all the negative values(if any) to zero.
def encode(x): if x <= 0: return 0 else: return 1df_set = df_set.applymap(encode)df_set
As the data-frame is ready we can apply Apriori algorithm to get the frequently bought item-sets.
frequent_itemsets = apriori(df_set, min_support = 0.015, use_colnames = True)
Here the minimum threshold support value is set as 1.5%. We get the following item-sets.
We then arrange the itemsets in descending order of their support values which gives us
frequent_itemsets = apriori(df_set, min_support = 0.015, use_colnames = True)top_items = frequent_itemsets.sort_values('support', ascending = False)[:20]for i in range(len(top_items.itemsets)): top_items.itemsets.iloc[i] = str(list(top_items.itemsets.iloc[i]))fig = plt.figure(figsize = (10,10))ax = fig.add_subplot(111)ax.bar(top_items.itemsets, top_items.support)for label in ax.xaxis.get_ticklabels(): label.set_rotation(90)plt.xlabel('Item')plt.ylabel('Support')
We then apply the association rules to these item-sets formed by Apriori algorithm.
rules = association_rules(frequent_itemsets, metric = 'confidence', min_threshold = 0.2)
The metric used here is confidence and its minimum threshold value is set to be 0.2.
The following data-frame is obtained
All the antecedents with the corresponding consequents are listed with their individual supports, the total support of the item-set and all other metrics.
The summary of the rules data-frames gives us the following insights:
There are a total of 187 rules.The summary of various metrics.
There are a total of 187 rules.
The summary of various metrics.
Lets take the top rules having the highest confidence
top_rules = rules.sort_values(‘confidence’, ascending = False)[:10]
fig = plt.figure(figsize = (10,10))ax = fig.add_subplot(111)ax.scatter(top_rules.support, top_rules.confidence, top_rules.lift)
Plotting the rules in a graph:
import networkx as nxG1 = nx.DiGraph()color_map = []N = 50colors = np.random.rand(N)strs = ['r0', 'r1', 'r2', 'r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9']for i in range(10): G1.add_nodes_from('r'+str(i)) for a in top_rules.iloc[i]['antecedents']: G1.add_nodes_from([a]) G1.add_edge(a, 'r'+str(i), color = colors[i], weight = 2) for c in top_rules.iloc[i]['consequents']: G1.add_nodes_from([c]) G1.add_edge('r'+str(i), c, color = colors[i], weight = 2)for node in G1: found_a_string = False for item in strs: if node == item: found_a_string = True if found_a_string: color_map.append('red') else: color_map.append('black')edges = G1.edges()colors = [G1[u][v]['color'] for u,v in edges]weights = [G1[u][v]['weight'] for u,v in edges]pos = nx.spring_layout(G1, k = 16, scale = 1)fig = plt.figure(figsize = (20,20))nx.draw(G1, pos, edges = edges, node_color = color_map, edge_color = colors, width = weights, font_size = 16, with_labels = False)for p in pos: pos[p][1] += 0.07nx.draw_networkx_labels(G1, pos)
All these plotting and and further analysis can be done more easily in R rather than python as there are more compatible libraries for data-mining and association rules in R.
Further filtering of the obtained item-sets can be done using lift and confidence values (as they measure association rule strength).
Here the mean value of lift and confidence are found to be 9.388 and 0.429 respectively.
rules[(rules.lift >= 9.388) & (rules.confidence >= 0.429)]
The item-sets are filtered such that only those having the lift and confidence values above the mean values are included.
In this way all the required item-sets can be found. Further fine-tuning of the item-sets to find the more probable ones can be done by increasing the threshold values of support and lift. We can store the found item-sets in a csv file for furtherance.
Summary:
We looked at the basic Association Mining Rule and its applications. Then we solved the problem of generating frequently bought item-sets by using Apriori algorithm. The process was applying Association Rules to these generated item-set was looked upon. We also learned how to do this entire process in Python using Pandas and Mlxtend on a comparatively large-scale dataset.
|
[
{
"code": null,
"e": 1160,
"s": 172,
"text": "We all have been shopping more from online e-commerce sites recently, probably due to the lock-down imposed in most parts of the world. You must have noticed an up-sell feature named ‘frequently bought together’ in most of these sites, for instance Amazon where it predicts what all items would go-along with the item that you have just added to the cart. Customers are given the choice of adding all the items shown under this feature to the cart or select the required ones. Amazon does it thorough what they call ‘item-to-item collaborative filtering’ where it runs recommendation algorithms based on the item-search history of the customer to improve the shopping experience. In the case of offline retailers, it works pretty much the same. Let us consider the basic example of Bread and Jam. If the retailer finds that there is an increase in the sales of bread, he can further up-sell by giving a discount in the price of jam, so that more customers are bound to buy them together."
},
{
"code": null,
"e": 1533,
"s": 1160,
"text": "This entire process of analyzing the shopping trends of customers is called ‘Market Basket Analysis’. It is an analyzing technique based on the idea that if we buy an item then we are bound to buy or not-buy a group (or single) items. For example, if a customer is buying bread then the chances of him/her buying jam is more. This is represented by the following equation:"
},
{
"code": null,
"e": 2007,
"s": 1533,
"text": "This equation is called the Association Mining Rule. This can be thought of as an IF-THEN relationship. If item A is bought by a customer then the chances of item B being bought by the same user in the same transaction is found out. Here A is called the Antecedent and B the consequent. Antecedents are primary item that are found in the basket and consequents are the items that are found with an antecedent/group of antecedents. The metrics for measuring association are:"
},
{
"code": null,
"e": 2148,
"s": 2007,
"text": "Support: It tells us about the combination of items bought together frequently. It gives the part of transactions that contain both A and B."
},
{
"code": null,
"e": 2222,
"s": 2148,
"text": "We can filter out the less frequently occurring items-sets using support."
},
{
"code": null,
"e": 2334,
"s": 2222,
"text": "Confidence: It tells us how frequently the items A and B are bought together, for the no. of times A is bought."
},
{
"code": null,
"e": 2534,
"s": 2334,
"text": "Lift: It indicates the strength of a rule over the randomness of A and B being bought together. It basically measures the strength of any association rule(we will talk about association rules below)."
},
{
"code": null,
"e": 2673,
"s": 2534,
"text": "More the lift more is the strength of the rule. If the lift is 3 for A -> B then it means if we buy A, the chances of buying B is 3 times."
},
{
"code": null,
"e": 3060,
"s": 2673,
"text": "So the process is to make rules for each item-set to figure out the metrics of its association so as to decide whether to include it in the analysis or not. But consider a large data-set having millions of user and transactions, thereby producing a large amount of item-sets. So to make rules for all of these would be a humongous task. This is where Apriori algorithm enters the scene."
},
{
"code": null,
"e": 3360,
"s": 3060,
"text": "Apriori algorithm uses frequently bought item-sets to generate association rules. It is built on the idea that the subset of a frequently bought items-set is also a frequently bought item-set. Frequently bought item-sets are decided if their support value is above a minimum threshold support value."
},
{
"code": null,
"e": 3442,
"s": 3360,
"text": "To demonstrate the working of this algorithm consider the following transactions:"
},
{
"code": null,
"e": 3630,
"s": 3442,
"text": "There are 5 items A,B,C,D and E in total which are bought together in different combinations in each transaction. Lets fix the minimum threshold support value of item-sets formed to be 2."
},
{
"code": null,
"e": 3710,
"s": 3630,
"text": "Iteration-1: Item-sets having 1 item is formed and their support is calculated."
},
{
"code": null,
"e": 3860,
"s": 3710,
"text": "As seen from the support values of each item-set, D has a support of 1 which is less than the threshold value. So we are going to omit that item-set."
},
{
"code": null,
"e": 3985,
"s": 3860,
"text": "Iteration-2: Next we make all the possible item-sets having 2 items in them. All the items in the table F1 are used in this."
},
{
"code": null,
"e": 4066,
"s": 3985,
"text": "Item-sets having support less than 2 are again omitted, {A,B} in this iteration."
},
{
"code": null,
"e": 4308,
"s": 4066,
"text": "Iteration-3: All the possible item-sets having 3 items in them are listed. Then we are going to divide these item-sets into their sub-sets and omit those having a support value less than the threshold i.e., 2. This process is called Pruning."
},
{
"code": null,
"e": 4461,
"s": 4308,
"text": "We will omit {A,B,C} and {A,B,E} as they both contain {A,B} which was omitted in Iteration-2. This pruning section is the key part of Apriori algorithm."
},
{
"code": null,
"e": 4524,
"s": 4461,
"text": "Iteration-4: Using F3 we will create item-sets having 4 items."
},
{
"code": null,
"e": 4664,
"s": 4524,
"text": "As we can see, the support of the only item-set having 4 items is less than 2. So we stop the iterations here and the final item-set is F3."
},
{
"code": null,
"e": 4734,
"s": 4664,
"text": "If I={A,C,E} then the subsets are {A,C}, {A,E}, {C,E}, {A}, {C}, {E}."
},
{
"code": null,
"e": 4803,
"s": 4734,
"text": "If I={B,C,E} the the subsets are {B,C}, {B,E}, {C,E}, {B}, {C}, {E}."
},
{
"code": null,
"e": 4951,
"s": 4803,
"text": "Rules: For filtering out the relevant item-sets we will create certain rules and apply it to the subsets. Assume a minimum confidence value of 60%."
},
{
"code": null,
"e": 4992,
"s": 4951,
"text": "For every subset S of I we make the rule"
},
{
"code": null,
"e": 5038,
"s": 4992,
"text": "S →(I-S) (which means if S then I minus S) if"
},
{
"code": null,
"e": 5098,
"s": 5038,
"text": "support(I)/support(S) ≥ minimum confidence value i.e., 60%."
},
{
"code": null,
"e": 5115,
"s": 5098,
"text": "Consider {A,C,E}"
},
{
"code": null,
"e": 5168,
"s": 5115,
"text": "Rule 1: {A,C} →({A,C,E}- {A,C}) which is {A,C} → {E}"
},
{
"code": null,
"e": 5229,
"s": 5168,
"text": "Confidence = support{A,C,E}/support{A,C} = 2/3 = 66.6% > 60%"
},
{
"code": null,
"e": 5270,
"s": 5229,
"text": "So rule 1 i.e., {A,C} → {E} is selected."
},
{
"code": null,
"e": 5323,
"s": 5270,
"text": "Rule 2: {A,E} →({A,C,E}- {A,E}) which is {A,E} → {C}"
},
{
"code": null,
"e": 5383,
"s": 5323,
"text": "Confidence = support{A,C,E}/support{A,E} = 2/2 = 100% > 60%"
},
{
"code": null,
"e": 5424,
"s": 5383,
"text": "So rule 2 i.e., {A,E} → {C} is selected."
},
{
"code": null,
"e": 5477,
"s": 5424,
"text": "Rule 3: {C,E} →({A,C,E}- {C,E}) which is {C,E} → {A}"
},
{
"code": null,
"e": 5538,
"s": 5477,
"text": "Confidence = support{A,C,E}/support{C,E} = 2/3 = 66.6% > 60%"
},
{
"code": null,
"e": 5579,
"s": 5538,
"text": "So rule 3 i.e., {C,E} → {A} is selected."
},
{
"code": null,
"e": 5628,
"s": 5579,
"text": "Rule 4: {A} →({A,C,E}- {A}) which is {A} → {C,E}"
},
{
"code": null,
"e": 5687,
"s": 5628,
"text": "Confidence = support{A,C,E}/support{A} = 2/3 = 66.6% > 60%"
},
{
"code": null,
"e": 5728,
"s": 5687,
"text": "So rule 4 i.e., {A} → {C,E} is selected."
},
{
"code": null,
"e": 5777,
"s": 5728,
"text": "Rule 5: {C} →({A,C,E}- {C}) which is {C} → {A,E}"
},
{
"code": null,
"e": 5834,
"s": 5777,
"text": "Confidence = support{A,C,E}/support{C} = 2/4 = 50% < 60%"
},
{
"code": null,
"e": 5875,
"s": 5834,
"text": "So rule 5 i.e., {C} → {A,E} is rejected."
},
{
"code": null,
"e": 5924,
"s": 5875,
"text": "Rule 6: {E} →({A,C,E}- {E}) which is {E} → {A,C}"
},
{
"code": null,
"e": 5981,
"s": 5924,
"text": "Confidence = support{A,C,E}/support{E} = 2/4 = 50% < 60%"
},
{
"code": null,
"e": 6022,
"s": 5981,
"text": "So rule 6 i.e., {E} → {A,C} is rejected."
},
{
"code": null,
"e": 6361,
"s": 6022,
"text": "Same steps can be done to {B,C,E}. Lift is not being used as the size of the input data-set is small and there is no need of further filtering. But in the case of larger data set further filtering is done by imposing a minimum lift value for the rules. The values of all three of the association metrics can be tweaked as per requirement."
},
{
"code": null,
"e": 6428,
"s": 6361,
"text": "Lets consider an actual data-set and see how the analysis is done."
},
{
"code": null,
"e": 6479,
"s": 6428,
"text": "The link to the data-set being used is given below"
},
{
"code": null,
"e": 6496,
"s": 6479,
"text": "drive.google.com"
},
{
"code": null,
"e": 6651,
"s": 6496,
"text": "We are going to sue python and pandas. We are also going to use Mlxtend lib as it contains inbuilt functions for Apriori algorithm and Associaction rules."
},
{
"code": null,
"e": 6681,
"s": 6651,
"text": "Load the necessary libraries:"
},
{
"code": null,
"e": 6878,
"s": 6681,
"text": "import pandas as pdfrom mlxtend.frequent_patterns import apriorifrom mlxtend.frequent_patterns import association_rulesimport matplotlib.pyplot as pltfrom matplotlib import styleimport numpy as np"
},
{
"code": null,
"e": 6955,
"s": 6878,
"text": "Ingest the data into a pandas data-frame and try to know about the features."
},
{
"code": null,
"e": 7029,
"s": 6955,
"text": "read_df = pd.read_csv(‘transaction_data.csv’)df = read_df.copy()df.info()"
},
{
"code": null,
"e": 7081,
"s": 7029,
"text": "Further description of the features are as follows:"
},
{
"code": null,
"e": 7119,
"s": 7081,
"text": "UserId — Unique identifier of a user."
},
{
"code": null,
"e": 7295,
"s": 7119,
"text": "TransactionId — Unique identifier of a transaction. If the same TransactionId is present in multiple rows, then all those products are bought together in the same transaction."
},
{
"code": null,
"e": 7356,
"s": 7295,
"text": "TransactionTime — Time at which the transaction is performed"
},
{
"code": null,
"e": 7410,
"s": 7356,
"text": "ItemCode — Unique identifier of the product purchased"
},
{
"code": null,
"e": 7472,
"s": 7410,
"text": "ItemDescription — Simple description of the product purchased"
},
{
"code": null,
"e": 7550,
"s": 7472,
"text": "NumberOfItemsPurchased — Quantity of the product purchased in the transaction"
},
{
"code": null,
"e": 7599,
"s": 7550,
"text": "CostPerItem — Price per each unit of the product"
},
{
"code": null,
"e": 7650,
"s": 7599,
"text": "Country — Country from which the purchase is made."
},
{
"code": null,
"e": 7692,
"s": 7650,
"text": "EDA and data cleaning is done as follows:"
},
{
"code": null,
"e": 7896,
"s": 7692,
"text": "df = df[df.UserId>0] # usedid <=0 : 25%df = df[df.ItemCode>0]df = df[df.NumberOfItemsPurchased>0]df = df[df.CostPerItem>0]df = df[df.ItemDescription.notna()]df = df[df.TransactionTime.str[-4:] != ‘2028’]"
},
{
"code": null,
"e": 7934,
"s": 7896,
"text": "The following data-frame is obtained:"
},
{
"code": null,
"e": 7939,
"s": 7934,
"text": "EDA:"
},
{
"code": null,
"e": 8053,
"s": 7939,
"text": "Lets do some exploratory data analysis now. Lets see the no. of transactions being done in each part of the year."
},
{
"code": null,
"e": 8575,
"s": 8053,
"text": "df.TransactionTime = pd.to_datetime(df.TransactionTime)df[‘month_year’]= pd.to_datetime(df.TransactionTime).dt.to_period(‘M’)df.sort_values(by = [‘month_year’], inplace = True)Ser = df.groupby(‘month_year’).TransactionId.nunique()x = np.arange(0,len(Ser),1)style.use(‘ggplot’)fig = plt.figure(figsize = (10,10))ax1 = fig.add_subplot(111)ax1.plot(x, Ser, color = ‘k’)ax1.fill_between(x, Ser, color = ‘r’, alpha = 0.5)ax1.set_xticks(x)ax1.set_xticklabels(Ser.index)plt.xlabel(‘Time period’)plt.ylabel(‘No. of transactions’)"
},
{
"code": null,
"e": 8798,
"s": 8575,
"text": "Basically we are creating a column named month_year to divide the datapoints into the month in which they occurred. Then we are taking the no. of unique transaction occurring in each month and plotting it using matplotlib."
},
{
"code": null,
"e": 8928,
"s": 8798,
"text": "As we can see the as the time advances the online retailer is getting more and more purchases which maxed in the month of Jan’19."
},
{
"code": null,
"e": 8986,
"s": 8928,
"text": "Lets explore the no. of items bought in each transaction."
},
{
"code": null,
"e": 9060,
"s": 8986,
"text": "Ser = df.groupby(‘TransactionId’).ItemDescription.nunique()Ser.describe()"
},
{
"code": null,
"e": 9169,
"s": 9060,
"text": "As we can see the min no. of items is 1 and the max is 540. So we need to plot our histogram as shown below:"
},
{
"code": null,
"e": 9378,
"s": 9169,
"text": "bins = [0,50,100,150,200,250,300,350,400,450,500,550]fig = plt.figure(figsize = (10,10))plt.hist(Ser, bins, histtype = 'bar', rwidth = 0.5)plt.xlabel('No. of items')plt.ylabel('No. of transactions')plt.show()"
},
{
"code": null,
"e": 9628,
"s": 9378,
"text": "Oops! We can see that most of the transactions include items between 0–100 and some between 100–200. The max items transactions shown above probably is an outlier or is a customer who purchases in a large scale. So we need to re-scale our histogram."
},
{
"code": null,
"e": 9911,
"s": 9628,
"text": "bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200]fig = plt.figure(figsize = (10,10))ax1 = fig.add_subplot(111)ax1.hist(Ser, bins, histtype = 'bar', rwidth = 0.5)ax1.set_xticks(bins)plt.xlabel('No. of items')plt.ylabel('No. of transactions')plt.show()"
},
{
"code": null,
"e": 9972,
"s": 9911,
"text": "As we can see most transactions included less than 10 items."
},
{
"code": null,
"e": 10237,
"s": 9972,
"text": "Lets find out the most-selling item in the market. This can be interpreted in many way such as the item which brings in the maximum revenue, items which were found in maximum no. of transactions etc. We will be considering the items which bring in maximum revenue."
},
{
"code": null,
"e": 10520,
"s": 10237,
"text": "df[‘total_cost_item’] = df.NumberOfItemsPurchased*df.CostPerItemSer = df.groupby(‘ItemDescription’).total_cost_item.sum()Ser.sort_values(ascending = False, inplace = True)Ser = Ser[:10]fig = plt.figure(figsize = (10,10))ax = fig.add_subplot(111)ax.barh(Ser.index, Ser, height = 0.5)"
},
{
"code": null,
"e": 10633,
"s": 10520,
"text": "From the above plot showing the top 10 items, we can see that the item ‘retrospot lamp’ has maximum sales value."
},
{
"code": null,
"e": 10749,
"s": 10633,
"text": "The no. of unique TransactionId’s is found to be 18334 and the no. of unique ItemDescription’s is found to be 3871."
},
{
"code": null,
"e": 10986,
"s": 10749,
"text": "Now that we have our data after all the pre-processing, lets arrange it with the TransactionId’s as the index and the ItemDescriptions as the columns with the total no. of items bought in each transaction of each item as the data-point."
},
{
"code": null,
"e": 11134,
"s": 10986,
"text": "df_set = df.groupby(['TransactionId', 'ItemDescription']).NumberOfItemsPurchased.sum().unstack().reset_index().fillna(0).set_index('TransactionId')"
},
{
"code": null,
"e": 11172,
"s": 11134,
"text": "The following data-frame is obtained:"
},
{
"code": null,
"e": 11282,
"s": 11172,
"text": "We need to make sure that any positive values are encoded to one and all the negative values(if any) to zero."
},
{
"code": null,
"e": 11370,
"s": 11282,
"text": "def encode(x): if x <= 0: return 0 else: return 1df_set = df_set.applymap(encode)df_set"
},
{
"code": null,
"e": 11468,
"s": 11370,
"text": "As the data-frame is ready we can apply Apriori algorithm to get the frequently bought item-sets."
},
{
"code": null,
"e": 11546,
"s": 11468,
"text": "frequent_itemsets = apriori(df_set, min_support = 0.015, use_colnames = True)"
},
{
"code": null,
"e": 11635,
"s": 11546,
"text": "Here the minimum threshold support value is set as 1.5%. We get the following item-sets."
},
{
"code": null,
"e": 11723,
"s": 11635,
"text": "We then arrange the itemsets in descending order of their support values which gives us"
},
{
"code": null,
"e": 12196,
"s": 11723,
"text": "frequent_itemsets = apriori(df_set, min_support = 0.015, use_colnames = True)top_items = frequent_itemsets.sort_values('support', ascending = False)[:20]for i in range(len(top_items.itemsets)): top_items.itemsets.iloc[i] = str(list(top_items.itemsets.iloc[i]))fig = plt.figure(figsize = (10,10))ax = fig.add_subplot(111)ax.bar(top_items.itemsets, top_items.support)for label in ax.xaxis.get_ticklabels(): label.set_rotation(90)plt.xlabel('Item')plt.ylabel('Support')"
},
{
"code": null,
"e": 12280,
"s": 12196,
"text": "We then apply the association rules to these item-sets formed by Apriori algorithm."
},
{
"code": null,
"e": 12369,
"s": 12280,
"text": "rules = association_rules(frequent_itemsets, metric = 'confidence', min_threshold = 0.2)"
},
{
"code": null,
"e": 12454,
"s": 12369,
"text": "The metric used here is confidence and its minimum threshold value is set to be 0.2."
},
{
"code": null,
"e": 12491,
"s": 12454,
"text": "The following data-frame is obtained"
},
{
"code": null,
"e": 12646,
"s": 12491,
"text": "All the antecedents with the corresponding consequents are listed with their individual supports, the total support of the item-set and all other metrics."
},
{
"code": null,
"e": 12716,
"s": 12646,
"text": "The summary of the rules data-frames gives us the following insights:"
},
{
"code": null,
"e": 12779,
"s": 12716,
"text": "There are a total of 187 rules.The summary of various metrics."
},
{
"code": null,
"e": 12811,
"s": 12779,
"text": "There are a total of 187 rules."
},
{
"code": null,
"e": 12843,
"s": 12811,
"text": "The summary of various metrics."
},
{
"code": null,
"e": 12897,
"s": 12843,
"text": "Lets take the top rules having the highest confidence"
},
{
"code": null,
"e": 12965,
"s": 12897,
"text": "top_rules = rules.sort_values(‘confidence’, ascending = False)[:10]"
},
{
"code": null,
"e": 13093,
"s": 12965,
"text": "fig = plt.figure(figsize = (10,10))ax = fig.add_subplot(111)ax.scatter(top_rules.support, top_rules.confidence, top_rules.lift)"
},
{
"code": null,
"e": 13124,
"s": 13093,
"text": "Plotting the rules in a graph:"
},
{
"code": null,
"e": 14210,
"s": 13124,
"text": "import networkx as nxG1 = nx.DiGraph()color_map = []N = 50colors = np.random.rand(N)strs = ['r0', 'r1', 'r2', 'r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9']for i in range(10): G1.add_nodes_from('r'+str(i)) for a in top_rules.iloc[i]['antecedents']: G1.add_nodes_from([a]) G1.add_edge(a, 'r'+str(i), color = colors[i], weight = 2) for c in top_rules.iloc[i]['consequents']: G1.add_nodes_from([c]) G1.add_edge('r'+str(i), c, color = colors[i], weight = 2)for node in G1: found_a_string = False for item in strs: if node == item: found_a_string = True if found_a_string: color_map.append('red') else: color_map.append('black')edges = G1.edges()colors = [G1[u][v]['color'] for u,v in edges]weights = [G1[u][v]['weight'] for u,v in edges]pos = nx.spring_layout(G1, k = 16, scale = 1)fig = plt.figure(figsize = (20,20))nx.draw(G1, pos, edges = edges, node_color = color_map, edge_color = colors, width = weights, font_size = 16, with_labels = False)for p in pos: pos[p][1] += 0.07nx.draw_networkx_labels(G1, pos)"
},
{
"code": null,
"e": 14385,
"s": 14210,
"text": "All these plotting and and further analysis can be done more easily in R rather than python as there are more compatible libraries for data-mining and association rules in R."
},
{
"code": null,
"e": 14519,
"s": 14385,
"text": "Further filtering of the obtained item-sets can be done using lift and confidence values (as they measure association rule strength)."
},
{
"code": null,
"e": 14608,
"s": 14519,
"text": "Here the mean value of lift and confidence are found to be 9.388 and 0.429 respectively."
},
{
"code": null,
"e": 14667,
"s": 14608,
"text": "rules[(rules.lift >= 9.388) & (rules.confidence >= 0.429)]"
},
{
"code": null,
"e": 14789,
"s": 14667,
"text": "The item-sets are filtered such that only those having the lift and confidence values above the mean values are included."
},
{
"code": null,
"e": 15042,
"s": 14789,
"text": "In this way all the required item-sets can be found. Further fine-tuning of the item-sets to find the more probable ones can be done by increasing the threshold values of support and lift. We can store the found item-sets in a csv file for furtherance."
},
{
"code": null,
"e": 15051,
"s": 15042,
"text": "Summary:"
}
] |
Pandas vs. Spark: how to handle dataframes (Part II) | by Emma Grimaldi | Towards Data Science
|
A few days ago I published a post comparing the basic commands of Python and Scala: how to deal with lists and arrays, functions, loops, dictionaries and so on. As I continue practicing with Scala, it seemed appropriate to follow-up with a second part, comparing how to handle dataframes in the two programming languages, in order to get the data ready before the modeling process. In Python, we will do all this by using Pandas library, while in Scala we will use Spark.
For this exercise, I will use the Titanic train dataset that can be easily downloaded at this link. Also, I do my Scala practices in Databricks: if you do so as well, remember to import your dataset first by clicking on Data and then Add Data.
I will import and name my dataframe df, in Python this will be just two lines of code. This will work if you saved your train.csv in the same folder where your notebook is.
import pandas as pddf = pd.read_csv('train.csv')
Scala will require more typing.
var df = sqlContext .read .format("csv") .option("header", "true") .option("inferSchema", "true") .load("Filestore/tables/train.csv")
Let’s see what’s going on up here. Scala does not assume your dataset has a header, so we need to specify that. Also, Python will assign automatically a dtype to the dataframe columns, while Scala doesn’t do so, unless we specify .option("inferSchema", "true"). Also notice that I did not import Spark Dataframe, because I practice Scala in Databricks, and it is preloaded. Otherwise we will need to do so.
Notice: booleans are capitalized in Python, while they are all lower-case in Scala!
In Python, df.head() will show the first five rows by default: the output will look like this.
If you want to see a number of rows different than five, you can just pass a different number in the parenthesis. Scala, with its df.show(),will display the first 20 rows by default.
If we want to keep it shorter, and also get rid of the ellipsis in order to read the entire content of the columns, we can run df.show(5, false).
To retrieve the column names, in both cases we can just type df.columns: Scala and Pandas will return an Array and an Index of strings, respectively.
If we want to check the dtypes, the command is again the same for both languages: df.dtypes. Pandas will return a Series object, while Scala will return an Array of tuples, each tuple containing respectively the name of the
column and the dtype. So, if we are in Python and we want to check what type is the Age column, we run df.dtypes['Age'], while in Scala we will need to filter and use the Tuple indexing: df.dtypes.filter(colTup => colTup._1 == "Age").
This is another thing that every Data Scientist does while exploring his/her data: summary statistics. For every numerical column, we can see information such as count, mean, median, deviation, so on and so forth, to see immediately if there is something that doesn’t look right. In both cases this will return a dataframe, where the columns are the numerical columns of the original dataframe, and the rows are the statistical values.
In Python, we type df.describe(), while in Scala df.describe().show(). The reason we have to add the .show() in the latter case, is because Scala doesn’t output the resulting dataframe automatically, while Python does so (as long as we don’t assign it to a new variable).
Suppose we want to see a subset of columns, for example Name and Survived.
In Python we can use either df[['Name','Survived]] or df.loc[:,['Name','Survived] indistinctly. Remember that the : in this case means “all the rows”.
In Scala, we will type df.select("Name","Survived").show(). If you want to assign the subset to a new variable, remember to omit the .show().
Let’s say we want to have a look at the Name and Pclass of the passengers who survived. We will need to filter a condition on the Survived column and then select the the other ones.
In Python, we will use .loc again, by passing the filter in the rows place and then selecting the columns with a list. Basically like the example above but substituting the : with a filter, which means df.loc[df['Survived'] == 1, ['Name','Pclass']].
In Scala we will use .filter followed by .select, which will be df.filter("Survived = 1").select("Name","Pclass").show().
If we want to check the null values, for example in the Embarked column, it will work like a normal filter, just with a different condition.
In Python, we apply the .isnull() when passing the condition, in this casedf[df['Embarked'].isnull()]. Since we didn’t specify any columns, this will return a dataframe will all the original columns, but only the rows where the Embarked values are empty.
In Scala, we will use .filter again: df.filter("Embarked IS NULL").show(). Notice that the boolean filters we pass in Scala, kind of look like SQL queries.
We should always give some thought before imputing null values in a dataset, because it is something that will influence our final model and we want to be careful with that. However, just for demonstrative purposes, let’s say we want to impute the string “N/A” to the null values in our dataframe.
We can do so in Python with either df = df.fillna('N/A') or df.fillna('N/A', inplace = True).
In Scala, quite similarly, this would be achieved with df = df.na.fill("N/A"). Remember to not use the .show() in this case, because we are assigning the revised dataframe to a variable.
This is something that you will need to for sure in Scala, since the machine learning models will need two columns named features and label in order to be trained. However, this is something you might want to do also in Pandas if you don’t like how a column has been named, for example. For this purpose, we want to change the Survived column into label.
In Python we will pass a dictionary, where the key and the value are respectively the old and the new name of the column. In this case, it will be df.rename(columns = {"Survived": "label"}, inplace = True).
In Scala, this equals to df = df.withColumnRenamed("Survived", "label").
Let’s say we want to calculate the maximum Age for men and women distinctively, in this case .groubpby comes in handy. Not only to retrieve the maximum value; after .groupby we can use all sorts of aggregation functions: mean, count, median, so on and so forth. We stick with .max() for this example.
In Python this will be df.groupby('Sex').mean()['Age']. If we don’t specify ['Age'] after .mean(), this will return a dataframe with the maximum values for all numerical columns, grouped by Sex.
In Scala, we will need to import the aggregation function we want to use, first.
import org.apache.spark.sql.functions.maxdf.groupBy("Sex").agg(max("Age")).show()
This is really useful for feature engineering, we might want to combine two variables to see how their interaction is related to the target. For purely demonstrative purpose, let’s see how to create a column containing the product between Age and Fare.
In Python it is pretty straightforward.
df['Age_times_Fare'] = df['Age'] * df['Fare']
In Scala, we will need to put $ before the names of the columns we want to use, so that the column object with the corresponding name will be considered.
df = df.withColumn("AgeTimesFare", $"Age" * $"Fare")
Exploring correlation among numerical variables and target is always convenient, and obtaining a matrix of correlation coefficients among all numeric variables is pretty easy in Python, just by running df.corr(). If you want to look at the correlation, let’s say between Age and Fare, we will just need to specify the columns: df[['Age','Fare']].corr().
In Scala, we will need to import first, and then run the command by specifying the columns.
import org.apache.spark.sql.functions.corrdf.select(corr("Age","Fare")).show()
This is it! I hope you found this post useful as much as it has been useful for me writing it. I intend to publish a Part III where I can walk through a machine learning model example to kind of complete the circle!
Feel free to check out:
part I of this post.
my other Medium posts.
my LinkedIn profile.
Thank you for reading!
|
[
{
"code": null,
"e": 644,
"s": 172,
"text": "A few days ago I published a post comparing the basic commands of Python and Scala: how to deal with lists and arrays, functions, loops, dictionaries and so on. As I continue practicing with Scala, it seemed appropriate to follow-up with a second part, comparing how to handle dataframes in the two programming languages, in order to get the data ready before the modeling process. In Python, we will do all this by using Pandas library, while in Scala we will use Spark."
},
{
"code": null,
"e": 888,
"s": 644,
"text": "For this exercise, I will use the Titanic train dataset that can be easily downloaded at this link. Also, I do my Scala practices in Databricks: if you do so as well, remember to import your dataset first by clicking on Data and then Add Data."
},
{
"code": null,
"e": 1061,
"s": 888,
"text": "I will import and name my dataframe df, in Python this will be just two lines of code. This will work if you saved your train.csv in the same folder where your notebook is."
},
{
"code": null,
"e": 1110,
"s": 1061,
"text": "import pandas as pddf = pd.read_csv('train.csv')"
},
{
"code": null,
"e": 1142,
"s": 1110,
"text": "Scala will require more typing."
},
{
"code": null,
"e": 1291,
"s": 1142,
"text": "var df = sqlContext .read .format(\"csv\") .option(\"header\", \"true\") .option(\"inferSchema\", \"true\") .load(\"Filestore/tables/train.csv\")"
},
{
"code": null,
"e": 1698,
"s": 1291,
"text": "Let’s see what’s going on up here. Scala does not assume your dataset has a header, so we need to specify that. Also, Python will assign automatically a dtype to the dataframe columns, while Scala doesn’t do so, unless we specify .option(\"inferSchema\", \"true\"). Also notice that I did not import Spark Dataframe, because I practice Scala in Databricks, and it is preloaded. Otherwise we will need to do so."
},
{
"code": null,
"e": 1782,
"s": 1698,
"text": "Notice: booleans are capitalized in Python, while they are all lower-case in Scala!"
},
{
"code": null,
"e": 1877,
"s": 1782,
"text": "In Python, df.head() will show the first five rows by default: the output will look like this."
},
{
"code": null,
"e": 2060,
"s": 1877,
"text": "If you want to see a number of rows different than five, you can just pass a different number in the parenthesis. Scala, with its df.show(),will display the first 20 rows by default."
},
{
"code": null,
"e": 2206,
"s": 2060,
"text": "If we want to keep it shorter, and also get rid of the ellipsis in order to read the entire content of the columns, we can run df.show(5, false)."
},
{
"code": null,
"e": 2356,
"s": 2206,
"text": "To retrieve the column names, in both cases we can just type df.columns: Scala and Pandas will return an Array and an Index of strings, respectively."
},
{
"code": null,
"e": 2580,
"s": 2356,
"text": "If we want to check the dtypes, the command is again the same for both languages: df.dtypes. Pandas will return a Series object, while Scala will return an Array of tuples, each tuple containing respectively the name of the"
},
{
"code": null,
"e": 2815,
"s": 2580,
"text": "column and the dtype. So, if we are in Python and we want to check what type is the Age column, we run df.dtypes['Age'], while in Scala we will need to filter and use the Tuple indexing: df.dtypes.filter(colTup => colTup._1 == \"Age\")."
},
{
"code": null,
"e": 3251,
"s": 2815,
"text": "This is another thing that every Data Scientist does while exploring his/her data: summary statistics. For every numerical column, we can see information such as count, mean, median, deviation, so on and so forth, to see immediately if there is something that doesn’t look right. In both cases this will return a dataframe, where the columns are the numerical columns of the original dataframe, and the rows are the statistical values."
},
{
"code": null,
"e": 3523,
"s": 3251,
"text": "In Python, we type df.describe(), while in Scala df.describe().show(). The reason we have to add the .show() in the latter case, is because Scala doesn’t output the resulting dataframe automatically, while Python does so (as long as we don’t assign it to a new variable)."
},
{
"code": null,
"e": 3598,
"s": 3523,
"text": "Suppose we want to see a subset of columns, for example Name and Survived."
},
{
"code": null,
"e": 3749,
"s": 3598,
"text": "In Python we can use either df[['Name','Survived]] or df.loc[:,['Name','Survived] indistinctly. Remember that the : in this case means “all the rows”."
},
{
"code": null,
"e": 3891,
"s": 3749,
"text": "In Scala, we will type df.select(\"Name\",\"Survived\").show(). If you want to assign the subset to a new variable, remember to omit the .show()."
},
{
"code": null,
"e": 4073,
"s": 3891,
"text": "Let’s say we want to have a look at the Name and Pclass of the passengers who survived. We will need to filter a condition on the Survived column and then select the the other ones."
},
{
"code": null,
"e": 4323,
"s": 4073,
"text": "In Python, we will use .loc again, by passing the filter in the rows place and then selecting the columns with a list. Basically like the example above but substituting the : with a filter, which means df.loc[df['Survived'] == 1, ['Name','Pclass']]."
},
{
"code": null,
"e": 4445,
"s": 4323,
"text": "In Scala we will use .filter followed by .select, which will be df.filter(\"Survived = 1\").select(\"Name\",\"Pclass\").show()."
},
{
"code": null,
"e": 4586,
"s": 4445,
"text": "If we want to check the null values, for example in the Embarked column, it will work like a normal filter, just with a different condition."
},
{
"code": null,
"e": 4841,
"s": 4586,
"text": "In Python, we apply the .isnull() when passing the condition, in this casedf[df['Embarked'].isnull()]. Since we didn’t specify any columns, this will return a dataframe will all the original columns, but only the rows where the Embarked values are empty."
},
{
"code": null,
"e": 4997,
"s": 4841,
"text": "In Scala, we will use .filter again: df.filter(\"Embarked IS NULL\").show(). Notice that the boolean filters we pass in Scala, kind of look like SQL queries."
},
{
"code": null,
"e": 5295,
"s": 4997,
"text": "We should always give some thought before imputing null values in a dataset, because it is something that will influence our final model and we want to be careful with that. However, just for demonstrative purposes, let’s say we want to impute the string “N/A” to the null values in our dataframe."
},
{
"code": null,
"e": 5389,
"s": 5295,
"text": "We can do so in Python with either df = df.fillna('N/A') or df.fillna('N/A', inplace = True)."
},
{
"code": null,
"e": 5576,
"s": 5389,
"text": "In Scala, quite similarly, this would be achieved with df = df.na.fill(\"N/A\"). Remember to not use the .show() in this case, because we are assigning the revised dataframe to a variable."
},
{
"code": null,
"e": 5931,
"s": 5576,
"text": "This is something that you will need to for sure in Scala, since the machine learning models will need two columns named features and label in order to be trained. However, this is something you might want to do also in Pandas if you don’t like how a column has been named, for example. For this purpose, we want to change the Survived column into label."
},
{
"code": null,
"e": 6138,
"s": 5931,
"text": "In Python we will pass a dictionary, where the key and the value are respectively the old and the new name of the column. In this case, it will be df.rename(columns = {\"Survived\": \"label\"}, inplace = True)."
},
{
"code": null,
"e": 6211,
"s": 6138,
"text": "In Scala, this equals to df = df.withColumnRenamed(\"Survived\", \"label\")."
},
{
"code": null,
"e": 6512,
"s": 6211,
"text": "Let’s say we want to calculate the maximum Age for men and women distinctively, in this case .groubpby comes in handy. Not only to retrieve the maximum value; after .groupby we can use all sorts of aggregation functions: mean, count, median, so on and so forth. We stick with .max() for this example."
},
{
"code": null,
"e": 6707,
"s": 6512,
"text": "In Python this will be df.groupby('Sex').mean()['Age']. If we don’t specify ['Age'] after .mean(), this will return a dataframe with the maximum values for all numerical columns, grouped by Sex."
},
{
"code": null,
"e": 6788,
"s": 6707,
"text": "In Scala, we will need to import the aggregation function we want to use, first."
},
{
"code": null,
"e": 6870,
"s": 6788,
"text": "import org.apache.spark.sql.functions.maxdf.groupBy(\"Sex\").agg(max(\"Age\")).show()"
},
{
"code": null,
"e": 7123,
"s": 6870,
"text": "This is really useful for feature engineering, we might want to combine two variables to see how their interaction is related to the target. For purely demonstrative purpose, let’s see how to create a column containing the product between Age and Fare."
},
{
"code": null,
"e": 7163,
"s": 7123,
"text": "In Python it is pretty straightforward."
},
{
"code": null,
"e": 7209,
"s": 7163,
"text": "df['Age_times_Fare'] = df['Age'] * df['Fare']"
},
{
"code": null,
"e": 7363,
"s": 7209,
"text": "In Scala, we will need to put $ before the names of the columns we want to use, so that the column object with the corresponding name will be considered."
},
{
"code": null,
"e": 7416,
"s": 7363,
"text": "df = df.withColumn(\"AgeTimesFare\", $\"Age\" * $\"Fare\")"
},
{
"code": null,
"e": 7770,
"s": 7416,
"text": "Exploring correlation among numerical variables and target is always convenient, and obtaining a matrix of correlation coefficients among all numeric variables is pretty easy in Python, just by running df.corr(). If you want to look at the correlation, let’s say between Age and Fare, we will just need to specify the columns: df[['Age','Fare']].corr()."
},
{
"code": null,
"e": 7862,
"s": 7770,
"text": "In Scala, we will need to import first, and then run the command by specifying the columns."
},
{
"code": null,
"e": 7941,
"s": 7862,
"text": "import org.apache.spark.sql.functions.corrdf.select(corr(\"Age\",\"Fare\")).show()"
},
{
"code": null,
"e": 8157,
"s": 7941,
"text": "This is it! I hope you found this post useful as much as it has been useful for me writing it. I intend to publish a Part III where I can walk through a machine learning model example to kind of complete the circle!"
},
{
"code": null,
"e": 8181,
"s": 8157,
"text": "Feel free to check out:"
},
{
"code": null,
"e": 8202,
"s": 8181,
"text": "part I of this post."
},
{
"code": null,
"e": 8225,
"s": 8202,
"text": "my other Medium posts."
},
{
"code": null,
"e": 8246,
"s": 8225,
"text": "my LinkedIn profile."
}
] |
Difference between count(*) and count(columnName) in MySQL?
|
The count(*) returns all rows whether column contains null value or not while count(columnName) returns the number of rows except null rows.
Let us first create a table.
Following is the query
mysql> create table ifNotNullDemo
-> (
-> Name varchar(20)
-> );
Query OK, 0 rows affected (0.54 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into ifNotNullDemo values('Chris');
Query OK, 1 row affected (0.15 sec)
mysql> insert into ifNotNullDemo values('');
Query OK, 1 row affected (0.13 sec)
mysql> insert into ifNotNullDemo values('Robert');
Query OK, 1 row affected (0.24 sec)
mysql> insert into ifNotNullDemo values(null);
Query OK, 1 row affected (0.30 sec)
mysql> insert into ifNotNullDemo values(0);
Query OK, 1 row affected (0.16 sec)
Following is the query to display all records from the table using select statement:
mysql> select *from ifNotNullDemo;
This will produce the following output
+--------+
| Name |
+--------+
| Chris |
| |
| Robert |
| NULL |
| 0 |
+--------+
5 rows in set (0.00 sec)
Case 1: Following is the demo of count(*) that includes null as well in the count:
mysql> select count(*) from ifNotNullDemo;
This will produce the following output
+----------+
| count(*) |
+----------+
| 5 |
+----------+
1 row in set (0.02 sec)
Case 2: Following is the query for count(columnName).
mysql> select count(Name) from ifNotNullDemo;
This will produce the following output
+-------------+
| count(Name) |
+-------------+
| 4 |
+-------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "The count(*) returns all rows whether column contains null value or not while count(columnName) returns the number of rows except null rows."
},
{
"code": null,
"e": 1232,
"s": 1203,
"text": "Let us first create a table."
},
{
"code": null,
"e": 1255,
"s": 1232,
"text": "Following is the query"
},
{
"code": null,
"e": 1366,
"s": 1255,
"text": "mysql> create table ifNotNullDemo\n -> (\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.54 sec)"
},
{
"code": null,
"e": 1447,
"s": 1366,
"text": "Following is the query to insert some records in the table using insert command:"
},
{
"code": null,
"e": 1868,
"s": 1447,
"text": "mysql> insert into ifNotNullDemo values('Chris');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into ifNotNullDemo values('');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into ifNotNullDemo values('Robert');\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into ifNotNullDemo values(null);\nQuery OK, 1 row affected (0.30 sec)\n\nmysql> insert into ifNotNullDemo values(0);\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1953,
"s": 1868,
"text": "Following is the query to display all records from the table using select statement:"
},
{
"code": null,
"e": 1988,
"s": 1953,
"text": "mysql> select *from ifNotNullDemo;"
},
{
"code": null,
"e": 2027,
"s": 1988,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2151,
"s": 2027,
"text": "+--------+\n| Name |\n+--------+\n| Chris |\n| |\n| Robert |\n| NULL |\n| 0 |\n+--------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2234,
"s": 2151,
"text": "Case 1: Following is the demo of count(*) that includes null as well in the count:"
},
{
"code": null,
"e": 2277,
"s": 2234,
"text": "mysql> select count(*) from ifNotNullDemo;"
},
{
"code": null,
"e": 2316,
"s": 2277,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2405,
"s": 2316,
"text": "+----------+\n| count(*) |\n+----------+\n| 5 |\n+----------+\n1 row in set (0.02 sec)"
},
{
"code": null,
"e": 2459,
"s": 2405,
"text": "Case 2: Following is the query for count(columnName)."
},
{
"code": null,
"e": 2505,
"s": 2459,
"text": "mysql> select count(Name) from ifNotNullDemo;"
},
{
"code": null,
"e": 2544,
"s": 2505,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2648,
"s": 2544,
"text": "+-------------+\n| count(Name) |\n+-------------+\n| 4 |\n+-------------+\n1 row in set (0.00 sec)"
}
] |
Asynchronous Operations
|
In this chapter, we will learn how to test asynchronous operations using Espresso Idling Resources.
One of the challenges of the modern application is to provide smooth user experience. Providing smooth user experience involves lot of work in the background to make sure that the application process does not take longer than few milliseconds. Background task ranges from the simple one to costly and complex task of fetching data from remote API / database. To encounter the challenge in the past, a developer used to write costly and long running task in a background thread and sync up with the main UIThread once background thread is completed.
If developing a multi-threaded application is complex, then writing test cases for it is even more complex. For example, we should not test an AdapterView before the necessary data is loaded from the database. If fetching the data is done in a separate thread, the test needs to wait until the thread completes. So, the test environment should be synced between background thread and UI thread. Espresso provides an excellent support for testing the multi-threaded application. An application uses thread in the following ways and espresso supports every scenario.
It is internally used by android SDK to provide smooth user experience with complex UI elements. Espresso supports this scenario transparently and does not need any configuration and special coding.
Modern programming languages support async programming to do light weight threading without the complexity of thread programming. Async task is also supported transparently by espresso framework.
A developer may start a new thread to fetch complex or large data from database. To support this scenario, espresso provides idling resource concept.
Let use learn the concept of idling resource and how to to it in this chapter.
The concept of idling resource is very simple and intuitive. The basic idea is to create a variable (boolean value) whenever a long running process is started in a separate thread to identify whether the process is running or not and register it in the testing environment. During testing, the test runner will check the registered variable, if any found and then find its running status. If the running status is true, test runner will wait until the status become false.
Espresso provides an interface, IdlingResources for the purpose of maintaining the running status. The main method to implement is isIdleNow(). If isIdleNow() returns true, espresso will resume the testing process or else wait until isIdleNow() returns false. We need to implement IdlingResources and use the derived class. Espresso also provides some of the built-in IdlingResources implementation to ease our workload. They are as follows,
This maintains an internal counter of running task. It exposes increment() and decrement() methods. increment() adds one to the counter and decrement() removes one from the counter. isIdleNow() returns true only when no task is active.
This is similar to CounintIdlingResource except that the counter needs to be zero for extended period to take the network latency as well.
This is a custom implementation of ThreadPoolExecutor to maintain the number active running task in the current thread pool.
This is similar to IdlingThreadPoolExecutor, but it schedules a task as well and a custom implementation of ScheduledThreadPoolExecutor.
If any one of the above implementation of IdlingResources or a custom one is used in the application, we need to register it to the testing environment as well before testing the application using IdlingRegistry class as below,
IdlingRegistry.getInstance().register(MyIdlingResource.getIdlingResource());
Moreover, it can be removed once testing is completed as below −
IdlingRegistry.getInstance().unregister(MyIdlingResource.getIdlingResource());
Espresso provides this functionality in a separate package, and the package needs to be configured as below in the app.gradle.
dependencies {
implementation 'androidx.test.espresso:espresso-idling-resource:3.1.1'
androidTestImplementation "androidx.test.espresso.idling:idlingconcurrent:3.1.1"
}
Let us create a simple application to list the fruits by fetching it from a web service in a separate thread and then, test it using idling resource concept.
Start Android studio.
Start Android studio.
Create new project as discussed earlier and name it, MyIdlingFruitApp
Create new project as discussed earlier and name it, MyIdlingFruitApp
Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu.
Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu.
Add espresso idling resource library in the app/build.gradle (and sync it) as specified below,
Add espresso idling resource library in the app/build.gradle (and sync it) as specified below,
dependencies {
implementation 'androidx.test.espresso:espresso-idling-resource:3.1.1'
androidTestImplementation "androidx.test.espresso.idling:idlingconcurrent:3.1.1"
}
Remove the default design in the main activity and add ListView. The content of the activity_main.xml is as follows,
Remove the default design in the main activity and add ListView. The content of the activity_main.xml is as follows,
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<ListView
android:id = "@+id/listView"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</RelativeLayout>
Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows,
Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows,
<?xml version = "1.0" encoding = "utf-8"?>
<TextView xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/name"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:padding = "8dp"
/>
Create a new class – MyIdlingResource. MyIdlingResource is used to hold our IdlingResource in one place and fetch it whenever necessary. We are going to use CountingIdlingResource in our example.
Create a new class – MyIdlingResource. MyIdlingResource is used to hold our IdlingResource in one place and fetch it whenever necessary. We are going to use CountingIdlingResource in our example.
package com.tutorialspoint.espressosamples.myidlingfruitapp;
import androidx.test.espresso.IdlingResource;
import androidx.test.espresso.idling.CountingIdlingResource;
public class MyIdlingResource {
private static CountingIdlingResource mCountingIdlingResource =
new CountingIdlingResource("my_idling_resource");
public static void increment() {
mCountingIdlingResource.increment();
}
public static void decrement() {
mCountingIdlingResource.decrement();
}
public static IdlingResource getIdlingResource() {
return mCountingIdlingResource;
}
}
Declare a global variable, mIdlingResource of type CountingIdlingResource in the MainActivity class as below,
Declare a global variable, mIdlingResource of type CountingIdlingResource in the MainActivity class as below,
@Nullable
private CountingIdlingResource mIdlingResource = null;
Write a private method to fetch fruit list from the web as below,
Write a private method to fetch fruit list from the web as below,
private ArrayList<String> getFruitList(String data) {
ArrayList<String> fruits = new ArrayList<String>();
try {
// Get url from async task and set it into a local variable
URL url = new URL(data);
Log.e("URL", url.toString());
// Create new HTTP connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set HTTP connection method as "Get"
conn.setRequestMethod("GET");
// Do a http request and get the response code
int responseCode = conn.getResponseCode();
// check the response code and if success, get response content
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
JSONArray jsonArray = new JSONArray(response.toString());
Log.e("HTTPResponse", response.toString());
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = String.valueOf(jsonObject.getString("name"));
fruits.add(name);
}
} else {
throw new IOException("Unable to fetch data from url");
}
conn.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return fruits;
}
Create a new task in the onCreate() method to fetch the data from the web using our getFruitList method followed by the creation of a new adapter and setting it out to list view. Also, decrement the idling resource once our work is completed in the thread. The code is as follows,
Create a new task in the onCreate() method to fetch the data from the web using our getFruitList method followed by the creation of a new adapter and setting it out to list view. Also, decrement the idling resource once our work is completed in the thread. The code is as follows,
// Get data
class FruitTask implements Runnable {
ListView listView;
CountingIdlingResource idlingResource;
FruitTask(CountingIdlingResource idlingRes, ListView listView) {
this.listView = listView;
this.idlingResource = idlingRes;
}
public void run() {
//code to do the HTTP request
final ArrayList<String> fruitList = getFruitList("http://<your domain or IP>/fruits.json");
try {
synchronized (this){
runOnUiThread(new Runnable() {
@Override
public void run() {
// Create adapter and set it to list view
final ArrayAdapter adapter = new
ArrayAdapter(MainActivity.this, R.layout.item, fruitList);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
if (!MyIdlingResource.getIdlingResource().isIdleNow()) {
MyIdlingResource.decrement(); // Set app as idle.
}
}
}
Here, the fruit url is considered as http://<your domain or IP/fruits.json and it is formated as JSON. The content is as follows,
[
{
"name":"Apple"
},
{
"name":"Banana"
},
{
"name":"Cherry"
},
{
"name":"Dates"
},
{
"name":"Elderberry"
},
{
"name":"Fig"
},
{
"name":"Grapes"
},
{
"name":"Grapefruit"
},
{
"name":"Guava"
},
{
"name":"Jack fruit"
},
{
"name":"Lemon"
},
{
"name":"Mango"
},
{
"name":"Orange"
},
{
"name":"Papaya"
},
{
"name":"Pears"
},
{
"name":"Peaches"
},
{
"name":"Pineapple"
},
{
"name":"Plums"
},
{
"name":"Raspberry"
},
{
"name":"Strawberry"
},
{
"name":"Watermelon"
}
]
Note − Place the file in your local web server and use it.
Now, find the view, create a new thread by passing FruitTask, increment the idling resource and finally start the task.
Now, find the view, create a new thread by passing FruitTask, increment the idling resource and finally start the task.
// Find list view
ListView listView = (ListView) findViewById(R.id.listView);
Thread fruitTask = new Thread(new FruitTask(this.mIdlingResource, listView));
MyIdlingResource.increment();
fruitTask.start();
The complete code of MainActivity is as follows,
The complete code of MainActivity is as follows,
package com.tutorialspoint.espressosamples.myidlingfruitapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.AppCompatActivity;
import androidx.test.espresso.idling.CountingIdlingResource;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Nullable
private CountingIdlingResource mIdlingResource = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get data
class FruitTask implements Runnable {
ListView listView;
CountingIdlingResource idlingResource;
FruitTask(CountingIdlingResource idlingRes, ListView listView) {
this.listView = listView;
this.idlingResource = idlingRes;
}
public void run() {
//code to do the HTTP request
final ArrayList<String> fruitList = getFruitList(
"http://<yourdomain or IP>/fruits.json");
try {
synchronized (this){
runOnUiThread(new Runnable() {
@Override
public void run() {
// Create adapter and set it to list view
final ArrayAdapter adapter = new ArrayAdapter(
MainActivity.this, R.layout.item, fruitList);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
if (!MyIdlingResource.getIdlingResource().isIdleNow()) {
MyIdlingResource.decrement(); // Set app as idle.
}
}
}
// Find list view
ListView listView = (ListView) findViewById(R.id.listView);
Thread fruitTask = new Thread(new FruitTask(this.mIdlingResource, listView));
MyIdlingResource.increment();
fruitTask.start();
}
private ArrayList<String> getFruitList(String data) {
ArrayList<String> fruits = new ArrayList<String>();
try {
// Get url from async task and set it into a local variable
URL url = new URL(data);
Log.e("URL", url.toString());
// Create new HTTP connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set HTTP connection method as "Get"
conn.setRequestMethod("GET");
// Do a http request and get the response code
int responseCode = conn.getResponseCode();
// check the response code and if success, get response content
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
JSONArray jsonArray = new JSONArray(response.toString());
Log.e("HTTPResponse", response.toString());
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = String.valueOf(jsonObject.getString("name"));
fruits.add(name);
}
} else {
throw new IOException("Unable to fetch data from url");
}
conn.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return fruits;
}
}
Now, add below configuration in the application manifest file, AndroidManifest.xml
Now, add below configuration in the application manifest file, AndroidManifest.xml
<uses-permission android:name = "android.permission.INTERNET" />
Now, compile the above code and run the application. The screenshot of the My Idling Fruit App is as follows,
Now, compile the above code and run the application. The screenshot of the My Idling Fruit App is as follows,
Now, open the ExampleInstrumentedTest.java file and add ActivityTestRule as specified below,
Now, open the ExampleInstrumentedTest.java file and add ActivityTestRule as specified below,
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<MainActivity>(MainActivity.class);
Also, make sure the test configuration is done in app/build.gradle
dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test:rules:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'androidx.test.espresso:espresso-idling-resource:3.1.1'
androidTestImplementation "androidx.test.espresso.idling:idlingconcurrent:3.1.1"
}
Add a new test case to test the list view as below,
Add a new test case to test the list view as below,
@Before
public void registerIdlingResource() {
IdlingRegistry.getInstance().register(MyIdlingResource.getIdlingResource());
}
@Test
public void contentTest() {
// click a child item
onData(allOf())
.inAdapterView(withId(R.id.listView))
.atPosition(10)
.perform(click());
}
@After
public void unregisterIdlingResource() {
IdlingRegistry.getInstance().unregister(MyIdlingResource.getIdlingResource());
}
Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding.
Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding.
17 Lectures
1.5 hours
Anuja Jain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2076,
"s": 1976,
"text": "In this chapter, we will learn how to test asynchronous operations using Espresso Idling Resources."
},
{
"code": null,
"e": 2625,
"s": 2076,
"text": "One of the challenges of the modern application is to provide smooth user experience. Providing smooth user experience involves lot of work in the background to make sure that the application process does not take longer than few milliseconds. Background task ranges from the simple one to costly and complex task of fetching data from remote API / database. To encounter the challenge in the past, a developer used to write costly and long running task in a background thread and sync up with the main UIThread once background thread is completed."
},
{
"code": null,
"e": 3190,
"s": 2625,
"text": "If developing a multi-threaded application is complex, then writing test cases for it is even more complex. For example, we should not test an AdapterView before the necessary data is loaded from the database. If fetching the data is done in a separate thread, the test needs to wait until the thread completes. So, the test environment should be synced between background thread and UI thread. Espresso provides an excellent support for testing the multi-threaded application. An application uses thread in the following ways and espresso supports every scenario."
},
{
"code": null,
"e": 3389,
"s": 3190,
"text": "It is internally used by android SDK to provide smooth user experience with complex UI elements. Espresso supports this scenario transparently and does not need any configuration and special coding."
},
{
"code": null,
"e": 3585,
"s": 3389,
"text": "Modern programming languages support async programming to do light weight threading without the complexity of thread programming. Async task is also supported transparently by espresso framework."
},
{
"code": null,
"e": 3735,
"s": 3585,
"text": "A developer may start a new thread to fetch complex or large data from database. To support this scenario, espresso provides idling resource concept."
},
{
"code": null,
"e": 3814,
"s": 3735,
"text": "Let use learn the concept of idling resource and how to to it in this chapter."
},
{
"code": null,
"e": 4287,
"s": 3814,
"text": "The concept of idling resource is very simple and intuitive. The basic idea is to create a variable (boolean value) whenever a long running process is started in a separate thread to identify whether the process is running or not and register it in the testing environment. During testing, the test runner will check the registered variable, if any found and then find its running status. If the running status is true, test runner will wait until the status become false."
},
{
"code": null,
"e": 4729,
"s": 4287,
"text": "Espresso provides an interface, IdlingResources for the purpose of maintaining the running status. The main method to implement is isIdleNow(). If isIdleNow() returns true, espresso will resume the testing process or else wait until isIdleNow() returns false. We need to implement IdlingResources and use the derived class. Espresso also provides some of the built-in IdlingResources implementation to ease our workload. They are as follows,"
},
{
"code": null,
"e": 4965,
"s": 4729,
"text": "This maintains an internal counter of running task. It exposes increment() and decrement() methods. increment() adds one to the counter and decrement() removes one from the counter. isIdleNow() returns true only when no task is active."
},
{
"code": null,
"e": 5104,
"s": 4965,
"text": "This is similar to CounintIdlingResource except that the counter needs to be zero for extended period to take the network latency as well."
},
{
"code": null,
"e": 5229,
"s": 5104,
"text": "This is a custom implementation of ThreadPoolExecutor to maintain the number active running task in the current thread pool."
},
{
"code": null,
"e": 5366,
"s": 5229,
"text": "This is similar to IdlingThreadPoolExecutor, but it schedules a task as well and a custom implementation of ScheduledThreadPoolExecutor."
},
{
"code": null,
"e": 5594,
"s": 5366,
"text": "If any one of the above implementation of IdlingResources or a custom one is used in the application, we need to register it to the testing environment as well before testing the application using IdlingRegistry class as below,"
},
{
"code": null,
"e": 5672,
"s": 5594,
"text": "IdlingRegistry.getInstance().register(MyIdlingResource.getIdlingResource());\n"
},
{
"code": null,
"e": 5737,
"s": 5672,
"text": "Moreover, it can be removed once testing is completed as below −"
},
{
"code": null,
"e": 5817,
"s": 5737,
"text": "IdlingRegistry.getInstance().unregister(MyIdlingResource.getIdlingResource());\n"
},
{
"code": null,
"e": 5944,
"s": 5817,
"text": "Espresso provides this functionality in a separate package, and the package needs to be configured as below in the app.gradle."
},
{
"code": null,
"e": 6120,
"s": 5944,
"text": "dependencies {\n implementation 'androidx.test.espresso:espresso-idling-resource:3.1.1'\n androidTestImplementation \"androidx.test.espresso.idling:idlingconcurrent:3.1.1\"\n}\n"
},
{
"code": null,
"e": 6278,
"s": 6120,
"text": "Let us create a simple application to list the fruits by fetching it from a web service in a separate thread and then, test it using idling resource concept."
},
{
"code": null,
"e": 6300,
"s": 6278,
"text": "Start Android studio."
},
{
"code": null,
"e": 6322,
"s": 6300,
"text": "Start Android studio."
},
{
"code": null,
"e": 6392,
"s": 6322,
"text": "Create new project as discussed earlier and name it, MyIdlingFruitApp"
},
{
"code": null,
"e": 6462,
"s": 6392,
"text": "Create new project as discussed earlier and name it, MyIdlingFruitApp"
},
{
"code": null,
"e": 6558,
"s": 6462,
"text": "Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu."
},
{
"code": null,
"e": 6654,
"s": 6558,
"text": "Migrate the application to AndroidX framework using Refactor → Migrate to AndroidX option menu."
},
{
"code": null,
"e": 6749,
"s": 6654,
"text": "Add espresso idling resource library in the app/build.gradle (and sync it) as specified below,"
},
{
"code": null,
"e": 6844,
"s": 6749,
"text": "Add espresso idling resource library in the app/build.gradle (and sync it) as specified below,"
},
{
"code": null,
"e": 7019,
"s": 6844,
"text": "dependencies {\n implementation 'androidx.test.espresso:espresso-idling-resource:3.1.1'\n androidTestImplementation \"androidx.test.espresso.idling:idlingconcurrent:3.1.1\"\n}"
},
{
"code": null,
"e": 7136,
"s": 7019,
"text": "Remove the default design in the main activity and add ListView. The content of the activity_main.xml is as follows,"
},
{
"code": null,
"e": 7253,
"s": 7136,
"text": "Remove the default design in the main activity and add ListView. The content of the activity_main.xml is as follows,"
},
{
"code": null,
"e": 7759,
"s": 7253,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <ListView\n android:id = \"@+id/listView\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 7883,
"s": 7759,
"text": "Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows,"
},
{
"code": null,
"e": 8007,
"s": 7883,
"text": "Add new layout resource, item.xml to specify the item template of the list view. The content of the item.xml is as follows,"
},
{
"code": null,
"e": 8260,
"s": 8007,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<TextView xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/name\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"fill_parent\"\n android:padding = \"8dp\"\n/>"
},
{
"code": null,
"e": 8456,
"s": 8260,
"text": "Create a new class – MyIdlingResource. MyIdlingResource is used to hold our IdlingResource in one place and fetch it whenever necessary. We are going to use CountingIdlingResource in our example."
},
{
"code": null,
"e": 8652,
"s": 8456,
"text": "Create a new class – MyIdlingResource. MyIdlingResource is used to hold our IdlingResource in one place and fetch it whenever necessary. We are going to use CountingIdlingResource in our example."
},
{
"code": null,
"e": 9243,
"s": 8652,
"text": "package com.tutorialspoint.espressosamples.myidlingfruitapp;\nimport androidx.test.espresso.IdlingResource;\nimport androidx.test.espresso.idling.CountingIdlingResource;\n\npublic class MyIdlingResource {\n private static CountingIdlingResource mCountingIdlingResource =\n new CountingIdlingResource(\"my_idling_resource\");\n public static void increment() {\n mCountingIdlingResource.increment();\n }\n public static void decrement() {\n mCountingIdlingResource.decrement();\n }\n public static IdlingResource getIdlingResource() {\n return mCountingIdlingResource;\n }\n}"
},
{
"code": null,
"e": 9353,
"s": 9243,
"text": "Declare a global variable, mIdlingResource of type CountingIdlingResource in the MainActivity class as below,"
},
{
"code": null,
"e": 9463,
"s": 9353,
"text": "Declare a global variable, mIdlingResource of type CountingIdlingResource in the MainActivity class as below,"
},
{
"code": null,
"e": 9529,
"s": 9463,
"text": "@Nullable\nprivate CountingIdlingResource mIdlingResource = null;\n"
},
{
"code": null,
"e": 9595,
"s": 9529,
"text": "Write a private method to fetch fruit list from the web as below,"
},
{
"code": null,
"e": 9661,
"s": 9595,
"text": "Write a private method to fetch fruit list from the web as below,"
},
{
"code": null,
"e": 11206,
"s": 9661,
"text": "private ArrayList<String> getFruitList(String data) {\n ArrayList<String> fruits = new ArrayList<String>();\n try {\n // Get url from async task and set it into a local variable\n URL url = new URL(data);\n Log.e(\"URL\", url.toString());\n \n // Create new HTTP connection\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n \n // Set HTTP connection method as \"Get\"\n conn.setRequestMethod(\"GET\");\n \n // Do a http request and get the response code\n int responseCode = conn.getResponseCode();\n \n // check the response code and if success, get response content\n if (responseCode == HttpURLConnection.HTTP_OK) {\n BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));\n String line;\n StringBuffer response = new StringBuffer();\n while ((line = in.readLine()) != null) {\n response.append(line);\n }\n in.close();\n JSONArray jsonArray = new JSONArray(response.toString());\n Log.e(\"HTTPResponse\", response.toString());\n for(int i = 0; i < jsonArray.length(); i++) {\n JSONObject jsonObject = jsonArray.getJSONObject(i);\n String name = String.valueOf(jsonObject.getString(\"name\"));\n fruits.add(name);\n }\n } else {\n throw new IOException(\"Unable to fetch data from url\");\n }\n conn.disconnect();\n } catch (IOException | JSONException e) {\n e.printStackTrace();\n }\n return fruits;\n}"
},
{
"code": null,
"e": 11487,
"s": 11206,
"text": "Create a new task in the onCreate() method to fetch the data from the web using our getFruitList method followed by the creation of a new adapter and setting it out to list view. Also, decrement the idling resource once our work is completed in the thread. The code is as follows,"
},
{
"code": null,
"e": 11768,
"s": 11487,
"text": "Create a new task in the onCreate() method to fetch the data from the web using our getFruitList method followed by the creation of a new adapter and setting it out to list view. Also, decrement the idling resource once our work is completed in the thread. The code is as follows,"
},
{
"code": null,
"e": 12894,
"s": 11768,
"text": "// Get data\nclass FruitTask implements Runnable {\n ListView listView;\n CountingIdlingResource idlingResource;\n FruitTask(CountingIdlingResource idlingRes, ListView listView) {\n this.listView = listView;\n this.idlingResource = idlingRes;\n }\n public void run() {\n //code to do the HTTP request\n final ArrayList<String> fruitList = getFruitList(\"http://<your domain or IP>/fruits.json\");\n try {\n synchronized (this){\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n // Create adapter and set it to list view\n final ArrayAdapter adapter = new\n ArrayAdapter(MainActivity.this, R.layout.item, fruitList);\n ListView listView = (ListView)findViewById(R.id.listView);\n listView.setAdapter(adapter);\n }\n });\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n if (!MyIdlingResource.getIdlingResource().isIdleNow()) {\n MyIdlingResource.decrement(); // Set app as idle.\n }\n }\n}\n"
},
{
"code": null,
"e": 13024,
"s": 12894,
"text": "Here, the fruit url is considered as http://<your domain or IP/fruits.json and it is formated as JSON. The content is as follows,"
},
{
"code": null,
"e": 13739,
"s": 13024,
"text": "[ \n {\n \"name\":\"Apple\"\n },\n {\n \"name\":\"Banana\"\n },\n {\n \"name\":\"Cherry\"\n },\n {\n \"name\":\"Dates\"\n },\n {\n \"name\":\"Elderberry\"\n },\n {\n \"name\":\"Fig\"\n },\n {\n \"name\":\"Grapes\"\n },\n {\n \"name\":\"Grapefruit\"\n },\n {\n \"name\":\"Guava\"\n },\n {\n \"name\":\"Jack fruit\"\n },\n {\n \"name\":\"Lemon\"\n },\n {\n \"name\":\"Mango\"\n },\n {\n \"name\":\"Orange\"\n },\n {\n \"name\":\"Papaya\"\n },\n {\n \"name\":\"Pears\"\n },\n {\n \"name\":\"Peaches\"\n },\n {\n \"name\":\"Pineapple\"\n },\n {\n \"name\":\"Plums\"\n },\n {\n \"name\":\"Raspberry\"\n },\n {\n \"name\":\"Strawberry\"\n },\n {\n \"name\":\"Watermelon\"\n }\n]\n"
},
{
"code": null,
"e": 13798,
"s": 13739,
"text": "Note − Place the file in your local web server and use it."
},
{
"code": null,
"e": 13918,
"s": 13798,
"text": "Now, find the view, create a new thread by passing FruitTask, increment the idling resource and finally start the task."
},
{
"code": null,
"e": 14038,
"s": 13918,
"text": "Now, find the view, create a new thread by passing FruitTask, increment the idling resource and finally start the task."
},
{
"code": null,
"e": 14244,
"s": 14038,
"text": "// Find list view\nListView listView = (ListView) findViewById(R.id.listView);\nThread fruitTask = new Thread(new FruitTask(this.mIdlingResource, listView));\nMyIdlingResource.increment();\nfruitTask.start();\n"
},
{
"code": null,
"e": 14293,
"s": 14244,
"text": "The complete code of MainActivity is as follows,"
},
{
"code": null,
"e": 14342,
"s": 14293,
"text": "The complete code of MainActivity is as follows,"
},
{
"code": null,
"e": 18565,
"s": 14342,
"text": "package com.tutorialspoint.espressosamples.myidlingfruitapp;\n\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.annotation.VisibleForTesting;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.test.espresso.idling.CountingIdlingResource;\n\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\n\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.util.ArrayList;\n\npublic class MainActivity extends AppCompatActivity {\n @Nullable\n private CountingIdlingResource mIdlingResource = null;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n // Get data\n class FruitTask implements Runnable {\n ListView listView;\n CountingIdlingResource idlingResource;\n FruitTask(CountingIdlingResource idlingRes, ListView listView) {\n this.listView = listView;\n this.idlingResource = idlingRes;\n }\n public void run() {\n //code to do the HTTP request\n final ArrayList<String> fruitList = getFruitList(\n \"http://<yourdomain or IP>/fruits.json\");\n try {\n synchronized (this){\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n // Create adapter and set it to list view\n final ArrayAdapter adapter = new ArrayAdapter(\n MainActivity.this, R.layout.item, fruitList);\n ListView listView = (ListView) findViewById(R.id.listView);\n listView.setAdapter(adapter);\n }\n });\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n if (!MyIdlingResource.getIdlingResource().isIdleNow()) {\n MyIdlingResource.decrement(); // Set app as idle.\n }\n }\n }\n // Find list view\n ListView listView = (ListView) findViewById(R.id.listView);\n Thread fruitTask = new Thread(new FruitTask(this.mIdlingResource, listView));\n MyIdlingResource.increment();\n fruitTask.start();\n }\n private ArrayList<String> getFruitList(String data) {\n ArrayList<String> fruits = new ArrayList<String>();\n try {\n // Get url from async task and set it into a local variable\n URL url = new URL(data);\n Log.e(\"URL\", url.toString());\n \n // Create new HTTP connection\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n \n // Set HTTP connection method as \"Get\"\n conn.setRequestMethod(\"GET\");\n \n // Do a http request and get the response code\n int responseCode = conn.getResponseCode();\n \n // check the response code and if success, get response content\n if (responseCode == HttpURLConnection.HTTP_OK) {\n BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));\n String line;\n StringBuffer response = new StringBuffer();\n while ((line = in.readLine()) != null) {\n response.append(line);\n }\n in.close();\n JSONArray jsonArray = new JSONArray(response.toString());\n Log.e(\"HTTPResponse\", response.toString());\n \n for(int i = 0; i < jsonArray.length(); i++) {\n JSONObject jsonObject = jsonArray.getJSONObject(i);\n String name = String.valueOf(jsonObject.getString(\"name\"));\n fruits.add(name);\n }\n } else {\n throw new IOException(\"Unable to fetch data from url\");\n }\n conn.disconnect();\n } catch (IOException | JSONException e) {\n e.printStackTrace();\n }\n return fruits;\n }\n}"
},
{
"code": null,
"e": 18648,
"s": 18565,
"text": "Now, add below configuration in the application manifest file, AndroidManifest.xml"
},
{
"code": null,
"e": 18731,
"s": 18648,
"text": "Now, add below configuration in the application manifest file, AndroidManifest.xml"
},
{
"code": null,
"e": 18797,
"s": 18731,
"text": "<uses-permission android:name = \"android.permission.INTERNET\" />\n"
},
{
"code": null,
"e": 18907,
"s": 18797,
"text": "Now, compile the above code and run the application. The screenshot of the My Idling Fruit App is as follows,"
},
{
"code": null,
"e": 19017,
"s": 18907,
"text": "Now, compile the above code and run the application. The screenshot of the My Idling Fruit App is as follows,"
},
{
"code": null,
"e": 19110,
"s": 19017,
"text": "Now, open the ExampleInstrumentedTest.java file and add ActivityTestRule as specified below,"
},
{
"code": null,
"e": 19203,
"s": 19110,
"text": "Now, open the ExampleInstrumentedTest.java file and add ActivityTestRule as specified below,"
},
{
"code": null,
"e": 19796,
"s": 19203,
"text": "@Rule\npublic ActivityTestRule<MainActivity> mActivityRule = \n new ActivityTestRule<MainActivity>(MainActivity.class);\nAlso, make sure the test configuration is done in app/build.gradle\ndependencies {\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'androidx.test:runner:1.1.1'\n androidTestImplementation 'androidx.test:rules:1.1.1'\n androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'\n implementation 'androidx.test.espresso:espresso-idling-resource:3.1.1'\n androidTestImplementation \"androidx.test.espresso.idling:idlingconcurrent:3.1.1\"\n}\n"
},
{
"code": null,
"e": 19848,
"s": 19796,
"text": "Add a new test case to test the list view as below,"
},
{
"code": null,
"e": 19900,
"s": 19848,
"text": "Add a new test case to test the list view as below,"
},
{
"code": null,
"e": 20323,
"s": 19900,
"text": "@Before\npublic void registerIdlingResource() {\n IdlingRegistry.getInstance().register(MyIdlingResource.getIdlingResource());\n}\n@Test\npublic void contentTest() {\n // click a child item\n onData(allOf())\n .inAdapterView(withId(R.id.listView))\n .atPosition(10)\n .perform(click());\n}\n@After\npublic void unregisterIdlingResource() {\n IdlingRegistry.getInstance().unregister(MyIdlingResource.getIdlingResource());\n}"
},
{
"code": null,
"e": 20435,
"s": 20323,
"text": "Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding."
},
{
"code": null,
"e": 20547,
"s": 20435,
"text": "Finally, run the test case using android studio’s context menu and check whether all test cases are succeeding."
},
{
"code": null,
"e": 20582,
"s": 20547,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 20594,
"s": 20582,
"text": " Anuja Jain"
},
{
"code": null,
"e": 20601,
"s": 20594,
"text": " Print"
},
{
"code": null,
"e": 20612,
"s": 20601,
"text": " Add Notes"
}
] |
Count of substrings of length K with exactly K distinct characters - GeeksforGeeks
|
19 Aug, 2021
Given string str of the lowercase alphabet and an integer K, the task is to count all substrings of length K which have exactly K distinct characters.
Example:
Input: str = “abcc”, K = 2 Output: 2 Explanation: Possible substrings of length K = 2 are ab : 2 distinct characters bc : 2 distinct characters cc : 1 distinct character Only two valid substrings exist {“ab”, “bc”}.
Input: str = “aabab”, K = 3 Output: 0 Explanation: Possible substrings of length K = 3 are aab : 2 distinct characters aba : 2 distinct characters bab : 2 distinct characters No substrings of length 3 exist with exactly 3 distinct characters.
Naive approach: The idea is to generate all substrings of length K and, for each substring count, a number of distinct characters. If the length of a string is N, then there can be N – K + 1 substring of length K. Generating these substrings will require O(N) complexity, and checking each substring requires O(K) complexity, hence making the overall complexity like O(N*K).
Efficient approach: The idea is to use Window Sliding Technique. Maintain a window of size K and keep a count of all the characters in the window using a HashMap. Traverse through the string reduces the count of the first character of the previous window and adds the frequency of the last character of the current window in the HashMap. If the count of distinct characters in a window of length K is equal to K, increment the answer by 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the// count of k length substrings// with k distinct characters// using sliding window#include <bits/stdc++.h>using namespace std; // Function to return the// required count of substringsint countSubstrings(string str, int K){ int N = str.size(); // Store the count int answer = 0; // Store the count of // distinct characters // in every window unordered_map<char, int> map; // Store the frequency of // the first K length substring for (int i = 0; i < K; i++) { // Increase frequency of // i-th character map[str[i]]++; } // If K distinct characters // exist if (map.size() == K) answer++; // Traverse the rest of the // substring for (int i = K; i < N; i++) { // Increase the frequency // of the last character // of the current substring map[str[i]]++; // Decrease the frequency // of the first character // of the previous substring map[str[i - K]]--; // If the character is not present // in the current substring if (map[str[i - K]] == 0) { map.erase(str[i - K]); } // If the count of distinct // characters is 0 if (map.size() == K) { answer++; } } // Return the count return answer;} // Driver codeint main(){ // string str string str = "aabcdabbcdc"; // integer K int K = 3; // Print the count of K length // substrings with k distinct characters cout << countSubstrings(str, K) << endl; return 0;}
// Java program to find the count// of k length substrings with k// distinct characters using// sliding windowimport java.util.*; class GFG{ // Function to return the// required count of substringspublic static int countSubstrings(String str, int K){ int N = str.length(); // Store the count int answer = 0; // Store the count of // distinct characters // in every window Map<Character, Integer> map = new HashMap<Character, Integer>(); // Store the frequency of // the first K length substring for(int i = 0; i < K; i++) { // Increase frequency of // i-th character if (map.get(str.charAt(i)) == null) { map.put(str.charAt(i), 1); } else { map.put(str.charAt(i), map.get(str.charAt(i)) + 1); } } // If K distinct characters // exist if (map.size() == K) answer++; // Traverse the rest of the // substring for(int i = K; i < N; i++) { // Increase the frequency // of the last character // of the current substring if (map.get(str.charAt(i)) == null) { map.put(str.charAt(i), 1); } else { map.put(str.charAt(i), map.get(str.charAt(i)) + 1); } // Decrease the frequency // of the first character // of the previous substring map.put(str.charAt(i - K), map.get(str.charAt(i - K)) - 1); // If the character is not present // in the current substring if (map.get(str.charAt(i - K)) == 0) { map.remove(str.charAt(i - K)); } // If the count of distinct // characters is 0 if (map.size() == K) { answer++; } } // Return the count return answer;} // Driver codepublic static void main(String[] args){ // string str String str = "aabcdabbcdc"; // integer K int K = 3; // Print the count of K length // substrings with k distinct characters System.out.println(countSubstrings(str, K));}} // This code is contributed by grand_master
# Python3 program to find the# count of k length substrings# with k distinct characters# using sliding window # Function to return the# required count of substringsdef countSubstrings(str, K): N = len(str) # Store the count answer = 0 # Store the count of # distinct characters # in every window map = {} # Store the frequency of # the first K length substring for i in range(K): # Increase frequency of # i-th character map[str[i]] = map.get(str[i], 0) + 1 # If K distinct characters # exist if (len(map) == K): answer += 1 # Traverse the rest of the # substring for i in range(K, N): # Increase the frequency # of the last character # of the current substring map[str[i]] = map.get(str[i], 0) + 1 # Decrease the frequency # of the first character # of the previous substring map[str[i - K]] -= 1 # If the character is not present # in the current substring if (map[str[i - K]] == 0): del map[str[i - K]] # If the count of distinct # characters is 0 if (len(map) == K): answer += 1 # Return the count return answer # Driver codeif __name__ == '__main__': str = "aabcdabbcdc" # Integer K K = 3 # Print the count of K length # substrings with k distinct characters print(countSubstrings(str, K)) # This code is contributed by mohit kumar 29
// C# program to find the count// of k length substrings with k// distinct characters using// sliding windowusing System;using System.Collections.Generic; class GFG{ // Function to return the// required count of substringspublic static int countSubstrings(string str, int K){ int N = str.Length; // Store the count int answer = 0; // Store the count of // distinct characters // in every window Dictionary<char, int> map = new Dictionary<char, int>(); // Store the frequency of // the first K length substring for(int i = 0; i < K; i++) { // Increase frequency of // i-th character if(!map.ContainsKey(str[i])) { map[str[i]] = 1; } else { map[str[i]]++; } } // If K distinct characters // exist if (map.Count == K) answer++; // Traverse the rest of the // substring for(int i = K; i < N; i++) { // Increase the frequency // of the last character // of the current substring if(!map.ContainsKey(str[i])) { map[str[i]] = 1; } else { map[str[i]]++; } // Decrease the frequency // of the first character // of the previous substring map[str[i - K]]--; // If the character is not present // in the current substring if (map[str[i - K]] == 0) { map.Remove(str[i - K]); } // If the count of distinct // characters is 0 if (map.Count == K) { answer++; } } // Return the count return answer;} // Driver codepublic static void Main(string[] args){ // string str string str = "aabcdabbcdc"; // integer K int K = 3; // Print the count of K length // substrings with k distinct characters Console.Write(countSubstrings(str, K));}} // This code is contributed by rutvik_56
<script> // Javascript program to find the// count of k length substrings// with k distinct characters// using sliding window // Function to return the// required count of substringsfunction countSubstrings(str, K){ var N = str.length; // Store the count var answer = 0; // Store the count of // distinct characters // in every window var map = new Map(); // Store the frequency of // the first K length substring for (var i = 0; i < K; i++) { // Increase frequency of // i-th character if(map.has(str[i])) map.set(str[i], map.get(str[i])+1) else map.set(str[i], 1) } // If K distinct characters // exist if (map.size == K) answer++; // Traverse the rest of the // substring for (var i = K; i < N; i++) { // Increase the frequency // of the last character // of the current substring if(map.has(str[i])) map.set(str[i], map.get(str[i])+1) else map.set(str[i], 1) // Decrease the frequency // of the first character // of the previous substring if(map.has(str[i-K])) map.set(str[i-K], map.get(str[i-K])-1) // If the character is not present // in the current substring if (map.has(str[i - K]) && map.get(str[i-K])==0) { map.delete(str[i - K]); } // If the count of distinct // characters is 0 if (map.size == K) { answer++; } } // Return the count return answer;} // Driver code// string strvar str = "aabcdabbcdc";// integer Kvar K = 3;// Print the count of K length// substrings with k distinct charactersdocument.write( countSubstrings(str, K) ); </script>
5
Time Complexity: O(N) Auxiliary Space: O(N)
mohit kumar 29
grand_master
rutvik_56
rrrtnx
pankajsharmagfg
Amazon
cpp-map
sliding-window
substring
Algorithms
Arrays
Competitive Programming
CS - Placements
Hash
Strings
Amazon
sliding-window
Arrays
Hash
Strings
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Difference between Informed and Uninformed Search in AI
Playfair Cipher with Examples
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Largest Sum Contiguous Subarray
|
[
{
"code": null,
"e": 24955,
"s": 24927,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 25107,
"s": 24955,
"text": "Given string str of the lowercase alphabet and an integer K, the task is to count all substrings of length K which have exactly K distinct characters. "
},
{
"code": null,
"e": 25116,
"s": 25107,
"text": "Example:"
},
{
"code": null,
"e": 25332,
"s": 25116,
"text": "Input: str = “abcc”, K = 2 Output: 2 Explanation: Possible substrings of length K = 2 are ab : 2 distinct characters bc : 2 distinct characters cc : 1 distinct character Only two valid substrings exist {“ab”, “bc”}."
},
{
"code": null,
"e": 25576,
"s": 25332,
"text": "Input: str = “aabab”, K = 3 Output: 0 Explanation: Possible substrings of length K = 3 are aab : 2 distinct characters aba : 2 distinct characters bab : 2 distinct characters No substrings of length 3 exist with exactly 3 distinct characters. "
},
{
"code": null,
"e": 25952,
"s": 25576,
"text": "Naive approach: The idea is to generate all substrings of length K and, for each substring count, a number of distinct characters. If the length of a string is N, then there can be N – K + 1 substring of length K. Generating these substrings will require O(N) complexity, and checking each substring requires O(K) complexity, hence making the overall complexity like O(N*K). "
},
{
"code": null,
"e": 26393,
"s": 25952,
"text": "Efficient approach: The idea is to use Window Sliding Technique. Maintain a window of size K and keep a count of all the characters in the window using a HashMap. Traverse through the string reduces the count of the first character of the previous window and adds the frequency of the last character of the current window in the HashMap. If the count of distinct characters in a window of length K is equal to K, increment the answer by 1. "
},
{
"code": null,
"e": 26445,
"s": 26393,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26449,
"s": 26445,
"text": "C++"
},
{
"code": null,
"e": 26454,
"s": 26449,
"text": "Java"
},
{
"code": null,
"e": 26462,
"s": 26454,
"text": "Python3"
},
{
"code": null,
"e": 26465,
"s": 26462,
"text": "C#"
},
{
"code": null,
"e": 26476,
"s": 26465,
"text": "Javascript"
},
{
"code": "// C++ program to find the// count of k length substrings// with k distinct characters// using sliding window#include <bits/stdc++.h>using namespace std; // Function to return the// required count of substringsint countSubstrings(string str, int K){ int N = str.size(); // Store the count int answer = 0; // Store the count of // distinct characters // in every window unordered_map<char, int> map; // Store the frequency of // the first K length substring for (int i = 0; i < K; i++) { // Increase frequency of // i-th character map[str[i]]++; } // If K distinct characters // exist if (map.size() == K) answer++; // Traverse the rest of the // substring for (int i = K; i < N; i++) { // Increase the frequency // of the last character // of the current substring map[str[i]]++; // Decrease the frequency // of the first character // of the previous substring map[str[i - K]]--; // If the character is not present // in the current substring if (map[str[i - K]] == 0) { map.erase(str[i - K]); } // If the count of distinct // characters is 0 if (map.size() == K) { answer++; } } // Return the count return answer;} // Driver codeint main(){ // string str string str = \"aabcdabbcdc\"; // integer K int K = 3; // Print the count of K length // substrings with k distinct characters cout << countSubstrings(str, K) << endl; return 0;}",
"e": 28066,
"s": 26476,
"text": null
},
{
"code": "// Java program to find the count// of k length substrings with k// distinct characters using// sliding windowimport java.util.*; class GFG{ // Function to return the// required count of substringspublic static int countSubstrings(String str, int K){ int N = str.length(); // Store the count int answer = 0; // Store the count of // distinct characters // in every window Map<Character, Integer> map = new HashMap<Character, Integer>(); // Store the frequency of // the first K length substring for(int i = 0; i < K; i++) { // Increase frequency of // i-th character if (map.get(str.charAt(i)) == null) { map.put(str.charAt(i), 1); } else { map.put(str.charAt(i), map.get(str.charAt(i)) + 1); } } // If K distinct characters // exist if (map.size() == K) answer++; // Traverse the rest of the // substring for(int i = K; i < N; i++) { // Increase the frequency // of the last character // of the current substring if (map.get(str.charAt(i)) == null) { map.put(str.charAt(i), 1); } else { map.put(str.charAt(i), map.get(str.charAt(i)) + 1); } // Decrease the frequency // of the first character // of the previous substring map.put(str.charAt(i - K), map.get(str.charAt(i - K)) - 1); // If the character is not present // in the current substring if (map.get(str.charAt(i - K)) == 0) { map.remove(str.charAt(i - K)); } // If the count of distinct // characters is 0 if (map.size() == K) { answer++; } } // Return the count return answer;} // Driver codepublic static void main(String[] args){ // string str String str = \"aabcdabbcdc\"; // integer K int K = 3; // Print the count of K length // substrings with k distinct characters System.out.println(countSubstrings(str, K));}} // This code is contributed by grand_master",
"e": 30300,
"s": 28066,
"text": null
},
{
"code": "# Python3 program to find the# count of k length substrings# with k distinct characters# using sliding window # Function to return the# required count of substringsdef countSubstrings(str, K): N = len(str) # Store the count answer = 0 # Store the count of # distinct characters # in every window map = {} # Store the frequency of # the first K length substring for i in range(K): # Increase frequency of # i-th character map[str[i]] = map.get(str[i], 0) + 1 # If K distinct characters # exist if (len(map) == K): answer += 1 # Traverse the rest of the # substring for i in range(K, N): # Increase the frequency # of the last character # of the current substring map[str[i]] = map.get(str[i], 0) + 1 # Decrease the frequency # of the first character # of the previous substring map[str[i - K]] -= 1 # If the character is not present # in the current substring if (map[str[i - K]] == 0): del map[str[i - K]] # If the count of distinct # characters is 0 if (len(map) == K): answer += 1 # Return the count return answer # Driver codeif __name__ == '__main__': str = \"aabcdabbcdc\" # Integer K K = 3 # Print the count of K length # substrings with k distinct characters print(countSubstrings(str, K)) # This code is contributed by mohit kumar 29",
"e": 31795,
"s": 30300,
"text": null
},
{
"code": "// C# program to find the count// of k length substrings with k// distinct characters using// sliding windowusing System;using System.Collections.Generic; class GFG{ // Function to return the// required count of substringspublic static int countSubstrings(string str, int K){ int N = str.Length; // Store the count int answer = 0; // Store the count of // distinct characters // in every window Dictionary<char, int> map = new Dictionary<char, int>(); // Store the frequency of // the first K length substring for(int i = 0; i < K; i++) { // Increase frequency of // i-th character if(!map.ContainsKey(str[i])) { map[str[i]] = 1; } else { map[str[i]]++; } } // If K distinct characters // exist if (map.Count == K) answer++; // Traverse the rest of the // substring for(int i = K; i < N; i++) { // Increase the frequency // of the last character // of the current substring if(!map.ContainsKey(str[i])) { map[str[i]] = 1; } else { map[str[i]]++; } // Decrease the frequency // of the first character // of the previous substring map[str[i - K]]--; // If the character is not present // in the current substring if (map[str[i - K]] == 0) { map.Remove(str[i - K]); } // If the count of distinct // characters is 0 if (map.Count == K) { answer++; } } // Return the count return answer;} // Driver codepublic static void Main(string[] args){ // string str string str = \"aabcdabbcdc\"; // integer K int K = 3; // Print the count of K length // substrings with k distinct characters Console.Write(countSubstrings(str, K));}} // This code is contributed by rutvik_56",
"e": 33864,
"s": 31795,
"text": null
},
{
"code": "<script> // Javascript program to find the// count of k length substrings// with k distinct characters// using sliding window // Function to return the// required count of substringsfunction countSubstrings(str, K){ var N = str.length; // Store the count var answer = 0; // Store the count of // distinct characters // in every window var map = new Map(); // Store the frequency of // the first K length substring for (var i = 0; i < K; i++) { // Increase frequency of // i-th character if(map.has(str[i])) map.set(str[i], map.get(str[i])+1) else map.set(str[i], 1) } // If K distinct characters // exist if (map.size == K) answer++; // Traverse the rest of the // substring for (var i = K; i < N; i++) { // Increase the frequency // of the last character // of the current substring if(map.has(str[i])) map.set(str[i], map.get(str[i])+1) else map.set(str[i], 1) // Decrease the frequency // of the first character // of the previous substring if(map.has(str[i-K])) map.set(str[i-K], map.get(str[i-K])-1) // If the character is not present // in the current substring if (map.has(str[i - K]) && map.get(str[i-K])==0) { map.delete(str[i - K]); } // If the count of distinct // characters is 0 if (map.size == K) { answer++; } } // Return the count return answer;} // Driver code// string strvar str = \"aabcdabbcdc\";// integer Kvar K = 3;// Print the count of K length// substrings with k distinct charactersdocument.write( countSubstrings(str, K) ); </script>",
"e": 35625,
"s": 33864,
"text": null
},
{
"code": null,
"e": 35627,
"s": 35625,
"text": "5"
},
{
"code": null,
"e": 35673,
"s": 35629,
"text": "Time Complexity: O(N) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 35688,
"s": 35673,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35701,
"s": 35688,
"text": "grand_master"
},
{
"code": null,
"e": 35711,
"s": 35701,
"text": "rutvik_56"
},
{
"code": null,
"e": 35718,
"s": 35711,
"text": "rrrtnx"
},
{
"code": null,
"e": 35734,
"s": 35718,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 35741,
"s": 35734,
"text": "Amazon"
},
{
"code": null,
"e": 35749,
"s": 35741,
"text": "cpp-map"
},
{
"code": null,
"e": 35764,
"s": 35749,
"text": "sliding-window"
},
{
"code": null,
"e": 35774,
"s": 35764,
"text": "substring"
},
{
"code": null,
"e": 35785,
"s": 35774,
"text": "Algorithms"
},
{
"code": null,
"e": 35792,
"s": 35785,
"text": "Arrays"
},
{
"code": null,
"e": 35816,
"s": 35792,
"text": "Competitive Programming"
},
{
"code": null,
"e": 35832,
"s": 35816,
"text": "CS - Placements"
},
{
"code": null,
"e": 35837,
"s": 35832,
"text": "Hash"
},
{
"code": null,
"e": 35845,
"s": 35837,
"text": "Strings"
},
{
"code": null,
"e": 35852,
"s": 35845,
"text": "Amazon"
},
{
"code": null,
"e": 35867,
"s": 35852,
"text": "sliding-window"
},
{
"code": null,
"e": 35874,
"s": 35867,
"text": "Arrays"
},
{
"code": null,
"e": 35879,
"s": 35874,
"text": "Hash"
},
{
"code": null,
"e": 35887,
"s": 35879,
"text": "Strings"
},
{
"code": null,
"e": 35898,
"s": 35887,
"text": "Algorithms"
},
{
"code": null,
"e": 35996,
"s": 35898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36005,
"s": 35996,
"text": "Comments"
},
{
"code": null,
"e": 36018,
"s": 36005,
"text": "Old Comments"
},
{
"code": null,
"e": 36067,
"s": 36018,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 36092,
"s": 36067,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36119,
"s": 36092,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 36175,
"s": 36119,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 36205,
"s": 36175,
"text": "Playfair Cipher with Examples"
},
{
"code": null,
"e": 36220,
"s": 36205,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36236,
"s": 36220,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 36263,
"s": 36236,
"text": "Program for array rotation"
},
{
"code": null,
"e": 36311,
"s": 36263,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
for loop in C
|
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax of a for loop in C programming language is −
for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a 'for' loop −
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.
After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.
#include <stdio.h>
int main () {
int a;
/* for loop execution */
for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", a);
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2223,
"s": 2084,
"text": "A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times."
},
{
"code": null,
"e": 2279,
"s": 2223,
"text": "The syntax of a for loop in C programming language is −"
},
{
"code": null,
"e": 2336,
"s": 2279,
"text": "for ( init; condition; increment ) {\n statement(s);\n}\n"
},
{
"code": null,
"e": 2382,
"s": 2336,
"text": "Here is the flow of control in a 'for' loop −"
},
{
"code": null,
"e": 2583,
"s": 2382,
"text": "The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears."
},
{
"code": null,
"e": 2784,
"s": 2583,
"text": "The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears."
},
{
"code": null,
"e": 3000,
"s": 2784,
"text": "Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop."
},
{
"code": null,
"e": 3216,
"s": 3000,
"text": "Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop."
},
{
"code": null,
"e": 3471,
"s": 3216,
"text": "After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition."
},
{
"code": null,
"e": 3726,
"s": 3471,
"text": "After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition."
},
{
"code": null,
"e": 3953,
"s": 3726,
"text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates."
},
{
"code": null,
"e": 4180,
"s": 3953,
"text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates."
},
{
"code": null,
"e": 4352,
"s": 4180,
"text": "#include <stdio.h>\n \nint main () {\n\n int a;\n\t\n /* for loop execution */\n for( a = 10; a < 20; a = a + 1 ){\n printf(\"value of a: %d\\n\", a);\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 4433,
"s": 4352,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4584,
"s": 4433,
"text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n"
},
{
"code": null,
"e": 4591,
"s": 4584,
"text": " Print"
},
{
"code": null,
"e": 4602,
"s": 4591,
"text": " Add Notes"
}
] |
Java program to cyclically rotate an array by one.
|
To rotate the contents of an array cyclically −
create an empty variable. (temp)
save the last element of the array in it.
Now, starting from the nth element of the array, replace the current element with the previous element.
Store the element in temp in the 1st position.
Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class CyclicallyRotateanArray {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the required size of the array ::");
int size = sc.nextInt();
int [] myArray = new int[size];
System.out.println("Enter elements of the array");
for(int i=0; i< size; i++){
myArray[i] = sc.nextInt();
}
System.out.println("Contents of the array: "+Arrays.toString(myArray));
int temp = myArray[size-1];
for(int i = size-1; i>0; i--){
myArray[i] = myArray[i-1];
}
myArray[0] = temp;
System.out.println("Contents of the cycled array: "+Arrays.toString(myArray));
}
}
Enter the required size of the array ::
5
Enter elements of the array
14
15
16
17
18
Contents of the array: [14, 15, 16, 17, 18]
Contents of the cycled array: [18, 14, 15, 16, 17]
|
[
{
"code": null,
"e": 1110,
"s": 1062,
"text": "To rotate the contents of an array cyclically −"
},
{
"code": null,
"e": 1143,
"s": 1110,
"text": "create an empty variable. (temp)"
},
{
"code": null,
"e": 1185,
"s": 1143,
"text": "save the last element of the array in it."
},
{
"code": null,
"e": 1289,
"s": 1185,
"text": "Now, starting from the nth element of the array, replace the current element with the previous element."
},
{
"code": null,
"e": 1336,
"s": 1289,
"text": "Store the element in temp in the 1st position."
},
{
"code": null,
"e": 1347,
"s": 1336,
"text": " Live Demo"
},
{
"code": null,
"e": 2106,
"s": 1347,
"text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class CyclicallyRotateanArray {\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the required size of the array ::\");\n int size = sc.nextInt();\n int [] myArray = new int[size];\n System.out.println(\"Enter elements of the array\");\n for(int i=0; i< size; i++){\n myArray[i] = sc.nextInt();\n }\n System.out.println(\"Contents of the array: \"+Arrays.toString(myArray));\n int temp = myArray[size-1];\n for(int i = size-1; i>0; i--){\n myArray[i] = myArray[i-1];\n }\n myArray[0] = temp;\n System.out.println(\"Contents of the cycled array: \"+Arrays.toString(myArray));\n }\n}"
},
{
"code": null,
"e": 2286,
"s": 2106,
"text": "Enter the required size of the array ::\n5\nEnter elements of the array\n14\n15\n16\n17\n18\nContents of the array: [14, 15, 16, 17, 18]\nContents of the cycled array: [18, 14, 15, 16, 17]"
}
] |
Introduction to procedures and cursors in SQL | by Sayak Paul | Towards Data Science
|
Learn how to write procedures and cursors for an RDBMS.
If you want to learn more about SQL specifically from a Data Science perspective, you can take DataCamp’s free “Intro to SQL for Data Science” course.
SQL is a must-have skill for any modern software engineer. Because most of the softwares depend on some kind of data and integrates well with an RDBMS (Relational Database Management System). Be it a web application, be it an API or be it an in-house application, RDBMS is there. And SQL is the language for querying an RDBMS.
As a data scientist, it is very primary to know SQL and its related techniques. For being able to query an RDBMS and get answers to specific questions that you will have about the data you are dealing with, SQL is the minimum need.
In his latest video with DataCamp, David Robinson(Chief Data Scientist @ DataCamp) showed us how he uses SQL in a Data Science problem. Please check it out, his workflow is very interesting.
In this tutorial, you will learn to write procedures and cursors; another important aspect of SQL. Have you ever wanted your RDBMS to automatically perform a certain of actions when a particular action is taken? For example, let’s say you have created a new employee record in table called Employees and you want this to reflect in the other related tables like Departments. Well, you are going to take just the right tutorial.
In this tutorial, you are going to learn:
What is a procedure in an RDBMS?
How can you write one procedure?
Different types of procedures
What is a cursor in an RDBMS?
How to write different types of cursors?
Different types of cursors
Sounds exciting? Let’s get started.
Before proceeding with procedures and cursors, you will need to know a bit about PL/SQL which is a block-structured language that enables developers like you to combine the power of SQL with procedural statements. But you will not learn in a conventional way, you will learn it as you go along and as required.
So if you have an SQL query and you want to execute it multiple times. Procedures are one of the solutions for it. Often procedures are called in this context because they remain stored and get triggered upon a particular action or a series of actions. Procedures are also referred to as Procs.
Now you will see how to write a procedure.
The general syntax for writing a procedure is as follows:
CREATE PROCEDURE procedure_nameASsql_statementGO;
Please note that these syntaxes applies to almost any RDBMS be it Oracle, be it PostgreSQL or be it MySQL.
After you have created a procedure you will have to execute it. Following is the syntax for that.
EXEC procedure_name;
Let’s write a simple procedure now. Consider the following snapshot from an RDBMS consisting of a table called Customers.
You will write a procedure named SelectAllCustomers which will select all the customers from Customers.
CREATE PROCEDURE SelectAllCustomersASSELECT * FROM CustomersGO;
Execute SelectAllCustomers by:
EXEC SelectAllCustomers;
Procedures can be stand-alone blocks of statements as well which makes them independent of any tables unlike the previous one. The following example creates a simple procedure that displays the string ‘Hello World!’ as output when executed.
CREATE PROCEDURE welcomeASBEGINdbms_output.put_line('Hello World!');END;
There are two ways of executing a stand-alone procedure.
Using the EXEC keyword
Calling the name of the procedure from a PL/SQL block
The above procedure named ‘welcome’ can be called with the EXEC keyword as:
EXEC welcome;
You will see the next method now i.e. calling a procedure from another PL/SQL block.
BEGINwelcome;END;
A procedure can be replaced as well. You just need to add REPLACE keyword when you are creating the procedure. This will replace the already existing procedure (if) otherwise will create a fresh one.
CREATE OR REPLACE PROCEDURE welcomeASBEGINdbms_output.put_line('Hello World!');END;
Deleting a stored procedure is no big deal:
DROP PROCEDURE procedure-name;
Procedures can be different based on parameters also. There can be one parameter procedures and also multiple parameters’ procedures. Now you will study these variants.
You will use the same table Customers for this. For your convenience, the snapshot is given again in the below section.
You will write a stored procedure that selects Customers from a particular City from the table:
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)ASSELECT * FROM Customers WHERE City = @CityGO;
Let’s dissect the common principles here:
You wrote the first @City and defined its type and size as one of the parameters which will be given when the procedure will be executed.
The second @City is assigned to condition variable City which is nothing but a column in the Customers table.
The procedure is executed as :
EXEC SelectAllCustomers City = "London";
Let’s see the other variant now.
Writing procedures with multiple parameters are exactly the same as the earlier one. You just need to append them.
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)ASSELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCodeGO;
Execute the procedure as:
EXEC SelectAllCustomers City = "London", PostalCode = "WA1 1DP";
Aren’t the above codes very readable? When the code is readable, it is more fun to do. That is all for the procedures. You will now study cursors.
Databases like Oracle creates a memory area, known as context area, for processing an SQL statement, which contains all information needed for processing the statement, for example — the number of rows processed.
A cursor is a pointer to this context area. PL/SQL controls the context area through a Cursor. A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. Therefore, cursors are used as to speed the processing time of queries in large databases. The reason you may need to use a database cursor is that you need to perform actions on individual rows.
Cursors can be of two types:
Implicit cursors
Explicit cursors
Now you will see how to write different types of cursors.
You will start off this section by understanding what implicit cursors are.
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed when there is no explicit cursor defined for the statement. Programmers cannot control the implicit cursors and the information in it. Whenever a DML (Data Manipulation Language) statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with that statement. For INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be affected.
You can refer to the most recent implicit cursor as the SQL cursor, which always has the attributes like:
%FOUND,
%ISOPEN,
%NOTFOUND,
%ROWCOUNT.
Following image describes these attributes briefly:
Let’s consider a snapshot of a database consisting a table called Employee:
Now, you will write a cursor that will increase salary by 1000 of those whose age is less than 30.
DECLAREtotal_rows number(2);BEGINUPDATE EmployeeSET salary = salary + 1000where age < 30;IF sql%notfound THEN dbms_output.put_line('No employees found for under 30 age');ELSIF sql%found THEN total_rows := sql%rowcount; dbms_output.put_line( total_rows || ' employees updated ');END IF;END;
Let’s now review what all you wrote:
You defined a variable named total_rows for storing the count of employees that will be affected for the action of the cursor.
You started the cursors block with BEGIN and wrote a simple SQL query which updates the salary of those whose age is less than 30.
You handled the output in case there is no such entry in the DB where an employee’s age is less than 30. You used %notfound attribute for that. Note that the implicit cursor sql here which stores all the relevant information.
Finally, you printed the number of records which got affected for the cursor using %rowcount attribute.
Great! You are doing fine!
When the above code is executed at SQL prompt, it produces the following result:
2 Employees updated (assume there are 2 records where age < 30)
You will now study explicit cursors.
Explicit cursors give more defined controls over context area. It is created on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is
CURSOR cursor_name IS select_statement;
If you are working with explicit cursors, you need to follow a sequence of steps which are as follows:
Declare the cursor for initializing in memory
Open the cursor for allocating a memory area
Fetch the cursor for retrieving data
Close the cursor for deallocating the memory
Following image denotes the life cycle of a typical explicit cursor:
You will now study more about each of these steps.
You declare a cursor along with a SELECT statement. For example:
CURSOR C IS SELECT id, name, address FROM Employee where age > 30;
When you open the cursor, CPU allocates memory for the cursor and makes it ready for fetching the rows returned by the SQL statement entailed to it. For example, we will open above-defined cursor as follows:
OPEN C;
Fetching the cursor involves accessing one row at a time from the associated table in the SQL entailed to the cursor.
FETCH C INTO C_id, C_name, C_address;
Closing the cursor means releasing the allocated memory. You will close above-opened cursor as:
CLOSE C;
You will now put all these pieces together in a meaningful way.
DECLAREC_id Employee.ID%type;C_name Employee.NAME%type;C_address Employee.ADDRESS%type;CURSOR C isSELECT id, name, address FROM Employee where age > 30;BEGINOPEN C;LOOPFETCH C INTO C_id, C_name, C_address; dbms_output.put_line(ID || ' ' || NAME || ' ' || ADDRESS); EXIT WHEN C%notfound;END LOOP;CLOSE C;END;
You learned to declare the cursor variables C_id, C_name and C_address as well. C_id Employee.ID%type; - this ensures that C_id gets created with the same data type as the ID's data type in the Employee table.
By using LOOP you looped through the cursor the fetched the records and displayed it. You also handled the case if no record is found by the cursor.
When the code is executed at the SQL prompt, it produces −
Congrats! You have made it to the end. You covered two of most prevalent topics of the database world — procedures and cursors. These are very common in the applications which deal with huge amount of transactions. Yes, you guessed it right! Banks are using these since time immemorial. You learned how to write a procedure, what are its different types and why they are so. You also studied cursors and its several variants and how you can write them.
Amazing!
Following are some references that were taken to write this tutorial:
Oracle PL/SQL Programming
TutorialsPoint blog on Cursors
SQL Stored Procedures — W3Schools
|
[
{
"code": null,
"e": 228,
"s": 172,
"text": "Learn how to write procedures and cursors for an RDBMS."
},
{
"code": null,
"e": 379,
"s": 228,
"text": "If you want to learn more about SQL specifically from a Data Science perspective, you can take DataCamp’s free “Intro to SQL for Data Science” course."
},
{
"code": null,
"e": 706,
"s": 379,
"text": "SQL is a must-have skill for any modern software engineer. Because most of the softwares depend on some kind of data and integrates well with an RDBMS (Relational Database Management System). Be it a web application, be it an API or be it an in-house application, RDBMS is there. And SQL is the language for querying an RDBMS."
},
{
"code": null,
"e": 938,
"s": 706,
"text": "As a data scientist, it is very primary to know SQL and its related techniques. For being able to query an RDBMS and get answers to specific questions that you will have about the data you are dealing with, SQL is the minimum need."
},
{
"code": null,
"e": 1129,
"s": 938,
"text": "In his latest video with DataCamp, David Robinson(Chief Data Scientist @ DataCamp) showed us how he uses SQL in a Data Science problem. Please check it out, his workflow is very interesting."
},
{
"code": null,
"e": 1557,
"s": 1129,
"text": "In this tutorial, you will learn to write procedures and cursors; another important aspect of SQL. Have you ever wanted your RDBMS to automatically perform a certain of actions when a particular action is taken? For example, let’s say you have created a new employee record in table called Employees and you want this to reflect in the other related tables like Departments. Well, you are going to take just the right tutorial."
},
{
"code": null,
"e": 1599,
"s": 1557,
"text": "In this tutorial, you are going to learn:"
},
{
"code": null,
"e": 1632,
"s": 1599,
"text": "What is a procedure in an RDBMS?"
},
{
"code": null,
"e": 1665,
"s": 1632,
"text": "How can you write one procedure?"
},
{
"code": null,
"e": 1695,
"s": 1665,
"text": "Different types of procedures"
},
{
"code": null,
"e": 1725,
"s": 1695,
"text": "What is a cursor in an RDBMS?"
},
{
"code": null,
"e": 1766,
"s": 1725,
"text": "How to write different types of cursors?"
},
{
"code": null,
"e": 1793,
"s": 1766,
"text": "Different types of cursors"
},
{
"code": null,
"e": 1829,
"s": 1793,
"text": "Sounds exciting? Let’s get started."
},
{
"code": null,
"e": 2140,
"s": 1829,
"text": "Before proceeding with procedures and cursors, you will need to know a bit about PL/SQL which is a block-structured language that enables developers like you to combine the power of SQL with procedural statements. But you will not learn in a conventional way, you will learn it as you go along and as required."
},
{
"code": null,
"e": 2435,
"s": 2140,
"text": "So if you have an SQL query and you want to execute it multiple times. Procedures are one of the solutions for it. Often procedures are called in this context because they remain stored and get triggered upon a particular action or a series of actions. Procedures are also referred to as Procs."
},
{
"code": null,
"e": 2478,
"s": 2435,
"text": "Now you will see how to write a procedure."
},
{
"code": null,
"e": 2536,
"s": 2478,
"text": "The general syntax for writing a procedure is as follows:"
},
{
"code": null,
"e": 2586,
"s": 2536,
"text": "CREATE PROCEDURE procedure_nameASsql_statementGO;"
},
{
"code": null,
"e": 2693,
"s": 2586,
"text": "Please note that these syntaxes applies to almost any RDBMS be it Oracle, be it PostgreSQL or be it MySQL."
},
{
"code": null,
"e": 2791,
"s": 2693,
"text": "After you have created a procedure you will have to execute it. Following is the syntax for that."
},
{
"code": null,
"e": 2812,
"s": 2791,
"text": "EXEC procedure_name;"
},
{
"code": null,
"e": 2934,
"s": 2812,
"text": "Let’s write a simple procedure now. Consider the following snapshot from an RDBMS consisting of a table called Customers."
},
{
"code": null,
"e": 3038,
"s": 2934,
"text": "You will write a procedure named SelectAllCustomers which will select all the customers from Customers."
},
{
"code": null,
"e": 3102,
"s": 3038,
"text": "CREATE PROCEDURE SelectAllCustomersASSELECT * FROM CustomersGO;"
},
{
"code": null,
"e": 3133,
"s": 3102,
"text": "Execute SelectAllCustomers by:"
},
{
"code": null,
"e": 3158,
"s": 3133,
"text": "EXEC SelectAllCustomers;"
},
{
"code": null,
"e": 3399,
"s": 3158,
"text": "Procedures can be stand-alone blocks of statements as well which makes them independent of any tables unlike the previous one. The following example creates a simple procedure that displays the string ‘Hello World!’ as output when executed."
},
{
"code": null,
"e": 3472,
"s": 3399,
"text": "CREATE PROCEDURE welcomeASBEGINdbms_output.put_line('Hello World!');END;"
},
{
"code": null,
"e": 3529,
"s": 3472,
"text": "There are two ways of executing a stand-alone procedure."
},
{
"code": null,
"e": 3552,
"s": 3529,
"text": "Using the EXEC keyword"
},
{
"code": null,
"e": 3606,
"s": 3552,
"text": "Calling the name of the procedure from a PL/SQL block"
},
{
"code": null,
"e": 3682,
"s": 3606,
"text": "The above procedure named ‘welcome’ can be called with the EXEC keyword as:"
},
{
"code": null,
"e": 3696,
"s": 3682,
"text": "EXEC welcome;"
},
{
"code": null,
"e": 3781,
"s": 3696,
"text": "You will see the next method now i.e. calling a procedure from another PL/SQL block."
},
{
"code": null,
"e": 3799,
"s": 3781,
"text": "BEGINwelcome;END;"
},
{
"code": null,
"e": 3999,
"s": 3799,
"text": "A procedure can be replaced as well. You just need to add REPLACE keyword when you are creating the procedure. This will replace the already existing procedure (if) otherwise will create a fresh one."
},
{
"code": null,
"e": 4083,
"s": 3999,
"text": "CREATE OR REPLACE PROCEDURE welcomeASBEGINdbms_output.put_line('Hello World!');END;"
},
{
"code": null,
"e": 4127,
"s": 4083,
"text": "Deleting a stored procedure is no big deal:"
},
{
"code": null,
"e": 4158,
"s": 4127,
"text": "DROP PROCEDURE procedure-name;"
},
{
"code": null,
"e": 4327,
"s": 4158,
"text": "Procedures can be different based on parameters also. There can be one parameter procedures and also multiple parameters’ procedures. Now you will study these variants."
},
{
"code": null,
"e": 4447,
"s": 4327,
"text": "You will use the same table Customers for this. For your convenience, the snapshot is given again in the below section."
},
{
"code": null,
"e": 4543,
"s": 4447,
"text": "You will write a stored procedure that selects Customers from a particular City from the table:"
},
{
"code": null,
"e": 4645,
"s": 4543,
"text": "CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)ASSELECT * FROM Customers WHERE City = @CityGO;"
},
{
"code": null,
"e": 4687,
"s": 4645,
"text": "Let’s dissect the common principles here:"
},
{
"code": null,
"e": 4825,
"s": 4687,
"text": "You wrote the first @City and defined its type and size as one of the parameters which will be given when the procedure will be executed."
},
{
"code": null,
"e": 4935,
"s": 4825,
"text": "The second @City is assigned to condition variable City which is nothing but a column in the Customers table."
},
{
"code": null,
"e": 4966,
"s": 4935,
"text": "The procedure is executed as :"
},
{
"code": null,
"e": 5007,
"s": 4966,
"text": "EXEC SelectAllCustomers City = \"London\";"
},
{
"code": null,
"e": 5040,
"s": 5007,
"text": "Let’s see the other variant now."
},
{
"code": null,
"e": 5155,
"s": 5040,
"text": "Writing procedures with multiple parameters are exactly the same as the earlier one. You just need to append them."
},
{
"code": null,
"e": 5312,
"s": 5155,
"text": "CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)ASSELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCodeGO;"
},
{
"code": null,
"e": 5338,
"s": 5312,
"text": "Execute the procedure as:"
},
{
"code": null,
"e": 5403,
"s": 5338,
"text": "EXEC SelectAllCustomers City = \"London\", PostalCode = \"WA1 1DP\";"
},
{
"code": null,
"e": 5550,
"s": 5403,
"text": "Aren’t the above codes very readable? When the code is readable, it is more fun to do. That is all for the procedures. You will now study cursors."
},
{
"code": null,
"e": 5763,
"s": 5550,
"text": "Databases like Oracle creates a memory area, known as context area, for processing an SQL statement, which contains all information needed for processing the statement, for example — the number of rows processed."
},
{
"code": null,
"e": 6240,
"s": 5763,
"text": "A cursor is a pointer to this context area. PL/SQL controls the context area through a Cursor. A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. Therefore, cursors are used as to speed the processing time of queries in large databases. The reason you may need to use a database cursor is that you need to perform actions on individual rows."
},
{
"code": null,
"e": 6269,
"s": 6240,
"text": "Cursors can be of two types:"
},
{
"code": null,
"e": 6286,
"s": 6269,
"text": "Implicit cursors"
},
{
"code": null,
"e": 6303,
"s": 6286,
"text": "Explicit cursors"
},
{
"code": null,
"e": 6361,
"s": 6303,
"text": "Now you will see how to write different types of cursors."
},
{
"code": null,
"e": 6437,
"s": 6361,
"text": "You will start off this section by understanding what implicit cursors are."
},
{
"code": null,
"e": 6975,
"s": 6437,
"text": "Implicit cursors are automatically created by Oracle whenever an SQL statement is executed when there is no explicit cursor defined for the statement. Programmers cannot control the implicit cursors and the information in it. Whenever a DML (Data Manipulation Language) statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with that statement. For INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be affected."
},
{
"code": null,
"e": 7081,
"s": 6975,
"text": "You can refer to the most recent implicit cursor as the SQL cursor, which always has the attributes like:"
},
{
"code": null,
"e": 7089,
"s": 7081,
"text": "%FOUND,"
},
{
"code": null,
"e": 7098,
"s": 7089,
"text": "%ISOPEN,"
},
{
"code": null,
"e": 7109,
"s": 7098,
"text": "%NOTFOUND,"
},
{
"code": null,
"e": 7120,
"s": 7109,
"text": "%ROWCOUNT."
},
{
"code": null,
"e": 7172,
"s": 7120,
"text": "Following image describes these attributes briefly:"
},
{
"code": null,
"e": 7248,
"s": 7172,
"text": "Let’s consider a snapshot of a database consisting a table called Employee:"
},
{
"code": null,
"e": 7347,
"s": 7248,
"text": "Now, you will write a cursor that will increase salary by 1000 of those whose age is less than 30."
},
{
"code": null,
"e": 7646,
"s": 7347,
"text": "DECLAREtotal_rows number(2);BEGINUPDATE EmployeeSET salary = salary + 1000where age < 30;IF sql%notfound THEN dbms_output.put_line('No employees found for under 30 age');ELSIF sql%found THEN total_rows := sql%rowcount; dbms_output.put_line( total_rows || ' employees updated ');END IF;END;"
},
{
"code": null,
"e": 7683,
"s": 7646,
"text": "Let’s now review what all you wrote:"
},
{
"code": null,
"e": 7810,
"s": 7683,
"text": "You defined a variable named total_rows for storing the count of employees that will be affected for the action of the cursor."
},
{
"code": null,
"e": 7941,
"s": 7810,
"text": "You started the cursors block with BEGIN and wrote a simple SQL query which updates the salary of those whose age is less than 30."
},
{
"code": null,
"e": 8167,
"s": 7941,
"text": "You handled the output in case there is no such entry in the DB where an employee’s age is less than 30. You used %notfound attribute for that. Note that the implicit cursor sql here which stores all the relevant information."
},
{
"code": null,
"e": 8271,
"s": 8167,
"text": "Finally, you printed the number of records which got affected for the cursor using %rowcount attribute."
},
{
"code": null,
"e": 8298,
"s": 8271,
"text": "Great! You are doing fine!"
},
{
"code": null,
"e": 8379,
"s": 8298,
"text": "When the above code is executed at SQL prompt, it produces the following result:"
},
{
"code": null,
"e": 8443,
"s": 8379,
"text": "2 Employees updated (assume there are 2 records where age < 30)"
},
{
"code": null,
"e": 8480,
"s": 8443,
"text": "You will now study explicit cursors."
},
{
"code": null,
"e": 8612,
"s": 8480,
"text": "Explicit cursors give more defined controls over context area. It is created on a SELECT Statement which returns more than one row."
},
{
"code": null,
"e": 8658,
"s": 8612,
"text": "The syntax for creating an explicit cursor is"
},
{
"code": null,
"e": 8698,
"s": 8658,
"text": "CURSOR cursor_name IS select_statement;"
},
{
"code": null,
"e": 8801,
"s": 8698,
"text": "If you are working with explicit cursors, you need to follow a sequence of steps which are as follows:"
},
{
"code": null,
"e": 8847,
"s": 8801,
"text": "Declare the cursor for initializing in memory"
},
{
"code": null,
"e": 8892,
"s": 8847,
"text": "Open the cursor for allocating a memory area"
},
{
"code": null,
"e": 8929,
"s": 8892,
"text": "Fetch the cursor for retrieving data"
},
{
"code": null,
"e": 8974,
"s": 8929,
"text": "Close the cursor for deallocating the memory"
},
{
"code": null,
"e": 9043,
"s": 8974,
"text": "Following image denotes the life cycle of a typical explicit cursor:"
},
{
"code": null,
"e": 9094,
"s": 9043,
"text": "You will now study more about each of these steps."
},
{
"code": null,
"e": 9159,
"s": 9094,
"text": "You declare a cursor along with a SELECT statement. For example:"
},
{
"code": null,
"e": 9226,
"s": 9159,
"text": "CURSOR C IS SELECT id, name, address FROM Employee where age > 30;"
},
{
"code": null,
"e": 9434,
"s": 9226,
"text": "When you open the cursor, CPU allocates memory for the cursor and makes it ready for fetching the rows returned by the SQL statement entailed to it. For example, we will open above-defined cursor as follows:"
},
{
"code": null,
"e": 9442,
"s": 9434,
"text": "OPEN C;"
},
{
"code": null,
"e": 9560,
"s": 9442,
"text": "Fetching the cursor involves accessing one row at a time from the associated table in the SQL entailed to the cursor."
},
{
"code": null,
"e": 9598,
"s": 9560,
"text": "FETCH C INTO C_id, C_name, C_address;"
},
{
"code": null,
"e": 9694,
"s": 9598,
"text": "Closing the cursor means releasing the allocated memory. You will close above-opened cursor as:"
},
{
"code": null,
"e": 9703,
"s": 9694,
"text": "CLOSE C;"
},
{
"code": null,
"e": 9767,
"s": 9703,
"text": "You will now put all these pieces together in a meaningful way."
},
{
"code": null,
"e": 10075,
"s": 9767,
"text": "DECLAREC_id Employee.ID%type;C_name Employee.NAME%type;C_address Employee.ADDRESS%type;CURSOR C isSELECT id, name, address FROM Employee where age > 30;BEGINOPEN C;LOOPFETCH C INTO C_id, C_name, C_address; dbms_output.put_line(ID || ' ' || NAME || ' ' || ADDRESS); EXIT WHEN C%notfound;END LOOP;CLOSE C;END;"
},
{
"code": null,
"e": 10285,
"s": 10075,
"text": "You learned to declare the cursor variables C_id, C_name and C_address as well. C_id Employee.ID%type; - this ensures that C_id gets created with the same data type as the ID's data type in the Employee table."
},
{
"code": null,
"e": 10434,
"s": 10285,
"text": "By using LOOP you looped through the cursor the fetched the records and displayed it. You also handled the case if no record is found by the cursor."
},
{
"code": null,
"e": 10493,
"s": 10434,
"text": "When the code is executed at the SQL prompt, it produces −"
},
{
"code": null,
"e": 10946,
"s": 10493,
"text": "Congrats! You have made it to the end. You covered two of most prevalent topics of the database world — procedures and cursors. These are very common in the applications which deal with huge amount of transactions. Yes, you guessed it right! Banks are using these since time immemorial. You learned how to write a procedure, what are its different types and why they are so. You also studied cursors and its several variants and how you can write them."
},
{
"code": null,
"e": 10955,
"s": 10946,
"text": "Amazing!"
},
{
"code": null,
"e": 11025,
"s": 10955,
"text": "Following are some references that were taken to write this tutorial:"
},
{
"code": null,
"e": 11051,
"s": 11025,
"text": "Oracle PL/SQL Programming"
},
{
"code": null,
"e": 11082,
"s": 11051,
"text": "TutorialsPoint blog on Cursors"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.