title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
A Quick Introduction On Granger Causality Testing For Time Series Analysis | by Susan Li | Towards Data Science
|
The Granger causality test is a statistical hypothesis test for determining whether one time series is a factor and offer useful information in forecasting another time series.
For example, given a question: Could we use today’s Apple’s stock price to predict tomorrow’s Tesla’s stock price? If this is true, our statement will be Apple’s stock price Granger causes Tesla’s stock price. If this is not true, we say Apple’s stock price does not Granger cause Tesla’s stock price.
So, let’s go to Yahoo Finance to fetch the adjusted close stock price data for Apple, Walmart and Tesla, start from 2010–06–30 to 2020–12–18.
Time series can be represented using either line chart or area chart.
Apple and Walmart time series have a fairly similar trend patterns over the years, where Tesla Stock IPOed just over 10 years ago and it has surprised everyone with over 700% rise year-to-date in 2020.
The ADF test is one of the most popular statistical tests. It can be used to help us understand whether the time series is stationary or not.
Null hypothesis: If failed to be rejected, it suggests the time series is not stationarity.
Alternative hypothesis: The null hypothesis is rejected, it suggests the time series is stationary.
The p-values are all well above the 0.05 alpha level, we cannot reject the null hypothesis. So the three time series are not stationary.
The KPSS test figures out if a time series is stationary around a mean or linear trend, or is non-stationary due to a unit root.
Null hypothesis: The time series is stationary
Alternative hypothesis: The time series is not stationary
The p-value are all less than 0.05 alpha level, therefore, we can reject the null hypothesis and derive that the three time series are not stationary.
After cross-check ADF test and KPSS test. We can conclude that the three time series data we have here are not stationary. We will transform the time series to be stationary by difference method.
After transforming the data, the p-values are all well below the 0.05 alpha level, therefore, we reject the null hypothesis. So the current data is stationary.
Some of the KPSS Null Hypothesis could not be rejected.
The VAR class assumes that the passed time series are stationary. Non-stationary or trending data can often be transformed to be stationary by first-differencing or some other method.
There is no hard-and-fast-rule on the choice of lag order. It is basically an empirical issue. However, it is often advised to use the AIC in selecting the lag order with the smallest value. Therefore, we will select lag order = 15.
results = model.fit(maxlags=15, ic='aic')results.summary()
The biggest correlation is 0.43 (Apple & Tesla).
The Durbin Watson Test is a measure of autocorrelation in residuals from regression analysis.
A value of 2.0 means that there is no autocorrelation detected in the residuals.
The following code was borrowed from stackoverflow:
The row are the response (y) and the columns are the predictors (x). If a given p-value is < significance level (0.05), for example, take the value 0.0 in (row 1, column 2), we can reject the null hypothesis and conclude that walmart_x Granger causes apple_y. Likewise, the 0.0 in (row 2, column 1) refers to walmart_y Granger causes apple_x.
All the time series in the above data are interchangeably Granger causing each other.
Remember we transformed the data by difference method, now we will invert the transformation.
Jupyter notebook can be found on Github. Happy Holidays!
|
[
{
"code": null,
"e": 224,
"s": 47,
"text": "The Granger causality test is a statistical hypothesis test for determining whether one time series is a factor and offer useful information in forecasting another time series."
},
{
"code": null,
"e": 526,
"s": 224,
"text": "For example, given a question: Could we use today’s Apple’s stock price to predict tomorrow’s Tesla’s stock price? If this is true, our statement will be Apple’s stock price Granger causes Tesla’s stock price. If this is not true, we say Apple’s stock price does not Granger cause Tesla’s stock price."
},
{
"code": null,
"e": 668,
"s": 526,
"text": "So, let’s go to Yahoo Finance to fetch the adjusted close stock price data for Apple, Walmart and Tesla, start from 2010–06–30 to 2020–12–18."
},
{
"code": null,
"e": 738,
"s": 668,
"text": "Time series can be represented using either line chart or area chart."
},
{
"code": null,
"e": 940,
"s": 738,
"text": "Apple and Walmart time series have a fairly similar trend patterns over the years, where Tesla Stock IPOed just over 10 years ago and it has surprised everyone with over 700% rise year-to-date in 2020."
},
{
"code": null,
"e": 1082,
"s": 940,
"text": "The ADF test is one of the most popular statistical tests. It can be used to help us understand whether the time series is stationary or not."
},
{
"code": null,
"e": 1174,
"s": 1082,
"text": "Null hypothesis: If failed to be rejected, it suggests the time series is not stationarity."
},
{
"code": null,
"e": 1274,
"s": 1174,
"text": "Alternative hypothesis: The null hypothesis is rejected, it suggests the time series is stationary."
},
{
"code": null,
"e": 1411,
"s": 1274,
"text": "The p-values are all well above the 0.05 alpha level, we cannot reject the null hypothesis. So the three time series are not stationary."
},
{
"code": null,
"e": 1540,
"s": 1411,
"text": "The KPSS test figures out if a time series is stationary around a mean or linear trend, or is non-stationary due to a unit root."
},
{
"code": null,
"e": 1587,
"s": 1540,
"text": "Null hypothesis: The time series is stationary"
},
{
"code": null,
"e": 1645,
"s": 1587,
"text": "Alternative hypothesis: The time series is not stationary"
},
{
"code": null,
"e": 1796,
"s": 1645,
"text": "The p-value are all less than 0.05 alpha level, therefore, we can reject the null hypothesis and derive that the three time series are not stationary."
},
{
"code": null,
"e": 1992,
"s": 1796,
"text": "After cross-check ADF test and KPSS test. We can conclude that the three time series data we have here are not stationary. We will transform the time series to be stationary by difference method."
},
{
"code": null,
"e": 2152,
"s": 1992,
"text": "After transforming the data, the p-values are all well below the 0.05 alpha level, therefore, we reject the null hypothesis. So the current data is stationary."
},
{
"code": null,
"e": 2208,
"s": 2152,
"text": "Some of the KPSS Null Hypothesis could not be rejected."
},
{
"code": null,
"e": 2392,
"s": 2208,
"text": "The VAR class assumes that the passed time series are stationary. Non-stationary or trending data can often be transformed to be stationary by first-differencing or some other method."
},
{
"code": null,
"e": 2625,
"s": 2392,
"text": "There is no hard-and-fast-rule on the choice of lag order. It is basically an empirical issue. However, it is often advised to use the AIC in selecting the lag order with the smallest value. Therefore, we will select lag order = 15."
},
{
"code": null,
"e": 2684,
"s": 2625,
"text": "results = model.fit(maxlags=15, ic='aic')results.summary()"
},
{
"code": null,
"e": 2733,
"s": 2684,
"text": "The biggest correlation is 0.43 (Apple & Tesla)."
},
{
"code": null,
"e": 2827,
"s": 2733,
"text": "The Durbin Watson Test is a measure of autocorrelation in residuals from regression analysis."
},
{
"code": null,
"e": 2908,
"s": 2827,
"text": "A value of 2.0 means that there is no autocorrelation detected in the residuals."
},
{
"code": null,
"e": 2960,
"s": 2908,
"text": "The following code was borrowed from stackoverflow:"
},
{
"code": null,
"e": 3303,
"s": 2960,
"text": "The row are the response (y) and the columns are the predictors (x). If a given p-value is < significance level (0.05), for example, take the value 0.0 in (row 1, column 2), we can reject the null hypothesis and conclude that walmart_x Granger causes apple_y. Likewise, the 0.0 in (row 2, column 1) refers to walmart_y Granger causes apple_x."
},
{
"code": null,
"e": 3389,
"s": 3303,
"text": "All the time series in the above data are interchangeably Granger causing each other."
},
{
"code": null,
"e": 3483,
"s": 3389,
"text": "Remember we transformed the data by difference method, now we will invert the transformation."
}
] |
Print all the duplicates in the input string in C++
|
In this problem, we are given a string and we have to find all the characters that are duplicated along with their number of occurrences in the string.
Let’s take an example to understand the problem −
Input:
TutorialsPoint
Output:
t (3)
o (2)
i (2)
Explanation− The frequencies of occurrence of each character are t → 3; u → 1; o → 2; r → 1; i → 2; a → 1; s → 1; n → 1.
Now, to solve this problem we will find the character count and store it in an
array from the string. And then print the characters and occurrences where freq. It is more than 1.
Live Demo
# include <iostream>
using namespace std;
# define NO_OF_CHARS 256
class duplicate_char{
public :
void charCounter(char *str, int *count){
int i;
for (i = 0; *(str + i); i++)
count[*(str + i)]++;
}
void printDuplicateCharacters(char *str){
int *count = (int *)calloc(NO_OF_CHARS, sizeof(int));
charCounter(str, count);
int i;
for (i = 0; i < NO_OF_CHARS; i++)
if(count[i] > 1)
printf("%c\t\t %d \n", i, count[i]);
free(count);
}
};
int main(){
duplicate_char dupchar ;
char str[] = "tutorialspoint";
cout<<"The duplicate characters in the string\n";
cout<<"character\tcount\n";
dupchar.printDuplicateCharacters(str);
return 0;
}
The duplicate characters in the string
character count
i 2
o 2
t 3
|
[
{
"code": null,
"e": 1214,
"s": 1062,
"text": "In this problem, we are given a string and we have to find all the characters that are duplicated along with their number of occurrences in the string."
},
{
"code": null,
"e": 1264,
"s": 1214,
"text": "Let’s take an example to understand the problem −"
},
{
"code": null,
"e": 1312,
"s": 1264,
"text": "Input:\nTutorialsPoint\nOutput:\nt (3)\no (2)\ni (2)"
},
{
"code": null,
"e": 1433,
"s": 1312,
"text": "Explanation− The frequencies of occurrence of each character are t → 3; u → 1; o → 2; r → 1; i → 2; a → 1; s → 1; n → 1."
},
{
"code": null,
"e": 1612,
"s": 1433,
"text": "Now, to solve this problem we will find the character count and store it in an\narray from the string. And then print the characters and occurrences where freq. It is more than 1."
},
{
"code": null,
"e": 1623,
"s": 1612,
"text": " Live Demo"
},
{
"code": null,
"e": 2354,
"s": 1623,
"text": "# include <iostream>\nusing namespace std;\n# define NO_OF_CHARS 256\nclass duplicate_char{\n public :\n void charCounter(char *str, int *count){\n int i;\n for (i = 0; *(str + i); i++)\n count[*(str + i)]++;\n }\n void printDuplicateCharacters(char *str){\n int *count = (int *)calloc(NO_OF_CHARS, sizeof(int));\n charCounter(str, count);\n int i;\n for (i = 0; i < NO_OF_CHARS; i++)\n if(count[i] > 1)\n printf(\"%c\\t\\t %d \\n\", i, count[i]);\n free(count);\n }\n};\nint main(){\n duplicate_char dupchar ;\n char str[] = \"tutorialspoint\";\n cout<<\"The duplicate characters in the string\\n\";\n cout<<\"character\\tcount\\n\";\n dupchar.printDuplicateCharacters(str);\n return 0;\n}"
},
{
"code": null,
"e": 2409,
"s": 2354,
"text": "The duplicate characters in the string\ncharacter count"
},
{
"code": null,
"e": 2421,
"s": 2409,
"text": "i 2\no 2\nt 3"
}
] |
How to write a function in Typescript ? - GeeksforGeeks
|
09 Aug, 2021
Writing a function in TypeScript is similar to writing them in JavaScript but with added parameters and return type. Note that any JavaScript function is a perfectly valid TypeScript function. However, we can do better by adding type.
Syntax: Let’s see a basic TypeScript function syntax (with two arguments)
function functionName(arg1: <arg1Type>,
arg2: <arg2Type>): <returnType> {
// Function body...
}
Below are some functions to help better understand.
Example 1: In this example, we are writing a function to add two numbers
Javascript
// TypeScript Code// Following function returns the addition// of it's two parametersfunction addTwo(a: number, b: number): number { return a + b;} console.log(addTwo(7, 8)); // logs 15
Output:
15
Example 2: Add two numbers and return equivalent hexadecimal string.
Javascript
// Following function adds it's two parameters then// returns it as string form in base 16function getHexAddition(a: number, b: number): string { return (a + b).toString(16);} console.log(getHexAddition(10, 16)); // logs '1a'
Output:
1a
Adding Optional and Default Parameters: Adding an optional parameter is super simple, just add ? to the end of the argument name.
Example 3: Write a function that logs a Good Morning message with a name, if a name is not passed then logs only Good Morning.
Javascript
// Following function returns good morning// message based on value of name passedfunction goodMorning(name?: string): string { // if name exits use it as suffix else ignore name const suffix = (name ? `, ${name}.` : '.'); return 'Good Morning' + suffix;} // logs 'Good Morning.'console.log(goodMorning()); // logs 'Good Morning, Sam.'console.log(goodMorning('Sam'));
Output: For default argument suffix it with an equal sign and default value (TS compiler will automatically deduce the type for default argument based on provided value).
Good Morning.
Good Morning, Sam.
Example 4: Write a function that returns the base^{power}, if power is not provided then it is assumed to be 1.
Javascript
function pow(base: number, power = 1): number { return Math.pow(base, power);} console.log(pow(7)); // logs 7console.log(pow(7, 2)); // logs 49
Output:
7
49
simmytarika5
JavaScript-Questions
Picked
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 25144,
"s": 24909,
"text": "Writing a function in TypeScript is similar to writing them in JavaScript but with added parameters and return type. Note that any JavaScript function is a perfectly valid TypeScript function. However, we can do better by adding type."
},
{
"code": null,
"e": 25218,
"s": 25144,
"text": "Syntax: Let’s see a basic TypeScript function syntax (with two arguments)"
},
{
"code": null,
"e": 25327,
"s": 25218,
"text": "function functionName(arg1: <arg1Type>, \n arg2: <arg2Type>): <returnType> {\n // Function body...\n}"
},
{
"code": null,
"e": 25379,
"s": 25327,
"text": "Below are some functions to help better understand."
},
{
"code": null,
"e": 25453,
"s": 25379,
"text": "Example 1: In this example, we are writing a function to add two numbers "
},
{
"code": null,
"e": 25464,
"s": 25453,
"text": "Javascript"
},
{
"code": "// TypeScript Code// Following function returns the addition// of it's two parametersfunction addTwo(a: number, b: number): number { return a + b;} console.log(addTwo(7, 8)); // logs 15",
"e": 25653,
"s": 25464,
"text": null
},
{
"code": null,
"e": 25661,
"s": 25653,
"text": "Output:"
},
{
"code": null,
"e": 25664,
"s": 25661,
"text": "15"
},
{
"code": null,
"e": 25733,
"s": 25664,
"text": "Example 2: Add two numbers and return equivalent hexadecimal string."
},
{
"code": null,
"e": 25744,
"s": 25733,
"text": "Javascript"
},
{
"code": "// Following function adds it's two parameters then// returns it as string form in base 16function getHexAddition(a: number, b: number): string { return (a + b).toString(16);} console.log(getHexAddition(10, 16)); // logs '1a'",
"e": 25973,
"s": 25744,
"text": null
},
{
"code": null,
"e": 25981,
"s": 25973,
"text": "Output:"
},
{
"code": null,
"e": 25984,
"s": 25981,
"text": "1a"
},
{
"code": null,
"e": 26116,
"s": 25984,
"text": "Adding Optional and Default Parameters: Adding an optional parameter is super simple, just add ? to the end of the argument name. "
},
{
"code": null,
"e": 26243,
"s": 26116,
"text": "Example 3: Write a function that logs a Good Morning message with a name, if a name is not passed then logs only Good Morning."
},
{
"code": null,
"e": 26254,
"s": 26243,
"text": "Javascript"
},
{
"code": "// Following function returns good morning// message based on value of name passedfunction goodMorning(name?: string): string { // if name exits use it as suffix else ignore name const suffix = (name ? `, ${name}.` : '.'); return 'Good Morning' + suffix;} // logs 'Good Morning.'console.log(goodMorning()); // logs 'Good Morning, Sam.'console.log(goodMorning('Sam'));",
"e": 26635,
"s": 26254,
"text": null
},
{
"code": null,
"e": 26806,
"s": 26635,
"text": "Output: For default argument suffix it with an equal sign and default value (TS compiler will automatically deduce the type for default argument based on provided value)."
},
{
"code": null,
"e": 26839,
"s": 26806,
"text": "Good Morning.\nGood Morning, Sam."
},
{
"code": null,
"e": 26951,
"s": 26839,
"text": "Example 4: Write a function that returns the base^{power}, if power is not provided then it is assumed to be 1."
},
{
"code": null,
"e": 26962,
"s": 26951,
"text": "Javascript"
},
{
"code": "function pow(base: number, power = 1): number { return Math.pow(base, power);} console.log(pow(7)); // logs 7console.log(pow(7, 2)); // logs 49",
"e": 27111,
"s": 26962,
"text": null
},
{
"code": null,
"e": 27119,
"s": 27111,
"text": "Output:"
},
{
"code": null,
"e": 27124,
"s": 27119,
"text": "7\n49"
},
{
"code": null,
"e": 27139,
"s": 27126,
"text": "simmytarika5"
},
{
"code": null,
"e": 27160,
"s": 27139,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 27167,
"s": 27160,
"text": "Picked"
},
{
"code": null,
"e": 27178,
"s": 27167,
"text": "TypeScript"
},
{
"code": null,
"e": 27189,
"s": 27178,
"text": "JavaScript"
},
{
"code": null,
"e": 27206,
"s": 27189,
"text": "Web Technologies"
},
{
"code": null,
"e": 27304,
"s": 27206,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27313,
"s": 27304,
"text": "Comments"
},
{
"code": null,
"e": 27326,
"s": 27313,
"text": "Old Comments"
},
{
"code": null,
"e": 27387,
"s": 27326,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27428,
"s": 27387,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27482,
"s": 27428,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27522,
"s": 27482,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27584,
"s": 27522,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27640,
"s": 27584,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27673,
"s": 27640,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27735,
"s": 27673,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27778,
"s": 27735,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
C++ String Library - substr
|
It returns a newly constructed string object with its value initialized to a copy of a substring of this object.
Following is the declaration for std::string::substr.
string substr (size_t pos = 0, size_t len = npos) const;
string substr (size_t pos = 0, size_t len = npos) const;
string substr (size_t pos = 0, size_t len = npos) const;
str − It is a string object.
str − It is a string object.
len − It is used to copy the characters.
len − It is used to copy the characters.
pos − Position of the first character to be copied.
pos − Position of the first character to be copied.
It returns a string object with a substring of this object.
if an exception is thrown, there are no changes in the string.
In below example for std::string::substr.
#include <iostream>
#include <string>
int main () {
std::string str="Tutorialspoit is a one the best site in the world, hope so it will move same .";
std::string str2 = str.substr (3,5);
std::size_t pos = str.find("live");
std::string str3 = str.substr (pos);
std::cout << str2 << ' ' << str3 << '\n';
return 0;
}
The sample output should be like this −
Hello, 1!
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2716,
"s": 2603,
"text": "It returns a newly constructed string object with its value initialized to a copy of a substring of this object."
},
{
"code": null,
"e": 2770,
"s": 2716,
"text": "Following is the declaration for std::string::substr."
},
{
"code": null,
"e": 2827,
"s": 2770,
"text": "string substr (size_t pos = 0, size_t len = npos) const;"
},
{
"code": null,
"e": 2884,
"s": 2827,
"text": "string substr (size_t pos = 0, size_t len = npos) const;"
},
{
"code": null,
"e": 2941,
"s": 2884,
"text": "string substr (size_t pos = 0, size_t len = npos) const;"
},
{
"code": null,
"e": 2970,
"s": 2941,
"text": "str − It is a string object."
},
{
"code": null,
"e": 2999,
"s": 2970,
"text": "str − It is a string object."
},
{
"code": null,
"e": 3040,
"s": 2999,
"text": "len − It is used to copy the characters."
},
{
"code": null,
"e": 3081,
"s": 3040,
"text": "len − It is used to copy the characters."
},
{
"code": null,
"e": 3133,
"s": 3081,
"text": "pos − Position of the first character to be copied."
},
{
"code": null,
"e": 3185,
"s": 3133,
"text": "pos − Position of the first character to be copied."
},
{
"code": null,
"e": 3245,
"s": 3185,
"text": "It returns a string object with a substring of this object."
},
{
"code": null,
"e": 3308,
"s": 3245,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 3350,
"s": 3308,
"text": "In below example for std::string::substr."
},
{
"code": null,
"e": 3688,
"s": 3350,
"text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string str=\"Tutorialspoit is a one the best site in the world, hope so it will move same .\";\n\n std::string str2 = str.substr (3,5);\n\n std::size_t pos = str.find(\"live\");\n\n std::string str3 = str.substr (pos);\n\n std::cout << str2 << ' ' << str3 << '\\n';\n\n return 0;\n}"
},
{
"code": null,
"e": 3728,
"s": 3688,
"text": "The sample output should be like this −"
},
{
"code": null,
"e": 3739,
"s": 3728,
"text": "Hello, 1!\n"
},
{
"code": null,
"e": 3746,
"s": 3739,
"text": " Print"
},
{
"code": null,
"e": 3757,
"s": 3746,
"text": " Add Notes"
}
] |
Linear Regression with PyTorch. Linear Regression is an approach that... | by Asad Mahmood | Towards Data Science
|
Linear Regression is an approach that tries to find a linear relationship between a dependent variable and an independent variable by minimizing the distance as shown below.
In this post, I’ll show how to implement a simple linear regression model using PyTorch.
Let’s consider a very basic linear equation i.e., y=2x+1. Here, ‘x’ is the independent variable and y is the dependent variable. We’ll use this equation to create a dummy dataset which will be used to train this linear regression model. Following is the code for creating the dataset.
import numpy as np# create dummy data for trainingx_values = [i for i in range(11)]x_train = np.array(x_values, dtype=np.float32)x_train = x_train.reshape(-1, 1)y_values = [2*i + 1 for i in x_values]y_train = np.array(y_values, dtype=np.float32)y_train = y_train.reshape(-1, 1)
Once we have created the dataset, we can start writing the code for our model. First thing will be to define the model architecture. We do that using the following piece of code.
import torchfrom torch.autograd import Variableclass linearRegression(torch.nn.Module): def __init__(self, inputSize, outputSize): super(linearRegression, self).__init__() self.linear = torch.nn.Linear(inputSize, outputSize) def forward(self, x): out = self.linear(x) return out
We defined a class for linear regression, that inherits torch.nn.Module which is the basic Neural Network module containing all the required functions. Our Linear Regression model only contains one simple linear function.
Next, we instantiate the model using the following code.
inputDim = 1 # takes variable 'x' outputDim = 1 # takes variable 'y'learningRate = 0.01 epochs = 100model = linearRegression(inputDim, outputDim)##### For GPU #######if torch.cuda.is_available(): model.cuda()
After that, we initialize the loss (Mean Squared Error) and optimization (Stochastic Gradient Descent) functions that we’ll use in the training of this model.
criterion = torch.nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)
After completing all the initializations, we can now begin to train our model. Following is the code for training the model.
for epoch in range(epochs): # Converting inputs and labels to Variable if torch.cuda.is_available(): inputs = Variable(torch.from_numpy(x_train).cuda()) labels = Variable(torch.from_numpy(y_train).cuda()) else: inputs = Variable(torch.from_numpy(x_train)) labels = Variable(torch.from_numpy(y_train)) # Clear gradient buffers because we don't want any gradient from previous epoch to carry forward, dont want to cummulate gradients optimizer.zero_grad() # get output from the model, given the inputs outputs = model(inputs) # get loss for the predicted output loss = criterion(outputs, labels) print(loss) # get gradients w.r.t to parameters loss.backward() # update parameters optimizer.step() print('epoch {}, loss {}'.format(epoch, loss.item()))
Now that our Linear Regression Model is trained, let’s test it. Since it’s a very trivial model, we’ll test this on our existing dataset and also plot to see the original vs the predicted outputs.
with torch.no_grad(): # we don't need gradients in the testing phase if torch.cuda.is_available(): predicted = model(Variable(torch.from_numpy(x_train).cuda())).cpu().data.numpy() else: predicted = model(Variable(torch.from_numpy(x_train))).data.numpy() print(predicted)plt.clf()plt.plot(x_train, y_train, 'go', label='True data', alpha=0.5)plt.plot(x_train, predicted, '--', label='Predictions', alpha=0.5)plt.legend(loc='best')plt.show()
This plots the following graph.
Looks like our model has correctly figured out the linear relation between our dependent and independent variables.
If you have understood this, you should try and train a linear regression model for a little more complex linear equation with multiple independent variables.
|
[
{
"code": null,
"e": 221,
"s": 47,
"text": "Linear Regression is an approach that tries to find a linear relationship between a dependent variable and an independent variable by minimizing the distance as shown below."
},
{
"code": null,
"e": 310,
"s": 221,
"text": "In this post, I’ll show how to implement a simple linear regression model using PyTorch."
},
{
"code": null,
"e": 595,
"s": 310,
"text": "Let’s consider a very basic linear equation i.e., y=2x+1. Here, ‘x’ is the independent variable and y is the dependent variable. We’ll use this equation to create a dummy dataset which will be used to train this linear regression model. Following is the code for creating the dataset."
},
{
"code": null,
"e": 873,
"s": 595,
"text": "import numpy as np# create dummy data for trainingx_values = [i for i in range(11)]x_train = np.array(x_values, dtype=np.float32)x_train = x_train.reshape(-1, 1)y_values = [2*i + 1 for i in x_values]y_train = np.array(y_values, dtype=np.float32)y_train = y_train.reshape(-1, 1)"
},
{
"code": null,
"e": 1052,
"s": 873,
"text": "Once we have created the dataset, we can start writing the code for our model. First thing will be to define the model architecture. We do that using the following piece of code."
},
{
"code": null,
"e": 1365,
"s": 1052,
"text": "import torchfrom torch.autograd import Variableclass linearRegression(torch.nn.Module): def __init__(self, inputSize, outputSize): super(linearRegression, self).__init__() self.linear = torch.nn.Linear(inputSize, outputSize) def forward(self, x): out = self.linear(x) return out"
},
{
"code": null,
"e": 1587,
"s": 1365,
"text": "We defined a class for linear regression, that inherits torch.nn.Module which is the basic Neural Network module containing all the required functions. Our Linear Regression model only contains one simple linear function."
},
{
"code": null,
"e": 1644,
"s": 1587,
"text": "Next, we instantiate the model using the following code."
},
{
"code": null,
"e": 1869,
"s": 1644,
"text": "inputDim = 1 # takes variable 'x' outputDim = 1 # takes variable 'y'learningRate = 0.01 epochs = 100model = linearRegression(inputDim, outputDim)##### For GPU #######if torch.cuda.is_available(): model.cuda()"
},
{
"code": null,
"e": 2028,
"s": 1869,
"text": "After that, we initialize the loss (Mean Squared Error) and optimization (Stochastic Gradient Descent) functions that we’ll use in the training of this model."
},
{
"code": null,
"e": 2124,
"s": 2028,
"text": "criterion = torch.nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)"
},
{
"code": null,
"e": 2249,
"s": 2124,
"text": "After completing all the initializations, we can now begin to train our model. Following is the code for training the model."
},
{
"code": null,
"e": 3071,
"s": 2249,
"text": "for epoch in range(epochs): # Converting inputs and labels to Variable if torch.cuda.is_available(): inputs = Variable(torch.from_numpy(x_train).cuda()) labels = Variable(torch.from_numpy(y_train).cuda()) else: inputs = Variable(torch.from_numpy(x_train)) labels = Variable(torch.from_numpy(y_train)) # Clear gradient buffers because we don't want any gradient from previous epoch to carry forward, dont want to cummulate gradients optimizer.zero_grad() # get output from the model, given the inputs outputs = model(inputs) # get loss for the predicted output loss = criterion(outputs, labels) print(loss) # get gradients w.r.t to parameters loss.backward() # update parameters optimizer.step() print('epoch {}, loss {}'.format(epoch, loss.item()))"
},
{
"code": null,
"e": 3268,
"s": 3071,
"text": "Now that our Linear Regression Model is trained, let’s test it. Since it’s a very trivial model, we’ll test this on our existing dataset and also plot to see the original vs the predicted outputs."
},
{
"code": null,
"e": 3731,
"s": 3268,
"text": "with torch.no_grad(): # we don't need gradients in the testing phase if torch.cuda.is_available(): predicted = model(Variable(torch.from_numpy(x_train).cuda())).cpu().data.numpy() else: predicted = model(Variable(torch.from_numpy(x_train))).data.numpy() print(predicted)plt.clf()plt.plot(x_train, y_train, 'go', label='True data', alpha=0.5)plt.plot(x_train, predicted, '--', label='Predictions', alpha=0.5)plt.legend(loc='best')plt.show()"
},
{
"code": null,
"e": 3763,
"s": 3731,
"text": "This plots the following graph."
},
{
"code": null,
"e": 3879,
"s": 3763,
"text": "Looks like our model has correctly figured out the linear relation between our dependent and independent variables."
}
] |
Build a BERT Sci-kit Transformer. BERT can get you state-of-the-art... | by Nicolas Bertagnolli | Towards Data Science
|
Getting state of the art results in NLP used to be a harrowing task. You’d have to design all kinds of pipelines, do part of speech tagging, link these to knowledge bases, lemmatize your words, and build crazy parsers. Now just throw your task at BERT and you’ll probably do pretty well. The purpose of this tutorial is to set up a minimal example of sentence level classification with BERT and Sci-kit Learn. I’m not going to talk about what BERT is or how it works in any detail. I just want to show you in the smallest amount of work how to use this model really easily with Sci-kit Learn. At the end of this blog post, we’ll have a world class Ekman emotion detection model and BERT packaged into a modular Sci-kit Learn transformer which we can plug and play in one line of code with any existing Sci-kit pipeline!
A big part of machine learning is figuring out what good features are for your Task. If you have features which represent your problem space well learning is a snap! The difficulty is it’s hard, or at least traditionally it was hard, to create good features for a language task. Each task had its own flavor of features and a lot of work went into figuring out what information should be included in the model and how.
BERT is a deep transformer model trained on an enormous amount of text. The massive amount of pretraining combined with the model architecture and a few neat training tricks allow BERT to learn “good” features for NLP tasks. Here we are going leverage all of this excellent work and use the PyTorch transformer library to create a reusable feature extractor. We’ll be able to plug this feature extractor into any Sci-kit Learn model. For more information on how BERT works please read Jay Alamar’s excellent blog posts on BERT, and using BERT.
For most of my projects, I try to start simple and see how far I can get with Sci-kit Learn. I personally like using their pipeline API where any given model is a composition of transformers and estimators. Whenever a newfangled method like BERT comes along I build a transformer or an estimator for it. Then I can incorporate it easily into any existing pipeline I have without much work. So let’s create a Sci-kit Learn transformer for BERT that we can plug and play with any estimator.
This transformer should map a list of strings to the corresponding BERT features associated with the string. So our type signature should be List[str]→torch.FloatTensor
Using the hugging face transformer library there are three main steps to this transformation:
Breaking the string into integer encoded tokensRunning BERT on the encoded tokens to get the BERT representations of the words and sentencesExtracting the parts of the BERT representations into the features that we want for our model.
Breaking the string into integer encoded tokens
Running BERT on the encoded tokens to get the BERT representations of the words and sentences
Extracting the parts of the BERT representations into the features that we want for our model.
Tokenization is only two lines of code. We define the tokenizer we want and then run the encode_plus method which lets us set things like maximum size and whether to include special characters.
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")tokenized_dict = tokenizer.encode_plus( "hi my name is nicolas", add_special_tokens=True, max_length=5 )
The output from this function is:
{'overflowing_tokens': [2003, 9473], 'num_truncated_tokens': 2, 'special_tokens_mask': [1, 0, 0, 0, 1], 'input_ids': [101, 7632, 2026, 2171, 102], 'token_type_ids': [0, 0, 0, 0, 0]}
You’ll notice that we set the maximum sequence length to five, there were only five words in the input I provided, and yet it says that there were two truncated tokens. This is because we set add_special_tokens to True. For the BERT model this means adding a [CLS] “class” token and a [SEP] “separator” token. These two tokens contribute to that maximum of five so we end up dropping two words. This is just something to be aware of. With this dictionary, we only need the input_ids field which holds the integer encoding of the tokenized words that we will pass to the BERT model.
The CLS token holds the sentence embedding and the separator token is used to tell BERT that a new sentence will come next. For our basic sentence classification task, we will use the CLS embedding as our set of features.
The next step is to generate the sentence embeddings using the BERT classifier. Again the transformer library does most of the work for us. We can create a simple BERT model and run the prediction on our tokenized output.
bert_model = BertModel.from_pretrained("bert-base-uncased")tokenized_text = torch.tensor(tokenized_dict["input_ids"])with torch.no_grad(): embeddings = bert_model(torch.tensor(tokenized_text.unsqueeze(0)))
Notice that the BERT model needs to take in a tensor of the form [batch_size,sentence_length] which means we need to unsqueeze the one dimensional matrix.
Also note how we use torch.no_grad() here. I forgot to do that the first time I processed a large batch of samples and ran my server out of memory. So remember to turn off the gradients before running predictions or you’ll save way too much gradient information and have a bad time. The returned tuple has two fields by default, the first is a matrix of size:
batch size × sentence length × embedding dimension
For the base BERT model and our example, this ends up being [1, 5, 768]. The first tensor holds the embeddings we are interested in for classification. The second tensor holds the pooled outputs. The pooled outputs are the [CLS] embedding after it has been passed through a Linear layer and a Tanh activation function while training on the next sentence. For this tutorial, we can ignore it.
The last thing we need to complete our BERT feature extractor is a way to combine the final embeddings into a single vector we can use for classification. For most classification tasks you can do pretty well by just grabbing the embedding for the [CLS] token. Which we can do with this function:
get_cls = lambda x: x[0][:, 0, :].squeeze()
This will take that Tuple of the embeddings and pooled outputs, grab the embeddings and take all the batches, just the first CLS token, and all of the embedding neurons.
But maybe you want to get fancy and use other features. Let’s say you want to use all of the embeddings for your prediction we could concatenate them all together with a different function:
flatten_embed = lambda x: torch.flatten(x[0])
This will return one big vector composed of the embedding for every token in the sequence. By defining functions which operate on the final layers we can be more flexible in the features we use for downstream classification. This will make more sense in the context of the Sci-kit Learn transformer.
Those three basic pieces are all that we need to get the embeddings for a single sentence. To link easily with Sci-kit Learn methods we want to operate on a large list of sentences. We can do that by building a Sci-kit Learn transformer (We’re making a transformer transformer!). This way we can just pass a list to it, call the transform function, and our classifier can start learning. We make a new class called BertTransformer which inherits from BaseEstimator and TransformerMixin and put the code we worked on above in as a tokenization step and a prediction step.
This transformer uses all of the tokenization code we wrote earlier in lines 25–39, and the prediction and extraction code on lines 41–46. The only other thing we do is link it all up in a transform method which uses a single list comprehension to tokenize and then embed all sentences in a list which happens on lines 51–52.
Now we can make super simple pipelines with all the power of BERT and all of the simplicity of classic Sci-kit Learn models!
For our data we will be using the Figure-Eight Sentiment Analysis: Emotion in Text data set. This data set has 40K tweets classified into 13 different emotional states. I just loaded the data into a pandas data frame and randomly split the data into a 70% train set, a 15% validation set, and a 15% test set.
figure8_df = pd.read_csv("text_emotion.csv")split = np.random.choice( ["train", "val", "test"], size=figure8_df.shape[0], p=[.7, .15, .15])figure8_df["split"] = splitx_train = figure8_df[figure8_df["split"] == "train"]y_train = x_train["sentiment"]
Training the model is wicked easy. We just define a pipeline with a single transformer and a single estimator.
bert_transformer = BertTransformer(tokenizer, bert_model)classifier = svm.LinearSVC(C=1.0, class_weight="balanced")model = Pipeline( [ ("vectorizer", bert_transformer), ("classifier", classifier), ])model.fit(x_train["content"], y_train)
That’s it, we’re done. This will train an SVM on the BERT CLS embeddings, but what if we wanted some classic TF-IDF features too? That’s easy as well! We just make a feature union and pass it to our classifier.
from sklearn.feature_extraction.text import ( CountVectorizer, TfidfTransformer)tf_idf = Pipeline([ ("vect", CountVectorizer()), ("tfidf", TfidfTransformer()) ])model = Pipeline([ ("union", FeatureUnion(transformer_list=[ ("bert", bert_transformer), ("tf_idf", tf_idf) ])), ("classifier", classifier), ])
What I love about using pipelines is they are so flexible and I can create these nice malleable components that fit together so easily. For now and all eternity we can add BERT features to any Sci-kit Learn model with a single line of code!
After running the above model we get pretty good results out of the box on our validation set. Some of the classes do terribly, but most do beyond amazing. Take a look. There is almost perfect classification on our validation set for a number of classes. This model only uses the CLS embedding from the BERT transformer and an SVM and it gets almost perfect predictions across all of the major labels! That’s pretty bananas.
These results were surprisingly good so I took a look at the confusion matrix and it seems like enthusiasm and fun are both being classified as happiness which I’m 100% okay with. It looks like the real problem children are empty and relief but if I’m being perfectly honest I don’t even know what those emotions are 🤷♂ so I’m going to mark this as a success.
Sci-kit Learn transformers are super convenient. Now we can easily plug BERT based features into any Sci-kit Learn model we want! It’s just a matter of defining our BERT model and adding it as a featurization step to a pipeline. Sci-kit Learn takes care of the rest. Try incorporating these features into one of your old models and see if it improves performance. It did for me.
|
[
{
"code": null,
"e": 992,
"s": 172,
"text": "Getting state of the art results in NLP used to be a harrowing task. You’d have to design all kinds of pipelines, do part of speech tagging, link these to knowledge bases, lemmatize your words, and build crazy parsers. Now just throw your task at BERT and you’ll probably do pretty well. The purpose of this tutorial is to set up a minimal example of sentence level classification with BERT and Sci-kit Learn. I’m not going to talk about what BERT is or how it works in any detail. I just want to show you in the smallest amount of work how to use this model really easily with Sci-kit Learn. At the end of this blog post, we’ll have a world class Ekman emotion detection model and BERT packaged into a modular Sci-kit Learn transformer which we can plug and play in one line of code with any existing Sci-kit pipeline!"
},
{
"code": null,
"e": 1411,
"s": 992,
"text": "A big part of machine learning is figuring out what good features are for your Task. If you have features which represent your problem space well learning is a snap! The difficulty is it’s hard, or at least traditionally it was hard, to create good features for a language task. Each task had its own flavor of features and a lot of work went into figuring out what information should be included in the model and how."
},
{
"code": null,
"e": 1955,
"s": 1411,
"text": "BERT is a deep transformer model trained on an enormous amount of text. The massive amount of pretraining combined with the model architecture and a few neat training tricks allow BERT to learn “good” features for NLP tasks. Here we are going leverage all of this excellent work and use the PyTorch transformer library to create a reusable feature extractor. We’ll be able to plug this feature extractor into any Sci-kit Learn model. For more information on how BERT works please read Jay Alamar’s excellent blog posts on BERT, and using BERT."
},
{
"code": null,
"e": 2444,
"s": 1955,
"text": "For most of my projects, I try to start simple and see how far I can get with Sci-kit Learn. I personally like using their pipeline API where any given model is a composition of transformers and estimators. Whenever a newfangled method like BERT comes along I build a transformer or an estimator for it. Then I can incorporate it easily into any existing pipeline I have without much work. So let’s create a Sci-kit Learn transformer for BERT that we can plug and play with any estimator."
},
{
"code": null,
"e": 2613,
"s": 2444,
"text": "This transformer should map a list of strings to the corresponding BERT features associated with the string. So our type signature should be List[str]→torch.FloatTensor"
},
{
"code": null,
"e": 2707,
"s": 2613,
"text": "Using the hugging face transformer library there are three main steps to this transformation:"
},
{
"code": null,
"e": 2942,
"s": 2707,
"text": "Breaking the string into integer encoded tokensRunning BERT on the encoded tokens to get the BERT representations of the words and sentencesExtracting the parts of the BERT representations into the features that we want for our model."
},
{
"code": null,
"e": 2990,
"s": 2942,
"text": "Breaking the string into integer encoded tokens"
},
{
"code": null,
"e": 3084,
"s": 2990,
"text": "Running BERT on the encoded tokens to get the BERT representations of the words and sentences"
},
{
"code": null,
"e": 3179,
"s": 3084,
"text": "Extracting the parts of the BERT representations into the features that we want for our model."
},
{
"code": null,
"e": 3373,
"s": 3179,
"text": "Tokenization is only two lines of code. We define the tokenizer we want and then run the encode_plus method which lets us set things like maximum size and whether to include special characters."
},
{
"code": null,
"e": 3552,
"s": 3373,
"text": "tokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")tokenized_dict = tokenizer.encode_plus( \"hi my name is nicolas\", add_special_tokens=True, max_length=5 )"
},
{
"code": null,
"e": 3586,
"s": 3552,
"text": "The output from this function is:"
},
{
"code": null,
"e": 3768,
"s": 3586,
"text": "{'overflowing_tokens': [2003, 9473], 'num_truncated_tokens': 2, 'special_tokens_mask': [1, 0, 0, 0, 1], 'input_ids': [101, 7632, 2026, 2171, 102], 'token_type_ids': [0, 0, 0, 0, 0]}"
},
{
"code": null,
"e": 4350,
"s": 3768,
"text": "You’ll notice that we set the maximum sequence length to five, there were only five words in the input I provided, and yet it says that there were two truncated tokens. This is because we set add_special_tokens to True. For the BERT model this means adding a [CLS] “class” token and a [SEP] “separator” token. These two tokens contribute to that maximum of five so we end up dropping two words. This is just something to be aware of. With this dictionary, we only need the input_ids field which holds the integer encoding of the tokenized words that we will pass to the BERT model."
},
{
"code": null,
"e": 4572,
"s": 4350,
"text": "The CLS token holds the sentence embedding and the separator token is used to tell BERT that a new sentence will come next. For our basic sentence classification task, we will use the CLS embedding as our set of features."
},
{
"code": null,
"e": 4794,
"s": 4572,
"text": "The next step is to generate the sentence embeddings using the BERT classifier. Again the transformer library does most of the work for us. We can create a simple BERT model and run the prediction on our tokenized output."
},
{
"code": null,
"e": 5001,
"s": 4794,
"text": "bert_model = BertModel.from_pretrained(\"bert-base-uncased\")tokenized_text = torch.tensor(tokenized_dict[\"input_ids\"])with torch.no_grad(): embeddings = bert_model(torch.tensor(tokenized_text.unsqueeze(0)))"
},
{
"code": null,
"e": 5156,
"s": 5001,
"text": "Notice that the BERT model needs to take in a tensor of the form [batch_size,sentence_length] which means we need to unsqueeze the one dimensional matrix."
},
{
"code": null,
"e": 5516,
"s": 5156,
"text": "Also note how we use torch.no_grad() here. I forgot to do that the first time I processed a large batch of samples and ran my server out of memory. So remember to turn off the gradients before running predictions or you’ll save way too much gradient information and have a bad time. The returned tuple has two fields by default, the first is a matrix of size:"
},
{
"code": null,
"e": 5567,
"s": 5516,
"text": "batch size × sentence length × embedding dimension"
},
{
"code": null,
"e": 5959,
"s": 5567,
"text": "For the base BERT model and our example, this ends up being [1, 5, 768]. The first tensor holds the embeddings we are interested in for classification. The second tensor holds the pooled outputs. The pooled outputs are the [CLS] embedding after it has been passed through a Linear layer and a Tanh activation function while training on the next sentence. For this tutorial, we can ignore it."
},
{
"code": null,
"e": 6255,
"s": 5959,
"text": "The last thing we need to complete our BERT feature extractor is a way to combine the final embeddings into a single vector we can use for classification. For most classification tasks you can do pretty well by just grabbing the embedding for the [CLS] token. Which we can do with this function:"
},
{
"code": null,
"e": 6299,
"s": 6255,
"text": "get_cls = lambda x: x[0][:, 0, :].squeeze()"
},
{
"code": null,
"e": 6469,
"s": 6299,
"text": "This will take that Tuple of the embeddings and pooled outputs, grab the embeddings and take all the batches, just the first CLS token, and all of the embedding neurons."
},
{
"code": null,
"e": 6659,
"s": 6469,
"text": "But maybe you want to get fancy and use other features. Let’s say you want to use all of the embeddings for your prediction we could concatenate them all together with a different function:"
},
{
"code": null,
"e": 6705,
"s": 6659,
"text": "flatten_embed = lambda x: torch.flatten(x[0])"
},
{
"code": null,
"e": 7005,
"s": 6705,
"text": "This will return one big vector composed of the embedding for every token in the sequence. By defining functions which operate on the final layers we can be more flexible in the features we use for downstream classification. This will make more sense in the context of the Sci-kit Learn transformer."
},
{
"code": null,
"e": 7576,
"s": 7005,
"text": "Those three basic pieces are all that we need to get the embeddings for a single sentence. To link easily with Sci-kit Learn methods we want to operate on a large list of sentences. We can do that by building a Sci-kit Learn transformer (We’re making a transformer transformer!). This way we can just pass a list to it, call the transform function, and our classifier can start learning. We make a new class called BertTransformer which inherits from BaseEstimator and TransformerMixin and put the code we worked on above in as a tokenization step and a prediction step."
},
{
"code": null,
"e": 7902,
"s": 7576,
"text": "This transformer uses all of the tokenization code we wrote earlier in lines 25–39, and the prediction and extraction code on lines 41–46. The only other thing we do is link it all up in a transform method which uses a single list comprehension to tokenize and then embed all sentences in a list which happens on lines 51–52."
},
{
"code": null,
"e": 8027,
"s": 7902,
"text": "Now we can make super simple pipelines with all the power of BERT and all of the simplicity of classic Sci-kit Learn models!"
},
{
"code": null,
"e": 8336,
"s": 8027,
"text": "For our data we will be using the Figure-Eight Sentiment Analysis: Emotion in Text data set. This data set has 40K tweets classified into 13 different emotional states. I just loaded the data into a pandas data frame and randomly split the data into a 70% train set, a 15% validation set, and a 15% test set."
},
{
"code": null,
"e": 8594,
"s": 8336,
"text": "figure8_df = pd.read_csv(\"text_emotion.csv\")split = np.random.choice( [\"train\", \"val\", \"test\"], size=figure8_df.shape[0], p=[.7, .15, .15])figure8_df[\"split\"] = splitx_train = figure8_df[figure8_df[\"split\"] == \"train\"]y_train = x_train[\"sentiment\"]"
},
{
"code": null,
"e": 8705,
"s": 8594,
"text": "Training the model is wicked easy. We just define a pipeline with a single transformer and a single estimator."
},
{
"code": null,
"e": 8963,
"s": 8705,
"text": "bert_transformer = BertTransformer(tokenizer, bert_model)classifier = svm.LinearSVC(C=1.0, class_weight=\"balanced\")model = Pipeline( [ (\"vectorizer\", bert_transformer), (\"classifier\", classifier), ])model.fit(x_train[\"content\"], y_train)"
},
{
"code": null,
"e": 9174,
"s": 8963,
"text": "That’s it, we’re done. This will train an SVM on the BERT CLS embeddings, but what if we wanted some classic TF-IDF features too? That’s easy as well! We just make a feature union and pass it to our classifier."
},
{
"code": null,
"e": 9524,
"s": 9174,
"text": "from sklearn.feature_extraction.text import ( CountVectorizer, TfidfTransformer)tf_idf = Pipeline([ (\"vect\", CountVectorizer()), (\"tfidf\", TfidfTransformer()) ])model = Pipeline([ (\"union\", FeatureUnion(transformer_list=[ (\"bert\", bert_transformer), (\"tf_idf\", tf_idf) ])), (\"classifier\", classifier), ])"
},
{
"code": null,
"e": 9765,
"s": 9524,
"text": "What I love about using pipelines is they are so flexible and I can create these nice malleable components that fit together so easily. For now and all eternity we can add BERT features to any Sci-kit Learn model with a single line of code!"
},
{
"code": null,
"e": 10190,
"s": 9765,
"text": "After running the above model we get pretty good results out of the box on our validation set. Some of the classes do terribly, but most do beyond amazing. Take a look. There is almost perfect classification on our validation set for a number of classes. This model only uses the CLS embedding from the BERT transformer and an SVM and it gets almost perfect predictions across all of the major labels! That’s pretty bananas."
},
{
"code": null,
"e": 10551,
"s": 10190,
"text": "These results were surprisingly good so I took a look at the confusion matrix and it seems like enthusiasm and fun are both being classified as happiness which I’m 100% okay with. It looks like the real problem children are empty and relief but if I’m being perfectly honest I don’t even know what those emotions are 🤷♂ so I’m going to mark this as a success."
}
] |
Kubernetes - Labels & Selectors
|
Labels are key-value pairs which are attached to pods, replication controller and services. They are used as identifying attributes for objects such as pods and replication controller. They can be added to an object at creation time and can be added or modified at the run time.
Labels do not provide uniqueness. In general, we can say many objects can carry the same labels. Labels selector are core grouping primitive in Kubernetes. They are used by the users to select a set of objects.
Kubernetes API currently supports two type of selectors −
Equality-based selectors
Set-based selectors
They allow filtering by key and value. Matching objects should satisfy all the specified labels.
Set-based selectors allow filtering of keys according to a set of values.
apiVersion: v1
kind: Service
metadata:
name: sp-neo4j-standalone
spec:
ports:
- port: 7474
name: neo4j
type: NodePort
selector:
app: salesplatform ---------> 1
component: neo4j -----------> 2
In the above code, we are using the label selector as app: salesplatform and component as component: neo4j.
Once we run the file using the kubectl command, it will create a service with the name sp-neo4j-standalone which will communicate on port 7474. The ype is NodePort with the new label selector as app: salesplatform and component: neo4j.
41 Lectures
5 hours
AR Shankar
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
18 Lectures
1.5 hours
Nigel Poulton
25 Lectures
1.5 hours
Pranjal Srivastava
18 Lectures
1 hours
Pranjal Srivastava
26 Lectures
1.5 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2474,
"s": 2195,
"text": "Labels are key-value pairs which are attached to pods, replication controller and services. They are used as identifying attributes for objects such as pods and replication controller. They can be added to an object at creation time and can be added or modified at the run time."
},
{
"code": null,
"e": 2685,
"s": 2474,
"text": "Labels do not provide uniqueness. In general, we can say many objects can carry the same labels. Labels selector are core grouping primitive in Kubernetes. They are used by the users to select a set of objects."
},
{
"code": null,
"e": 2743,
"s": 2685,
"text": "Kubernetes API currently supports two type of selectors −"
},
{
"code": null,
"e": 2768,
"s": 2743,
"text": "Equality-based selectors"
},
{
"code": null,
"e": 2788,
"s": 2768,
"text": "Set-based selectors"
},
{
"code": null,
"e": 2885,
"s": 2788,
"text": "They allow filtering by key and value. Matching objects should satisfy all the specified labels."
},
{
"code": null,
"e": 2959,
"s": 2885,
"text": "Set-based selectors allow filtering of keys according to a set of values."
},
{
"code": null,
"e": 3188,
"s": 2959,
"text": "apiVersion: v1\nkind: Service\nmetadata:\n name: sp-neo4j-standalone\nspec:\n ports:\n - port: 7474\n name: neo4j\n type: NodePort\n selector:\n app: salesplatform ---------> 1\n component: neo4j -----------> 2\n"
},
{
"code": null,
"e": 3296,
"s": 3188,
"text": "In the above code, we are using the label selector as app: salesplatform and component as component: neo4j."
},
{
"code": null,
"e": 3532,
"s": 3296,
"text": "Once we run the file using the kubectl command, it will create a service with the name sp-neo4j-standalone which will communicate on port 7474. The ype is NodePort with the new label selector as app: salesplatform and component: neo4j."
},
{
"code": null,
"e": 3565,
"s": 3532,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3577,
"s": 3565,
"text": " AR Shankar"
},
{
"code": null,
"e": 3610,
"s": 3577,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3650,
"s": 3610,
"text": " Harshit Srivastava, Pranjal Srivastava"
},
{
"code": null,
"e": 3685,
"s": 3650,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3700,
"s": 3685,
"text": " Nigel Poulton"
},
{
"code": null,
"e": 3735,
"s": 3700,
"text": "\n 25 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3755,
"s": 3735,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3788,
"s": 3755,
"text": "\n 18 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3808,
"s": 3788,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3843,
"s": 3808,
"text": "\n 26 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3863,
"s": 3843,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3870,
"s": 3863,
"text": " Print"
},
{
"code": null,
"e": 3881,
"s": 3870,
"text": " Add Notes"
}
] |
Apache Kafka - Quick Guide
|
In Big Data, an enormous volume of data is used. Regarding data, we have two main challenges.The first challenge is how to collect large volume of data and the second challenge is to analyze the collected data. To overcome those challenges, you must need a messaging system.
Kafka is designed for distributed high throughput systems. Kafka tends to work very well as a replacement for a more traditional message broker. In comparison to other messaging systems, Kafka has better throughput, built-in partitioning, replication and inherent fault-tolerance, which makes it a good fit for large-scale message processing applications.
A Messaging System is responsible for transferring data from one application to another, so the applications can focus on data, but not worry about how to share it. Distributed messaging is based on the concept of reliable message queuing. Messages are queued asynchronously between client applications and messaging system. Two types of messaging patterns are available − one is point to point and the other is publish-subscribe (pub-sub) messaging system. Most of the messaging patterns follow pub-sub.
In a point-to-point system, messages are persisted in a queue. One or more consumers can consume the messages in the queue, but a particular message can be consumed by a maximum of one consumer only. Once a consumer reads a message in the queue, it disappears from that queue. The typical example of this system is an Order Processing System, where each order will be processed by one Order Processor, but Multiple Order Processors can work as well at the same time. The following diagram depicts the structure.
In the publish-subscribe system, messages are persisted in a topic. Unlike point-to-point system, consumers can subscribe to one or more topic and consume all the messages in that topic. In the Publish-Subscribe system, message producers are called publishers and message consumers are called subscribers. A real-life example is Dish TV, which publishes different channels like sports, movies, music, etc., and anyone can subscribe to their own set of channels and get them whenever their subscribed channels are available.
Apache Kafka is a distributed publish-subscribe messaging system and a robust queue that can handle a high volume of data and enables you to pass messages from one end-point to another. Kafka is suitable for both offline and online message consumption. Kafka messages are persisted on the disk and replicated within the cluster to prevent data loss. Kafka is built on top of the ZooKeeper synchronization service. It integrates very well with Apache Storm and Spark for real-time streaming data analysis.
Following are a few benefits of Kafka −
Reliability − Kafka is distributed, partitioned, replicated and fault tolerance.
Reliability − Kafka is distributed, partitioned, replicated and fault tolerance.
Scalability − Kafka messaging system scales easily without down time..
Scalability − Kafka messaging system scales easily without down time..
Durability − Kafka uses Distributed commit log which means messages persists on disk as fast as possible, hence it is durable..
Durability − Kafka uses Distributed commit log which means messages persists on disk as fast as possible, hence it is durable..
Performance − Kafka has high throughput for both publishing and subscribing messages. It maintains stable performance even many TB of messages are stored.
Performance − Kafka has high throughput for both publishing and subscribing messages. It maintains stable performance even many TB of messages are stored.
Kafka is very fast and guarantees zero downtime and zero data loss.
Kafka can be used in many Use Cases. Some of them are listed below −
Metrics − Kafka is often used for operational monitoring data. This involves aggregating statistics from distributed applications to produce centralized feeds of operational data.
Metrics − Kafka is often used for operational monitoring data. This involves aggregating statistics from distributed applications to produce centralized feeds of operational data.
Log Aggregation Solution − Kafka can be used across an organization to collect logs from multiple services and make them available in a standard format to multiple con-sumers.
Log Aggregation Solution − Kafka can be used across an organization to collect logs from multiple services and make them available in a standard format to multiple con-sumers.
Stream Processing − Popular frameworks such as Storm and Spark Streaming read data from a topic, processes it, and write processed data to a new topic where it becomes available for users and applications. Kafka’s strong durability is also very useful in the context of stream processing.
Stream Processing − Popular frameworks such as Storm and Spark Streaming read data from a topic, processes it, and write processed data to a new topic where it becomes available for users and applications. Kafka’s strong durability is also very useful in the context of stream processing.
Kafka is a unified platform for handling all the real-time data feeds. Kafka supports low latency message delivery and gives guarantee for fault tolerance in the presence of machine failures. It has the ability to handle a large number of diverse consumers. Kafka is very fast, performs 2 million writes/sec. Kafka persists all data to the disk, which essentially means that all the writes go to the page cache of the OS (RAM). This makes it very efficient to transfer data from page cache to a network socket.
Before moving deep into the Kafka, you must aware of the main terminologies such as topics, brokers, producers and consumers. The following diagram illustrates the main terminologies and the table describes the diagram components in detail.
In the above diagram, a topic is configured into three partitions. Partition 1 has two offset factors 0 and 1. Partition 2 has four offset factors 0, 1, 2, and 3. Partition 3 has one offset factor 0. The id of the replica is same as the id of the server that hosts it.
Assume, if the replication factor of the topic is set to 3, then Kafka will create 3 identical replicas of each partition and place them in the cluster to make available for all its operations. To balance a load in cluster, each broker stores one or more of those partitions. Multiple producers and consumers can publish and retrieve messages at the same time.
Topics
A stream of messages belonging to a particular category is called a topic. Data is stored in topics.
Topics are split into partitions. For each topic, Kafka keeps a mini-mum of one partition. Each such partition contains messages in an immutable ordered sequence. A partition is implemented as a set of segment files of equal sizes.
Partition
Topics may have many partitions, so it can handle an arbitrary amount of data.
Partition offset
Each partitioned message has a unique sequence id called as offset.
Replicas of partition
Replicas are nothing but backups of a partition. Replicas are never read or write data. They are used to prevent data loss.
Brokers
Brokers are simple system responsible for maintaining the pub-lished data. Each broker may have zero or more partitions per topic. Assume, if there are N partitions in a topic and N number of brokers, each broker will have one partition.
Brokers are simple system responsible for maintaining the pub-lished data. Each broker may have zero or more partitions per topic. Assume, if there are N partitions in a topic and N number of brokers, each broker will have one partition.
Assume if there are N partitions in a topic and more than N brokers (n + m), the first N broker will have one partition and the next M broker will not have any partition for that particular topic.
Assume if there are N partitions in a topic and more than N brokers (n + m), the first N broker will have one partition and the next M broker will not have any partition for that particular topic.
Assume if there are N partitions in a topic and less than N brokers (n-m), each broker will have one or more partition sharing among them. This scenario is not recommended due to unequal load distri-bution among the broker.
Assume if there are N partitions in a topic and less than N brokers (n-m), each broker will have one or more partition sharing among them. This scenario is not recommended due to unequal load distri-bution among the broker.
Kafka Cluster
Kafka’s having more than one broker are called as Kafka cluster. A Kafka cluster can be expanded without downtime. These clusters are used to manage the persistence and replication of message data.
Producers
Producers are the publisher of messages to one or more Kafka topics. Producers send data to Kafka brokers. Every time a producer pub-lishes a message to a broker, the broker simply appends the message to the last segment file. Actually, the message will be appended to a partition. Producer can also send messages to a partition of their choice.
Consumers
Consumers read data from brokers. Consumers subscribes to one or more topics and consume published messages by pulling data from the brokers.
Leader
Leader is the node responsible for all reads and writes for the given partition. Every partition has one server acting as a leader.
Follower
Node which follows leader instructions are called as follower. If the leader fails, one of the follower will automatically become the new leader. A follower acts as normal consumer, pulls messages and up-dates its own data store.
Take a look at the following illustration. It shows the cluster diagram of Kafka.
The following table describes each of the components shown in the above diagram.
Broker
Kafka cluster typically consists of multiple brokers to maintain load balance. Kafka brokers are stateless, so they use ZooKeeper for maintaining their cluster state. One Kafka broker instance can handle hundreds of thousands of reads and writes per second and each bro-ker can handle TB of messages without performance impact. Kafka broker leader election can be done by ZooKeeper.
ZooKeeper
ZooKeeper is used for managing and coordinating Kafka broker. ZooKeeper service is mainly used to notify producer and consumer about the presence of any new broker in the Kafka system or failure of the broker in the Kafka system. As per the notification received by the Zookeeper regarding presence or failure of the broker then pro-ducer and consumer takes decision and starts coordinating their task with some other broker.
Producers
Producers push data to brokers. When the new broker is started, all the producers search it and automatically sends a message to that new broker. Kafka producer doesn’t wait for acknowledgements from the broker and sends messages as fast as the broker can handle.
Consumers
Since Kafka brokers are stateless, which means that the consumer has to maintain how many messages have been consumed by using partition offset. If the consumer acknowledges a particular message offset, it implies that the consumer has consumed all prior messages. The consumer issues an asynchronous pull request to the broker to have a buffer of bytes ready to consume. The consumers can rewind or skip to any point in a partition simply by supplying an offset value. Consumer offset value is notified by ZooKeeper.
As of now, we discussed the core concepts of Kafka. Let us now throw some light on the workflow of Kafka.
Kafka is simply a collection of topics split into one or more partitions. A Kafka partition is a linearly ordered sequence of messages, where each message is identified by their index (called as offset). All the data in a Kafka cluster is the disjointed union of partitions. Incoming messages are written at the end of a partition and messages are sequentially read by consumers. Durability is provided by replicating messages to different brokers.
Kafka provides both pub-sub and queue based messaging system in a fast, reliable, persisted, fault-tolerance and zero downtime manner. In both cases, producers simply send the message to a topic and consumer can choose any one type of messaging system depending on their need. Let us follow the steps in the next section to understand how the consumer can choose the messaging system of their choice.
Following is the step wise workflow of the Pub-Sub Messaging −
Producers send message to a topic at regular intervals.
Producers send message to a topic at regular intervals.
Kafka broker stores all messages in the partitions configured for that particular topic. It ensures the messages are equally shared between partitions. If the producer sends two messages and there are two partitions, Kafka will store one message in the first partition and the second message in the second partition.
Kafka broker stores all messages in the partitions configured for that particular topic. It ensures the messages are equally shared between partitions. If the producer sends two messages and there are two partitions, Kafka will store one message in the first partition and the second message in the second partition.
Consumer subscribes to a specific topic.
Consumer subscribes to a specific topic.
Once the consumer subscribes to a topic, Kafka will provide the current offset of the topic to the consumer and also saves the offset in the Zookeeper ensemble.
Once the consumer subscribes to a topic, Kafka will provide the current offset of the topic to the consumer and also saves the offset in the Zookeeper ensemble.
Consumer will request the Kafka in a regular interval (like 100 Ms) for new messages.
Consumer will request the Kafka in a regular interval (like 100 Ms) for new messages.
Once Kafka receives the messages from producers, it forwards these messages to the consumers.
Once Kafka receives the messages from producers, it forwards these messages to the consumers.
Consumer will receive the message and process it.
Consumer will receive the message and process it.
Once the messages are processed, consumer will send an acknowledgement to the Kafka broker.
Once the messages are processed, consumer will send an acknowledgement to the Kafka broker.
Once Kafka receives an acknowledgement, it changes the offset to the new value and updates it in the Zookeeper. Since offsets are maintained in the Zookeeper, the consumer can read next message correctly even during server outrages.
Once Kafka receives an acknowledgement, it changes the offset to the new value and updates it in the Zookeeper. Since offsets are maintained in the Zookeeper, the consumer can read next message correctly even during server outrages.
This above flow will repeat until the consumer stops the request.
This above flow will repeat until the consumer stops the request.
Consumer has the option to rewind/skip to the desired offset of a topic at any time and read all the subsequent messages.
Consumer has the option to rewind/skip to the desired offset of a topic at any time and read all the subsequent messages.
In a queue messaging system instead of a single consumer, a group of consumers having the same Group ID will subscribe to a topic. In simple terms, consumers subscribing to a topic with same Group ID are considered as a single group and the messages are shared among them. Let us check the actual workflow of this system.
Producers send message to a topic in a regular interval.
Producers send message to a topic in a regular interval.
Kafka stores all messages in the partitions configured for that particular topic similar to the earlier scenario.
Kafka stores all messages in the partitions configured for that particular topic similar to the earlier scenario.
A single consumer subscribes to a specific topic, assume Topic-01 with Group ID as Group-1.
A single consumer subscribes to a specific topic, assume Topic-01 with Group ID as Group-1.
Kafka interacts with the consumer in the same way as Pub-Sub Messaging until new consumer subscribes the same topic, Topic-01 with the same Group ID as Group-1.
Kafka interacts with the consumer in the same way as Pub-Sub Messaging until new consumer subscribes the same topic, Topic-01 with the same Group ID as Group-1.
Once the new consumer arrives, Kafka switches its operation to share mode and shares the data between the two consumers. This sharing will go on until the number of con-sumers reach the number of partition configured for that particular topic.
Once the new consumer arrives, Kafka switches its operation to share mode and shares the data between the two consumers. This sharing will go on until the number of con-sumers reach the number of partition configured for that particular topic.
Once the number of consumer exceeds the number of partitions, the new consumer will not receive any further message until any one of the existing consumer unsubscribes. This scenario arises because each consumer in Kafka will be assigned a minimum of one partition and once all the partitions are assigned to the existing consumers, the new consumers will have to wait.
Once the number of consumer exceeds the number of partitions, the new consumer will not receive any further message until any one of the existing consumer unsubscribes. This scenario arises because each consumer in Kafka will be assigned a minimum of one partition and once all the partitions are assigned to the existing consumers, the new consumers will have to wait.
This feature is also called as Consumer Group. In the same way, Kafka will provide the best of both the systems in a very simple and efficient manner.
This feature is also called as Consumer Group. In the same way, Kafka will provide the best of both the systems in a very simple and efficient manner.
A critical dependency of Apache Kafka is Apache Zookeeper, which is a distributed configuration and synchronization service. Zookeeper serves as the coordination interface between the Kafka brokers and consumers. The Kafka servers share information via a Zookeeper cluster. Kafka stores basic metadata in Zookeeper such as information about topics, brokers, consumer offsets (queue readers) and so on.
Since all the critical information is stored in the Zookeeper and it normally replicates this data across its ensemble, failure of Kafka broker / Zookeeper does not affect the state of the Kafka cluster. Kafka will restore the state, once the Zookeeper restarts. This gives zero downtime for Kafka. The leader election between the Kafka broker is also done by using Zookeeper in the event of leader failure.
To learn more on Zookeeper, please refer zookeeper
Let us continue further on how to install Java, ZooKeeper, and Kafka on your machine in the next chapter.
Following are the steps for installing Java on your machine.
Hopefully you have already installed java on your machine right now, so you just verify it using the following command.
$ java -version
If java is successfully installed on your machine, you could see the version of the installed Java.
If Java is not downloaded, please download the latest version of JDK by visiting the following link and download latest version.
Now the latest version is JDK 8u 60 and the file is “jdk-8u60-linux-x64.tar.gz”. Please download the file on your machine.
Generally, files being downloaded are stored in the downloads folder, verify it and extract the tar setup using the following commands.
$ cd /go/to/download/path
$ tar -zxf jdk-8u60-linux-x64.gz
To make java available to all users, move the extracted java content to usr/local/java/ folder.
$ su
password: (type password of root user)
$ mkdir /opt/jdk
$ mv jdk-1.8.0_60 /opt/jdk/
To set path and JAVA_HOME variables, add the following commands to ~/.bashrc file.
export JAVA_HOME =/usr/jdk/jdk-1.8.0_60
export PATH=$PATH:$JAVA_HOME/bin
Now apply all the changes into current running system.
$ source ~/.bashrc
Use the following command to change Java Alternatives.
update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_60/bin/java 100
Step 1.6 − Now verify java using verification command (java -version) explained in Step 1.
To install ZooKeeper framework on your machine, visit the following link and download the latest version of ZooKeeper.
As of now, latest version of ZooKeeper is 3.4.6 (ZooKeeper-3.4.6.tar.gz).
Extract tar file using the following command
$ cd opt/
$ tar -zxf zookeeper-3.4.6.tar.gz
$ cd zookeeper-3.4.6
$ mkdir data
Open Configuration File named conf/zoo.cfg using the command vi “conf/zoo.cfg” and all the following parameters to set as starting point.
$ vi conf/zoo.cfg
tickTime=2000
dataDir=/path/to/zookeeper/data
clientPort=2181
initLimit=5
syncLimit=2
Once the configuration file has been saved successfully and return to terminal again, you can start the zookeeper server.
$ bin/zkServer.sh start
After executing this command, you will get a response as shown below −
$ JMX enabled by default
$ Using config: /Users/../zookeeper-3.4.6/bin/../conf/zoo.cfg
$ Starting zookeeper ... STARTED
$ bin/zkCli.sh
After typing the above command, you will be connected to the zookeeper server and will get the below response.
Connecting to localhost:2181
................
................
................
Welcome to ZooKeeper!
................
................
WATCHER::
WatchedEvent state:SyncConnected type: None path:null
[zk: localhost:2181(CONNECTED) 0]
After connecting the server and performing all the operations, you can stop the zookeeper server with the following command −
$ bin/zkServer.sh stop
Now you have successfully installed Java and ZooKeeper on your machine. Let us see the steps to install Apache Kafka.
Let us continue with the following steps to install Kafka on your machine.
To install Kafka on your machine, click on the below link −
Now the latest version i.e., – kafka_2.11_0.9.0.0.tgz will be downloaded onto your machine.
Extract the tar file using the following command −
$ cd opt/
$ tar -zxf kafka_2.11.0.9.0.0 tar.gz
$ cd kafka_2.11.0.9.0.0
Now you have downloaded the latest version of Kafka on your machine.
You can start the server by giving the following command −
$ bin/kafka-server-start.sh config/server.properties
After the server starts, you would see the below response on your screen −
$ bin/kafka-server-start.sh config/server.properties
[2016-01-02 15:37:30,410] INFO KafkaConfig values:
request.timeout.ms = 30000
log.roll.hours = 168
inter.broker.protocol.version = 0.9.0.X
log.preallocate = false
security.inter.broker.protocol = PLAINTEXT
....................................................
....................................................
After performing all the operations, you can stop the server using the following command −
$ bin/kafka-server-stop.sh config/server.properties
Now that we have already discussed the Kafka installation, we can learn how to perform basic operations on Kafka in the next chapter.
First let us start implementing single node-single broker configuration and we will then migrate our setup to single node-multiple brokers configuration.
Hopefully you would have installed Java, ZooKeeper and Kafka on your machine by now. Before moving to the Kafka Cluster Setup, first you would need to start your ZooKeeper because Kafka Cluster uses ZooKeeper.
Open a new terminal and type the following command −
bin/zookeeper-server-start.sh config/zookeeper.properties
To start Kafka Broker, type the following command −
bin/kafka-server-start.sh config/server.properties
After starting Kafka Broker, type the command jps on ZooKeeper terminal and you would see the following response −
821 QuorumPeerMain
928 Kafka
931 Jps
Now you could see two daemons running on the terminal where QuorumPeerMain is ZooKeeper daemon and another one is Kafka daemon.
In this configuration you have a single ZooKeeper and broker id instance. Following are the steps to configure it −
Creating a Kafka Topic − Kafka provides a command line utility named kafka-topics.sh to create topics on the server. Open new terminal and type the below example.
Syntax
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1
--partitions 1 --topic topic-name
Example
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1
--partitions 1 --topic Hello-Kafka
We just created a topic named Hello-Kafka with a single partition and one replica factor. The above created output will be similar to the following output −
Output − Created topic Hello-Kafka
Once the topic has been created, you can get the notification in Kafka broker terminal window and the log for the created topic specified in “/tmp/kafka-logs/“ in the config/server.properties file.
To get a list of topics in Kafka server, you can use the following command −
Syntax
bin/kafka-topics.sh --list --zookeeper localhost:2181
Output
Hello-Kafka
Since we have created a topic, it will list out Hello-Kafka only. Suppose, if you create more than one topics, you will get the topic names in the output.
Syntax
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic topic-name
From the above syntax, two main parameters are required for the producer command line client −
Broker-list − The list of brokers that we want to send the messages to. In this case we only have one broker. The Config/server.properties file contains broker port id, since we know our broker is listening on port 9092, so you can specify it directly.
Topic name − Here is an example for the topic name.
Example
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Hello-Kafka
The producer will wait on input from stdin and publishes to the Kafka cluster. By default, every new line is published as a new message then the default producer properties are specified in config/producer.properties file. Now you can type a few lines of messages in the terminal as shown below.
Output
$ bin/kafka-console-producer.sh --broker-list localhost:9092
--topic Hello-Kafka[2016-01-16 13:50:45,931]
WARN property topic is not valid (kafka.utils.Verifia-bleProperties)
Hello
My first message
My second message
Similar to producer, the default consumer properties are specified in config/consumer.proper-ties file. Open a new terminal and type the below syntax for consuming messages.
Syntax
bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic topic-name
--from-beginning
Example
bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic Hello-Kafka
--from-beginning
Output
Hello
My first message
My second message
Finally, you are able to enter messages from the producer’s terminal and see them appearing in the consumer’s terminal. As of now, you have a very good understanding on the single node cluster with a single broker. Let us now move on to the multiple brokers configuration.
Before moving on to the multiple brokers cluster setup, first start your ZooKeeper server.
Create Multiple Kafka Brokers − We have one Kafka broker instance already in con-fig/server.properties. Now we need multiple broker instances, so copy the existing server.prop-erties file into two new config files and rename it as server-one.properties and server-two.prop-erties. Then edit both new files and assign the following changes −
# The id of the broker. This must be set to a unique integer for each broker.
broker.id=1
# The port the socket server listens on
port=9093
# A comma seperated list of directories under which to store log files
log.dirs=/tmp/kafka-logs-1
# The id of the broker. This must be set to a unique integer for each broker.
broker.id=2
# The port the socket server listens on
port=9094
# A comma seperated list of directories under which to store log files
log.dirs=/tmp/kafka-logs-2
Start Multiple Brokers− After all the changes have been made on three servers then open three new terminals to start each broker one by one.
Broker1
bin/kafka-server-start.sh config/server.properties
Broker2
bin/kafka-server-start.sh config/server-one.properties
Broker3
bin/kafka-server-start.sh config/server-two.properties
Now we have three different brokers running on the machine. Try it by yourself to check all the daemons by typing jps on the ZooKeeper terminal, then you would see the response.
Let us assign the replication factor value as three for this topic because we have three different brokers running. If you have two brokers, then the assigned replica value will be two.
Syntax
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3
-partitions 1 --topic topic-name
Example
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3
-partitions 1 --topic Multibrokerapplication
Output
created topic “Multibrokerapplication”
The Describe command is used to check which broker is listening on the current created topic as shown below −
bin/kafka-topics.sh --describe --zookeeper localhost:2181
--topic Multibrokerappli-cation
Output
bin/kafka-topics.sh --describe --zookeeper localhost:2181
--topic Multibrokerappli-cation
Topic:Multibrokerapplication PartitionCount:1
ReplicationFactor:3 Configs:
Topic:Multibrokerapplication Partition:0 Leader:0
Replicas:0,2,1 Isr:0,2,1
From the above output, we can conclude that first line gives a summary of all the partitions, showing topic name, partition count and the replication factor that we have chosen already. In the second line, each node will be the leader for a randomly selected portion of the partitions.
In our case, we see that our first broker (with broker.id 0) is the leader. Then Replicas:0,2,1 means that all the brokers replicate the topic finally Isr is the set of in-sync replicas. Well, this is the subset of replicas that are currently alive and caught up by the leader.
This procedure remains the same as in the single broker setup.
Example
bin/kafka-console-producer.sh --broker-list localhost:9092
--topic Multibrokerapplication
Output
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Multibrokerapplication
[2016-01-20 19:27:21,045] WARN Property topic is not valid (kafka.utils.Verifia-bleProperties)
This is single node-multi broker demo
This is the second message
This procedure remains the same as shown in the single broker setup.
Example
bin/kafka-console-consumer.sh --zookeeper localhost:2181
—topic Multibrokerapplica-tion --from-beginning
Output
bin/kafka-console-consumer.sh --zookeeper localhost:2181
—topic Multibrokerapplica-tion —from-beginning
This is single node-multi broker demo
This is the second message
In this chapter we will discuss the various basic topic operations.
As you have already understood how to create a topic in Kafka Cluster. Now let us modify a created topic using the following command
Syntax
bin/kafka-topics.sh —zookeeper localhost:2181 --alter --topic topic_name
--parti-tions count
Example
We have already created a topic “Hello-Kafka” with single partition count and one replica factor.
Now using “alter” command we have changed the partition count.
bin/kafka-topics.sh --zookeeper localhost:2181
--alter --topic Hello-kafka --parti-tions 2
Output
WARNING: If partitions are increased for a topic that has a key,
the partition logic or ordering of the messages will be affected
Adding partitions succeeded!
To delete a topic, you can use the following syntax.
Syntax
bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic topic_name
Example
bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic Hello-kafka
Output
> Topic Hello-kafka marked for deletion
Note −This will have no impact if delete.topic.enable is not set to true
Let us create an application for publishing and consuming messages using a Java client. Kafka producer client consists of the following API’s.
Let us understand the most important set of Kafka producer API in this section. The central part of the KafkaProducer API is KafkaProducer class. The KafkaProducer class provides an option to connect a Kafka broker in its constructor with the following methods.
KafkaProducer class provides send method to send messages asynchronously to a topic. The signature of send() is as follows
KafkaProducer class provides send method to send messages asynchronously to a topic. The signature of send() is as follows
producer.send(new ProducerRecord<byte[],byte[]>(topic,
partition, key1, value1) , callback);
ProducerRecord − The producer manages a buffer of records waiting to be sent.
ProducerRecord − The producer manages a buffer of records waiting to be sent.
Callback − A user-supplied callback to execute when the record has been acknowl-edged by the server (null indicates no callback).
Callback − A user-supplied callback to execute when the record has been acknowl-edged by the server (null indicates no callback).
KafkaProducer class provides a flush method to ensure all previously sent messages have been actually completed. Syntax of the flush method is as follows −
KafkaProducer class provides a flush method to ensure all previously sent messages have been actually completed. Syntax of the flush method is as follows −
public void flush()
KafkaProducer class provides partitionFor method, which helps in getting the partition metadata for a given topic. This can be used for custom partitioning. The signature of this method is as follows −
KafkaProducer class provides partitionFor method, which helps in getting the partition metadata for a given topic. This can be used for custom partitioning. The signature of this method is as follows −
public Map metrics()
It returns the map of internal metrics maintained by the producer.
public void close() − KafkaProducer class provides close method blocks until all previously sent requests are completed.
public void close() − KafkaProducer class provides close method blocks until all previously sent requests are completed.
The central part of the Producer API is Producer class. Producer class provides an option to connect Kafka broker in its constructor by the following methods.
The producer class provides send method to send messages to either single or multiple topics using the following signatures.
public void send(KeyedMessaget<k,v> message)
- sends the data to a single topic,par-titioned by key using either sync or async producer.
public void send(List<KeyedMessage<k,v>>messages)
- sends data to multiple topics.
Properties prop = new Properties();
prop.put(producer.type,”async”)
ProducerConfig config = new ProducerConfig(prop);
There are two types of producers – Sync and Async.
The same API configuration applies to Sync producer as well. The difference between them is a sync producer sends messages directly, but sends messages in background. Async producer is preferred when you want a higher throughput. In the previous releases like 0.8, an async producer does not have a callback for send() to register error handlers. This is available only in the current release of 0.9.
Producer class provides close method to close the producer pool connections to all Kafka bro-kers.
The Producer API’s main configuration settings are listed in the following table for better under-standing −
client.id
identifies producer application
producer.type
either sync or async
acks
The acks config controls the criteria under producer requests are con-sidered complete.
retries
If producer request fails, then automatically retry with specific value.
bootstrap.servers
bootstrapping list of brokers.
linger.ms
if you want to reduce the number of requests you can set linger.ms to something greater than some value.
key.serializer
Key for the serializer interface.
value.serializer
value for the serializer interface.
batch.size
Buffer size.
buffer.memory
controls the total amount of memory available to the producer for buff-ering.
ProducerRecord is a key/value pair that is sent to Kafka cluster.ProducerRecord class constructor for creating a record with partition, key and value pairs using the following signature.
public ProducerRecord (string topic, int partition, k key, v value)
Topic − user defined topic name that will appended to record.
Topic − user defined topic name that will appended to record.
Partition − partition count
Partition − partition count
Key − The key that will be included in the record.
Key − The key that will be included in the record.
Value − Record contents
public ProducerRecord (string topic, k key, v value)
ProducerRecord class constructor is used to create a record with key, value pairs and without partition.
Topic − Create a topic to assign record.
Topic − Create a topic to assign record.
Key − key for the record.
Key − key for the record.
Value − record contents.
Value − record contents.
public ProducerRecord (string topic, v value)
ProducerRecord class creates a record without partition and key.
Topic − create a topic.
Topic − create a topic.
Value − record contents.
Value − record contents.
The ProducerRecord class methods are listed in the following table −
public string topic()
Topic will append to the record.
public K key()
Key that will be included in the record. If no such key, null will be re-turned here.
public V value()
Record contents.
partition()
Partition count for the record
Before creating the application, first start ZooKeeper and Kafka broker then create your own topic in Kafka broker using create topic command. After that create a java class named Sim-pleProducer.java and type in the following coding.
//import util.properties packages
import java.util.Properties;
//import simple producer packages
import org.apache.kafka.clients.producer.Producer;
//import KafkaProducer packages
import org.apache.kafka.clients.producer.KafkaProducer;
//import ProducerRecord packages
import org.apache.kafka.clients.producer.ProducerRecord;
//Create java class named “SimpleProducer”
public class SimpleProducer {
public static void main(String[] args) throws Exception{
// Check arguments length value
if(args.length == 0){
System.out.println("Enter topic name");
return;
}
//Assign topicName to string variable
String topicName = args[0].toString();
// create instance for properties to access producer configs
Properties props = new Properties();
//Assign localhost id
props.put("bootstrap.servers", “localhost:9092");
//Set acknowledgements for producer requests.
props.put("acks", “all");
//If the request fails, the producer can automatically retry,
props.put("retries", 0);
//Specify buffer size in config
props.put("batch.size", 16384);
//Reduce the no of requests less than 0
props.put("linger.ms", 1);
//The buffer.memory controls the total amount of memory available to the producer for buffering.
props.put("buffer.memory", 33554432);
props.put("key.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
Producer<String, String> producer = new KafkaProducer
<String, String>(props);
for(int i = 0; i < 10; i++)
producer.send(new ProducerRecord<String, String>(topicName,
Integer.toString(i), Integer.toString(i)));
System.out.println(“Message sent successfully”);
producer.close();
}
}
Compilation − The application can be compiled using the following command.
javac -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*” *.java
Execution − The application can be executed using the following command.
java -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*”:. SimpleProducer <topic-name>
Output
Message sent successfully
To check the above output open new terminal and type Consumer CLI command to receive messages.
>> bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic <topic-name> —from-beginning
1
2
3
4
5
6
7
8
9
10
As of now we have created a producer to send messages to Kafka cluster. Now let us create a consumer to consume messages form the Kafka cluster. KafkaConsumer API is used to consume messages from the Kafka cluster. KafkaConsumer class constructor is defined below.
public KafkaConsumer(java.util.Map<java.lang.String,java.lang.Object> configs)
configs − Return a map of consumer configs.
KafkaConsumer class has the following significant methods that are listed in the table below.
public java.util.Set<TopicPar-tition> assignment()
Get the set of partitions currently assigned by the con-sumer.
public string subscription()
Subscribe to the given list of topics to get dynamically as-signed partitions.
public void sub-scribe(java.util.List<java.lang.String> topics, ConsumerRe-balanceListener listener)
Subscribe to the given list of topics to get dynamically as-signed partitions.
public void unsubscribe()
Unsubscribe the topics from the given list of partitions.
public void sub-scribe(java.util.List<java.lang.String> topics)
Subscribe to the given list of topics to get dynamically as-signed partitions. If the given list of topics is empty, it is treated the same as unsubscribe().
public void sub-scribe(java.util.regex.Pattern pattern, ConsumerRebalanceLis-tener listener)
The argument pattern refers to the subscribing pattern in the format of regular expression and the listener argument gets notifications from the subscribing pattern.
public void as-sign(java.util.List<TopicParti-tion> partitions)
Manually assign a list of partitions to the customer.
poll()
Fetch data for the topics or partitions specified using one of the subscribe/assign APIs. This will return error, if the topics are not subscribed before the polling for data.
public void commitSync()
Commit offsets returned on the last poll() for all the sub-scribed list of topics and partitions. The same operation is applied to commitAsyn().
public void seek(TopicPartition partition, long offset)
Fetch the current offset value that consumer will use on the next poll() method.
public void resume()
Resume the paused partitions.
public void wakeup()
Wakeup the consumer.
The ConsumerRecord API is used to receive records from the Kafka cluster. This API consists of a topic name, partition number, from which the record is being received and an offset that points to the record in a Kafka partition. ConsumerRecord class is used to create a consumer record with specific topic name, partition count and <key, value> pairs. It has the following signature.
public ConsumerRecord(string topic,int partition, long offset,K key, V value)
Topic − The topic name for consumer record received from the Kafka cluster.
Topic − The topic name for consumer record received from the Kafka cluster.
Partition − Partition for the topic.
Partition − Partition for the topic.
Key − The key of the record, if no key exists null will be returned.
Key − The key of the record, if no key exists null will be returned.
Value − Record contents.
Value − Record contents.
ConsumerRecords API acts as a container for ConsumerRecord. This API is used to keep the list of ConsumerRecord per partition for a particular topic. Its Constructor is defined below.
public ConsumerRecords(java.util.Map<TopicPartition,java.util.List
<Consumer-Record>K,V>>> records)
TopicPartition − Return a map of partition for a particular topic.
TopicPartition − Return a map of partition for a particular topic.
Records − Return list of ConsumerRecord.
Records − Return list of ConsumerRecord.
ConsumerRecords class has the following methods defined.
public int count()
The number of records for all the topics.
public Set partitions()
The set of partitions with data in this record set (if no data was returned then the set is empty).
public Iterator iterator()
Iterator enables you to cycle through a collection, obtaining or re-moving elements.
public List records()
Get list of records for the given partition.
The configuration settings for the Consumer client API main configuration settings are listed below −
bootstrap.servers
Bootstrapping list of brokers.
group.id
Assigns an individual consumer to a group.
enable.auto.commit
Enable auto commit for offsets if the value is true, otherwise not committed.
auto.commit.interval.ms
Return how often updated consumed offsets are written to ZooKeeper.
session.timeout.ms
Indicates how many milliseconds Kafka will wait for the ZooKeeper to respond to a request (read or write) before giving up and continuing to consume messages.
The producer application steps remain the same here. First, start your ZooKeeper and Kafka broker. Then create a SimpleConsumer application with the java class named SimpleCon-sumer.java and type the following code.
import java.util.Properties;
import java.util.Arrays;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.ConsumerRecord;
public class SimpleConsumer {
public static void main(String[] args) throws Exception {
if(args.length == 0){
System.out.println("Enter topic name");
return;
}
//Kafka consumer configuration settings
String topicName = args[0].toString();
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test");
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("session.timeout.ms", "30000");
props.put("key.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer
<String, String>(props);
//Kafka Consumer subscribes list of topics here.
consumer.subscribe(Arrays.asList(topicName))
//print the topic name
System.out.println("Subscribed to topic " + topicName);
int i = 0;
while (true) {
ConsumerRecords<String, String> records = con-sumer.poll(100);
for (ConsumerRecord<String, String> record : records)
// print the offset,key and value for the consumer records.
System.out.printf("offset = %d, key = %s, value = %s\n",
record.offset(), record.key(), record.value());
}
}
}
Compilation − The application can be compiled using the following command.
javac -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*” *.java
Execution − The application can be executed using the following command
java -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*”:. SimpleConsumer <topic-name>
Input − Open the producer CLI and send some messages to the topic. You can put the smple input as ‘Hello Consumer’.
Output − Following will be the output.
Subscribed to topic Hello-Kafka
offset = 3, key = null, value = Hello Consumer
Consumer group is a multi-threaded or multi-machine consumption from Kafka topics.
Consumers can join a group by using the samegroup.id.
Consumers can join a group by using the samegroup.id.
The maximum parallelism of a group is that the number of consumers in the group ← no of partitions.
The maximum parallelism of a group is that the number of consumers in the group ← no of partitions.
Kafka assigns the partitions of a topic to the consumer in a group, so that each partition is consumed by exactly one consumer in the group.
Kafka assigns the partitions of a topic to the consumer in a group, so that each partition is consumed by exactly one consumer in the group.
Kafka guarantees that a message is only ever read by a single consumer in the group.
Kafka guarantees that a message is only ever read by a single consumer in the group.
Consumers can see the message in the order they were stored in the log.
Consumers can see the message in the order they were stored in the log.
Adding more processes/threads will cause Kafka to re-balance. If any consumer or broker fails to send heartbeat to ZooKeeper, then it can be re-configured via the Kafka cluster. During this re-balance, Kafka will assign available partitions to the available threads, possibly moving a partition to another process.
import java.util.Properties;
import java.util.Arrays;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.ConsumerRecord;
public class ConsumerGroup {
public static void main(String[] args) throws Exception {
if(args.length < 2){
System.out.println("Usage: consumer <topic> <groupname>");
return;
}
String topic = args[0].toString();
String group = args[1].toString();
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", group);
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("session.timeout.ms", "30000");
props.put("key.deserializer",
"org.apache.kafka.common.serialization.ByteArraySerializer");
props.put("value.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
consumer.subscribe(Arrays.asList(topic));
System.out.println("Subscribed to topic " + topic);
int i = 0;
while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records)
System.out.printf("offset = %d, key = %s, value = %s\n",
record.offset(), record.key(), record.value());
}
}
}
javac -cp “/path/to/kafka/kafka_2.11-0.9.0.0/libs/*" ConsumerGroup.java
>>java -cp “/path/to/kafka/kafka_2.11-0.9.0.0/libs/*":.
ConsumerGroup <topic-name> my-group
>>java -cp "/home/bala/Workspace/kafka/kafka_2.11-0.9.0.0/libs/*":.
ConsumerGroup <topic-name> my-group
Here we have created a sample group name as my-group with two consumers. Similarly, you can create your group and number of consumers in the group.
Open producer CLI and send some messages like −
Test consumer group 01
Test consumer group 02
Subscribed to topic Hello-kafka
offset = 3, key = null, value = Test consumer group 01
Subscribed to topic Hello-kafka
offset = 3, key = null, value = Test consumer group 02
Now hopefully you would have understood SimpleConsumer and ConsumeGroup by using the Java client demo. Now you have an idea about how to send and receive messages using a Java client. Let us continue Kafka integration with big data technologies in the next chapter.
In this chapter, we will learn how to integrate Kafka with Apache Storm.
Storm was originally created by Nathan Marz and team at BackType. In a short time, Apache Storm became a standard for distributed real-time processing system that allows you to process a huge volume of data. Storm is very fast and a benchmark clocked it at over a million tuples processed per second per node. Apache Storm runs continuously, consuming data from the configured sources (Spouts) and passes the data down the processing pipeline (Bolts). Com-bined, Spouts and Bolts make a Topology.
Kafka and Storm naturally complement each other, and their powerful cooperation enables real-time streaming analytics for fast-moving big data. Kafka and Storm integration is to make easier for developers to ingest and publish data streams from Storm topologies.
A spout is a source of streams. For example, a spout may read tuples off a Kafka Topic and emit them as a stream. A bolt consumes input streams, process and possibly emits new streams. Bolts can do anything from running functions, filtering tuples, do streaming aggregations, streaming joins, talk to databases, and more. Each node in a Storm topology executes in parallel. A topology runs indefinitely until you terminate it. Storm will automatically reassign any failed tasks. Additionally, Storm guarantees that there will be no data loss, even if the machines go down and messages are dropped.
Let us go through the Kafka-Storm integration API’s in detail. There are three main classes to integrate Kafka with Storm. They are as follows −
BrokerHosts is an interface and ZkHosts and StaticHosts are its two main implementations. ZkHosts is used to track the Kafka brokers dynamically by maintaining the details in ZooKeeper, while StaticHosts is used to manually / statically set the Kafka brokers and its details. ZkHosts is the simple and fast way to access the Kafka broker.
The signature of ZkHosts is as follows −
public ZkHosts(String brokerZkStr, String brokerZkPath)
public ZkHosts(String brokerZkStr)
Where brokerZkStr is ZooKeeper host and brokerZkPath is the ZooKeeper path to maintain the Kafka broker details.
This API is used to define configuration settings for the Kafka cluster. The signature of Kafka Con-fig is defined as follows
public KafkaConfig(BrokerHosts hosts, string topic)
Hosts − The BrokerHosts can be ZkHosts / StaticHosts.
Topic − topic name.
Spoutconfig is an extension of KafkaConfig that supports additional ZooKeeper information.
public SpoutConfig(BrokerHosts hosts, string topic, string zkRoot, string id)
Hosts − The BrokerHosts can be any implementation of BrokerHosts interface
Hosts − The BrokerHosts can be any implementation of BrokerHosts interface
Topic − topic name.
Topic − topic name.
zkRoot − ZooKeeper root path.
zkRoot − ZooKeeper root path.
id − The spout stores the state of the offsets its consumed in Zookeeper. The id should uniquely identify your spout.
id − The spout stores the state of the offsets its consumed in Zookeeper. The id should uniquely identify your spout.
SchemeAsMultiScheme is an interface that dictates how the ByteBuffer consumed from Kafka gets transformed into a storm tuple. It is derived from MultiScheme and accept implementation of Scheme class. There are lot of implementation of Scheme class and one such implementation is StringScheme, which parses the byte as a simple string. It also controls the naming of your output field. The signature is defined as follows.
public SchemeAsMultiScheme(Scheme scheme)
Scheme − byte buffer consumed from kafka.
Scheme − byte buffer consumed from kafka.
KafkaSpout is our spout implementation, which will integrate with Storm. It fetches the mes-sages from kafka topic and emits it into Storm ecosystem as tuples. KafkaSpout get its config-uration details from SpoutConfig.
Below is a sample code to create a simple Kafka spout.
// ZooKeeper connection string
BrokerHosts hosts = new ZkHosts(zkConnString);
//Creating SpoutConfig Object
SpoutConfig spoutConfig = new SpoutConfig(hosts,
topicName, "/" + topicName UUID.randomUUID().toString());
//convert the ByteBuffer to String.
spoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme());
//Assign SpoutConfig to KafkaSpout.
KafkaSpout kafkaSpout = new KafkaSpout(spoutConfig);
Bolt is a component that takes tuples as input, processes the tuple, and produces new tuples as output. Bolts will implement IRichBolt interface. In this program, two bolt classes WordSplitter-Bolt and WordCounterBolt are used to perform the operations.
IRichBolt interface has the following methods −
Prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout.
Prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout.
Execute − Process a single tuple of input.
Execute − Process a single tuple of input.
Cleanup − Called when a bolt is going to shut down.
Cleanup − Called when a bolt is going to shut down.
declareOutputFields − Declares the output schema of the tuple.
declareOutputFields − Declares the output schema of the tuple.
Let us create SplitBolt.java, which implements the logic to split a sentence into words and CountBolt.java, which implements logic to separate unique words and count its occurrence.
import java.util.Map;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.task.OutputCollector;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.IRichBolt;
import backtype.storm.task.TopologyContext;
public class SplitBolt implements IRichBolt {
private OutputCollector collector;
@Override
public void prepare(Map stormConf, TopologyContext context,
OutputCollector collector) {
this.collector = collector;
}
@Override
public void execute(Tuple input) {
String sentence = input.getString(0);
String[] words = sentence.split(" ");
for(String word: words) {
word = word.trim();
if(!word.isEmpty()) {
word = word.toLowerCase();
collector.emit(new Values(word));
}
}
collector.ack(input);
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word"));
}
@Override
public void cleanup() {}
@Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
import java.util.Map;
import java.util.HashMap;
import backtype.storm.tuple.Tuple;
import backtype.storm.task.OutputCollector;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.IRichBolt;
import backtype.storm.task.TopologyContext;
public class CountBolt implements IRichBolt{
Map<String, Integer> counters;
private OutputCollector collector;
@Override
public void prepare(Map stormConf, TopologyContext context,
OutputCollector collector) {
this.counters = new HashMap<String, Integer>();
this.collector = collector;
}
@Override
public void execute(Tuple input) {
String str = input.getString(0);
if(!counters.containsKey(str)){
counters.put(str, 1);
}else {
Integer c = counters.get(str) +1;
counters.put(str, c);
}
collector.ack(input);
}
@Override
public void cleanup() {
for(Map.Entry<String, Integer> entry:counters.entrySet()){
System.out.println(entry.getKey()+" : " + entry.getValue());
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
}
@Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
The Storm topology is basically a Thrift structure. TopologyBuilder class provides simple and easy methods to create complex topologies. The TopologyBuilder class has methods to set spout (setSpout) and to set bolt (setBolt). Finally, TopologyBuilder has createTopology to create to-pology. shuffleGrouping and fieldsGrouping methods help to set stream grouping for spout and bolts.
Local Cluster − For development purposes, we can create a local cluster using LocalCluster object and then submit the topology using submitTopology method of LocalCluster class.
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.topology.TopologyBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import backtype.storm.spout.SchemeAsMultiScheme;
import storm.kafka.trident.GlobalPartitionInformation;
import storm.kafka.ZkHosts;
import storm.kafka.Broker;
import storm.kafka.StaticHosts;
import storm.kafka.BrokerHosts;
import storm.kafka.SpoutConfig;
import storm.kafka.KafkaConfig;
import storm.kafka.KafkaSpout;
import storm.kafka.StringScheme;
public class KafkaStormSample {
public static void main(String[] args) throws Exception{
Config config = new Config();
config.setDebug(true);
config.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 1);
String zkConnString = "localhost:2181";
String topic = "my-first-topic";
BrokerHosts hosts = new ZkHosts(zkConnString);
SpoutConfig kafkaSpoutConfig = new SpoutConfig (hosts, topic, "/" + topic,
UUID.randomUUID().toString());
kafkaSpoutConfig.bufferSizeBytes = 1024 * 1024 * 4;
kafkaSpoutConfig.fetchSizeBytes = 1024 * 1024 * 4;
kafkaSpoutConfig.forceFromStart = true;
kafkaSpoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme());
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("kafka-spout", new KafkaSpout(kafkaSpoutCon-fig));
builder.setBolt("word-spitter", new SplitBolt()).shuffleGroup-ing("kafka-spout");
builder.setBolt("word-counter", new CountBolt()).shuffleGroup-ing("word-spitter");
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("KafkaStormSample", config, builder.create-Topology());
Thread.sleep(10000);
cluster.shutdown();
}
}
Before moving compilation, Kakfa-Storm integration needs curator ZooKeeper client java library. Curator version 2.9.1 support Apache Storm version 0.9.5 (which we use in this tutorial). Down-load the below specified jar files and place it in java class path.
curator-client-2.9.1.jar
curator-framework-2.9.1.jar
After including dependency files, compile the program using the following command,
javac -cp "/path/to/Kafka/apache-storm-0.9.5/lib/*" *.java
Start Kafka Producer CLI (explained in previous chapter), create a new topic called my-first-topic and provide some sample messages as shown below −
hello
kafka
storm
spark
test message
another test message
Now execute the application using the following command −
java -cp “/path/to/Kafka/apache-storm-0.9.5/lib/*”:. KafkaStormSample
The sample output of this application is specified below −
storm : 1
test : 2
spark : 1
another : 1
kafka : 1
hello : 1
message : 2
In this chapter, we will be discussing about how to integrate Apache Kafka with Spark Streaming API.
Spark Streaming API enables scalable, high-throughput, fault-tolerant stream processing of live data streams. Data can be ingested from many sources like Kafka, Flume, Twitter, etc., and can be processed using complex algorithms such as high-level functions like map, reduce, join and window. Finally, processed data can be pushed out to filesystems, databases, and live dash-boards. Resilient Distributed Datasets (RDD) is a fundamental data structure of Spark. It is an immutable distributed collection of objects. Each dataset in RDD is divided into logical partitions, which may be computed on different nodes of the cluster.
Kafka is a potential messaging and integration platform for Spark streaming. Kafka act as the central hub for real-time streams of data and are processed using complex algorithms in Spark Streaming. Once the data is processed, Spark Streaming could be publishing results into yet another Kafka topic or store in HDFS, databases or dashboards. The following diagram depicts the conceptual flow.
Now, let us go through Kafka-Spark API’s in detail.
It represents configuration for a Spark application. Used to set various Spark parameters as key-value pairs.
SparkConf class has the following methods −
set(string key, string value) − set configuration variable.
set(string key, string value) − set configuration variable.
remove(string key) − remove key from the configuration.
remove(string key) − remove key from the configuration.
setAppName(string name) − set application name for your application.
setAppName(string name) − set application name for your application.
get(string key) − get key
get(string key) − get key
This is the main entry point for Spark functionality. A SparkContext represents the connection to a Spark cluster, and can be used to create RDDs, accumulators and broadcast variables on the cluster. The signature is defined as shown below.
public StreamingContext(String master, String appName, Duration batchDuration,
String sparkHome, scala.collection.Seq<String> jars,
scala.collection.Map<String,String> environment)
master − cluster URL to connect to (e.g. mesos://host:port, spark://host:port, local[4]).
master − cluster URL to connect to (e.g. mesos://host:port, spark://host:port, local[4]).
appName − a name for your job, to display on the cluster web UI
appName − a name for your job, to display on the cluster web UI
batchDuration − the time interval at which streaming data will be divided into batches
batchDuration − the time interval at which streaming data will be divided into batches
public StreamingContext(SparkConf conf, Duration batchDuration)
Create a StreamingContext by providing the configuration necessary for a new SparkContext.
conf − Spark parameters
conf − Spark parameters
batchDuration − the time interval at which streaming data will be divided into batches
batchDuration − the time interval at which streaming data will be divided into batches
KafkaUtils API is used to connect the Kafka cluster to Spark streaming. This API has the signifi-cant method createStream signature defined as below.
public static ReceiverInputDStream<scala.Tuple2<String,String>> createStream(
StreamingContext ssc, String zkQuorum, String groupId,
scala.collection.immutable.Map<String,Object> topics, StorageLevel storageLevel)
The above shown method is used to Create an input stream that pulls messages from Kafka Brokers.
ssc − StreamingContext object.
ssc − StreamingContext object.
zkQuorum − Zookeeper quorum.
zkQuorum − Zookeeper quorum.
groupId − The group id for this consumer.
groupId − The group id for this consumer.
topics − return a map of topics to consume.
topics − return a map of topics to consume.
storageLevel − Storage level to use for storing the received objects.
storageLevel − Storage level to use for storing the received objects.
KafkaUtils API has another method createDirectStream, which is used to create an input stream that directly pulls messages from Kafka Brokers without using any receiver. This stream can guarantee that each message from Kafka is included in transformations exactly once.
The sample application is done in Scala. To compile the application, please download and install sbt, scala build tool (similar to maven). The main application code is presented below.
import java.util.HashMap
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, Produc-erRecord}
import org.apache.spark.SparkConf
import org.apache.spark.streaming._
import org.apache.spark.streaming.kafka._
object KafkaWordCount {
def main(args: Array[String]) {
if (args.length < 4) {
System.err.println("Usage: KafkaWordCount <zkQuorum><group> <topics> <numThreads>")
System.exit(1)
}
val Array(zkQuorum, group, topics, numThreads) = args
val sparkConf = new SparkConf().setAppName("KafkaWordCount")
val ssc = new StreamingContext(sparkConf, Seconds(2))
ssc.checkpoint("checkpoint")
val topicMap = topics.split(",").map((_, numThreads.toInt)).toMap
val lines = KafkaUtils.createStream(ssc, zkQuorum, group, topicMap).map(_._2)
val words = lines.flatMap(_.split(" "))
val wordCounts = words.map(x => (x, 1L))
.reduceByKeyAndWindow(_ + _, _ - _, Minutes(10), Seconds(2), 2)
wordCounts.print()
ssc.start()
ssc.awaitTermination()
}
}
The spark-kafka integration depends on the spark, spark streaming and spark Kafka integration jar. Create a new file build.sbt and specify the application details and its dependency. The sbt will download the necessary jar while compiling and packing the application.
name := "Spark Kafka Project"
version := "1.0"
scalaVersion := "2.10.5"
libraryDependencies += "org.apache.spark" %% "spark-core" % "1.6.0"
libraryDependencies += "org.apache.spark" %% "spark-streaming" % "1.6.0"
libraryDependencies += "org.apache.spark" %% "spark-streaming-kafka" % "1.6.0"
Run the following command to compile and package the jar file of the application. We need to submit the jar file into the spark console to run the application.
sbt package
Start Kafka Producer CLI (explained in the previous chapter), create a new topic called my-first-topic and provide some sample messages as shown below.
Another spark test message
Run the following command to submit the application to spark console.
/usr/local/spark/bin/spark-submit --packages org.apache.spark:spark-streaming
-kafka_2.10:1.6.0 --class "KafkaWordCount" --master local[4] target/scala-2.10/spark
-kafka-project_2.10-1.0.jar localhost:2181 <group name> <topic name> <number of threads>
The sample output of this application is shown below.
spark console messages ..
(Test,1)
(spark,1)
(another,1)
(message,1)
spark console message ..
Let us analyze a real time application to get the latest twitter feeds and its hashtags. Earlier, we have seen integration of Storm and Spark with Kafka. In both the scenarios, we created a Kafka Producer (using cli) to send message to the Kafka ecosystem. Then, the storm and spark inte-gration reads the messages by using the Kafka consumer and injects it into storm and spark ecosystem respectively. So, practically we need to create a Kafka Producer, which should −
Read the twitter feeds using “Twitter Streaming API”,
Process the feeds,
Extract the HashTags and
Send it to Kafka.
Once the HashTags are received by Kafka, the Storm / Spark integration receive the infor-mation and send it to Storm / Spark ecosystem.
The “Twitter Streaming API” can be accessed in any programming language. The “twitter4j” is an open source, unofficial Java library, which provides a Java based module to easily access the “Twitter Streaming API”. The “twitter4j” provides a listener based framework to access the tweets. To access the “Twitter Streaming API”, we need to sign in for Twitter developer account and should get the following OAuth authentication details.
Customerkey
CustomerSecret
AccessToken
AccessTookenSecret
Once the developer account is created, download the “twitter4j” jar files and place it in the java class path.
The Complete Twitter Kafka producer coding (KafkaTwitterProducer.java) is listed below −
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;
import twitter4j.*;
import twitter4j.conf.*;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
public class KafkaTwitterProducer {
public static void main(String[] args) throws Exception {
LinkedBlockingQueue<Status> queue = new LinkedBlockingQueue<Sta-tus>(1000);
if(args.length < 5){
System.out.println(
"Usage: KafkaTwitterProducer <twitter-consumer-key>
<twitter-consumer-secret> <twitter-access-token>
<twitter-access-token-secret>
<topic-name> <twitter-search-keywords>");
return;
}
String consumerKey = args[0].toString();
String consumerSecret = args[1].toString();
String accessToken = args[2].toString();
String accessTokenSecret = args[3].toString();
String topicName = args[4].toString();
String[] arguments = args.clone();
String[] keyWords = Arrays.copyOfRange(arguments, 5, arguments.length);
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessTokenSecret);
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).get-Instance();
StatusListener listener = new StatusListener() {
@Override
public void onStatus(Status status) {
queue.offer(status);
// System.out.println("@" + status.getUser().getScreenName()
+ " - " + status.getText());
// System.out.println("@" + status.getUser().getScreen-Name());
/*for(URLEntity urle : status.getURLEntities()) {
System.out.println(urle.getDisplayURL());
}*/
/*for(HashtagEntity hashtage : status.getHashtagEntities()) {
System.out.println(hashtage.getText());
}*/
}
@Override
public void onDeletionNotice(StatusDeletionNotice statusDeletion-Notice) {
// System.out.println("Got a status deletion notice id:"
+ statusDeletionNotice.getStatusId());
}
@Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
// System.out.println("Got track limitation notice:" +
num-berOfLimitedStatuses);
}
@Override
public void onScrubGeo(long userId, long upToStatusId) {
// System.out.println("Got scrub_geo event userId:" + userId +
"upToStatusId:" + upToStatusId);
}
@Override
public void onStallWarning(StallWarning warning) {
// System.out.println("Got stall warning:" + warning);
}
@Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
twitterStream.addListener(listener);
FilterQuery query = new FilterQuery().track(keyWords);
twitterStream.filter(query);
Thread.sleep(5000);
//Add Kafka producer config settings
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
Producer<String, String> producer = new KafkaProducer<String, String>(props);
int i = 0;
int j = 0;
while(i < 10) {
Status ret = queue.poll();
if (ret == null) {
Thread.sleep(100);
i++;
}else {
for(HashtagEntity hashtage : ret.getHashtagEntities()) {
System.out.println("Hashtag: " + hashtage.getText());
producer.send(new ProducerRecord<String, String>(
top-icName, Integer.toString(j++), hashtage.getText()));
}
}
}
producer.close();
Thread.sleep(5000);
twitterStream.shutdown();
}
}
Compile the application using the following command −
javac -cp “/path/to/kafka/libs/*”:”/path/to/twitter4j/lib/*”:. KafkaTwitterProducer.java
Open two consoles. Run the above compiled application as shown below in one console.
java -cp “/path/to/kafka/libs/*”:”/path/to/twitter4j/lib/*”:
. KafkaTwitterProducer <twitter-consumer-key>
<twitter-consumer-secret>
<twitter-access-token>
<twitter-ac-cess-token-secret>
my-first-topic food
Run any one of the Spark / Storm application explained in the previous chapter in another win-dow. The main point to note is that the topic used should be same in both cases. Here, we have used “my-first-topic” as the topic name.
The output of this application will depend on the keywords and the current feed of the twitter. A sample output is specified below (storm integration).
. . .
food : 1
foodie : 2
burger : 1
. . .
Kafka Tool packaged under “org.apache.kafka.tools.*. Tools are categorized into system tools and replication tools.
System tools can be run from the command line using the run class script. The syntax is as follows −
bin/kafka-run-class.sh package.class - - options
Some of the system tools are mentioned below −
Kafka Migration Tool − This tool is used to migrate a broker from one version to an-other.
Kafka Migration Tool − This tool is used to migrate a broker from one version to an-other.
Mirror Maker − This tool is used to provide mirroring of one Kafka cluster to another.
Mirror Maker − This tool is used to provide mirroring of one Kafka cluster to another.
Consumer Offset Checker − This tool displays Consumer Group, Topic, Partitions, Off-set, logSize, Owner for the specified set of Topics and Consumer Group.
Consumer Offset Checker − This tool displays Consumer Group, Topic, Partitions, Off-set, logSize, Owner for the specified set of Topics and Consumer Group.
Kafka replication is a high level design tool. The purpose of adding replication tool is for stronger durability and higher availability. Some of the replication tools are mentioned below −
Create Topic Tool − This creates a topic with a default number of partitions, replication factor and uses Kafka's default scheme to do replica assignment.
Create Topic Tool − This creates a topic with a default number of partitions, replication factor and uses Kafka's default scheme to do replica assignment.
List Topic Tool − This tool lists the information for a given list of topics. If no topics are provided in the command line, the tool queries Zookeeper to get all the topics and lists the information for them. The fields that the tool displays are topic name, partition, leader, replicas, isr.
List Topic Tool − This tool lists the information for a given list of topics. If no topics are provided in the command line, the tool queries Zookeeper to get all the topics and lists the information for them. The fields that the tool displays are topic name, partition, leader, replicas, isr.
Add Partition Tool − Creation of a topic, the number of partitions for topic has to be specified. Later on, more partitions may be needed for the topic, when the volume of the topic will increase. This tool helps to add more partitions for a specific topic and also allows manual replica assignment of the added partitions.
Add Partition Tool − Creation of a topic, the number of partitions for topic has to be specified. Later on, more partitions may be needed for the topic, when the volume of the topic will increase. This tool helps to add more partitions for a specific topic and also allows manual replica assignment of the added partitions.
Kafka supports many of today's best industrial applications. We will provide a very brief overview of some of the most notable applications of Kafka in this chapter.
Twitter is an online social networking service that provides a platform to send and receive user tweets. Registered users can read and post tweets, but unregistered users can only read tweets. Twitter uses Storm-Kafka as a part of their stream processing infrastructure.
Apache Kafka is used at LinkedIn for activity stream data and operational metrics. Kafka mes-saging system helps LinkedIn with various products like LinkedIn Newsfeed, LinkedIn Today for online message consumption and in addition to offline analytics systems like Hadoop. Kafka’s strong durability is also one of the key factors in connection with LinkedIn.
Netflix is an American multinational provider of on-demand Internet streaming media. Netflix uses Kafka for real-time monitoring and event processing.
Mozilla is a free-software community, created in 1998 by members of Netscape. Kafka will soon be replacing a part of Mozilla current production system to collect performance and usage data from the end-user’s browser for projects like Telemetry, Test Pilot, etc.
Oracle provides native connectivity to Kafka from its Enterprise Service Bus product called OSB (Oracle Service Bus) which allows developers to leverage OSB built-in mediation capabilities to implement staged data pipelines.
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": 2242,
"s": 1967,
"text": "In Big Data, an enormous volume of data is used. Regarding data, we have two main challenges.The first challenge is how to collect large volume of data and the second challenge is to analyze the collected data. To overcome those challenges, you must need a messaging system."
},
{
"code": null,
"e": 2598,
"s": 2242,
"text": "Kafka is designed for distributed high throughput systems. Kafka tends to work very well as a replacement for a more traditional message broker. In comparison to other messaging systems, Kafka has better throughput, built-in partitioning, replication and inherent fault-tolerance, which makes it a good fit for large-scale message processing applications."
},
{
"code": null,
"e": 3103,
"s": 2598,
"text": "A Messaging System is responsible for transferring data from one application to another, so the applications can focus on data, but not worry about how to share it. Distributed messaging is based on the concept of reliable message queuing. Messages are queued asynchronously between client applications and messaging system. Two types of messaging patterns are available − one is point to point and the other is publish-subscribe (pub-sub) messaging system. Most of the messaging patterns follow pub-sub."
},
{
"code": null,
"e": 3615,
"s": 3103,
"text": "In a point-to-point system, messages are persisted in a queue. One or more consumers can consume the messages in the queue, but a particular message can be consumed by a maximum of one consumer only. Once a consumer reads a message in the queue, it disappears from that queue. The typical example of this system is an Order Processing System, where each order will be processed by one Order Processor, but Multiple Order Processors can work as well at the same time. The following diagram depicts the structure."
},
{
"code": null,
"e": 4139,
"s": 3615,
"text": "In the publish-subscribe system, messages are persisted in a topic. Unlike point-to-point system, consumers can subscribe to one or more topic and consume all the messages in that topic. In the Publish-Subscribe system, message producers are called publishers and message consumers are called subscribers. A real-life example is Dish TV, which publishes different channels like sports, movies, music, etc., and anyone can subscribe to their own set of channels and get them whenever their subscribed channels are available."
},
{
"code": null,
"e": 4644,
"s": 4139,
"text": "Apache Kafka is a distributed publish-subscribe messaging system and a robust queue that can handle a high volume of data and enables you to pass messages from one end-point to another. Kafka is suitable for both offline and online message consumption. Kafka messages are persisted on the disk and replicated within the cluster to prevent data loss. Kafka is built on top of the ZooKeeper synchronization service. It integrates very well with Apache Storm and Spark for real-time streaming data analysis."
},
{
"code": null,
"e": 4684,
"s": 4644,
"text": "Following are a few benefits of Kafka −"
},
{
"code": null,
"e": 4765,
"s": 4684,
"text": "Reliability − Kafka is distributed, partitioned, replicated and fault tolerance."
},
{
"code": null,
"e": 4846,
"s": 4765,
"text": "Reliability − Kafka is distributed, partitioned, replicated and fault tolerance."
},
{
"code": null,
"e": 4917,
"s": 4846,
"text": "Scalability − Kafka messaging system scales easily without down time.."
},
{
"code": null,
"e": 4988,
"s": 4917,
"text": "Scalability − Kafka messaging system scales easily without down time.."
},
{
"code": null,
"e": 5116,
"s": 4988,
"text": "Durability − Kafka uses Distributed commit log which means messages persists on disk as fast as possible, hence it is durable.."
},
{
"code": null,
"e": 5244,
"s": 5116,
"text": "Durability − Kafka uses Distributed commit log which means messages persists on disk as fast as possible, hence it is durable.."
},
{
"code": null,
"e": 5399,
"s": 5244,
"text": "Performance − Kafka has high throughput for both publishing and subscribing messages. It maintains stable performance even many TB of messages are stored."
},
{
"code": null,
"e": 5554,
"s": 5399,
"text": "Performance − Kafka has high throughput for both publishing and subscribing messages. It maintains stable performance even many TB of messages are stored."
},
{
"code": null,
"e": 5622,
"s": 5554,
"text": "Kafka is very fast and guarantees zero downtime and zero data loss."
},
{
"code": null,
"e": 5691,
"s": 5622,
"text": "Kafka can be used in many Use Cases. Some of them are listed below −"
},
{
"code": null,
"e": 5871,
"s": 5691,
"text": "Metrics − Kafka is often used for operational monitoring data. This involves aggregating statistics from distributed applications to produce centralized feeds of operational data."
},
{
"code": null,
"e": 6051,
"s": 5871,
"text": "Metrics − Kafka is often used for operational monitoring data. This involves aggregating statistics from distributed applications to produce centralized feeds of operational data."
},
{
"code": null,
"e": 6227,
"s": 6051,
"text": "Log Aggregation Solution − Kafka can be used across an organization to collect logs from multiple services and make them available in a standard format to multiple con-sumers."
},
{
"code": null,
"e": 6403,
"s": 6227,
"text": "Log Aggregation Solution − Kafka can be used across an organization to collect logs from multiple services and make them available in a standard format to multiple con-sumers."
},
{
"code": null,
"e": 6692,
"s": 6403,
"text": "Stream Processing − Popular frameworks such as Storm and Spark Streaming read data from a topic, processes it, and write processed data to a new topic where it becomes available for users and applications. Kafka’s strong durability is also very useful in the context of stream processing."
},
{
"code": null,
"e": 6981,
"s": 6692,
"text": "Stream Processing − Popular frameworks such as Storm and Spark Streaming read data from a topic, processes it, and write processed data to a new topic where it becomes available for users and applications. Kafka’s strong durability is also very useful in the context of stream processing."
},
{
"code": null,
"e": 7492,
"s": 6981,
"text": "Kafka is a unified platform for handling all the real-time data feeds. Kafka supports low latency message delivery and gives guarantee for fault tolerance in the presence of machine failures. It has the ability to handle a large number of diverse consumers. Kafka is very fast, performs 2 million writes/sec. Kafka persists all data to the disk, which essentially means that all the writes go to the page cache of the OS (RAM). This makes it very efficient to transfer data from page cache to a network socket."
},
{
"code": null,
"e": 7733,
"s": 7492,
"text": "Before moving deep into the Kafka, you must aware of the main terminologies such as topics, brokers, producers and consumers. The following diagram illustrates the main terminologies and the table describes the diagram components in detail."
},
{
"code": null,
"e": 8002,
"s": 7733,
"text": "In the above diagram, a topic is configured into three partitions. Partition 1 has two offset factors 0 and 1. Partition 2 has four offset factors 0, 1, 2, and 3. Partition 3 has one offset factor 0. The id of the replica is same as the id of the server that hosts it."
},
{
"code": null,
"e": 8363,
"s": 8002,
"text": "Assume, if the replication factor of the topic is set to 3, then Kafka will create 3 identical replicas of each partition and place them in the cluster to make available for all its operations. To balance a load in cluster, each broker stores one or more of those partitions. Multiple producers and consumers can publish and retrieve messages at the same time."
},
{
"code": null,
"e": 8370,
"s": 8363,
"text": "Topics"
},
{
"code": null,
"e": 8471,
"s": 8370,
"text": "A stream of messages belonging to a particular category is called a topic. Data is stored in topics."
},
{
"code": null,
"e": 8703,
"s": 8471,
"text": "Topics are split into partitions. For each topic, Kafka keeps a mini-mum of one partition. Each such partition contains messages in an immutable ordered sequence. A partition is implemented as a set of segment files of equal sizes."
},
{
"code": null,
"e": 8713,
"s": 8703,
"text": "Partition"
},
{
"code": null,
"e": 8792,
"s": 8713,
"text": "Topics may have many partitions, so it can handle an arbitrary amount of data."
},
{
"code": null,
"e": 8809,
"s": 8792,
"text": "Partition offset"
},
{
"code": null,
"e": 8877,
"s": 8809,
"text": "Each partitioned message has a unique sequence id called as offset."
},
{
"code": null,
"e": 8899,
"s": 8877,
"text": "Replicas of partition"
},
{
"code": null,
"e": 9023,
"s": 8899,
"text": "Replicas are nothing but backups of a partition. Replicas are never read or write data. They are used to prevent data loss."
},
{
"code": null,
"e": 9031,
"s": 9023,
"text": "Brokers"
},
{
"code": null,
"e": 9269,
"s": 9031,
"text": "Brokers are simple system responsible for maintaining the pub-lished data. Each broker may have zero or more partitions per topic. Assume, if there are N partitions in a topic and N number of brokers, each broker will have one partition."
},
{
"code": null,
"e": 9507,
"s": 9269,
"text": "Brokers are simple system responsible for maintaining the pub-lished data. Each broker may have zero or more partitions per topic. Assume, if there are N partitions in a topic and N number of brokers, each broker will have one partition."
},
{
"code": null,
"e": 9704,
"s": 9507,
"text": "Assume if there are N partitions in a topic and more than N brokers (n + m), the first N broker will have one partition and the next M broker will not have any partition for that particular topic."
},
{
"code": null,
"e": 9901,
"s": 9704,
"text": "Assume if there are N partitions in a topic and more than N brokers (n + m), the first N broker will have one partition and the next M broker will not have any partition for that particular topic."
},
{
"code": null,
"e": 10125,
"s": 9901,
"text": "Assume if there are N partitions in a topic and less than N brokers (n-m), each broker will have one or more partition sharing among them. This scenario is not recommended due to unequal load distri-bution among the broker."
},
{
"code": null,
"e": 10349,
"s": 10125,
"text": "Assume if there are N partitions in a topic and less than N brokers (n-m), each broker will have one or more partition sharing among them. This scenario is not recommended due to unequal load distri-bution among the broker."
},
{
"code": null,
"e": 10363,
"s": 10349,
"text": "Kafka Cluster"
},
{
"code": null,
"e": 10561,
"s": 10363,
"text": "Kafka’s having more than one broker are called as Kafka cluster. A Kafka cluster can be expanded without downtime. These clusters are used to manage the persistence and replication of message data."
},
{
"code": null,
"e": 10571,
"s": 10561,
"text": "Producers"
},
{
"code": null,
"e": 10917,
"s": 10571,
"text": "Producers are the publisher of messages to one or more Kafka topics. Producers send data to Kafka brokers. Every time a producer pub-lishes a message to a broker, the broker simply appends the message to the last segment file. Actually, the message will be appended to a partition. Producer can also send messages to a partition of their choice."
},
{
"code": null,
"e": 10927,
"s": 10917,
"text": "Consumers"
},
{
"code": null,
"e": 11069,
"s": 10927,
"text": "Consumers read data from brokers. Consumers subscribes to one or more topics and consume published messages by pulling data from the brokers."
},
{
"code": null,
"e": 11076,
"s": 11069,
"text": "Leader"
},
{
"code": null,
"e": 11208,
"s": 11076,
"text": "Leader is the node responsible for all reads and writes for the given partition. Every partition has one server acting as a leader."
},
{
"code": null,
"e": 11217,
"s": 11208,
"text": "Follower"
},
{
"code": null,
"e": 11447,
"s": 11217,
"text": "Node which follows leader instructions are called as follower. If the leader fails, one of the follower will automatically become the new leader. A follower acts as normal consumer, pulls messages and up-dates its own data store."
},
{
"code": null,
"e": 11529,
"s": 11447,
"text": "Take a look at the following illustration. It shows the cluster diagram of Kafka."
},
{
"code": null,
"e": 11610,
"s": 11529,
"text": "The following table describes each of the components shown in the above diagram."
},
{
"code": null,
"e": 11617,
"s": 11610,
"text": "Broker"
},
{
"code": null,
"e": 12000,
"s": 11617,
"text": "Kafka cluster typically consists of multiple brokers to maintain load balance. Kafka brokers are stateless, so they use ZooKeeper for maintaining their cluster state. One Kafka broker instance can handle hundreds of thousands of reads and writes per second and each bro-ker can handle TB of messages without performance impact. Kafka broker leader election can be done by ZooKeeper."
},
{
"code": null,
"e": 12010,
"s": 12000,
"text": "ZooKeeper"
},
{
"code": null,
"e": 12436,
"s": 12010,
"text": "ZooKeeper is used for managing and coordinating Kafka broker. ZooKeeper service is mainly used to notify producer and consumer about the presence of any new broker in the Kafka system or failure of the broker in the Kafka system. As per the notification received by the Zookeeper regarding presence or failure of the broker then pro-ducer and consumer takes decision and starts coordinating their task with some other broker."
},
{
"code": null,
"e": 12446,
"s": 12436,
"text": "Producers"
},
{
"code": null,
"e": 12710,
"s": 12446,
"text": "Producers push data to brokers. When the new broker is started, all the producers search it and automatically sends a message to that new broker. Kafka producer doesn’t wait for acknowledgements from the broker and sends messages as fast as the broker can handle."
},
{
"code": null,
"e": 12720,
"s": 12710,
"text": "Consumers"
},
{
"code": null,
"e": 13238,
"s": 12720,
"text": "Since Kafka brokers are stateless, which means that the consumer has to maintain how many messages have been consumed by using partition offset. If the consumer acknowledges a particular message offset, it implies that the consumer has consumed all prior messages. The consumer issues an asynchronous pull request to the broker to have a buffer of bytes ready to consume. The consumers can rewind or skip to any point in a partition simply by supplying an offset value. Consumer offset value is notified by ZooKeeper."
},
{
"code": null,
"e": 13344,
"s": 13238,
"text": "As of now, we discussed the core concepts of Kafka. Let us now throw some light on the workflow of Kafka."
},
{
"code": null,
"e": 13793,
"s": 13344,
"text": "Kafka is simply a collection of topics split into one or more partitions. A Kafka partition is a linearly ordered sequence of messages, where each message is identified by their index (called as offset). All the data in a Kafka cluster is the disjointed union of partitions. Incoming messages are written at the end of a partition and messages are sequentially read by consumers. Durability is provided by replicating messages to different brokers."
},
{
"code": null,
"e": 14194,
"s": 13793,
"text": "Kafka provides both pub-sub and queue based messaging system in a fast, reliable, persisted, fault-tolerance and zero downtime manner. In both cases, producers simply send the message to a topic and consumer can choose any one type of messaging system depending on their need. Let us follow the steps in the next section to understand how the consumer can choose the messaging system of their choice."
},
{
"code": null,
"e": 14257,
"s": 14194,
"text": "Following is the step wise workflow of the Pub-Sub Messaging −"
},
{
"code": null,
"e": 14313,
"s": 14257,
"text": "Producers send message to a topic at regular intervals."
},
{
"code": null,
"e": 14369,
"s": 14313,
"text": "Producers send message to a topic at regular intervals."
},
{
"code": null,
"e": 14686,
"s": 14369,
"text": "Kafka broker stores all messages in the partitions configured for that particular topic. It ensures the messages are equally shared between partitions. If the producer sends two messages and there are two partitions, Kafka will store one message in the first partition and the second message in the second partition."
},
{
"code": null,
"e": 15003,
"s": 14686,
"text": "Kafka broker stores all messages in the partitions configured for that particular topic. It ensures the messages are equally shared between partitions. If the producer sends two messages and there are two partitions, Kafka will store one message in the first partition and the second message in the second partition."
},
{
"code": null,
"e": 15044,
"s": 15003,
"text": "Consumer subscribes to a specific topic."
},
{
"code": null,
"e": 15085,
"s": 15044,
"text": "Consumer subscribes to a specific topic."
},
{
"code": null,
"e": 15246,
"s": 15085,
"text": "Once the consumer subscribes to a topic, Kafka will provide the current offset of the topic to the consumer and also saves the offset in the Zookeeper ensemble."
},
{
"code": null,
"e": 15407,
"s": 15246,
"text": "Once the consumer subscribes to a topic, Kafka will provide the current offset of the topic to the consumer and also saves the offset in the Zookeeper ensemble."
},
{
"code": null,
"e": 15493,
"s": 15407,
"text": "Consumer will request the Kafka in a regular interval (like 100 Ms) for new messages."
},
{
"code": null,
"e": 15579,
"s": 15493,
"text": "Consumer will request the Kafka in a regular interval (like 100 Ms) for new messages."
},
{
"code": null,
"e": 15673,
"s": 15579,
"text": "Once Kafka receives the messages from producers, it forwards these messages to the consumers."
},
{
"code": null,
"e": 15767,
"s": 15673,
"text": "Once Kafka receives the messages from producers, it forwards these messages to the consumers."
},
{
"code": null,
"e": 15817,
"s": 15767,
"text": "Consumer will receive the message and process it."
},
{
"code": null,
"e": 15867,
"s": 15817,
"text": "Consumer will receive the message and process it."
},
{
"code": null,
"e": 15959,
"s": 15867,
"text": "Once the messages are processed, consumer will send an acknowledgement to the Kafka broker."
},
{
"code": null,
"e": 16051,
"s": 15959,
"text": "Once the messages are processed, consumer will send an acknowledgement to the Kafka broker."
},
{
"code": null,
"e": 16284,
"s": 16051,
"text": "Once Kafka receives an acknowledgement, it changes the offset to the new value and updates it in the Zookeeper. Since offsets are maintained in the Zookeeper, the consumer can read next message correctly even during server outrages."
},
{
"code": null,
"e": 16517,
"s": 16284,
"text": "Once Kafka receives an acknowledgement, it changes the offset to the new value and updates it in the Zookeeper. Since offsets are maintained in the Zookeeper, the consumer can read next message correctly even during server outrages."
},
{
"code": null,
"e": 16583,
"s": 16517,
"text": "This above flow will repeat until the consumer stops the request."
},
{
"code": null,
"e": 16649,
"s": 16583,
"text": "This above flow will repeat until the consumer stops the request."
},
{
"code": null,
"e": 16771,
"s": 16649,
"text": "Consumer has the option to rewind/skip to the desired offset of a topic at any time and read all the subsequent messages."
},
{
"code": null,
"e": 16893,
"s": 16771,
"text": "Consumer has the option to rewind/skip to the desired offset of a topic at any time and read all the subsequent messages."
},
{
"code": null,
"e": 17215,
"s": 16893,
"text": "In a queue messaging system instead of a single consumer, a group of consumers having the same Group ID will subscribe to a topic. In simple terms, consumers subscribing to a topic with same Group ID are considered as a single group and the messages are shared among them. Let us check the actual workflow of this system."
},
{
"code": null,
"e": 17272,
"s": 17215,
"text": "Producers send message to a topic in a regular interval."
},
{
"code": null,
"e": 17329,
"s": 17272,
"text": "Producers send message to a topic in a regular interval."
},
{
"code": null,
"e": 17443,
"s": 17329,
"text": "Kafka stores all messages in the partitions configured for that particular topic similar to the earlier scenario."
},
{
"code": null,
"e": 17557,
"s": 17443,
"text": "Kafka stores all messages in the partitions configured for that particular topic similar to the earlier scenario."
},
{
"code": null,
"e": 17649,
"s": 17557,
"text": "A single consumer subscribes to a specific topic, assume Topic-01 with Group ID as Group-1."
},
{
"code": null,
"e": 17741,
"s": 17649,
"text": "A single consumer subscribes to a specific topic, assume Topic-01 with Group ID as Group-1."
},
{
"code": null,
"e": 17902,
"s": 17741,
"text": "Kafka interacts with the consumer in the same way as Pub-Sub Messaging until new consumer subscribes the same topic, Topic-01 with the same Group ID as Group-1."
},
{
"code": null,
"e": 18063,
"s": 17902,
"text": "Kafka interacts with the consumer in the same way as Pub-Sub Messaging until new consumer subscribes the same topic, Topic-01 with the same Group ID as Group-1."
},
{
"code": null,
"e": 18307,
"s": 18063,
"text": "Once the new consumer arrives, Kafka switches its operation to share mode and shares the data between the two consumers. This sharing will go on until the number of con-sumers reach the number of partition configured for that particular topic."
},
{
"code": null,
"e": 18551,
"s": 18307,
"text": "Once the new consumer arrives, Kafka switches its operation to share mode and shares the data between the two consumers. This sharing will go on until the number of con-sumers reach the number of partition configured for that particular topic."
},
{
"code": null,
"e": 18921,
"s": 18551,
"text": "Once the number of consumer exceeds the number of partitions, the new consumer will not receive any further message until any one of the existing consumer unsubscribes. This scenario arises because each consumer in Kafka will be assigned a minimum of one partition and once all the partitions are assigned to the existing consumers, the new consumers will have to wait."
},
{
"code": null,
"e": 19291,
"s": 18921,
"text": "Once the number of consumer exceeds the number of partitions, the new consumer will not receive any further message until any one of the existing consumer unsubscribes. This scenario arises because each consumer in Kafka will be assigned a minimum of one partition and once all the partitions are assigned to the existing consumers, the new consumers will have to wait."
},
{
"code": null,
"e": 19442,
"s": 19291,
"text": "This feature is also called as Consumer Group. In the same way, Kafka will provide the best of both the systems in a very simple and efficient manner."
},
{
"code": null,
"e": 19593,
"s": 19442,
"text": "This feature is also called as Consumer Group. In the same way, Kafka will provide the best of both the systems in a very simple and efficient manner."
},
{
"code": null,
"e": 19995,
"s": 19593,
"text": "A critical dependency of Apache Kafka is Apache Zookeeper, which is a distributed configuration and synchronization service. Zookeeper serves as the coordination interface between the Kafka brokers and consumers. The Kafka servers share information via a Zookeeper cluster. Kafka stores basic metadata in Zookeeper such as information about topics, brokers, consumer offsets (queue readers) and so on."
},
{
"code": null,
"e": 20403,
"s": 19995,
"text": "Since all the critical information is stored in the Zookeeper and it normally replicates this data across its ensemble, failure of Kafka broker / Zookeeper does not affect the state of the Kafka cluster. Kafka will restore the state, once the Zookeeper restarts. This gives zero downtime for Kafka. The leader election between the Kafka broker is also done by using Zookeeper in the event of leader failure."
},
{
"code": null,
"e": 20454,
"s": 20403,
"text": "To learn more on Zookeeper, please refer zookeeper"
},
{
"code": null,
"e": 20560,
"s": 20454,
"text": "Let us continue further on how to install Java, ZooKeeper, and Kafka on your machine in the next chapter."
},
{
"code": null,
"e": 20621,
"s": 20560,
"text": "Following are the steps for installing Java on your machine."
},
{
"code": null,
"e": 20741,
"s": 20621,
"text": "Hopefully you have already installed java on your machine right now, so you just verify it using the following command."
},
{
"code": null,
"e": 20758,
"s": 20741,
"text": "$ java -version\n"
},
{
"code": null,
"e": 20858,
"s": 20758,
"text": "If java is successfully installed on your machine, you could see the version of the installed Java."
},
{
"code": null,
"e": 20987,
"s": 20858,
"text": "If Java is not downloaded, please download the latest version of JDK by visiting the following link and download latest version."
},
{
"code": null,
"e": 21110,
"s": 20987,
"text": "Now the latest version is JDK 8u 60 and the file is “jdk-8u60-linux-x64.tar.gz”. Please download the file on your machine."
},
{
"code": null,
"e": 21246,
"s": 21110,
"text": "Generally, files being downloaded are stored in the downloads folder, verify it and extract the tar setup using the following commands."
},
{
"code": null,
"e": 21306,
"s": 21246,
"text": "$ cd /go/to/download/path\n$ tar -zxf jdk-8u60-linux-x64.gz\n"
},
{
"code": null,
"e": 21402,
"s": 21306,
"text": "To make java available to all users, move the extracted java content to usr/local/java/ folder."
},
{
"code": null,
"e": 21492,
"s": 21402,
"text": "$ su\npassword: (type password of root user)\n$ mkdir /opt/jdk\n$ mv jdk-1.8.0_60 /opt/jdk/\n"
},
{
"code": null,
"e": 21575,
"s": 21492,
"text": "To set path and JAVA_HOME variables, add the following commands to ~/.bashrc file."
},
{
"code": null,
"e": 21649,
"s": 21575,
"text": "export JAVA_HOME =/usr/jdk/jdk-1.8.0_60\nexport PATH=$PATH:$JAVA_HOME/bin\n"
},
{
"code": null,
"e": 21704,
"s": 21649,
"text": "Now apply all the changes into current running system."
},
{
"code": null,
"e": 21724,
"s": 21704,
"text": "$ source ~/.bashrc\n"
},
{
"code": null,
"e": 21779,
"s": 21724,
"text": "Use the following command to change Java Alternatives."
},
{
"code": null,
"e": 21863,
"s": 21779,
"text": "update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_60/bin/java 100\n"
},
{
"code": null,
"e": 21954,
"s": 21863,
"text": "Step 1.6 − Now verify java using verification command (java -version) explained in Step 1."
},
{
"code": null,
"e": 22073,
"s": 21954,
"text": "To install ZooKeeper framework on your machine, visit the following link and download the latest version of ZooKeeper."
},
{
"code": null,
"e": 22147,
"s": 22073,
"text": "As of now, latest version of ZooKeeper is 3.4.6 (ZooKeeper-3.4.6.tar.gz)."
},
{
"code": null,
"e": 22192,
"s": 22147,
"text": "Extract tar file using the following command"
},
{
"code": null,
"e": 22271,
"s": 22192,
"text": "$ cd opt/\n$ tar -zxf zookeeper-3.4.6.tar.gz\n$ cd zookeeper-3.4.6\n$ mkdir data\n"
},
{
"code": null,
"e": 22409,
"s": 22271,
"text": "Open Configuration File named conf/zoo.cfg using the command vi “conf/zoo.cfg” and all the following parameters to set as starting point."
},
{
"code": null,
"e": 22514,
"s": 22409,
"text": "$ vi conf/zoo.cfg\ntickTime=2000\ndataDir=/path/to/zookeeper/data\nclientPort=2181\ninitLimit=5\nsyncLimit=2\n"
},
{
"code": null,
"e": 22636,
"s": 22514,
"text": "Once the configuration file has been saved successfully and return to terminal again, you can start the zookeeper server."
},
{
"code": null,
"e": 22661,
"s": 22636,
"text": "$ bin/zkServer.sh start\n"
},
{
"code": null,
"e": 22732,
"s": 22661,
"text": "After executing this command, you will get a response as shown below −"
},
{
"code": null,
"e": 22853,
"s": 22732,
"text": "$ JMX enabled by default\n$ Using config: /Users/../zookeeper-3.4.6/bin/../conf/zoo.cfg\n$ Starting zookeeper ... STARTED\n"
},
{
"code": null,
"e": 22869,
"s": 22853,
"text": "$ bin/zkCli.sh\n"
},
{
"code": null,
"e": 22980,
"s": 22869,
"text": "After typing the above command, you will be connected to the zookeeper server and will get the below response."
},
{
"code": null,
"e": 23215,
"s": 22980,
"text": "Connecting to localhost:2181\n................\n................\n................\nWelcome to ZooKeeper!\n................\n................\nWATCHER::\nWatchedEvent state:SyncConnected type: None path:null\n[zk: localhost:2181(CONNECTED) 0]\n"
},
{
"code": null,
"e": 23341,
"s": 23215,
"text": "After connecting the server and performing all the operations, you can stop the zookeeper server with the following command −"
},
{
"code": null,
"e": 23365,
"s": 23341,
"text": "$ bin/zkServer.sh stop\n"
},
{
"code": null,
"e": 23483,
"s": 23365,
"text": "Now you have successfully installed Java and ZooKeeper on your machine. Let us see the steps to install Apache Kafka."
},
{
"code": null,
"e": 23558,
"s": 23483,
"text": "Let us continue with the following steps to install Kafka on your machine."
},
{
"code": null,
"e": 23618,
"s": 23558,
"text": "To install Kafka on your machine, click on the below link −"
},
{
"code": null,
"e": 23710,
"s": 23618,
"text": "Now the latest version i.e., – kafka_2.11_0.9.0.0.tgz will be downloaded onto your machine."
},
{
"code": null,
"e": 23761,
"s": 23710,
"text": "Extract the tar file using the following command −"
},
{
"code": null,
"e": 23833,
"s": 23761,
"text": "$ cd opt/\n$ tar -zxf kafka_2.11.0.9.0.0 tar.gz\n$ cd kafka_2.11.0.9.0.0\n"
},
{
"code": null,
"e": 23902,
"s": 23833,
"text": "Now you have downloaded the latest version of Kafka on your machine."
},
{
"code": null,
"e": 23961,
"s": 23902,
"text": "You can start the server by giving the following command −"
},
{
"code": null,
"e": 24015,
"s": 23961,
"text": "$ bin/kafka-server-start.sh config/server.properties\n"
},
{
"code": null,
"e": 24090,
"s": 24015,
"text": "After the server starts, you would see the below response on your screen −"
},
{
"code": null,
"e": 24456,
"s": 24090,
"text": "$ bin/kafka-server-start.sh config/server.properties\n[2016-01-02 15:37:30,410] INFO KafkaConfig values:\nrequest.timeout.ms = 30000\nlog.roll.hours = 168\ninter.broker.protocol.version = 0.9.0.X\nlog.preallocate = false\nsecurity.inter.broker.protocol = PLAINTEXT\n....................................................\n....................................................\n"
},
{
"code": null,
"e": 24547,
"s": 24456,
"text": "After performing all the operations, you can stop the server using the following command −"
},
{
"code": null,
"e": 24600,
"s": 24547,
"text": "$ bin/kafka-server-stop.sh config/server.properties\n"
},
{
"code": null,
"e": 24734,
"s": 24600,
"text": "Now that we have already discussed the Kafka installation, we can learn how to perform basic operations on Kafka in the next chapter."
},
{
"code": null,
"e": 24888,
"s": 24734,
"text": "First let us start implementing single node-single broker configuration and we will then migrate our setup to single node-multiple brokers configuration."
},
{
"code": null,
"e": 25098,
"s": 24888,
"text": "Hopefully you would have installed Java, ZooKeeper and Kafka on your machine by now. Before moving to the Kafka Cluster Setup, first you would need to start your ZooKeeper because Kafka Cluster uses ZooKeeper."
},
{
"code": null,
"e": 25151,
"s": 25098,
"text": "Open a new terminal and type the following command −"
},
{
"code": null,
"e": 25210,
"s": 25151,
"text": "bin/zookeeper-server-start.sh config/zookeeper.properties\n"
},
{
"code": null,
"e": 25262,
"s": 25210,
"text": "To start Kafka Broker, type the following command −"
},
{
"code": null,
"e": 25314,
"s": 25262,
"text": "bin/kafka-server-start.sh config/server.properties\n"
},
{
"code": null,
"e": 25429,
"s": 25314,
"text": "After starting Kafka Broker, type the command jps on ZooKeeper terminal and you would see the following response −"
},
{
"code": null,
"e": 25467,
"s": 25429,
"text": "821 QuorumPeerMain\n928 Kafka\n931 Jps\n"
},
{
"code": null,
"e": 25595,
"s": 25467,
"text": "Now you could see two daemons running on the terminal where QuorumPeerMain is ZooKeeper daemon and another one is Kafka daemon."
},
{
"code": null,
"e": 25711,
"s": 25595,
"text": "In this configuration you have a single ZooKeeper and broker id instance. Following are the steps to configure it −"
},
{
"code": null,
"e": 25874,
"s": 25711,
"text": "Creating a Kafka Topic − Kafka provides a command line utility named kafka-topics.sh to create topics on the server. Open new terminal and type the below example."
},
{
"code": null,
"e": 25881,
"s": 25874,
"text": "Syntax"
},
{
"code": null,
"e": 25996,
"s": 25881,
"text": "bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 \n--partitions 1 --topic topic-name\n"
},
{
"code": null,
"e": 26004,
"s": 25996,
"text": "Example"
},
{
"code": null,
"e": 26121,
"s": 26004,
"text": "bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 \n--partitions 1 --topic Hello-Kafka"
},
{
"code": null,
"e": 26278,
"s": 26121,
"text": "We just created a topic named Hello-Kafka with a single partition and one replica factor. The above created output will be similar to the following output −"
},
{
"code": null,
"e": 26313,
"s": 26278,
"text": "Output − Created topic Hello-Kafka"
},
{
"code": null,
"e": 26511,
"s": 26313,
"text": "Once the topic has been created, you can get the notification in Kafka broker terminal window and the log for the created topic specified in “/tmp/kafka-logs/“ in the config/server.properties file."
},
{
"code": null,
"e": 26588,
"s": 26511,
"text": "To get a list of topics in Kafka server, you can use the following command −"
},
{
"code": null,
"e": 26595,
"s": 26588,
"text": "Syntax"
},
{
"code": null,
"e": 26650,
"s": 26595,
"text": "bin/kafka-topics.sh --list --zookeeper localhost:2181\n"
},
{
"code": null,
"e": 26657,
"s": 26650,
"text": "Output"
},
{
"code": null,
"e": 26670,
"s": 26657,
"text": "Hello-Kafka\n"
},
{
"code": null,
"e": 26825,
"s": 26670,
"text": "Since we have created a topic, it will list out Hello-Kafka only. Suppose, if you create more than one topics, you will get the topic names in the output."
},
{
"code": null,
"e": 26832,
"s": 26825,
"text": "Syntax"
},
{
"code": null,
"e": 26911,
"s": 26832,
"text": "bin/kafka-console-producer.sh --broker-list localhost:9092 --topic topic-name\n"
},
{
"code": null,
"e": 27006,
"s": 26911,
"text": "From the above syntax, two main parameters are required for the producer command line client −"
},
{
"code": null,
"e": 27259,
"s": 27006,
"text": "Broker-list − The list of brokers that we want to send the messages to. In this case we only have one broker. The Config/server.properties file contains broker port id, since we know our broker is listening on port 9092, so you can specify it directly."
},
{
"code": null,
"e": 27311,
"s": 27259,
"text": "Topic name − Here is an example for the topic name."
},
{
"code": null,
"e": 27319,
"s": 27311,
"text": "Example"
},
{
"code": null,
"e": 27398,
"s": 27319,
"text": "bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Hello-Kafka"
},
{
"code": null,
"e": 27694,
"s": 27398,
"text": "The producer will wait on input from stdin and publishes to the Kafka cluster. By default, every new line is published as a new message then the default producer properties are specified in config/producer.properties file. Now you can type a few lines of messages in the terminal as shown below."
},
{
"code": null,
"e": 27701,
"s": 27694,
"text": "Output"
},
{
"code": null,
"e": 27901,
"s": 27701,
"text": "$ bin/kafka-console-producer.sh --broker-list localhost:9092 \n--topic Hello-Kafka[2016-01-16 13:50:45,931] \nWARN property topic is not valid (kafka.utils.Verifia-bleProperties)\nHello\nMy first message"
},
{
"code": null,
"e": 27920,
"s": 27901,
"text": "My second message\n"
},
{
"code": null,
"e": 28094,
"s": 27920,
"text": "Similar to producer, the default consumer properties are specified in config/consumer.proper-ties file. Open a new terminal and type the below syntax for consuming messages."
},
{
"code": null,
"e": 28101,
"s": 28094,
"text": "Syntax"
},
{
"code": null,
"e": 28195,
"s": 28101,
"text": "bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic topic-name \n--from-beginning\n"
},
{
"code": null,
"e": 28203,
"s": 28195,
"text": "Example"
},
{
"code": null,
"e": 28297,
"s": 28203,
"text": "bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic Hello-Kafka \n--from-beginning"
},
{
"code": null,
"e": 28304,
"s": 28297,
"text": "Output"
},
{
"code": null,
"e": 28346,
"s": 28304,
"text": "Hello\nMy first message\nMy second message\n"
},
{
"code": null,
"e": 28619,
"s": 28346,
"text": "Finally, you are able to enter messages from the producer’s terminal and see them appearing in the consumer’s terminal. As of now, you have a very good understanding on the single node cluster with a single broker. Let us now move on to the multiple brokers configuration."
},
{
"code": null,
"e": 28710,
"s": 28619,
"text": "Before moving on to the multiple brokers cluster setup, first start your ZooKeeper server."
},
{
"code": null,
"e": 29051,
"s": 28710,
"text": "Create Multiple Kafka Brokers − We have one Kafka broker instance already in con-fig/server.properties. Now we need multiple broker instances, so copy the existing server.prop-erties file into two new config files and rename it as server-one.properties and server-two.prop-erties. Then edit both new files and assign the following changes −"
},
{
"code": null,
"e": 29290,
"s": 29051,
"text": "# The id of the broker. This must be set to a unique integer for each broker.\nbroker.id=1\n# The port the socket server listens on\nport=9093\n# A comma seperated list of directories under which to store log files\nlog.dirs=/tmp/kafka-logs-1\n"
},
{
"code": null,
"e": 29529,
"s": 29290,
"text": "# The id of the broker. This must be set to a unique integer for each broker.\nbroker.id=2\n# The port the socket server listens on\nport=9094\n# A comma seperated list of directories under which to store log files\nlog.dirs=/tmp/kafka-logs-2\n"
},
{
"code": null,
"e": 29670,
"s": 29529,
"text": "Start Multiple Brokers− After all the changes have been made on three servers then open three new terminals to start each broker one by one."
},
{
"code": null,
"e": 29856,
"s": 29670,
"text": "Broker1\nbin/kafka-server-start.sh config/server.properties\nBroker2\nbin/kafka-server-start.sh config/server-one.properties\nBroker3\nbin/kafka-server-start.sh config/server-two.properties\n"
},
{
"code": null,
"e": 30034,
"s": 29856,
"text": "Now we have three different brokers running on the machine. Try it by yourself to check all the daemons by typing jps on the ZooKeeper terminal, then you would see the response."
},
{
"code": null,
"e": 30220,
"s": 30034,
"text": "Let us assign the replication factor value as three for this topic because we have three different brokers running. If you have two brokers, then the assigned replica value will be two."
},
{
"code": null,
"e": 30227,
"s": 30220,
"text": "Syntax"
},
{
"code": null,
"e": 30341,
"s": 30227,
"text": "bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3 \n-partitions 1 --topic topic-name\n"
},
{
"code": null,
"e": 30349,
"s": 30341,
"text": "Example"
},
{
"code": null,
"e": 30474,
"s": 30349,
"text": "bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3 \n-partitions 1 --topic Multibrokerapplication"
},
{
"code": null,
"e": 30481,
"s": 30474,
"text": "Output"
},
{
"code": null,
"e": 30521,
"s": 30481,
"text": "created topic “Multibrokerapplication”\n"
},
{
"code": null,
"e": 30631,
"s": 30521,
"text": "The Describe command is used to check which broker is listening on the current created topic as shown below −"
},
{
"code": null,
"e": 30723,
"s": 30631,
"text": "bin/kafka-topics.sh --describe --zookeeper localhost:2181 \n--topic Multibrokerappli-cation\n"
},
{
"code": null,
"e": 30730,
"s": 30723,
"text": "Output"
},
{
"code": null,
"e": 30982,
"s": 30730,
"text": "bin/kafka-topics.sh --describe --zookeeper localhost:2181 \n--topic Multibrokerappli-cation\n\nTopic:Multibrokerapplication PartitionCount:1 \nReplicationFactor:3 Configs:\n \nTopic:Multibrokerapplication Partition:0 Leader:0 \nReplicas:0,2,1 Isr:0,2,1\n"
},
{
"code": null,
"e": 31268,
"s": 30982,
"text": "From the above output, we can conclude that first line gives a summary of all the partitions, showing topic name, partition count and the replication factor that we have chosen already. In the second line, each node will be the leader for a randomly selected portion of the partitions."
},
{
"code": null,
"e": 31546,
"s": 31268,
"text": "In our case, we see that our first broker (with broker.id 0) is the leader. Then Replicas:0,2,1 means that all the brokers replicate the topic finally Isr is the set of in-sync replicas. Well, this is the subset of replicas that are currently alive and caught up by the leader."
},
{
"code": null,
"e": 31609,
"s": 31546,
"text": "This procedure remains the same as in the single broker setup."
},
{
"code": null,
"e": 31617,
"s": 31609,
"text": "Example"
},
{
"code": null,
"e": 31708,
"s": 31617,
"text": "bin/kafka-console-producer.sh --broker-list localhost:9092 \n--topic Multibrokerapplication"
},
{
"code": null,
"e": 31715,
"s": 31708,
"text": "Output"
},
{
"code": null,
"e": 31966,
"s": 31715,
"text": "bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Multibrokerapplication\n[2016-01-20 19:27:21,045] WARN Property topic is not valid (kafka.utils.Verifia-bleProperties)\nThis is single node-multi broker demo\nThis is the second message\n"
},
{
"code": null,
"e": 32035,
"s": 31966,
"text": "This procedure remains the same as shown in the single broker setup."
},
{
"code": null,
"e": 32043,
"s": 32035,
"text": "Example"
},
{
"code": null,
"e": 32149,
"s": 32043,
"text": "bin/kafka-console-consumer.sh --zookeeper localhost:2181 \n—topic Multibrokerapplica-tion --from-beginning"
},
{
"code": null,
"e": 32156,
"s": 32149,
"text": "Output"
},
{
"code": null,
"e": 32327,
"s": 32156,
"text": "bin/kafka-console-consumer.sh --zookeeper localhost:2181 \n—topic Multibrokerapplica-tion —from-beginning\nThis is single node-multi broker demo\nThis is the second message\n"
},
{
"code": null,
"e": 32395,
"s": 32327,
"text": "In this chapter we will discuss the various basic topic operations."
},
{
"code": null,
"e": 32528,
"s": 32395,
"text": "As you have already understood how to create a topic in Kafka Cluster. Now let us modify a created topic using the following command"
},
{
"code": null,
"e": 32535,
"s": 32528,
"text": "Syntax"
},
{
"code": null,
"e": 32630,
"s": 32535,
"text": "bin/kafka-topics.sh —zookeeper localhost:2181 --alter --topic topic_name \n--parti-tions count\n"
},
{
"code": null,
"e": 32638,
"s": 32630,
"text": "Example"
},
{
"code": null,
"e": 32892,
"s": 32638,
"text": "We have already created a topic “Hello-Kafka” with single partition count and one replica factor. \nNow using “alter” command we have changed the partition count.\nbin/kafka-topics.sh --zookeeper localhost:2181 \n--alter --topic Hello-kafka --parti-tions 2"
},
{
"code": null,
"e": 32899,
"s": 32892,
"text": "Output"
},
{
"code": null,
"e": 33060,
"s": 32899,
"text": "WARNING: If partitions are increased for a topic that has a key, \nthe partition logic or ordering of the messages will be affected\nAdding partitions succeeded!\n"
},
{
"code": null,
"e": 33113,
"s": 33060,
"text": "To delete a topic, you can use the following syntax."
},
{
"code": null,
"e": 33120,
"s": 33113,
"text": "Syntax"
},
{
"code": null,
"e": 33196,
"s": 33120,
"text": "bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic topic_name\n"
},
{
"code": null,
"e": 33204,
"s": 33196,
"text": "Example"
},
{
"code": null,
"e": 33280,
"s": 33204,
"text": "bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic Hello-kafka"
},
{
"code": null,
"e": 33287,
"s": 33280,
"text": "Output"
},
{
"code": null,
"e": 33328,
"s": 33287,
"text": "> Topic Hello-kafka marked for deletion\n"
},
{
"code": null,
"e": 33401,
"s": 33328,
"text": "Note −This will have no impact if delete.topic.enable is not set to true"
},
{
"code": null,
"e": 33544,
"s": 33401,
"text": "Let us create an application for publishing and consuming messages using a Java client. Kafka producer client consists of the following API’s."
},
{
"code": null,
"e": 33806,
"s": 33544,
"text": "Let us understand the most important set of Kafka producer API in this section. The central part of the KafkaProducer API is KafkaProducer class. The KafkaProducer class provides an option to connect a Kafka broker in its constructor with the following methods."
},
{
"code": null,
"e": 33929,
"s": 33806,
"text": "KafkaProducer class provides send method to send messages asynchronously to a topic. The signature of send() is as follows"
},
{
"code": null,
"e": 34052,
"s": 33929,
"text": "KafkaProducer class provides send method to send messages asynchronously to a topic. The signature of send() is as follows"
},
{
"code": null,
"e": 34147,
"s": 34052,
"text": "producer.send(new ProducerRecord<byte[],byte[]>(topic, \npartition, key1, value1) , callback);\n"
},
{
"code": null,
"e": 34225,
"s": 34147,
"text": "ProducerRecord − The producer manages a buffer of records waiting to be sent."
},
{
"code": null,
"e": 34303,
"s": 34225,
"text": "ProducerRecord − The producer manages a buffer of records waiting to be sent."
},
{
"code": null,
"e": 34433,
"s": 34303,
"text": "Callback − A user-supplied callback to execute when the record has been acknowl-edged by the server (null indicates no callback)."
},
{
"code": null,
"e": 34563,
"s": 34433,
"text": "Callback − A user-supplied callback to execute when the record has been acknowl-edged by the server (null indicates no callback)."
},
{
"code": null,
"e": 34719,
"s": 34563,
"text": "KafkaProducer class provides a flush method to ensure all previously sent messages have been actually completed. Syntax of the flush method is as follows −"
},
{
"code": null,
"e": 34875,
"s": 34719,
"text": "KafkaProducer class provides a flush method to ensure all previously sent messages have been actually completed. Syntax of the flush method is as follows −"
},
{
"code": null,
"e": 34896,
"s": 34875,
"text": "public void flush()\n"
},
{
"code": null,
"e": 35098,
"s": 34896,
"text": "KafkaProducer class provides partitionFor method, which helps in getting the partition metadata for a given topic. This can be used for custom partitioning. The signature of this method is as follows −"
},
{
"code": null,
"e": 35300,
"s": 35098,
"text": "KafkaProducer class provides partitionFor method, which helps in getting the partition metadata for a given topic. This can be used for custom partitioning. The signature of this method is as follows −"
},
{
"code": null,
"e": 35322,
"s": 35300,
"text": "public Map metrics()\n"
},
{
"code": null,
"e": 35389,
"s": 35322,
"text": "It returns the map of internal metrics maintained by the producer."
},
{
"code": null,
"e": 35510,
"s": 35389,
"text": "public void close() − KafkaProducer class provides close method blocks until all previously sent requests are completed."
},
{
"code": null,
"e": 35631,
"s": 35510,
"text": "public void close() − KafkaProducer class provides close method blocks until all previously sent requests are completed."
},
{
"code": null,
"e": 35790,
"s": 35631,
"text": "The central part of the Producer API is Producer class. Producer class provides an option to connect Kafka broker in its constructor by the following methods."
},
{
"code": null,
"e": 35915,
"s": 35790,
"text": "The producer class provides send method to send messages to either single or multiple topics using the following signatures."
},
{
"code": null,
"e": 36254,
"s": 35915,
"text": "public void send(KeyedMessaget<k,v> message) \n- sends the data to a single topic,par-titioned by key using either sync or async producer.\npublic void send(List<KeyedMessage<k,v>>messages)\n- sends data to multiple topics.\nProperties prop = new Properties();\nprop.put(producer.type,”async”)\nProducerConfig config = new ProducerConfig(prop);"
},
{
"code": null,
"e": 36305,
"s": 36254,
"text": "There are two types of producers – Sync and Async."
},
{
"code": null,
"e": 36706,
"s": 36305,
"text": "The same API configuration applies to Sync producer as well. The difference between them is a sync producer sends messages directly, but sends messages in background. Async producer is preferred when you want a higher throughput. In the previous releases like 0.8, an async producer does not have a callback for send() to register error handlers. This is available only in the current release of 0.9."
},
{
"code": null,
"e": 36805,
"s": 36706,
"text": "Producer class provides close method to close the producer pool connections to all Kafka bro-kers."
},
{
"code": null,
"e": 36914,
"s": 36805,
"text": "The Producer API’s main configuration settings are listed in the following table for better under-standing −"
},
{
"code": null,
"e": 36924,
"s": 36914,
"text": "client.id"
},
{
"code": null,
"e": 36956,
"s": 36924,
"text": "identifies producer application"
},
{
"code": null,
"e": 36970,
"s": 36956,
"text": "producer.type"
},
{
"code": null,
"e": 36991,
"s": 36970,
"text": "either sync or async"
},
{
"code": null,
"e": 36996,
"s": 36991,
"text": "acks"
},
{
"code": null,
"e": 37084,
"s": 36996,
"text": "The acks config controls the criteria under producer requests are con-sidered complete."
},
{
"code": null,
"e": 37092,
"s": 37084,
"text": "retries"
},
{
"code": null,
"e": 37165,
"s": 37092,
"text": "If producer request fails, then automatically retry with specific value."
},
{
"code": null,
"e": 37183,
"s": 37165,
"text": "bootstrap.servers"
},
{
"code": null,
"e": 37214,
"s": 37183,
"text": "bootstrapping list of brokers."
},
{
"code": null,
"e": 37224,
"s": 37214,
"text": "linger.ms"
},
{
"code": null,
"e": 37329,
"s": 37224,
"text": "if you want to reduce the number of requests you can set linger.ms to something greater than some value."
},
{
"code": null,
"e": 37344,
"s": 37329,
"text": "key.serializer"
},
{
"code": null,
"e": 37378,
"s": 37344,
"text": "Key for the serializer interface."
},
{
"code": null,
"e": 37395,
"s": 37378,
"text": "value.serializer"
},
{
"code": null,
"e": 37431,
"s": 37395,
"text": "value for the serializer interface."
},
{
"code": null,
"e": 37442,
"s": 37431,
"text": "batch.size"
},
{
"code": null,
"e": 37455,
"s": 37442,
"text": "Buffer size."
},
{
"code": null,
"e": 37469,
"s": 37455,
"text": "buffer.memory"
},
{
"code": null,
"e": 37547,
"s": 37469,
"text": "controls the total amount of memory available to the producer for buff-ering."
},
{
"code": null,
"e": 37734,
"s": 37547,
"text": "ProducerRecord is a key/value pair that is sent to Kafka cluster.ProducerRecord class constructor for creating a record with partition, key and value pairs using the following signature."
},
{
"code": null,
"e": 37803,
"s": 37734,
"text": "public ProducerRecord (string topic, int partition, k key, v value)\n"
},
{
"code": null,
"e": 37865,
"s": 37803,
"text": "Topic − user defined topic name that will appended to record."
},
{
"code": null,
"e": 37927,
"s": 37865,
"text": "Topic − user defined topic name that will appended to record."
},
{
"code": null,
"e": 37955,
"s": 37927,
"text": "Partition − partition count"
},
{
"code": null,
"e": 37983,
"s": 37955,
"text": "Partition − partition count"
},
{
"code": null,
"e": 38034,
"s": 37983,
"text": "Key − The key that will be included in the record."
},
{
"code": null,
"e": 38085,
"s": 38034,
"text": "Key − The key that will be included in the record."
},
{
"code": null,
"e": 38109,
"s": 38085,
"text": "Value − Record contents"
},
{
"code": null,
"e": 38163,
"s": 38109,
"text": "public ProducerRecord (string topic, k key, v value)\n"
},
{
"code": null,
"e": 38268,
"s": 38163,
"text": "ProducerRecord class constructor is used to create a record with key, value pairs and without partition."
},
{
"code": null,
"e": 38309,
"s": 38268,
"text": "Topic − Create a topic to assign record."
},
{
"code": null,
"e": 38350,
"s": 38309,
"text": "Topic − Create a topic to assign record."
},
{
"code": null,
"e": 38376,
"s": 38350,
"text": "Key − key for the record."
},
{
"code": null,
"e": 38402,
"s": 38376,
"text": "Key − key for the record."
},
{
"code": null,
"e": 38427,
"s": 38402,
"text": "Value − record contents."
},
{
"code": null,
"e": 38452,
"s": 38427,
"text": "Value − record contents."
},
{
"code": null,
"e": 38499,
"s": 38452,
"text": "public ProducerRecord (string topic, v value)\n"
},
{
"code": null,
"e": 38564,
"s": 38499,
"text": "ProducerRecord class creates a record without partition and key."
},
{
"code": null,
"e": 38588,
"s": 38564,
"text": "Topic − create a topic."
},
{
"code": null,
"e": 38612,
"s": 38588,
"text": "Topic − create a topic."
},
{
"code": null,
"e": 38637,
"s": 38612,
"text": "Value − record contents."
},
{
"code": null,
"e": 38662,
"s": 38637,
"text": "Value − record contents."
},
{
"code": null,
"e": 38731,
"s": 38662,
"text": "The ProducerRecord class methods are listed in the following table −"
},
{
"code": null,
"e": 38753,
"s": 38731,
"text": "public string topic()"
},
{
"code": null,
"e": 38786,
"s": 38753,
"text": "Topic will append to the record."
},
{
"code": null,
"e": 38801,
"s": 38786,
"text": "public K key()"
},
{
"code": null,
"e": 38887,
"s": 38801,
"text": "Key that will be included in the record. If no such key, null will be re-turned here."
},
{
"code": null,
"e": 38904,
"s": 38887,
"text": "public V value()"
},
{
"code": null,
"e": 38921,
"s": 38904,
"text": "Record contents."
},
{
"code": null,
"e": 38933,
"s": 38921,
"text": "partition()"
},
{
"code": null,
"e": 38964,
"s": 38933,
"text": "Partition count for the record"
},
{
"code": null,
"e": 39199,
"s": 38964,
"text": "Before creating the application, first start ZooKeeper and Kafka broker then create your own topic in Kafka broker using create topic command. After that create a java class named Sim-pleProducer.java and type in the following coding."
},
{
"code": null,
"e": 41255,
"s": 39199,
"text": "//import util.properties packages\nimport java.util.Properties;\n\n//import simple producer packages\nimport org.apache.kafka.clients.producer.Producer;\n\n//import KafkaProducer packages\nimport org.apache.kafka.clients.producer.KafkaProducer;\n\n//import ProducerRecord packages\nimport org.apache.kafka.clients.producer.ProducerRecord;\n\n//Create java class named “SimpleProducer”\npublic class SimpleProducer {\n \n public static void main(String[] args) throws Exception{\n \n // Check arguments length value\n if(args.length == 0){\n System.out.println(\"Enter topic name\");\n return;\n }\n \n //Assign topicName to string variable\n String topicName = args[0].toString();\n \n // create instance for properties to access producer configs \n Properties props = new Properties();\n \n //Assign localhost id\n props.put(\"bootstrap.servers\", “localhost:9092\");\n \n //Set acknowledgements for producer requests. \n props.put(\"acks\", “all\");\n \n //If the request fails, the producer can automatically retry,\n props.put(\"retries\", 0);\n \n //Specify buffer size in config\n props.put(\"batch.size\", 16384);\n \n //Reduce the no of requests less than 0 \n props.put(\"linger.ms\", 1);\n \n //The buffer.memory controls the total amount of memory available to the producer for buffering. \n props.put(\"buffer.memory\", 33554432);\n \n props.put(\"key.serializer\", \n \"org.apache.kafka.common.serialization.StringSerializer\");\n \n props.put(\"value.serializer\", \n \"org.apache.kafka.common.serialization.StringSerializer\");\n \n Producer<String, String> producer = new KafkaProducer\n <String, String>(props);\n \n for(int i = 0; i < 10; i++)\n producer.send(new ProducerRecord<String, String>(topicName, \n Integer.toString(i), Integer.toString(i)));\n System.out.println(“Message sent successfully”);\n producer.close();\n }\n}"
},
{
"code": null,
"e": 41330,
"s": 41255,
"text": "Compilation − The application can be compiled using the following command."
},
{
"code": null,
"e": 41390,
"s": 41330,
"text": "javac -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*” *.java\n"
},
{
"code": null,
"e": 41463,
"s": 41390,
"text": "Execution − The application can be executed using the following command."
},
{
"code": null,
"e": 41545,
"s": 41463,
"text": "java -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*”:. SimpleProducer <topic-name>\n"
},
{
"code": null,
"e": 41552,
"s": 41545,
"text": "Output"
},
{
"code": null,
"e": 41791,
"s": 41552,
"text": "Message sent successfully\nTo check the above output open new terminal and type Consumer CLI command to receive messages.\n>> bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic <topic-name> —from-beginning\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n"
},
{
"code": null,
"e": 42056,
"s": 41791,
"text": "As of now we have created a producer to send messages to Kafka cluster. Now let us create a consumer to consume messages form the Kafka cluster. KafkaConsumer API is used to consume messages from the Kafka cluster. KafkaConsumer class constructor is defined below."
},
{
"code": null,
"e": 42136,
"s": 42056,
"text": "public KafkaConsumer(java.util.Map<java.lang.String,java.lang.Object> configs)\n"
},
{
"code": null,
"e": 42180,
"s": 42136,
"text": "configs − Return a map of consumer configs."
},
{
"code": null,
"e": 42274,
"s": 42180,
"text": "KafkaConsumer class has the following significant methods that are listed in the table below."
},
{
"code": null,
"e": 42325,
"s": 42274,
"text": "public java.util.Set<TopicPar-tition> assignment()"
},
{
"code": null,
"e": 42388,
"s": 42325,
"text": "Get the set of partitions currently assigned by the con-sumer."
},
{
"code": null,
"e": 42417,
"s": 42388,
"text": "public string subscription()"
},
{
"code": null,
"e": 42496,
"s": 42417,
"text": "Subscribe to the given list of topics to get dynamically as-signed partitions."
},
{
"code": null,
"e": 42597,
"s": 42496,
"text": "public void sub-scribe(java.util.List<java.lang.String> topics, ConsumerRe-balanceListener listener)"
},
{
"code": null,
"e": 42676,
"s": 42597,
"text": "Subscribe to the given list of topics to get dynamically as-signed partitions."
},
{
"code": null,
"e": 42702,
"s": 42676,
"text": "public void unsubscribe()"
},
{
"code": null,
"e": 42760,
"s": 42702,
"text": "Unsubscribe the topics from the given list of partitions."
},
{
"code": null,
"e": 42824,
"s": 42760,
"text": "public void sub-scribe(java.util.List<java.lang.String> topics)"
},
{
"code": null,
"e": 42982,
"s": 42824,
"text": "Subscribe to the given list of topics to get dynamically as-signed partitions. If the given list of topics is empty, it is treated the same as unsubscribe()."
},
{
"code": null,
"e": 43075,
"s": 42982,
"text": "public void sub-scribe(java.util.regex.Pattern pattern, ConsumerRebalanceLis-tener listener)"
},
{
"code": null,
"e": 43241,
"s": 43075,
"text": "The argument pattern refers to the subscribing pattern in the format of regular expression and the listener argument gets notifications from the subscribing pattern."
},
{
"code": null,
"e": 43305,
"s": 43241,
"text": "public void as-sign(java.util.List<TopicParti-tion> partitions)"
},
{
"code": null,
"e": 43359,
"s": 43305,
"text": "Manually assign a list of partitions to the customer."
},
{
"code": null,
"e": 43366,
"s": 43359,
"text": "poll()"
},
{
"code": null,
"e": 43542,
"s": 43366,
"text": "Fetch data for the topics or partitions specified using one of the subscribe/assign APIs. This will return error, if the topics are not subscribed before the polling for data."
},
{
"code": null,
"e": 43567,
"s": 43542,
"text": "public void commitSync()"
},
{
"code": null,
"e": 43712,
"s": 43567,
"text": "Commit offsets returned on the last poll() for all the sub-scribed list of topics and partitions. The same operation is applied to commitAsyn()."
},
{
"code": null,
"e": 43768,
"s": 43712,
"text": "public void seek(TopicPartition partition, long offset)"
},
{
"code": null,
"e": 43849,
"s": 43768,
"text": "Fetch the current offset value that consumer will use on the next poll() method."
},
{
"code": null,
"e": 43870,
"s": 43849,
"text": "public void resume()"
},
{
"code": null,
"e": 43900,
"s": 43870,
"text": "Resume the paused partitions."
},
{
"code": null,
"e": 43921,
"s": 43900,
"text": "public void wakeup()"
},
{
"code": null,
"e": 43942,
"s": 43921,
"text": "Wakeup the consumer."
},
{
"code": null,
"e": 44326,
"s": 43942,
"text": "The ConsumerRecord API is used to receive records from the Kafka cluster. This API consists of a topic name, partition number, from which the record is being received and an offset that points to the record in a Kafka partition. ConsumerRecord class is used to create a consumer record with specific topic name, partition count and <key, value> pairs. It has the following signature."
},
{
"code": null,
"e": 44405,
"s": 44326,
"text": "public ConsumerRecord(string topic,int partition, long offset,K key, V value)\n"
},
{
"code": null,
"e": 44481,
"s": 44405,
"text": "Topic − The topic name for consumer record received from the Kafka cluster."
},
{
"code": null,
"e": 44557,
"s": 44481,
"text": "Topic − The topic name for consumer record received from the Kafka cluster."
},
{
"code": null,
"e": 44594,
"s": 44557,
"text": "Partition − Partition for the topic."
},
{
"code": null,
"e": 44631,
"s": 44594,
"text": "Partition − Partition for the topic."
},
{
"code": null,
"e": 44700,
"s": 44631,
"text": "Key − The key of the record, if no key exists null will be returned."
},
{
"code": null,
"e": 44769,
"s": 44700,
"text": "Key − The key of the record, if no key exists null will be returned."
},
{
"code": null,
"e": 44794,
"s": 44769,
"text": "Value − Record contents."
},
{
"code": null,
"e": 44819,
"s": 44794,
"text": "Value − Record contents."
},
{
"code": null,
"e": 45003,
"s": 44819,
"text": "ConsumerRecords API acts as a container for ConsumerRecord. This API is used to keep the list of ConsumerRecord per partition for a particular topic. Its Constructor is defined below."
},
{
"code": null,
"e": 45104,
"s": 45003,
"text": "public ConsumerRecords(java.util.Map<TopicPartition,java.util.List\n<Consumer-Record>K,V>>> records)\n"
},
{
"code": null,
"e": 45171,
"s": 45104,
"text": "TopicPartition − Return a map of partition for a particular topic."
},
{
"code": null,
"e": 45238,
"s": 45171,
"text": "TopicPartition − Return a map of partition for a particular topic."
},
{
"code": null,
"e": 45279,
"s": 45238,
"text": "Records − Return list of ConsumerRecord."
},
{
"code": null,
"e": 45320,
"s": 45279,
"text": "Records − Return list of ConsumerRecord."
},
{
"code": null,
"e": 45377,
"s": 45320,
"text": "ConsumerRecords class has the following methods defined."
},
{
"code": null,
"e": 45396,
"s": 45377,
"text": "public int count()"
},
{
"code": null,
"e": 45438,
"s": 45396,
"text": "The number of records for all the topics."
},
{
"code": null,
"e": 45462,
"s": 45438,
"text": "public Set partitions()"
},
{
"code": null,
"e": 45562,
"s": 45462,
"text": "The set of partitions with data in this record set (if no data was returned then the set is empty)."
},
{
"code": null,
"e": 45589,
"s": 45562,
"text": "public Iterator iterator()"
},
{
"code": null,
"e": 45674,
"s": 45589,
"text": "Iterator enables you to cycle through a collection, obtaining or re-moving elements."
},
{
"code": null,
"e": 45696,
"s": 45674,
"text": "public List records()"
},
{
"code": null,
"e": 45741,
"s": 45696,
"text": "Get list of records for the given partition."
},
{
"code": null,
"e": 45843,
"s": 45741,
"text": "The configuration settings for the Consumer client API main configuration settings are listed below −"
},
{
"code": null,
"e": 45861,
"s": 45843,
"text": "bootstrap.servers"
},
{
"code": null,
"e": 45892,
"s": 45861,
"text": "Bootstrapping list of brokers."
},
{
"code": null,
"e": 45901,
"s": 45892,
"text": "group.id"
},
{
"code": null,
"e": 45944,
"s": 45901,
"text": "Assigns an individual consumer to a group."
},
{
"code": null,
"e": 45963,
"s": 45944,
"text": "enable.auto.commit"
},
{
"code": null,
"e": 46041,
"s": 45963,
"text": "Enable auto commit for offsets if the value is true, otherwise not committed."
},
{
"code": null,
"e": 46065,
"s": 46041,
"text": "auto.commit.interval.ms"
},
{
"code": null,
"e": 46133,
"s": 46065,
"text": "Return how often updated consumed offsets are written to ZooKeeper."
},
{
"code": null,
"e": 46152,
"s": 46133,
"text": "session.timeout.ms"
},
{
"code": null,
"e": 46311,
"s": 46152,
"text": "Indicates how many milliseconds Kafka will wait for the ZooKeeper to respond to a request (read or write) before giving up and continuing to consume messages."
},
{
"code": null,
"e": 46527,
"s": 46311,
"text": "The producer application steps remain the same here. First, start your ZooKeeper and Kafka broker. Then create a SimpleConsumer application with the java class named SimpleCon-sumer.java and type the following code."
},
{
"code": null,
"e": 48254,
"s": 46527,
"text": "import java.util.Properties;\nimport java.util.Arrays;\nimport org.apache.kafka.clients.consumer.KafkaConsumer;\nimport org.apache.kafka.clients.consumer.ConsumerRecords;\nimport org.apache.kafka.clients.consumer.ConsumerRecord;\n\npublic class SimpleConsumer {\n public static void main(String[] args) throws Exception {\n if(args.length == 0){\n System.out.println(\"Enter topic name\");\n return;\n }\n //Kafka consumer configuration settings\n String topicName = args[0].toString();\n Properties props = new Properties();\n \n props.put(\"bootstrap.servers\", \"localhost:9092\");\n props.put(\"group.id\", \"test\");\n props.put(\"enable.auto.commit\", \"true\");\n props.put(\"auto.commit.interval.ms\", \"1000\");\n props.put(\"session.timeout.ms\", \"30000\");\n props.put(\"key.deserializer\", \n \"org.apache.kafka.common.serialization.StringDeserializer\");\n props.put(\"value.deserializer\", \n \"org.apache.kafka.common.serialization.StringDeserializer\");\n KafkaConsumer<String, String> consumer = new KafkaConsumer\n <String, String>(props);\n \n //Kafka Consumer subscribes list of topics here.\n consumer.subscribe(Arrays.asList(topicName))\n \n //print the topic name\n System.out.println(\"Subscribed to topic \" + topicName);\n int i = 0;\n \n while (true) {\n ConsumerRecords<String, String> records = con-sumer.poll(100);\n for (ConsumerRecord<String, String> record : records)\n \n // print the offset,key and value for the consumer records.\n System.out.printf(\"offset = %d, key = %s, value = %s\\n\", \n record.offset(), record.key(), record.value());\n }\n }\n}"
},
{
"code": null,
"e": 48329,
"s": 48254,
"text": "Compilation − The application can be compiled using the following command."
},
{
"code": null,
"e": 48389,
"s": 48329,
"text": "javac -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*” *.java\n"
},
{
"code": null,
"e": 48461,
"s": 48389,
"text": "Execution − The application can be executed using the following command"
},
{
"code": null,
"e": 48543,
"s": 48461,
"text": "java -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*”:. SimpleConsumer <topic-name>\n"
},
{
"code": null,
"e": 48659,
"s": 48543,
"text": "Input − Open the producer CLI and send some messages to the topic. You can put the smple input as ‘Hello Consumer’."
},
{
"code": null,
"e": 48698,
"s": 48659,
"text": "Output − Following will be the output."
},
{
"code": null,
"e": 48778,
"s": 48698,
"text": "Subscribed to topic Hello-Kafka\noffset = 3, key = null, value = Hello Consumer\n"
},
{
"code": null,
"e": 48861,
"s": 48778,
"text": "Consumer group is a multi-threaded or multi-machine consumption from Kafka topics."
},
{
"code": null,
"e": 48915,
"s": 48861,
"text": "Consumers can join a group by using the samegroup.id."
},
{
"code": null,
"e": 48969,
"s": 48915,
"text": "Consumers can join a group by using the samegroup.id."
},
{
"code": null,
"e": 49069,
"s": 48969,
"text": "The maximum parallelism of a group is that the number of consumers in the group ← no of partitions."
},
{
"code": null,
"e": 49169,
"s": 49069,
"text": "The maximum parallelism of a group is that the number of consumers in the group ← no of partitions."
},
{
"code": null,
"e": 49310,
"s": 49169,
"text": "Kafka assigns the partitions of a topic to the consumer in a group, so that each partition is consumed by exactly one consumer in the group."
},
{
"code": null,
"e": 49451,
"s": 49310,
"text": "Kafka assigns the partitions of a topic to the consumer in a group, so that each partition is consumed by exactly one consumer in the group."
},
{
"code": null,
"e": 49536,
"s": 49451,
"text": "Kafka guarantees that a message is only ever read by a single consumer in the group."
},
{
"code": null,
"e": 49621,
"s": 49536,
"text": "Kafka guarantees that a message is only ever read by a single consumer in the group."
},
{
"code": null,
"e": 49693,
"s": 49621,
"text": "Consumers can see the message in the order they were stored in the log."
},
{
"code": null,
"e": 49765,
"s": 49693,
"text": "Consumers can see the message in the order they were stored in the log."
},
{
"code": null,
"e": 50080,
"s": 49765,
"text": "Adding more processes/threads will cause Kafka to re-balance. If any consumer or broker fails to send heartbeat to ZooKeeper, then it can be re-configured via the Kafka cluster. During this re-balance, Kafka will assign available partitions to the available threads, possibly moving a partition to another process."
},
{
"code": null,
"e": 51658,
"s": 50080,
"text": "import java.util.Properties;\nimport java.util.Arrays;\nimport org.apache.kafka.clients.consumer.KafkaConsumer;\nimport org.apache.kafka.clients.consumer.ConsumerRecords;\nimport org.apache.kafka.clients.consumer.ConsumerRecord;\n\npublic class ConsumerGroup {\n public static void main(String[] args) throws Exception {\n if(args.length < 2){\n System.out.println(\"Usage: consumer <topic> <groupname>\");\n return;\n }\n \n String topic = args[0].toString();\n String group = args[1].toString();\n Properties props = new Properties();\n props.put(\"bootstrap.servers\", \"localhost:9092\");\n props.put(\"group.id\", group);\n props.put(\"enable.auto.commit\", \"true\");\n props.put(\"auto.commit.interval.ms\", \"1000\");\n props.put(\"session.timeout.ms\", \"30000\");\n props.put(\"key.deserializer\", \n \"org.apache.kafka.common.serialization.ByteArraySerializer\");\n props.put(\"value.deserializer\", \n \"org.apache.kafka.common.serialization.StringDeserializer\");\n KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);\n \n consumer.subscribe(Arrays.asList(topic));\n System.out.println(\"Subscribed to topic \" + topic);\n int i = 0;\n \n while (true) {\n ConsumerRecords<String, String> records = consumer.poll(100);\n for (ConsumerRecord<String, String> record : records)\n System.out.printf(\"offset = %d, key = %s, value = %s\\n\", \n record.offset(), record.key(), record.value());\n } \n } \n}"
},
{
"code": null,
"e": 51730,
"s": 51658,
"text": "javac -cp “/path/to/kafka/kafka_2.11-0.9.0.0/libs/*\" ConsumerGroup.java"
},
{
"code": null,
"e": 51929,
"s": 51730,
"text": ">>java -cp “/path/to/kafka/kafka_2.11-0.9.0.0/libs/*\":. \nConsumerGroup <topic-name> my-group\n>>java -cp \"/home/bala/Workspace/kafka/kafka_2.11-0.9.0.0/libs/*\":. \nConsumerGroup <topic-name> my-group\n"
},
{
"code": null,
"e": 52077,
"s": 51929,
"text": "Here we have created a sample group name as my-group with two consumers. Similarly, you can create your group and number of consumers in the group."
},
{
"code": null,
"e": 52125,
"s": 52077,
"text": "Open producer CLI and send some messages like −"
},
{
"code": null,
"e": 52172,
"s": 52125,
"text": "Test consumer group 01\nTest consumer group 02\n"
},
{
"code": null,
"e": 52259,
"s": 52172,
"text": "Subscribed to topic Hello-kafka\noffset = 3, key = null, value = Test consumer group 01"
},
{
"code": null,
"e": 52347,
"s": 52259,
"text": "Subscribed to topic Hello-kafka\noffset = 3, key = null, value = Test consumer group 02\n"
},
{
"code": null,
"e": 52613,
"s": 52347,
"text": "Now hopefully you would have understood SimpleConsumer and ConsumeGroup by using the Java client demo. Now you have an idea about how to send and receive messages using a Java client. Let us continue Kafka integration with big data technologies in the next chapter."
},
{
"code": null,
"e": 52686,
"s": 52613,
"text": "In this chapter, we will learn how to integrate Kafka with Apache Storm."
},
{
"code": null,
"e": 53183,
"s": 52686,
"text": "Storm was originally created by Nathan Marz and team at BackType. In a short time, Apache Storm became a standard for distributed real-time processing system that allows you to process a huge volume of data. Storm is very fast and a benchmark clocked it at over a million tuples processed per second per node. Apache Storm runs continuously, consuming data from the configured sources (Spouts) and passes the data down the processing pipeline (Bolts). Com-bined, Spouts and Bolts make a Topology."
},
{
"code": null,
"e": 53446,
"s": 53183,
"text": "Kafka and Storm naturally complement each other, and their powerful cooperation enables real-time streaming analytics for fast-moving big data. Kafka and Storm integration is to make easier for developers to ingest and publish data streams from Storm topologies."
},
{
"code": null,
"e": 54044,
"s": 53446,
"text": "A spout is a source of streams. For example, a spout may read tuples off a Kafka Topic and emit them as a stream. A bolt consumes input streams, process and possibly emits new streams. Bolts can do anything from running functions, filtering tuples, do streaming aggregations, streaming joins, talk to databases, and more. Each node in a Storm topology executes in parallel. A topology runs indefinitely until you terminate it. Storm will automatically reassign any failed tasks. Additionally, Storm guarantees that there will be no data loss, even if the machines go down and messages are dropped."
},
{
"code": null,
"e": 54189,
"s": 54044,
"text": "Let us go through the Kafka-Storm integration API’s in detail. There are three main classes to integrate Kafka with Storm. They are as follows −"
},
{
"code": null,
"e": 54528,
"s": 54189,
"text": "BrokerHosts is an interface and ZkHosts and StaticHosts are its two main implementations. ZkHosts is used to track the Kafka brokers dynamically by maintaining the details in ZooKeeper, while StaticHosts is used to manually / statically set the Kafka brokers and its details. ZkHosts is the simple and fast way to access the Kafka broker."
},
{
"code": null,
"e": 54569,
"s": 54528,
"text": "The signature of ZkHosts is as follows −"
},
{
"code": null,
"e": 54661,
"s": 54569,
"text": "public ZkHosts(String brokerZkStr, String brokerZkPath)\npublic ZkHosts(String brokerZkStr)\n"
},
{
"code": null,
"e": 54774,
"s": 54661,
"text": "Where brokerZkStr is ZooKeeper host and brokerZkPath is the ZooKeeper path to maintain the Kafka broker details."
},
{
"code": null,
"e": 54900,
"s": 54774,
"text": "This API is used to define configuration settings for the Kafka cluster. The signature of Kafka Con-fig is defined as follows"
},
{
"code": null,
"e": 54953,
"s": 54900,
"text": "public KafkaConfig(BrokerHosts hosts, string topic)\n"
},
{
"code": null,
"e": 55007,
"s": 54953,
"text": "Hosts − The BrokerHosts can be ZkHosts / StaticHosts."
},
{
"code": null,
"e": 55027,
"s": 55007,
"text": "Topic − topic name."
},
{
"code": null,
"e": 55118,
"s": 55027,
"text": "Spoutconfig is an extension of KafkaConfig that supports additional ZooKeeper information."
},
{
"code": null,
"e": 55197,
"s": 55118,
"text": "public SpoutConfig(BrokerHosts hosts, string topic, string zkRoot, string id)\n"
},
{
"code": null,
"e": 55272,
"s": 55197,
"text": "Hosts − The BrokerHosts can be any implementation of BrokerHosts interface"
},
{
"code": null,
"e": 55347,
"s": 55272,
"text": "Hosts − The BrokerHosts can be any implementation of BrokerHosts interface"
},
{
"code": null,
"e": 55367,
"s": 55347,
"text": "Topic − topic name."
},
{
"code": null,
"e": 55387,
"s": 55367,
"text": "Topic − topic name."
},
{
"code": null,
"e": 55417,
"s": 55387,
"text": "zkRoot − ZooKeeper root path."
},
{
"code": null,
"e": 55447,
"s": 55417,
"text": "zkRoot − ZooKeeper root path."
},
{
"code": null,
"e": 55565,
"s": 55447,
"text": "id − The spout stores the state of the offsets its consumed in Zookeeper. The id should uniquely identify your spout."
},
{
"code": null,
"e": 55683,
"s": 55565,
"text": "id − The spout stores the state of the offsets its consumed in Zookeeper. The id should uniquely identify your spout."
},
{
"code": null,
"e": 56105,
"s": 55683,
"text": "SchemeAsMultiScheme is an interface that dictates how the ByteBuffer consumed from Kafka gets transformed into a storm tuple. It is derived from MultiScheme and accept implementation of Scheme class. There are lot of implementation of Scheme class and one such implementation is StringScheme, which parses the byte as a simple string. It also controls the naming of your output field. The signature is defined as follows."
},
{
"code": null,
"e": 56148,
"s": 56105,
"text": "public SchemeAsMultiScheme(Scheme scheme)\n"
},
{
"code": null,
"e": 56190,
"s": 56148,
"text": "Scheme − byte buffer consumed from kafka."
},
{
"code": null,
"e": 56232,
"s": 56190,
"text": "Scheme − byte buffer consumed from kafka."
},
{
"code": null,
"e": 56452,
"s": 56232,
"text": "KafkaSpout is our spout implementation, which will integrate with Storm. It fetches the mes-sages from kafka topic and emits it into Storm ecosystem as tuples. KafkaSpout get its config-uration details from SpoutConfig."
},
{
"code": null,
"e": 56507,
"s": 56452,
"text": "Below is a sample code to create a simple Kafka spout."
},
{
"code": null,
"e": 56920,
"s": 56507,
"text": "// ZooKeeper connection string\nBrokerHosts hosts = new ZkHosts(zkConnString);\n\n//Creating SpoutConfig Object\nSpoutConfig spoutConfig = new SpoutConfig(hosts, \n topicName, \"/\" + topicName UUID.randomUUID().toString());\n\n//convert the ByteBuffer to String.\nspoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme());\n\n//Assign SpoutConfig to KafkaSpout.\nKafkaSpout kafkaSpout = new KafkaSpout(spoutConfig);"
},
{
"code": null,
"e": 57174,
"s": 56920,
"text": "Bolt is a component that takes tuples as input, processes the tuple, and produces new tuples as output. Bolts will implement IRichBolt interface. In this program, two bolt classes WordSplitter-Bolt and WordCounterBolt are used to perform the operations."
},
{
"code": null,
"e": 57222,
"s": 57174,
"text": "IRichBolt interface has the following methods −"
},
{
"code": null,
"e": 57342,
"s": 57222,
"text": "Prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout."
},
{
"code": null,
"e": 57462,
"s": 57342,
"text": "Prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout."
},
{
"code": null,
"e": 57505,
"s": 57462,
"text": "Execute − Process a single tuple of input."
},
{
"code": null,
"e": 57548,
"s": 57505,
"text": "Execute − Process a single tuple of input."
},
{
"code": null,
"e": 57600,
"s": 57548,
"text": "Cleanup − Called when a bolt is going to shut down."
},
{
"code": null,
"e": 57652,
"s": 57600,
"text": "Cleanup − Called when a bolt is going to shut down."
},
{
"code": null,
"e": 57715,
"s": 57652,
"text": "declareOutputFields − Declares the output schema of the tuple."
},
{
"code": null,
"e": 57778,
"s": 57715,
"text": "declareOutputFields − Declares the output schema of the tuple."
},
{
"code": null,
"e": 57960,
"s": 57778,
"text": "Let us create SplitBolt.java, which implements the logic to split a sentence into words and CountBolt.java, which implements logic to separate unique words and count its occurrence."
},
{
"code": null,
"e": 59196,
"s": 57960,
"text": "import java.util.Map;\n\nimport backtype.storm.tuple.Tuple;\nimport backtype.storm.tuple.Fields;\nimport backtype.storm.tuple.Values;\n\nimport backtype.storm.task.OutputCollector;\nimport backtype.storm.topology.OutputFieldsDeclarer;\nimport backtype.storm.topology.IRichBolt;\nimport backtype.storm.task.TopologyContext;\n\npublic class SplitBolt implements IRichBolt {\n private OutputCollector collector;\n \n @Override\n public void prepare(Map stormConf, TopologyContext context,\n OutputCollector collector) {\n this.collector = collector;\n }\n \n @Override\n public void execute(Tuple input) {\n String sentence = input.getString(0);\n String[] words = sentence.split(\" \");\n \n for(String word: words) {\n word = word.trim();\n \n if(!word.isEmpty()) {\n word = word.toLowerCase();\n collector.emit(new Values(word));\n }\n \n }\n\n collector.ack(input);\n }\n \n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n declarer.declare(new Fields(\"word\"));\n }\n\n @Override\n public void cleanup() {}\n \n @Override\n public Map<String, Object> getComponentConfiguration() {\n return null;\n }\n \n}"
},
{
"code": null,
"e": 60466,
"s": 59196,
"text": "import java.util.Map;\nimport java.util.HashMap;\n\nimport backtype.storm.tuple.Tuple;\nimport backtype.storm.task.OutputCollector;\nimport backtype.storm.topology.OutputFieldsDeclarer;\nimport backtype.storm.topology.IRichBolt;\nimport backtype.storm.task.TopologyContext;\n\npublic class CountBolt implements IRichBolt{\n Map<String, Integer> counters;\n private OutputCollector collector;\n \n @Override\n public void prepare(Map stormConf, TopologyContext context,\n OutputCollector collector) {\n this.counters = new HashMap<String, Integer>();\n this.collector = collector;\n }\n\n @Override\n public void execute(Tuple input) {\n String str = input.getString(0);\n \n if(!counters.containsKey(str)){\n counters.put(str, 1);\n }else {\n Integer c = counters.get(str) +1;\n counters.put(str, c);\n }\n \n collector.ack(input);\n }\n\n @Override\n public void cleanup() {\n for(Map.Entry<String, Integer> entry:counters.entrySet()){\n System.out.println(entry.getKey()+\" : \" + entry.getValue());\n }\n }\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n \n }\n\n @Override\n public Map<String, Object> getComponentConfiguration() {\n return null;\n }\n}"
},
{
"code": null,
"e": 60849,
"s": 60466,
"text": "The Storm topology is basically a Thrift structure. TopologyBuilder class provides simple and easy methods to create complex topologies. The TopologyBuilder class has methods to set spout (setSpout) and to set bolt (setBolt). Finally, TopologyBuilder has createTopology to create to-pology. shuffleGrouping and fieldsGrouping methods help to set stream grouping for spout and bolts."
},
{
"code": null,
"e": 61027,
"s": 60849,
"text": "Local Cluster − For development purposes, we can create a local cluster using LocalCluster object and then submit the topology using submitTopology method of LocalCluster class."
},
{
"code": null,
"e": 62809,
"s": 61027,
"text": "import backtype.storm.Config;\nimport backtype.storm.LocalCluster;\nimport backtype.storm.topology.TopologyBuilder;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.UUID;\n\nimport backtype.storm.spout.SchemeAsMultiScheme;\nimport storm.kafka.trident.GlobalPartitionInformation;\nimport storm.kafka.ZkHosts;\nimport storm.kafka.Broker;\nimport storm.kafka.StaticHosts;\nimport storm.kafka.BrokerHosts;\nimport storm.kafka.SpoutConfig;\nimport storm.kafka.KafkaConfig;\nimport storm.kafka.KafkaSpout;\nimport storm.kafka.StringScheme;\n\npublic class KafkaStormSample {\n public static void main(String[] args) throws Exception{\n Config config = new Config();\n config.setDebug(true);\n config.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 1);\n String zkConnString = \"localhost:2181\";\n String topic = \"my-first-topic\";\n BrokerHosts hosts = new ZkHosts(zkConnString);\n \n SpoutConfig kafkaSpoutConfig = new SpoutConfig (hosts, topic, \"/\" + topic, \n UUID.randomUUID().toString());\n kafkaSpoutConfig.bufferSizeBytes = 1024 * 1024 * 4;\n kafkaSpoutConfig.fetchSizeBytes = 1024 * 1024 * 4;\n kafkaSpoutConfig.forceFromStart = true;\n kafkaSpoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme());\n\n TopologyBuilder builder = new TopologyBuilder();\n builder.setSpout(\"kafka-spout\", new KafkaSpout(kafkaSpoutCon-fig));\n builder.setBolt(\"word-spitter\", new SplitBolt()).shuffleGroup-ing(\"kafka-spout\");\n builder.setBolt(\"word-counter\", new CountBolt()).shuffleGroup-ing(\"word-spitter\");\n \n LocalCluster cluster = new LocalCluster();\n cluster.submitTopology(\"KafkaStormSample\", config, builder.create-Topology());\n\n Thread.sleep(10000);\n \n cluster.shutdown();\n }\n}"
},
{
"code": null,
"e": 63068,
"s": 62809,
"text": "Before moving compilation, Kakfa-Storm integration needs curator ZooKeeper client java library. Curator version 2.9.1 support Apache Storm version 0.9.5 (which we use in this tutorial). Down-load the below specified jar files and place it in java class path."
},
{
"code": null,
"e": 63093,
"s": 63068,
"text": "curator-client-2.9.1.jar"
},
{
"code": null,
"e": 63121,
"s": 63093,
"text": "curator-framework-2.9.1.jar"
},
{
"code": null,
"e": 63204,
"s": 63121,
"text": "After including dependency files, compile the program using the following command,"
},
{
"code": null,
"e": 63264,
"s": 63204,
"text": "javac -cp \"/path/to/Kafka/apache-storm-0.9.5/lib/*\" *.java\n"
},
{
"code": null,
"e": 63413,
"s": 63264,
"text": "Start Kafka Producer CLI (explained in previous chapter), create a new topic called my-first-topic and provide some sample messages as shown below −"
},
{
"code": null,
"e": 63472,
"s": 63413,
"text": "hello\nkafka\nstorm\nspark\ntest message\nanother test message\n"
},
{
"code": null,
"e": 63530,
"s": 63472,
"text": "Now execute the application using the following command −"
},
{
"code": null,
"e": 63601,
"s": 63530,
"text": "java -cp “/path/to/Kafka/apache-storm-0.9.5/lib/*”:. KafkaStormSample\n"
},
{
"code": null,
"e": 63660,
"s": 63601,
"text": "The sample output of this application is specified below −"
},
{
"code": null,
"e": 63734,
"s": 63660,
"text": "storm : 1\ntest : 2\nspark : 1\nanother : 1\nkafka : 1\nhello : 1\nmessage : 2\n"
},
{
"code": null,
"e": 63835,
"s": 63734,
"text": "In this chapter, we will be discussing about how to integrate Apache Kafka with Spark Streaming API."
},
{
"code": null,
"e": 64465,
"s": 63835,
"text": "Spark Streaming API enables scalable, high-throughput, fault-tolerant stream processing of live data streams. Data can be ingested from many sources like Kafka, Flume, Twitter, etc., and can be processed using complex algorithms such as high-level functions like map, reduce, join and window. Finally, processed data can be pushed out to filesystems, databases, and live dash-boards. Resilient Distributed Datasets (RDD) is a fundamental data structure of Spark. It is an immutable distributed collection of objects. Each dataset in RDD is divided into logical partitions, which may be computed on different nodes of the cluster."
},
{
"code": null,
"e": 64859,
"s": 64465,
"text": "Kafka is a potential messaging and integration platform for Spark streaming. Kafka act as the central hub for real-time streams of data and are processed using complex algorithms in Spark Streaming. Once the data is processed, Spark Streaming could be publishing results into yet another Kafka topic or store in HDFS, databases or dashboards. The following diagram depicts the conceptual flow."
},
{
"code": null,
"e": 64911,
"s": 64859,
"text": "Now, let us go through Kafka-Spark API’s in detail."
},
{
"code": null,
"e": 65021,
"s": 64911,
"text": "It represents configuration for a Spark application. Used to set various Spark parameters as key-value pairs."
},
{
"code": null,
"e": 65065,
"s": 65021,
"text": "SparkConf class has the following methods −"
},
{
"code": null,
"e": 65125,
"s": 65065,
"text": "set(string key, string value) − set configuration variable."
},
{
"code": null,
"e": 65185,
"s": 65125,
"text": "set(string key, string value) − set configuration variable."
},
{
"code": null,
"e": 65241,
"s": 65185,
"text": "remove(string key) − remove key from the configuration."
},
{
"code": null,
"e": 65297,
"s": 65241,
"text": "remove(string key) − remove key from the configuration."
},
{
"code": null,
"e": 65366,
"s": 65297,
"text": "setAppName(string name) − set application name for your application."
},
{
"code": null,
"e": 65435,
"s": 65366,
"text": "setAppName(string name) − set application name for your application."
},
{
"code": null,
"e": 65461,
"s": 65435,
"text": "get(string key) − get key"
},
{
"code": null,
"e": 65487,
"s": 65461,
"text": "get(string key) − get key"
},
{
"code": null,
"e": 65728,
"s": 65487,
"text": "This is the main entry point for Spark functionality. A SparkContext represents the connection to a Spark cluster, and can be used to create RDDs, accumulators and broadcast variables on the cluster. The signature is defined as shown below."
},
{
"code": null,
"e": 65917,
"s": 65728,
"text": "public StreamingContext(String master, String appName, Duration batchDuration, \n String sparkHome, scala.collection.Seq<String> jars, \n scala.collection.Map<String,String> environment)"
},
{
"code": null,
"e": 66007,
"s": 65917,
"text": "master − cluster URL to connect to (e.g. mesos://host:port, spark://host:port, local[4])."
},
{
"code": null,
"e": 66097,
"s": 66007,
"text": "master − cluster URL to connect to (e.g. mesos://host:port, spark://host:port, local[4])."
},
{
"code": null,
"e": 66161,
"s": 66097,
"text": "appName − a name for your job, to display on the cluster web UI"
},
{
"code": null,
"e": 66225,
"s": 66161,
"text": "appName − a name for your job, to display on the cluster web UI"
},
{
"code": null,
"e": 66312,
"s": 66225,
"text": "batchDuration − the time interval at which streaming data will be divided into batches"
},
{
"code": null,
"e": 66399,
"s": 66312,
"text": "batchDuration − the time interval at which streaming data will be divided into batches"
},
{
"code": null,
"e": 66464,
"s": 66399,
"text": "public StreamingContext(SparkConf conf, Duration batchDuration)\n"
},
{
"code": null,
"e": 66555,
"s": 66464,
"text": "Create a StreamingContext by providing the configuration necessary for a new SparkContext."
},
{
"code": null,
"e": 66579,
"s": 66555,
"text": "conf − Spark parameters"
},
{
"code": null,
"e": 66603,
"s": 66579,
"text": "conf − Spark parameters"
},
{
"code": null,
"e": 66690,
"s": 66603,
"text": "batchDuration − the time interval at which streaming data will be divided into batches"
},
{
"code": null,
"e": 66777,
"s": 66690,
"text": "batchDuration − the time interval at which streaming data will be divided into batches"
},
{
"code": null,
"e": 66927,
"s": 66777,
"text": "KafkaUtils API is used to connect the Kafka cluster to Spark streaming. This API has the signifi-cant method createStream signature defined as below."
},
{
"code": null,
"e": 67148,
"s": 66927,
"text": "public static ReceiverInputDStream<scala.Tuple2<String,String>> createStream(\n StreamingContext ssc, String zkQuorum, String groupId,\n scala.collection.immutable.Map<String,Object> topics, StorageLevel storageLevel)\n"
},
{
"code": null,
"e": 67245,
"s": 67148,
"text": "The above shown method is used to Create an input stream that pulls messages from Kafka Brokers."
},
{
"code": null,
"e": 67276,
"s": 67245,
"text": "ssc − StreamingContext object."
},
{
"code": null,
"e": 67307,
"s": 67276,
"text": "ssc − StreamingContext object."
},
{
"code": null,
"e": 67336,
"s": 67307,
"text": "zkQuorum − Zookeeper quorum."
},
{
"code": null,
"e": 67365,
"s": 67336,
"text": "zkQuorum − Zookeeper quorum."
},
{
"code": null,
"e": 67407,
"s": 67365,
"text": "groupId − The group id for this consumer."
},
{
"code": null,
"e": 67449,
"s": 67407,
"text": "groupId − The group id for this consumer."
},
{
"code": null,
"e": 67493,
"s": 67449,
"text": "topics − return a map of topics to consume."
},
{
"code": null,
"e": 67537,
"s": 67493,
"text": "topics − return a map of topics to consume."
},
{
"code": null,
"e": 67607,
"s": 67537,
"text": "storageLevel − Storage level to use for storing the received objects."
},
{
"code": null,
"e": 67677,
"s": 67607,
"text": "storageLevel − Storage level to use for storing the received objects."
},
{
"code": null,
"e": 67947,
"s": 67677,
"text": "KafkaUtils API has another method createDirectStream, which is used to create an input stream that directly pulls messages from Kafka Brokers without using any receiver. This stream can guarantee that each message from Kafka is included in transformations exactly once."
},
{
"code": null,
"e": 68132,
"s": 67947,
"text": "The sample application is done in Scala. To compile the application, please download and install sbt, scala build tool (similar to maven). The main application code is presented below."
},
{
"code": null,
"e": 69200,
"s": 68132,
"text": "import java.util.HashMap\n\nimport org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, Produc-erRecord}\nimport org.apache.spark.SparkConf\nimport org.apache.spark.streaming._\nimport org.apache.spark.streaming.kafka._\n\nobject KafkaWordCount {\n def main(args: Array[String]) {\n if (args.length < 4) {\n System.err.println(\"Usage: KafkaWordCount <zkQuorum><group> <topics> <numThreads>\")\n System.exit(1)\n }\n\n val Array(zkQuorum, group, topics, numThreads) = args\n val sparkConf = new SparkConf().setAppName(\"KafkaWordCount\")\n val ssc = new StreamingContext(sparkConf, Seconds(2))\n ssc.checkpoint(\"checkpoint\")\n\n val topicMap = topics.split(\",\").map((_, numThreads.toInt)).toMap\n val lines = KafkaUtils.createStream(ssc, zkQuorum, group, topicMap).map(_._2)\n val words = lines.flatMap(_.split(\" \"))\n val wordCounts = words.map(x => (x, 1L))\n .reduceByKeyAndWindow(_ + _, _ - _, Minutes(10), Seconds(2), 2)\n wordCounts.print()\n\n ssc.start()\n ssc.awaitTermination()\n }\n}"
},
{
"code": null,
"e": 69468,
"s": 69200,
"text": "The spark-kafka integration depends on the spark, spark streaming and spark Kafka integration jar. Create a new file build.sbt and specify the application details and its dependency. The sbt will download the necessary jar while compiling and packing the application."
},
{
"code": null,
"e": 69761,
"s": 69468,
"text": "name := \"Spark Kafka Project\"\nversion := \"1.0\"\nscalaVersion := \"2.10.5\"\n\nlibraryDependencies += \"org.apache.spark\" %% \"spark-core\" % \"1.6.0\"\nlibraryDependencies += \"org.apache.spark\" %% \"spark-streaming\" % \"1.6.0\"\nlibraryDependencies += \"org.apache.spark\" %% \"spark-streaming-kafka\" % \"1.6.0\""
},
{
"code": null,
"e": 69921,
"s": 69761,
"text": "Run the following command to compile and package the jar file of the application. We need to submit the jar file into the spark console to run the application."
},
{
"code": null,
"e": 69934,
"s": 69921,
"text": "sbt package\n"
},
{
"code": null,
"e": 70086,
"s": 69934,
"text": "Start Kafka Producer CLI (explained in the previous chapter), create a new topic called my-first-topic and provide some sample messages as shown below."
},
{
"code": null,
"e": 70114,
"s": 70086,
"text": "Another spark test message\n"
},
{
"code": null,
"e": 70184,
"s": 70114,
"text": "Run the following command to submit the application to spark console."
},
{
"code": null,
"e": 70436,
"s": 70184,
"text": "/usr/local/spark/bin/spark-submit --packages org.apache.spark:spark-streaming\n-kafka_2.10:1.6.0 --class \"KafkaWordCount\" --master local[4] target/scala-2.10/spark\n-kafka-project_2.10-1.0.jar localhost:2181 <group name> <topic name> <number of threads>"
},
{
"code": null,
"e": 70490,
"s": 70436,
"text": "The sample output of this application is shown below."
},
{
"code": null,
"e": 70585,
"s": 70490,
"text": "spark console messages ..\n(Test,1)\n(spark,1)\n(another,1)\n(message,1)\nspark console message ..\n"
},
{
"code": null,
"e": 71055,
"s": 70585,
"text": "Let us analyze a real time application to get the latest twitter feeds and its hashtags. Earlier, we have seen integration of Storm and Spark with Kafka. In both the scenarios, we created a Kafka Producer (using cli) to send message to the Kafka ecosystem. Then, the storm and spark inte-gration reads the messages by using the Kafka consumer and injects it into storm and spark ecosystem respectively. So, practically we need to create a Kafka Producer, which should −"
},
{
"code": null,
"e": 71109,
"s": 71055,
"text": "Read the twitter feeds using “Twitter Streaming API”,"
},
{
"code": null,
"e": 71128,
"s": 71109,
"text": "Process the feeds,"
},
{
"code": null,
"e": 71153,
"s": 71128,
"text": "Extract the HashTags and"
},
{
"code": null,
"e": 71171,
"s": 71153,
"text": "Send it to Kafka."
},
{
"code": null,
"e": 71307,
"s": 71171,
"text": "Once the HashTags are received by Kafka, the Storm / Spark integration receive the infor-mation and send it to Storm / Spark ecosystem."
},
{
"code": null,
"e": 71742,
"s": 71307,
"text": "The “Twitter Streaming API” can be accessed in any programming language. The “twitter4j” is an open source, unofficial Java library, which provides a Java based module to easily access the “Twitter Streaming API”. The “twitter4j” provides a listener based framework to access the tweets. To access the “Twitter Streaming API”, we need to sign in for Twitter developer account and should get the following OAuth authentication details."
},
{
"code": null,
"e": 71754,
"s": 71742,
"text": "Customerkey"
},
{
"code": null,
"e": 71769,
"s": 71754,
"text": "CustomerSecret"
},
{
"code": null,
"e": 71781,
"s": 71769,
"text": "AccessToken"
},
{
"code": null,
"e": 71800,
"s": 71781,
"text": "AccessTookenSecret"
},
{
"code": null,
"e": 71911,
"s": 71800,
"text": "Once the developer account is created, download the “twitter4j” jar files and place it in the java class path."
},
{
"code": null,
"e": 72001,
"s": 71911,
"text": "The Complete Twitter Kafka producer coding (KafkaTwitterProducer.java) is listed below −"
},
{
"code": null,
"e": 76607,
"s": 72001,
"text": "import java.util.Arrays;\nimport java.util.Properties;\nimport java.util.concurrent.LinkedBlockingQueue;\n\nimport twitter4j.*;\nimport twitter4j.conf.*;\n\nimport org.apache.kafka.clients.producer.Producer;\nimport org.apache.kafka.clients.producer.KafkaProducer;\nimport org.apache.kafka.clients.producer.ProducerRecord;\n\npublic class KafkaTwitterProducer {\n public static void main(String[] args) throws Exception {\n LinkedBlockingQueue<Status> queue = new LinkedBlockingQueue<Sta-tus>(1000);\n \n if(args.length < 5){\n System.out.println(\n \"Usage: KafkaTwitterProducer <twitter-consumer-key>\n <twitter-consumer-secret> <twitter-access-token>\n <twitter-access-token-secret>\n <topic-name> <twitter-search-keywords>\");\n return;\n }\n \n String consumerKey = args[0].toString();\n String consumerSecret = args[1].toString();\n String accessToken = args[2].toString();\n String accessTokenSecret = args[3].toString();\n String topicName = args[4].toString();\n String[] arguments = args.clone();\n String[] keyWords = Arrays.copyOfRange(arguments, 5, arguments.length);\n\n ConfigurationBuilder cb = new ConfigurationBuilder();\n cb.setDebugEnabled(true)\n .setOAuthConsumerKey(consumerKey)\n .setOAuthConsumerSecret(consumerSecret)\n .setOAuthAccessToken(accessToken)\n .setOAuthAccessTokenSecret(accessTokenSecret);\n\n TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).get-Instance();\n StatusListener listener = new StatusListener() {\n \n @Override\n public void onStatus(Status status) { \n queue.offer(status);\n\n // System.out.println(\"@\" + status.getUser().getScreenName() \n + \" - \" + status.getText());\n // System.out.println(\"@\" + status.getUser().getScreen-Name());\n\n /*for(URLEntity urle : status.getURLEntities()) {\n System.out.println(urle.getDisplayURL());\n }*/\n\n /*for(HashtagEntity hashtage : status.getHashtagEntities()) {\n System.out.println(hashtage.getText());\n }*/\n }\n \n @Override\n public void onDeletionNotice(StatusDeletionNotice statusDeletion-Notice) {\n // System.out.println(\"Got a status deletion notice id:\" \n + statusDeletionNotice.getStatusId());\n }\n \n @Override\n public void onTrackLimitationNotice(int numberOfLimitedStatuses) {\n // System.out.println(\"Got track limitation notice:\" + \n num-berOfLimitedStatuses);\n }\n\n @Override\n public void onScrubGeo(long userId, long upToStatusId) {\n // System.out.println(\"Got scrub_geo event userId:\" + userId + \n \"upToStatusId:\" + upToStatusId);\n } \n \n @Override\n public void onStallWarning(StallWarning warning) {\n // System.out.println(\"Got stall warning:\" + warning);\n }\n \n @Override\n public void onException(Exception ex) {\n ex.printStackTrace();\n }\n };\n twitterStream.addListener(listener);\n \n FilterQuery query = new FilterQuery().track(keyWords);\n twitterStream.filter(query);\n\n Thread.sleep(5000);\n \n //Add Kafka producer config settings\n Properties props = new Properties();\n props.put(\"bootstrap.servers\", \"localhost:9092\");\n props.put(\"acks\", \"all\");\n props.put(\"retries\", 0);\n props.put(\"batch.size\", 16384);\n props.put(\"linger.ms\", 1);\n props.put(\"buffer.memory\", 33554432);\n \n props.put(\"key.serializer\", \n \"org.apache.kafka.common.serialization.StringSerializer\");\n props.put(\"value.serializer\", \n \"org.apache.kafka.common.serialization.StringSerializer\");\n \n Producer<String, String> producer = new KafkaProducer<String, String>(props);\n int i = 0;\n int j = 0;\n \n while(i < 10) {\n Status ret = queue.poll();\n \n if (ret == null) {\n Thread.sleep(100);\n i++;\n }else {\n for(HashtagEntity hashtage : ret.getHashtagEntities()) {\n System.out.println(\"Hashtag: \" + hashtage.getText());\n producer.send(new ProducerRecord<String, String>(\n top-icName, Integer.toString(j++), hashtage.getText()));\n }\n }\n }\n producer.close();\n Thread.sleep(5000);\n twitterStream.shutdown();\n }\n}"
},
{
"code": null,
"e": 76661,
"s": 76607,
"text": "Compile the application using the following command −"
},
{
"code": null,
"e": 76750,
"s": 76661,
"text": "javac -cp “/path/to/kafka/libs/*”:”/path/to/twitter4j/lib/*”:. KafkaTwitterProducer.java"
},
{
"code": null,
"e": 76835,
"s": 76750,
"text": "Open two consoles. Run the above compiled application as shown below in one console."
},
{
"code": null,
"e": 77042,
"s": 76835,
"text": "java -cp “/path/to/kafka/libs/*”:”/path/to/twitter4j/lib/*”:\n. KafkaTwitterProducer <twitter-consumer-key>\n<twitter-consumer-secret>\n<twitter-access-token>\n<twitter-ac-cess-token-secret>\nmy-first-topic food"
},
{
"code": null,
"e": 77272,
"s": 77042,
"text": "Run any one of the Spark / Storm application explained in the previous chapter in another win-dow. The main point to note is that the topic used should be same in both cases. Here, we have used “my-first-topic” as the topic name."
},
{
"code": null,
"e": 77424,
"s": 77272,
"text": "The output of this application will depend on the keywords and the current feed of the twitter. A sample output is specified below (storm integration)."
},
{
"code": null,
"e": 77468,
"s": 77424,
"text": ". . .\nfood : 1\nfoodie : 2\nburger : 1\n. . .\n"
},
{
"code": null,
"e": 77584,
"s": 77468,
"text": "Kafka Tool packaged under “org.apache.kafka.tools.*. Tools are categorized into system tools and replication tools."
},
{
"code": null,
"e": 77685,
"s": 77584,
"text": "System tools can be run from the command line using the run class script. The syntax is as follows −"
},
{
"code": null,
"e": 77734,
"s": 77685,
"text": "bin/kafka-run-class.sh package.class - - options"
},
{
"code": null,
"e": 77781,
"s": 77734,
"text": "Some of the system tools are mentioned below −"
},
{
"code": null,
"e": 77872,
"s": 77781,
"text": "Kafka Migration Tool − This tool is used to migrate a broker from one version to an-other."
},
{
"code": null,
"e": 77963,
"s": 77872,
"text": "Kafka Migration Tool − This tool is used to migrate a broker from one version to an-other."
},
{
"code": null,
"e": 78050,
"s": 77963,
"text": "Mirror Maker − This tool is used to provide mirroring of one Kafka cluster to another."
},
{
"code": null,
"e": 78137,
"s": 78050,
"text": "Mirror Maker − This tool is used to provide mirroring of one Kafka cluster to another."
},
{
"code": null,
"e": 78293,
"s": 78137,
"text": "Consumer Offset Checker − This tool displays Consumer Group, Topic, Partitions, Off-set, logSize, Owner for the specified set of Topics and Consumer Group."
},
{
"code": null,
"e": 78449,
"s": 78293,
"text": "Consumer Offset Checker − This tool displays Consumer Group, Topic, Partitions, Off-set, logSize, Owner for the specified set of Topics and Consumer Group."
},
{
"code": null,
"e": 78639,
"s": 78449,
"text": "Kafka replication is a high level design tool. The purpose of adding replication tool is for stronger durability and higher availability. Some of the replication tools are mentioned below −"
},
{
"code": null,
"e": 78794,
"s": 78639,
"text": "Create Topic Tool − This creates a topic with a default number of partitions, replication factor and uses Kafka's default scheme to do replica assignment."
},
{
"code": null,
"e": 78949,
"s": 78794,
"text": "Create Topic Tool − This creates a topic with a default number of partitions, replication factor and uses Kafka's default scheme to do replica assignment."
},
{
"code": null,
"e": 79243,
"s": 78949,
"text": "List Topic Tool − This tool lists the information for a given list of topics. If no topics are provided in the command line, the tool queries Zookeeper to get all the topics and lists the information for them. The fields that the tool displays are topic name, partition, leader, replicas, isr."
},
{
"code": null,
"e": 79537,
"s": 79243,
"text": "List Topic Tool − This tool lists the information for a given list of topics. If no topics are provided in the command line, the tool queries Zookeeper to get all the topics and lists the information for them. The fields that the tool displays are topic name, partition, leader, replicas, isr."
},
{
"code": null,
"e": 79861,
"s": 79537,
"text": "Add Partition Tool − Creation of a topic, the number of partitions for topic has to be specified. Later on, more partitions may be needed for the topic, when the volume of the topic will increase. This tool helps to add more partitions for a specific topic and also allows manual replica assignment of the added partitions."
},
{
"code": null,
"e": 80185,
"s": 79861,
"text": "Add Partition Tool − Creation of a topic, the number of partitions for topic has to be specified. Later on, more partitions may be needed for the topic, when the volume of the topic will increase. This tool helps to add more partitions for a specific topic and also allows manual replica assignment of the added partitions."
},
{
"code": null,
"e": 80351,
"s": 80185,
"text": "Kafka supports many of today's best industrial applications. We will provide a very brief overview of some of the most notable applications of Kafka in this chapter."
},
{
"code": null,
"e": 80622,
"s": 80351,
"text": "Twitter is an online social networking service that provides a platform to send and receive user tweets. Registered users can read and post tweets, but unregistered users can only read tweets. Twitter uses Storm-Kafka as a part of their stream processing infrastructure."
},
{
"code": null,
"e": 80980,
"s": 80622,
"text": "Apache Kafka is used at LinkedIn for activity stream data and operational metrics. Kafka mes-saging system helps LinkedIn with various products like LinkedIn Newsfeed, LinkedIn Today for online message consumption and in addition to offline analytics systems like Hadoop. Kafka’s strong durability is also one of the key factors in connection with LinkedIn."
},
{
"code": null,
"e": 81131,
"s": 80980,
"text": "Netflix is an American multinational provider of on-demand Internet streaming media. Netflix uses Kafka for real-time monitoring and event processing."
},
{
"code": null,
"e": 81394,
"s": 81131,
"text": "Mozilla is a free-software community, created in 1998 by members of Netscape. Kafka will soon be replacing a part of Mozilla current production system to collect performance and usage data from the end-user’s browser for projects like Telemetry, Test Pilot, etc."
},
{
"code": null,
"e": 81619,
"s": 81394,
"text": "Oracle provides native connectivity to Kafka from its Enterprise Service Bus product called OSB (Oracle Service Bus) which allows developers to leverage OSB built-in mediation capabilities to implement staged data pipelines."
},
{
"code": null,
"e": 81654,
"s": 81619,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 81673,
"s": 81654,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 81708,
"s": 81673,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 81729,
"s": 81708,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 81762,
"s": 81729,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 81775,
"s": 81762,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 81810,
"s": 81775,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 81828,
"s": 81810,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 81861,
"s": 81828,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 81879,
"s": 81861,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 81912,
"s": 81879,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 81930,
"s": 81912,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 81937,
"s": 81930,
"text": " Print"
},
{
"code": null,
"e": 81948,
"s": 81937,
"text": " Add Notes"
}
] |
Advantages & Disadvantages of COCOMO Model - GeeksforGeeks
|
31 May, 2021
Overview :Cocomo stands for Constructive Cost Model is a regression model based on LOC, i.e number of Lines of Code. COCOMO model is proposed by Boehm in 1981 It is a procedural cost estimate model for software projects and often used as a process of reliably predicting the various parameters related to making a project such as size, effort, cost, time and quality COCOMO model is one of the most generally used models within the world
Categories of COCOMO :Any of the software models are divided into three categories on the basis of development complexities organic, semi-detached, and embedded as follows.
Organic – A development project is considered to be organic if the project size is the same, the team is well experienced and the project deals with developing a well-understood application program Examples are data processing systems and simple business systems.Semi-detached – A development project is considered to be semi-detached if it contains a mixture of experience or inexperienced team members Example a database management system.Embedded – A development project is considered to be embedded if the software being developed is strongly coupled to complex hardware, or if stringent regulations on the operational method exist. It is developed in a set of tight constraint example ATM.
Organic – A development project is considered to be organic if the project size is the same, the team is well experienced and the project deals with developing a well-understood application program Examples are data processing systems and simple business systems.
Semi-detached – A development project is considered to be semi-detached if it contains a mixture of experience or inexperienced team members Example a database management system.
Embedded – A development project is considered to be embedded if the software being developed is strongly coupled to complex hardware, or if stringent regulations on the operational method exist. It is developed in a set of tight constraint example ATM.
Types of COCOMO models :Three types of COCOMO models as follows.
Basic model :COCOMO model provides an accurate size of the project parameters. It is good for a quick estimate of the cost. The estimated effort and scheduled time are given by the relationship as follows.
Effort (E) = a*(KLOC)b MM
Scheduled Time (D) = c*(E)d Months(M)
Where,
E = Total effort required for the project in Man-Months (MM).
a, b, c, d = The constant parameters for a software project.
D = Total time required for project development in Months (M).
KLOC = The size of the code for the project in Kilo lines of code.
Intermediate model :Intermediate COCOMO computes software development effort as a function of program size and a set of “cost drivers” that include subjective assessment of the product, hardware, personnel, and project attributes. The estimated effort and scheduled time are given by the relationship as follows.
Effort (E) = a*(KLOC)b *EAF MM
Scheduled Time (D) = c*(E)d Months(M)
E = Total effort required for the project in Man-Months (MM).
a, b, c, d = The constant parameters for a software project.
D = Total time required for project development in Months (M).
KLOC = the size of the code for the project in Kilo lines of code.
EAF = Efforts adjustment factors
Detailed model : Detailed COCOMO incorporates all qualities of the standard version with an assessment of the cost driver’s effect on each method of the software engineering process.
Advantages :
It works on historical data and provides more accurate details.
Easy to implement with various factors. One can easily understand how it works.
Easy to estimate the total cost of the project.
The drivers are very helpful to understand the impact of the different factors that affect project crises.
Disadvantages :
It ignores the hardware issues as well as the personal turnover level.
It ignores all the documentation and requirements.
It mostly depends on time factors.
It limits the accuracy of software costs.
It oversimplifies the impact of safety or security aspects.
It also ignores customer skills, cooperation, and knowledge.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DFD for Library Management System
What is DFD(Data Flow Diagram)?
Use Case Diagram for Library Management System
RUP and its Phases
System Testing
Software Development Life Cycle (SDLC)
Software Engineering | Black box testing
Software Engineering | Incremental process model
Software Engineering | Seven Principles of software testing
Software Engineering | Rapid application development model (RAD)
|
[
{
"code": null,
"e": 24868,
"s": 24840,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 25309,
"s": 24868,
"text": "Overview :Cocomo stands for Constructive Cost Model is a regression model based on LOC, i.e number of Lines of Code. COCOMO model is proposed by Boehm in 1981 It is a procedural cost estimate model for software projects and often used as a process of reliably predicting the various parameters related to making a project such as size, effort, cost, time and quality COCOMO model is one of the most generally used models within the world "
},
{
"code": null,
"e": 25482,
"s": 25309,
"text": "Categories of COCOMO :Any of the software models are divided into three categories on the basis of development complexities organic, semi-detached, and embedded as follows."
},
{
"code": null,
"e": 26177,
"s": 25482,
"text": "Organic – A development project is considered to be organic if the project size is the same, the team is well experienced and the project deals with developing a well-understood application program Examples are data processing systems and simple business systems.Semi-detached – A development project is considered to be semi-detached if it contains a mixture of experience or inexperienced team members Example a database management system.Embedded – A development project is considered to be embedded if the software being developed is strongly coupled to complex hardware, or if stringent regulations on the operational method exist. It is developed in a set of tight constraint example ATM."
},
{
"code": null,
"e": 26441,
"s": 26177,
"text": "Organic – A development project is considered to be organic if the project size is the same, the team is well experienced and the project deals with developing a well-understood application program Examples are data processing systems and simple business systems."
},
{
"code": null,
"e": 26620,
"s": 26441,
"text": "Semi-detached – A development project is considered to be semi-detached if it contains a mixture of experience or inexperienced team members Example a database management system."
},
{
"code": null,
"e": 26874,
"s": 26620,
"text": "Embedded – A development project is considered to be embedded if the software being developed is strongly coupled to complex hardware, or if stringent regulations on the operational method exist. It is developed in a set of tight constraint example ATM."
},
{
"code": null,
"e": 26939,
"s": 26874,
"text": "Types of COCOMO models :Three types of COCOMO models as follows."
},
{
"code": null,
"e": 27145,
"s": 26939,
"text": "Basic model :COCOMO model provides an accurate size of the project parameters. It is good for a quick estimate of the cost. The estimated effort and scheduled time are given by the relationship as follows."
},
{
"code": null,
"e": 27504,
"s": 27145,
"text": "Effort (E) = a*(KLOC)b MM\nScheduled Time (D) = c*(E)d Months(M)\nWhere,\n\nE = Total effort required for the project in Man-Months (MM).\na, b, c, d = The constant parameters for a software project.\nD = Total time required for project development in Months (M).\nKLOC = The size of the code for the project in Kilo lines of code."
},
{
"code": null,
"e": 27817,
"s": 27504,
"text": "Intermediate model :Intermediate COCOMO computes software development effort as a function of program size and a set of “cost drivers” that include subjective assessment of the product, hardware, personnel, and project attributes. The estimated effort and scheduled time are given by the relationship as follows."
},
{
"code": null,
"e": 28212,
"s": 27817,
"text": "Effort (E) = a*(KLOC)b *EAF MM\nScheduled Time (D) = c*(E)d Months(M)\n\nE = Total effort required for the project in Man-Months (MM).\na, b, c, d = The constant parameters for a software project.\nD = Total time required for project development in Months (M).\nKLOC = the size of the code for the project in Kilo lines of code.\nEAF = Efforts adjustment factors "
},
{
"code": null,
"e": 28395,
"s": 28212,
"text": "Detailed model : Detailed COCOMO incorporates all qualities of the standard version with an assessment of the cost driver’s effect on each method of the software engineering process."
},
{
"code": null,
"e": 28408,
"s": 28395,
"text": "Advantages :"
},
{
"code": null,
"e": 28472,
"s": 28408,
"text": "It works on historical data and provides more accurate details."
},
{
"code": null,
"e": 28552,
"s": 28472,
"text": "Easy to implement with various factors. One can easily understand how it works."
},
{
"code": null,
"e": 28600,
"s": 28552,
"text": "Easy to estimate the total cost of the project."
},
{
"code": null,
"e": 28707,
"s": 28600,
"text": "The drivers are very helpful to understand the impact of the different factors that affect project crises."
},
{
"code": null,
"e": 28723,
"s": 28707,
"text": "Disadvantages :"
},
{
"code": null,
"e": 28794,
"s": 28723,
"text": "It ignores the hardware issues as well as the personal turnover level."
},
{
"code": null,
"e": 28845,
"s": 28794,
"text": "It ignores all the documentation and requirements."
},
{
"code": null,
"e": 28880,
"s": 28845,
"text": "It mostly depends on time factors."
},
{
"code": null,
"e": 28922,
"s": 28880,
"text": "It limits the accuracy of software costs."
},
{
"code": null,
"e": 28982,
"s": 28922,
"text": "It oversimplifies the impact of safety or security aspects."
},
{
"code": null,
"e": 29043,
"s": 28982,
"text": "It also ignores customer skills, cooperation, and knowledge."
},
{
"code": null,
"e": 29064,
"s": 29043,
"text": "Software Engineering"
},
{
"code": null,
"e": 29162,
"s": 29064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29171,
"s": 29162,
"text": "Comments"
},
{
"code": null,
"e": 29184,
"s": 29171,
"text": "Old Comments"
},
{
"code": null,
"e": 29218,
"s": 29184,
"text": "DFD for Library Management System"
},
{
"code": null,
"e": 29250,
"s": 29218,
"text": "What is DFD(Data Flow Diagram)?"
},
{
"code": null,
"e": 29297,
"s": 29250,
"text": "Use Case Diagram for Library Management System"
},
{
"code": null,
"e": 29316,
"s": 29297,
"text": "RUP and its Phases"
},
{
"code": null,
"e": 29331,
"s": 29316,
"text": "System Testing"
},
{
"code": null,
"e": 29370,
"s": 29331,
"text": "Software Development Life Cycle (SDLC)"
},
{
"code": null,
"e": 29411,
"s": 29370,
"text": "Software Engineering | Black box testing"
},
{
"code": null,
"e": 29460,
"s": 29411,
"text": "Software Engineering | Incremental process model"
},
{
"code": null,
"e": 29520,
"s": 29460,
"text": "Software Engineering | Seven Principles of software testing"
}
] |
JDBC Updatable ResultSet Example | Updatable ResultSet Online TutorialsPoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Whenever we create a ResultSet object that never allows us to update the database through the ResultSet object, it allows retrieving the data only forward. Such type of ResultSet is known as non-updatable and non-scrollable ResultSet.
In this tutorial, I am going to tell you how to make a ResultSet as Updatable. You can find How to make a ResultSet as Updatable ResultSet and Scrollable here.
To make the ResultSet object updatable and scrollable we must use the following constants which are present in the ResultSet interface.
TYPE_SCROLL_SENSITIVE
CONCUR_UPDATABLE
The above two constants must be specified while we are creating Statement object by using the following method:
Statement st=con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
On the above ResultSet object, we can perform the following three operations:
inserting a record,
deleting a record and
updating a record.
We can insert the record in the database through ResultSet object using absolute() method, but before inserting a record, you need to decide at which position you are inserting, since the absolute() method takes a position as a parameter where it to be inserted.
Step-1 :
rs.absolute (3);
Step-2 :
Since we are inserting a record we must use the following method to make the ResultSet object hold the record.
rs.moveToInsertRow ();
Step-3:
Update all columns of the database or provide the values to all columns of the database by using the following generalized method which is present in the ResultSet interface.
rs.updateXXX(int colno, XXX val);
Example :
rs.updateInt (1, 5);
rs.updateString (2, “abc”);
rs.updateInt (3, 80);
Step-4 :
Up to step-3, the data is inserted in the ResultSet object and whose data must be inserted in the database permanently by calling the following method:
public void insertRow();
By calling the above insertRow() method, the record can be inserted into the database permanently. Here the insertRow() method throws SQLException, We need to handle the exception or you can throw.
First, you need to decide which record you need to delete because you need to pass the position of the record to absolute() to point the resultset to a particular record.
rs.absolute (3); // rs pointing to 3 rd record & marked for deletion
To delete the record permanently from the database we must call the deleteRow() method which is present in ResultSet interface
rs.deleteRow ();
First, you need to decide which record you need to update because you need to pass the position of the record to absolute() to point the resultset to a particular record.
rs.absolute (2);
And then decide which column to update.
rs.updateString (2, “pqr”);
rs.updateInt (3, 91);
Using step-2 we can modify the content of the ResultSet object and the content of the ResultSet object must be updated to the database permanently by calling the following method which is present in the ResultSet interface.
rs.updateRow ();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Jdbc_Updatable_ResultSet {
public static void main(String[] args) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/onlinetutorialspoint", "root",
"123456");
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("select * from person");
rs.next();
rs.updateInt(1, 1001);
rs.updateRow();
System.out.println("1 ROW UPDATED...");
rs.moveToInsertRow();
rs.updateInt(1, 1002);
rs.updateString(2, "Banglore");
rs.updateString(3, "Vinayak");
rs.insertRow();
System.out.println("1 ROW INSERTED...");
System.out.println("After Updation...");
con.close();
}
}
Before going to execute the above example the data inside the table like below :
Id 1050 Name : Venu Gopal City : Vizag
Id 1060 Name : Kamal City : Pune
Id 1070 Name : Ram Gopal City : Mumbai
Id 4104 Name : Chandra Shekhar Goka City : Vijayawada
Output Of the Above Example :
1 ROW UPDATED...
1 ROW INSERTED...
1 ROW DELETED...
After Updation...
After the successful execution, we have data in the database like below :
Id 1001 Name : Venu Gopal City : Vizag
Id 1002 Name : Vinayak City : Banglore
Id 1060 Name : Kamal City : Pune
Id 4104 Name : Chandra Shekhar Goka City : Vijayawada
This is the way we can make the JDBC ResultSet updatable.
Happy Learning 🙂
JDBC Scrollable ResultSet Example
JDBC Select Program Example
ResultSetMetaData in JDBC Example
Step by Step JDBC Program Example
JDBC Delete Program Example
JDBC Update Program Example
Read an Image in JDBC Example
JDBC Insert Program Example
JDBC Interview Questions and Answers
CallableStatement in jdbc Example
Insert an Image using JDBC in Mysql DB
JDBC PreparedStatement Example Program
JDBC Connection with Properties file
Batch Processing in JDBC Example
DatabaseMetaData in JDBC Example
JDBC Scrollable ResultSet Example
JDBC Select Program Example
ResultSetMetaData in JDBC Example
Step by Step JDBC Program Example
JDBC Delete Program Example
JDBC Update Program Example
Read an Image in JDBC Example
JDBC Insert Program Example
JDBC Interview Questions and Answers
CallableStatement in jdbc Example
Insert an Image using JDBC in Mysql DB
JDBC PreparedStatement Example Program
JDBC Connection with Properties file
Batch Processing in JDBC Example
DatabaseMetaData in JDBC Example
Δ
JDBC Driver Types
Step by Step JDBC Program
JDBC Select Program
JDBC Insert Program
JDBC Update Program
JDBC Delete Program
JDBC Connection – Properties File
JDBC PreparedStatement Program
JDBC – CallableStatement Example
JDBC – Read an Image from DB
JDBC – Insert an Image in DB
JDBC – Updatable ResultSet
JDBC – Scrollable ResultSet
JDBC – ResultSetMetaData
JDBC – DatabaseMetaData
JDBC – Transaction Management
JDBC – Batch Processing
JDBC Interview Questions
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 633,
"s": 398,
"text": "Whenever we create a ResultSet object that never allows us to update the database through the ResultSet object, it allows retrieving the data only forward. Such type of ResultSet is known as non-updatable and non-scrollable ResultSet."
},
{
"code": null,
"e": 793,
"s": 633,
"text": "In this tutorial, I am going to tell you how to make a ResultSet as Updatable. You can find How to make a ResultSet as Updatable ResultSet and Scrollable here."
},
{
"code": null,
"e": 929,
"s": 793,
"text": "To make the ResultSet object updatable and scrollable we must use the following constants which are present in the ResultSet interface."
},
{
"code": null,
"e": 951,
"s": 929,
"text": "TYPE_SCROLL_SENSITIVE"
},
{
"code": null,
"e": 968,
"s": 951,
"text": "CONCUR_UPDATABLE"
},
{
"code": null,
"e": 1080,
"s": 968,
"text": "The above two constants must be specified while we are creating Statement object by using the following method:"
},
{
"code": null,
"e": 1176,
"s": 1080,
"text": "Statement st=con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);"
},
{
"code": null,
"e": 1254,
"s": 1176,
"text": "On the above ResultSet object, we can perform the following three operations:"
},
{
"code": null,
"e": 1274,
"s": 1254,
"text": "inserting a record,"
},
{
"code": null,
"e": 1296,
"s": 1274,
"text": "deleting a record and"
},
{
"code": null,
"e": 1315,
"s": 1296,
"text": "updating a record."
},
{
"code": null,
"e": 1578,
"s": 1315,
"text": "We can insert the record in the database through ResultSet object using absolute() method, but before inserting a record, you need to decide at which position you are inserting, since the absolute() method takes a position as a parameter where it to be inserted."
},
{
"code": null,
"e": 1587,
"s": 1578,
"text": "Step-1 :"
},
{
"code": null,
"e": 1604,
"s": 1587,
"text": "rs.absolute (3);"
},
{
"code": null,
"e": 1613,
"s": 1604,
"text": "Step-2 :"
},
{
"code": null,
"e": 1724,
"s": 1613,
"text": "Since we are inserting a record we must use the following method to make the ResultSet object hold the record."
},
{
"code": null,
"e": 1747,
"s": 1724,
"text": "rs.moveToInsertRow ();"
},
{
"code": null,
"e": 1755,
"s": 1747,
"text": "Step-3:"
},
{
"code": null,
"e": 1930,
"s": 1755,
"text": "Update all columns of the database or provide the values to all columns of the database by using the following generalized method which is present in the ResultSet interface."
},
{
"code": null,
"e": 1964,
"s": 1930,
"text": "rs.updateXXX(int colno, XXX val);"
},
{
"code": null,
"e": 1974,
"s": 1964,
"text": "Example :"
},
{
"code": null,
"e": 2045,
"s": 1974,
"text": "rs.updateInt (1, 5);\nrs.updateString (2, “abc”);\nrs.updateInt (3, 80);"
},
{
"code": null,
"e": 2054,
"s": 2045,
"text": "Step-4 :"
},
{
"code": null,
"e": 2206,
"s": 2054,
"text": "Up to step-3, the data is inserted in the ResultSet object and whose data must be inserted in the database permanently by calling the following method:"
},
{
"code": null,
"e": 2231,
"s": 2206,
"text": "public void insertRow();"
},
{
"code": null,
"e": 2429,
"s": 2231,
"text": "By calling the above insertRow() method, the record can be inserted into the database permanently. Here the insertRow() method throws SQLException, We need to handle the exception or you can throw."
},
{
"code": null,
"e": 2600,
"s": 2429,
"text": "First, you need to decide which record you need to delete because you need to pass the position of the record to absolute() to point the resultset to a particular record."
},
{
"code": null,
"e": 2669,
"s": 2600,
"text": "rs.absolute (3); // rs pointing to 3 rd record & marked for deletion"
},
{
"code": null,
"e": 2796,
"s": 2669,
"text": "To delete the record permanently from the database we must call the deleteRow() method which is present in ResultSet interface"
},
{
"code": null,
"e": 2813,
"s": 2796,
"text": "rs.deleteRow ();"
},
{
"code": null,
"e": 2984,
"s": 2813,
"text": "First, you need to decide which record you need to update because you need to pass the position of the record to absolute() to point the resultset to a particular record."
},
{
"code": null,
"e": 3001,
"s": 2984,
"text": "rs.absolute (2);"
},
{
"code": null,
"e": 3041,
"s": 3001,
"text": "And then decide which column to update."
},
{
"code": null,
"e": 3091,
"s": 3041,
"text": "rs.updateString (2, “pqr”);\nrs.updateInt (3, 91);"
},
{
"code": null,
"e": 3315,
"s": 3091,
"text": "Using step-2 we can modify the content of the ResultSet object and the content of the ResultSet object must be updated to the database permanently by calling the following method which is present in the ResultSet interface."
},
{
"code": null,
"e": 3332,
"s": 3315,
"text": "rs.updateRow ();"
},
{
"code": null,
"e": 4360,
"s": 3332,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\npublic class Jdbc_Updatable_ResultSet {\n\n public static void main(String[] args) throws Exception {\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n Connection con = DriverManager.getConnection(\n \"jdbc:mysql://localhost:3306/onlinetutorialspoint\", \"root\",\n \"123456\");\n Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,\n ResultSet.CONCUR_UPDATABLE);\n ResultSet rs = st.executeQuery(\"select * from person\");\n rs.next();\n rs.updateInt(1, 1001);\n rs.updateRow();\n System.out.println(\"1 ROW UPDATED...\");\n rs.moveToInsertRow();\n rs.updateInt(1, 1002);\n rs.updateString(2, \"Banglore\");\n rs.updateString(3, \"Vinayak\");\n rs.insertRow();\n System.out.println(\"1 ROW INSERTED...\");\n System.out.println(\"After Updation...\");\n con.close();\n }\n\n}"
},
{
"code": null,
"e": 4441,
"s": 4360,
"text": "Before going to execute the above example the data inside the table like below :"
},
{
"code": null,
"e": 4606,
"s": 4441,
"text": "Id 1050 Name : Venu Gopal City : Vizag\nId 1060 Name : Kamal City : Pune\nId 1070 Name : Ram Gopal City : Mumbai\nId 4104 Name : Chandra Shekhar Goka City : Vijayawada"
},
{
"code": null,
"e": 4636,
"s": 4606,
"text": "Output Of the Above Example :"
},
{
"code": null,
"e": 4706,
"s": 4636,
"text": "1 ROW UPDATED...\n1 ROW INSERTED...\n1 ROW DELETED...\nAfter Updation..."
},
{
"code": null,
"e": 4780,
"s": 4706,
"text": "After the successful execution, we have data in the database like below :"
},
{
"code": null,
"e": 4945,
"s": 4780,
"text": "Id 1001 Name : Venu Gopal City : Vizag\nId 1002 Name : Vinayak City : Banglore\nId 1060 Name : Kamal City : Pune\nId 4104 Name : Chandra Shekhar Goka City : Vijayawada"
},
{
"code": null,
"e": 5003,
"s": 4945,
"text": "This is the way we can make the JDBC ResultSet updatable."
},
{
"code": null,
"e": 5020,
"s": 5003,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 5518,
"s": 5020,
"text": "\nJDBC Scrollable ResultSet Example\nJDBC Select Program Example\nResultSetMetaData in JDBC Example\nStep by Step JDBC Program Example\nJDBC Delete Program Example\nJDBC Update Program Example\nRead an Image in JDBC Example\nJDBC Insert Program Example\nJDBC Interview Questions and Answers\nCallableStatement in jdbc Example\nInsert an Image using JDBC in Mysql DB\nJDBC PreparedStatement Example Program\nJDBC Connection with Properties file\nBatch Processing in JDBC Example\nDatabaseMetaData in JDBC Example\n"
},
{
"code": null,
"e": 5552,
"s": 5518,
"text": "JDBC Scrollable ResultSet Example"
},
{
"code": null,
"e": 5580,
"s": 5552,
"text": "JDBC Select Program Example"
},
{
"code": null,
"e": 5614,
"s": 5580,
"text": "ResultSetMetaData in JDBC Example"
},
{
"code": null,
"e": 5648,
"s": 5614,
"text": "Step by Step JDBC Program Example"
},
{
"code": null,
"e": 5676,
"s": 5648,
"text": "JDBC Delete Program Example"
},
{
"code": null,
"e": 5704,
"s": 5676,
"text": "JDBC Update Program Example"
},
{
"code": null,
"e": 5734,
"s": 5704,
"text": "Read an Image in JDBC Example"
},
{
"code": null,
"e": 5762,
"s": 5734,
"text": "JDBC Insert Program Example"
},
{
"code": null,
"e": 5799,
"s": 5762,
"text": "JDBC Interview Questions and Answers"
},
{
"code": null,
"e": 5833,
"s": 5799,
"text": "CallableStatement in jdbc Example"
},
{
"code": null,
"e": 5872,
"s": 5833,
"text": "Insert an Image using JDBC in Mysql DB"
},
{
"code": null,
"e": 5911,
"s": 5872,
"text": "JDBC PreparedStatement Example Program"
},
{
"code": null,
"e": 5948,
"s": 5911,
"text": "JDBC Connection with Properties file"
},
{
"code": null,
"e": 5981,
"s": 5948,
"text": "Batch Processing in JDBC Example"
},
{
"code": null,
"e": 6014,
"s": 5981,
"text": "DatabaseMetaData in JDBC Example"
},
{
"code": null,
"e": 6020,
"s": 6018,
"text": "Δ"
},
{
"code": null,
"e": 6039,
"s": 6020,
"text": " JDBC Driver Types"
},
{
"code": null,
"e": 6066,
"s": 6039,
"text": " Step by Step JDBC Program"
},
{
"code": null,
"e": 6087,
"s": 6066,
"text": " JDBC Select Program"
},
{
"code": null,
"e": 6108,
"s": 6087,
"text": " JDBC Insert Program"
},
{
"code": null,
"e": 6129,
"s": 6108,
"text": " JDBC Update Program"
},
{
"code": null,
"e": 6150,
"s": 6129,
"text": " JDBC Delete Program"
},
{
"code": null,
"e": 6185,
"s": 6150,
"text": " JDBC Connection – Properties File"
},
{
"code": null,
"e": 6217,
"s": 6185,
"text": " JDBC PreparedStatement Program"
},
{
"code": null,
"e": 6251,
"s": 6217,
"text": " JDBC – CallableStatement Example"
},
{
"code": null,
"e": 6281,
"s": 6251,
"text": " JDBC – Read an Image from DB"
},
{
"code": null,
"e": 6311,
"s": 6281,
"text": " JDBC – Insert an Image in DB"
},
{
"code": null,
"e": 6339,
"s": 6311,
"text": " JDBC – Updatable ResultSet"
},
{
"code": null,
"e": 6368,
"s": 6339,
"text": " JDBC – Scrollable ResultSet"
},
{
"code": null,
"e": 6394,
"s": 6368,
"text": " JDBC – ResultSetMetaData"
},
{
"code": null,
"e": 6419,
"s": 6394,
"text": " JDBC – DatabaseMetaData"
},
{
"code": null,
"e": 6450,
"s": 6419,
"text": " JDBC – Transaction Management"
},
{
"code": null,
"e": 6475,
"s": 6450,
"text": " JDBC – Batch Processing"
}
] |
How to check if two dates are equal in Java 8?
|
The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay,Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives.
Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock.
The of() method of the java.time.LocalDate class accepts three integer parameters representing and year, a month of an year, day of a month and, returns the instance of the LocalDate object from the given details.
The now() method of the java.time.LocalDate obtains and returns the current date from the system clock.
The equals() method of the java.time.LocalDate class accepts an object (representing a LocalDate ) and compares it with the current LocalDate object, if both are equal this method returns true else it returns false. If the object you pass to this method is not of type LocalDate this method returns false.
Following Java example reads date values from user and constructs a LocalDate instance. Retrieves the current Date and compares these two values and prints the result.
import java.time.LocalDate;
import java.util.Scanner;
public class LocalDateJava8 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the year: ");
int year = sc.nextInt();
System.out.println("Enter the month: ");
int month = sc.nextInt();
System.out.println("Enter the day: ");
int day = sc.nextInt();
//Getting the current date value
LocalDate givenDate = LocalDate.of(year, month, day);
System.out.println("Date: "+givenDate);
//Retrieving the current date
LocalDate currentDate = LocalDate.now();
//Comparing both values
boolean bool = givenDate.equals(currentDate);
if(bool) {
System.out.println("Given date is equal to the current date ");
}else {
System.out.println("Given date is not equal to the current date ");
}
}
}
Enter the year:
2019
Enter the month:
07
Enter the day:
24
Date: 2019-07-24
Given date is equal to the current date
|
[
{
"code": null,
"e": 1387,
"s": 1062,
"text": "The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay,Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives."
},
{
"code": null,
"e": 1571,
"s": 1387,
"text": "Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock."
},
{
"code": null,
"e": 1785,
"s": 1571,
"text": "The of() method of the java.time.LocalDate class accepts three integer parameters representing and year, a month of an year, day of a month and, returns the instance of the LocalDate object from the given details."
},
{
"code": null,
"e": 1889,
"s": 1785,
"text": "The now() method of the java.time.LocalDate obtains and returns the current date from the system clock."
},
{
"code": null,
"e": 2195,
"s": 1889,
"text": "The equals() method of the java.time.LocalDate class accepts an object (representing a LocalDate ) and compares it with the current LocalDate object, if both are equal this method returns true else it returns false. If the object you pass to this method is not of type LocalDate this method returns false."
},
{
"code": null,
"e": 2363,
"s": 2195,
"text": "Following Java example reads date values from user and constructs a LocalDate instance. Retrieves the current Date and compares these two values and prints the result."
},
{
"code": null,
"e": 3271,
"s": 2363,
"text": "import java.time.LocalDate;\nimport java.util.Scanner;\npublic class LocalDateJava8 {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the year: \");\n int year = sc.nextInt();\n System.out.println(\"Enter the month: \");\n int month = sc.nextInt();\n System.out.println(\"Enter the day: \");\n int day = sc.nextInt();\n //Getting the current date value\n LocalDate givenDate = LocalDate.of(year, month, day);\n System.out.println(\"Date: \"+givenDate);\n //Retrieving the current date\n LocalDate currentDate = LocalDate.now();\n //Comparing both values\n boolean bool = givenDate.equals(currentDate);\n if(bool) {\n System.out.println(\"Given date is equal to the current date \");\n }else {\n System.out.println(\"Given date is not equal to the current date \");\n }\n }\n}"
},
{
"code": null,
"e": 3387,
"s": 3271,
"text": "Enter the year:\n2019\nEnter the month:\n07\nEnter the day:\n24\nDate: 2019-07-24\nGiven date is equal to the current date"
}
] |
Apache Drill - Quick Guide
|
In this chapter, we will discuss about the basic overview of Apache Drill, its benefits and key features. Apart from this, we will also get some basic knowledge on Google Dremel.
Google manages big data every second of every day to provide services like Search, YouTube, Gmail and Google Docs. Google uses an efficient technology to scan big data at a blazing speed which is called as “Dremel”. Well, Dremel is a query service that allows you to run SQL-like queries against very large data sets and return accurate results in seconds.
Dremel can scan 35 billion rows without an index within ten-seconds. Dremel stores data in a columnar storage model, which means that it separates a record into column values and then stores each value on a different storage volume. But at the same time, traditional databases store the whole record on one volume. This columnar approach is the main reason that it makes Dremel drastically fast.
Google has been using Dremel in production since year 2006 and has been continuously evolving it for the applications like Spam analysis, Debugging of map tiles on Google Maps, etc. For this reason, Drill is inspired by Dremel. Recently, Google released BigQuery and it is the public implementation of Dremel that was launched for general businesses or developers to use.
Apache Drill is a low latency schema-free query engine for big data. Drill uses a JSON document model internally which allows it to query data of any structure. Drill works with a variety of non-relational data stores, including Hadoop, NoSQL databases (MongoDB, HBase) and cloud storage like Amazon S3, Azure Blob Storage, etc. Users can query the data using a standard SQL and BI Tools, which doesn’t require to create and manage schemas.
Following are some of the most important benefits of Apache Drill −
Drill can scale data from a single node to thousands of nodes and query petabytes of data within seconds.
Drill can scale data from a single node to thousands of nodes and query petabytes of data within seconds.
Drill supports user defined functions.
Drill supports user defined functions.
Drill's symmetrical architecture and simple installation makes it easy to deploy and operate very large clusters.
Drill's symmetrical architecture and simple installation makes it easy to deploy and operate very large clusters.
Drill has flexible data model and extensible architecture.
Drill has flexible data model and extensible architecture.
Drill columnar execution model performs SQL processing on complex data without flattening into rows.
Drill columnar execution model performs SQL processing on complex data without flattening into rows.
Supports large datasets
Supports large datasets
Following are some of the most significant key features of Apache Drill −
Drill’s pluggable architecture enables connectivity to multiple datastores.
Drill’s pluggable architecture enables connectivity to multiple datastores.
Drill has a distributed execution engine for processing queries. Users can submit requests to any node in the cluster.
Drill has a distributed execution engine for processing queries. Users can submit requests to any node in the cluster.
Drill supports complex/multi-structured data types.
Drill supports complex/multi-structured data types.
Drill uses self-describing data where a schema is specified as a part of the data itself, so no need for centralized schema definitions or management.
Drill uses self-describing data where a schema is specified as a part of the data itself, so no need for centralized schema definitions or management.
Flexible deployment options either local node or cluster.
Flexible deployment options either local node or cluster.
Specialized memory management that reduces the amount of main memory that a program uses or references while running and eliminates garbage collections.
Specialized memory management that reduces the amount of main memory that a program uses or references while running and eliminates garbage collections.
Decentralized data management.
Decentralized data management.
Apache Drill can work along with a few other softwares, some of which are −
Cloud JSON and Sensor Analytics − Drill’s columnar approach leverages to access JSON data and expose those data via REST API to apply sensor analytics information.
Cloud JSON and Sensor Analytics − Drill’s columnar approach leverages to access JSON data and expose those data via REST API to apply sensor analytics information.
Works well with Hive − Apache Drill serves as a complement to Hive deployments with low latency queries. Drill’s hive metastore integration exposes existing datasets at interactive speeds.
Works well with Hive − Apache Drill serves as a complement to Hive deployments with low latency queries. Drill’s hive metastore integration exposes existing datasets at interactive speeds.
SQL for NoSQL − Drill’s ODBC driver and powerful parallelization capabilities provide interactive query capabilities.
SQL for NoSQL − Drill’s ODBC driver and powerful parallelization capabilities provide interactive query capabilities.
Apache Drill comes with a flexible JSON-like data model to natively query and process complex/multi-structured data. The data does not need to be flattened or transformed either at the design time or runtime, which provides high performance for queries. Drill exposes an easy and high performance Java API to build custom functions. Apache Drill is built to scale to big data needs and is not restricted by memory available on the cluster nodes.
Drill has to integrate with a variety of data stores like relational data stores or non-relational data stores. It has the flexibility to add new data stores.
Traditional file system − Local files and NAS (Network Attached Storage)
Traditional file system − Local files and NAS (Network Attached Storage)
Hadoop − HDFS and MAPR-FS (MAPR-File System)
Hadoop − HDFS and MAPR-FS (MAPR-File System)
Cloud storage − Amazon S3, Google Cloud Storage, Azure Blob Storage
Cloud storage − Amazon S3, Google Cloud Storage, Azure Blob Storage
MongoDB
HBase
HIVE
MapR-DB
In this chapter, we will discuss about the nested data model, JSON, Apache Avro, nested query language along with some other components in detail.
Apache Drill supports various data models. The initial goal is to support the column-based format used by Dremel, then it is designed to support schema less models such as JSON, BSON (Binary JSON) and schema based models like Avro and CSV.
JSON (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. JSON format is used for serializing and transmitting structured data over network connection. It is primarily used to transmit data between a server and web applications. JSON is typically perceived as a format whose main advantage is that it is simple and lean. It can be used without knowing or caring about any underlying schema.
Following is a basic JSON schema, which covers a classical product catalog description −
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": “Classical product catalog",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "integer"
},
"name": {
"description": "Name of the product",
"type": "string"
},
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
}
},
"required": ["id", "name", "price"]
}
The JSON Schema has the capability to express basic definitions and constraints for data types contained in objects, and it also supports some more advanced features such as properties typed as other objects, inheritance, and links.
Avro is an Apache open source project that provides data serialization and data exchange services for Hadoop. These services can be used together or independently. Avro is a schema-based system. A language-independent schema is associated with its read and write operations. Using Avro, big data can be exchanged between programs written in any language. Avro supports a rich set of primitive data types including numeric, binary data and strings, and a number of complex types including arrays, maps, enumerations and records. A key feature of Avro is the robust support for data schemas that change over time.
Avro schema is created in JavaScript Object Notation (JSON) document format, which is a lightweight text-based data interchange format.
For example
The given schema defines a (record type) document within "AvroSample" namespace. The name of document is "Employee" which contains two "Fields" → Name and Age.
{
" type " : "record",
" namespace " : "AvroSample",
" name " : "Employee",
" fields " : [
{ "name" : " Name" , "type" : "string" },
{ "name" : "age" , "type" : "int" }
]
}
The above schema contains four attributes, they have been briefly described here −
type − Describes document type, in this case a “record"
type − Describes document type, in this case a “record"
namespace − Describes the name of the namespace in which the object resides
namespace − Describes the name of the namespace in which the object resides
name − Describes the schema name
name − Describes the schema name
fields − This is an attribute array which contains the following
fields − This is an attribute array which contains the following
name − Describes the name of field
name − Describes the name of field
type − Describes data type of field
type − Describes data type of field
Apache Drill supports various query languages. The initial goal is to support the SQL-like language used by Dremel and Google BigQuery. DrQL and Mongo query languages are an examples of Drill nested query languages.
The DrQL (Drill Query Language) is a nested query language. DrQL is SQL like query language for nested data. It is designed to support efficient column-based processing.
The MongoDB is an open-source document database, and leading NoSQL database. MongoDB is written in C++ and it is a cross-platform, document-oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on the concept of collection and documenting.
Wherein, collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. A document is a set of key-value pairs.
Drill supports various file formats such as CSV, TSV, PSV, JSON and Parquet. Wherein, “Parquet” is the special file format which helps Drill to run faster and its data representation is almost identical to Drill data representation.
Parquet is a columnar storage format in the Hadoop ecosystem. Compared to a traditional row-oriented format, it is much more efficient in storage and has better query performance. Parquet stores binary data in a column-oriented way, where the values of each column are organized so that they are all adjacent, enabling better compression.
It has the following important characteristics −
Self-describing data format
Columnar format
Flexible compression options
Large file size
The Apache Drill allows access to structured file types and plain text files (flat files). It consists of the following types −
CSV files (comma-separated values)
TSV files (tab-separated values)
PSV files (pipe-separated values)
CSV file format − A CSV is a comma separated values file, which allows data to be saved in a table structured format. CSV data fields are often separated or delimited by comma (,). The following example refers to a CSV format.
firstname, age
Alice,21
Peter,34
This CSV format can be defined as follows in a drill configuration.
"formats": {
"csv": {
"type": "text",
"extensions": [
“csv2"
],
"delimiter": “,”
}
}
TSV file format − The TSV data fields are often separated or delimited by a tab and saved with an extension of “.tsv" format. The following example refers to a TSV format.
firstname age
Alice 21
Peter 34
The TSV format can be defined as follows in a drill configuration.
"tsv": {
"type": "text",
"extensions": [
"tsv"
],
"delimiter": “\t"
},
PSV file format − The PSV data fields are separated or delimited by a pipe (|) symbol. The following example refers to a PSV format.
firstname|age
Alice|21
Peter|34
The PSV format can be defined as follows in a drill configuration.
"formats": {
"psv": {
"type": "text",
"extensions": [
"tbl"
],
"delimiter": "|"
}
}
These PSV files are saved with an extension of “.tbl” format.
Managing millions of data from multiple data sources requires a great deal of planning. When creating your data model, you need to consider the key goals such as the impact on speed of processing, how you can optimize memory usage and performance, scalability when handling growing volumes of data and requests.
Apache Drill provides the flexibility to immediately query complex data in native formats, such as schema-less data, nested data, and data with rapidly evolving schemas.
High-performance analysis of data in its native format including self-describing data such as Parquet, JSON files and HBase tables.
High-performance analysis of data in its native format including self-describing data such as Parquet, JSON files and HBase tables.
Direct querying of data in HBase tables without defining and maintaining a schema in the Hive metastore.
Direct querying of data in HBase tables without defining and maintaining a schema in the Hive metastore.
SQL to query and work with semi-structured/nested data, such as data from NoSQL stores like MongoDB and online REST APIs.
SQL to query and work with semi-structured/nested data, such as data from NoSQL stores like MongoDB and online REST APIs.
Apache Drill can connect to the following clients −
Multiple interfaces such as JDBC, ODBC, C++ API, REST using JSON
Drill shell
Drill web console (http://localhost:8047)
BI tools such as Tableau, MicroStrategy, etc.
Excel
As of now, you are aware of the Apache Drill fundamentals. This chapter will explain about its architecture in detail. Following is a diagram that illustrates the Apache Drill core module.
The above diagram consists of different components. Let’s take a look at each of these components in detail.
DrillBit − Apache Drill consists of a Daemon service called the DrillBit. It is responsible for accepting requests from the client, processing queries, and returning results to the client. There is no master-slave concept in DrillBit.
DrillBit − Apache Drill consists of a Daemon service called the DrillBit. It is responsible for accepting requests from the client, processing queries, and returning results to the client. There is no master-slave concept in DrillBit.
SQL Parser − The SQL parser parses all the incoming queries based on the open source framework called Calcite.
SQL Parser − The SQL parser parses all the incoming queries based on the open source framework called Calcite.
Logical Plan − A Logical plan describes the abstract data flow of a query. Once a query is parsed into a logical plan, the Drill optimizer determines the most efficient execution plan using a variety of rule-based and cost-based techniques, translating the logical plan into a physical plan.
Logical Plan − A Logical plan describes the abstract data flow of a query. Once a query is parsed into a logical plan, the Drill optimizer determines the most efficient execution plan using a variety of rule-based and cost-based techniques, translating the logical plan into a physical plan.
Optimizer − Apache Drill uses various database optimizations such as rule based/cost based, as well as other optimization rules exposed by the storage engine to re-write and split the query. The output of the optimizer is a distributed physical query plan. Optimization in Drill is pluggable so you can provide rules for optimization at various parts of the query execution.
Optimizer − Apache Drill uses various database optimizations such as rule based/cost based, as well as other optimization rules exposed by the storage engine to re-write and split the query. The output of the optimizer is a distributed physical query plan. Optimization in Drill is pluggable so you can provide rules for optimization at various parts of the query execution.
Physical Plan − A Physical plan is also called as the execution plan. It represents the most efficient and fastest way to execute the query across the different nodes in the cluster. The physical plan is a DAG (directed acyclic graph) of physical operators, and each parent-child relationship implies how data flows through the graph.
Physical Plan − A Physical plan is also called as the execution plan. It represents the most efficient and fastest way to execute the query across the different nodes in the cluster. The physical plan is a DAG (directed acyclic graph) of physical operators, and each parent-child relationship implies how data flows through the graph.
Storage Engine interface − A Storage plugin interfaces in Drill represent the abstractions that Drill uses to interact with the data sources. The plugins are extensible, allowing you to write new plugins for any additional data sources.
Storage Engine interface − A Storage plugin interfaces in Drill represent the abstractions that Drill uses to interact with the data sources. The plugins are extensible, allowing you to write new plugins for any additional data sources.
The following image shows a DrillBit query execution diagram −
The above diagram involves the following steps −
The Drill client issues a query. Any Drillbit in the cluster can accept queries from clients.
The Drill client issues a query. Any Drillbit in the cluster can accept queries from clients.
A Drillbit then parses the query, optimizes it, and generates an optimized distributed query plan for fast and efficient execution.
A Drillbit then parses the query, optimizes it, and generates an optimized distributed query plan for fast and efficient execution.
The Drillbit that accepts the initial query becomes the Foreman (driving Drillbit) for the request. It gets a list of available Drillbit nodes in the cluster from ZooKeeper.
The Drillbit that accepts the initial query becomes the Foreman (driving Drillbit) for the request. It gets a list of available Drillbit nodes in the cluster from ZooKeeper.
The foreman gets a list of available Drillbit nodes in the cluster from ZooKeeper and schedules the execution of query fragments on individual nodes according to the execution plan.
The foreman gets a list of available Drillbit nodes in the cluster from ZooKeeper and schedules the execution of query fragments on individual nodes according to the execution plan.
The individual nodes finish their execution and return data to the foreman.
The individual nodes finish their execution and return data to the foreman.
The foreman finally returns the results back to the client.
The foreman finally returns the results back to the client.
This chapter will cover how to install Apache Drill on your machine. We have two modes of installation in Drill.
Embedded mode − This mode refers to install Drill on a single node (local) on your machine. It doesn’t require ZooKeeper setup.
Embedded mode − This mode refers to install Drill on a single node (local) on your machine. It doesn’t require ZooKeeper setup.
Distributed mode − Install Apache Drill on a distributed environment. ZooKeeper is mandatory for this mode because it co-ordinates clusters. Once you installed successfully, then you will be able to connect and query Hive, HBase or any other distributed data sources.
Distributed mode − Install Apache Drill on a distributed environment. ZooKeeper is mandatory for this mode because it co-ordinates clusters. Once you installed successfully, then you will be able to connect and query Hive, HBase or any other distributed data sources.
Now let’s continue with the embedded mode steps for installation.
Embedded mode is a quick way to install. You can install Apache Drill in the embedded mode on Linux, Mac OS or Windows Operating System.
Hopefully, you have already installed java on your machine, so you just verify it using the following command.
$ java -version
If Java is successfully installed on your machine, you could see the version of installed Java. Otherwise download the latest version of JDK by visiting the following link −
http://www.oracle.com/technetwork/java/javase/downloads/index.html
After downloading the latest version, extract those files, move to the directory after setting the path and add Java alternatives. Then Java will be installed on your machine.
Download the latest version of Apache Drill by visiting the following link −
http://www.apache.org/dyn/closer.cgi/drill/drill-1.6.0/apache-drill-1.6.0.tar.gz
Now apache-drill-1.6.0.tar.gz will be downloaded on your machine.
You can then extract the tar file using the following program −
$ cd opt/
$ tar apache-drill-1.6.0.tar.gz
$ cd apache-drill-1.6.0
To start the Drill shell in the embedded mode, use the following command. Internally, the command uses a jdbc connection string and identifies the local node as the ZooKeeper node.
$ bin/drill-embedded
After the command, you can see the following response −
$ 0: jdbc:drill:zk = local>
Where,
0 − is the number of connections to Drill, which can be only one in embedded node
0 − is the number of connections to Drill, which can be only one in embedded node
jdbc − is the connection type
jdbc − is the connection type
zk = local − means the local node substitutes for the ZooKeeper node
zk = local − means the local node substitutes for the ZooKeeper node
Once you get this prompt, you will be able to run your queries on Drill.
To exit the Drill shell, issue the following command −
$ !quit
You will have to follow the subsequent steps to ensure a proper Distributed Mode Installation on your system.
$ java -version
If java is successfully installed on your machine, you could see the version of installed Java. Otherwise download latest version of JDK by visiting the following link −
http://www.oracle.com/technetwork/java/javase/downloads/index.html
After downloading the latest version, extract those files and move them to the directory after setting the path and adding Java alternatives. Then Java will be installed on your machine.
Hopefully, you have installed Apache ZooKeeper on your machine. To verify the installation, you can issue the following command −
$ bin/zkServer.sh start
Then you will get the following program on your screen −
$ JMX enabled by default
$ Using config: /Users/../zookeeper-3.4.6/bin/../conf/zoo.cfg
$ Starting zookeeper ... STARTED
http://www.apache.org/dyn/closer.cgi/drill/drill-1.6.0/apache-drill-1.6.0.tar.gz
Now apache-drill-1.6.0.tar.gz will be downloaded on your machine.
The next step is to extract the tar file by issuing the following command −
$ cd opt/
$ tar apache-drill-1.6.0.tar.gz
$ cd apache-drill-1.6.0
Open the drill-override file by using the following command.
$ vi conf/drill-override.conf
Then you will see the following response −
drill.exec: {
cluster-id: "drillbits1",
zk.connect: "localhost:2181"
}
Here cluster-id: “drillbits1” indicates we have one instance running. If two or more instances are running, then drillbits also increases.
To start the drillbit shell you can use the following command.
$ bin/drillbit.sh start
Then you will see the following response −
$ 0: jdbc:drill:zk = <zk1host>:
To exit the Drill shell, you can issue the following command −
$ 0: jdbc:drill:zk = <zk1host>: !quit
Navigate to the Drill installation directory, and issue the following command to stop a Drillbit.
$ bin/drillbit.sh stop
Apache Drill Web Console is one of the client interfaces to access Drill.
To open this Drill Web Console, launch a web browser, and then type the following URL –
http://localhost:8047
Now you will see the following screen which is similar to the Query option.
Apache Drill is an open-source SQL-On-Everything engine. It allows SQL queries to be executed on any kind of data source, ranging from a simple CSV file to an advanced SQL and NoSQL database servers.
To execute a query in a Drill shell, open your terminal move to the Drill installed directory and then type the following command.
$ bin/drill-embedded
Then you will see the response as shown in the following program.
0: jdbc:drill:zk = local>
Now you can execute your queries. Otherwise you can run your queries through web console application to the url of http://localhost:8047. If you need any help info type the following command.
$ 0: jdbc:drill:zk = local> !help
Apache Drill supports the following list of data types.
BIGINT
8-byte signed integer in the range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
BINARY
Variable-length byte string
BOOLEAN
True or false
DATE
Years, months, and days in YYYY-MM-DD format since 4713 BC
DECIMAL(p,s), DEC(p,s), or NUMERIC(p,s)*
38-digit precision number, precision is p, and scale is s
INTEGER or INT
4-byte signed integer in the range -2,147,483,648 to 2,147,483,647
INTERVAL
A day-time or year-month interval
SMALLINT
2-byte signed integer in the range -32,768 to 32,767
FLOAT
4-byte floating point number
DOUBLE
8-byte floating point number
TIME
24-hour based time in hours, minutes, seconds format: HH:mm:ss
TIMESTAMP
JDBC timestamp in year, month, date hour, minute, second, and optional milliseconds format: yyyy-MM-dd HH:mm:ss.SSS
CHARACTER VARYING, CHAR or VARCHAR
variable-length string. The default limit is 1 character. The maximum character limit is 2,147,483,647.
Let us continue with simple examples on the data types.
Apache Drill supports time functions in the range from 1971 to 2037. The processing logic of data types can be easily tested by “VALUES()” statement. The following query returns date, time and timestamp for the given values.
0: jdbc:drill:zk = local> select DATE '2016-04-07',
TIME '12:12:23',TIMESTAMP '2016-04-07 12:12:23' from (values(1));
+-------------+-----------+------------------------+
| EXPR$0 | EXPR$1 | EXPR$2 |
+-------------+-----------+------------------------+
| 2016-04-07 | 12:12:23 | 2016-04-07 12:12:23.0 |
+-------------+-----------+------------------------+
The INTERVALYEAR and INTERVALDAY internal types represent a period of time.
The INTERVALYEAR type specifies values from a year to a month.
The INTERVALDAY type specifies values from a day to seconds.
0: jdbc:drill:zk = local> select timestamp '2016-04-07 12:45:50' +
interval '10' year(2) from (values(1));
+------------------------+
| EXPR$0 |
+------------------------+
| 2026-04-07 12:45:50.0 |
+———————————————————————-+
1 row selected (0.251 seconds)
In the above query, INTERVAL keyword followed by 10 adds 10 years to the timestamp. The 2 in parentheses in YEAR(2) specifies the precision of the year interval, 2 digits in this case to support the ten interval.
0: jdbc:drill:zk = local> select timestamp '2016-04-07 12:45:52' +
interval '1' day(1) from (values(1));
+------------------------+
| EXPR$0 |
+------------------------+
| 2016-04-08 12:45:52.0 |
+———————————————————————-+
Here INTERVAL ‘1’ indicates that two days will be added from that specified day.
The following operators are used in Apache Drill to perform the desired operations.
Logical Operators
AND, BETWEEN, IN , LIKE , NOT , OR
Comparison Operators
<, > , <= , >= , = , <> , IS NULL , IS NOT NULL , IS FALSE , IS NOT FALSE , IS TRUE , IS NOT TRUE,
Pattern Matching Operator - LIKE
Math Operators
+,-,*,/
Subquery Operators
EXISTS, IN
Apache Drill scalar functions supports Math and Trig functions. Most scalar functions use data types such as INTEGER, BIGINT, FLOAT and DOUBLE.
The following table describes the list of “Math functions” in Apache Drill.
ABS(x)
Returns the absolute value of the input argument x.
CBRT(x)
Returns the cubic root of x.
CEIL(x)
Returns the smallest integer not less than x.
CEILING(x)
Same as CEIL.
DEGREES(x)
Converts x radians to degrees.
EXP(x)
Returns e (Euler's number) to the power of x.
FLOOR(x)
Returns the largest integer not greater than x.
LOG(x, y)
Returns log base x to the y power.
Now let’s run queries for the scalar functions. The Drill scalar functions can be easily tested by the values() statement, otherwise you can also use the select statement.
Apache Drill supports the following trig functions and these functions’ return type is a floating point value.
SIN(x)
Sine of angle x in radians
ACOS(x)
Inverse cosine of angle x in radians
COSH()
Hyperbolic cosine of hyperbolic angle x in radians
In Apache Drill, you can cast or convert data to the required type for moving data from one data source to another. Drill also supports the following functions for casting and converting data types −
CAST(x AS y)
CONVERT_TO(x,y)
CONVERT_FROM(x,y)
Apache Drill supports time functions based on the Gregorian calendar and in the range from 1971 to 2037. The following table describes the list of Date/Time functions.
AGE(x [, y ] )
INTERVALDAY
or
INTERVALYEAR
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
DATE_SUB(x,y)
EXTRACT(x FROM y)
Extracts a time unit from a date or timestamp expression (y).
This must be one of the following values: SECOND, MINUTE, HOUR, DAY, MONTH, and YEAR.
LOCALTIME
LOCALTIMESTAMP
NOW()
TIMEOFDAY()
Apache Drill supports the following list of string functions.
BYTE_SUBSTR(x,y [, z ] )
CHAR_LENGTH(x)
CONCAT(x,y)
INITCAP(x)
LENGTH(x)
LOWER(x)
LPAD(x,y [ , z ] )
The value of x is filled in the front (the left-hand side) with the value of z until the total length of the value is equal y’s length.
If no z value then blanks are used to fill the position.
LTRIM(x)
POSITION( x IN y)
REGEXP_REPLACE(x,y,z)
RPAD(x,y,z)
RTRIM(x)
STRPOS(x,y)
SUBSTR(x,y,z)
UPPER(x)
Apache Drill supports the following list of null handling functions.
COALESCE(x, y [ , y ]... )
NULLIF(x,y )
The following table describes the list of “Math functions” in Apache Drill.
E()
Returns 2.718281828459045.
LOG(x)
Returns the natural log (base e) of x.
LOG10(x)
Returns the common log of x.
LSHIFT(x, y)
Shifts the binary x by y times to the left.
MOD(x, y)
Returns the remainder of x divided by y.
NEGATIVE(x)
Returns x as a negative number.
PI
Returns pi.
POW(x, y)
Returns the value of x to the y power.
RADIANS
Converts x degrees to radians.
RAND
Returns a random number from 0-1.
ROUND(x)
Rounds to the nearest integer.
ROUND(x, y)
Rounds x to y decimal places. Return type is decimal.
RSHIFT(x, y)
Shifts the binary x by y times to the right.
SIGN(x)
Returns the sign of x.
SQRT(x)
Returns the square root of x.
TRUNC(x)
Apache Drill supports the following trig functions and these functions’ return type is a floating point value.
COS(x)
Cosine of angle x in radians
TAN(x)
Tangent of angle x in radians
ASIN(x)
Inverse sine of angle x in radians
ATAN(x)
Inverse tangent of angle x in radians
SINH()
Hyperbolic sine of hyperbolic angle x in radians
TANH()
Hyperbolic tangent of hyperbolic angle x in radians
The following table describes the list of Date/Time functions.
DATE_ADD(x,y)
Returns the sum of the sum of a date/time and a number of days/hours, or of a date/time and date/time interval.
Where,
x - date, time or timestamp
y - integer or an interval expression.
DATE_PART(x,y)
Returns a field of a date, time, timestamp, or interval.
where,
x - year, month, day, hour, minute, or second
y - date, time, timestamp, or interval literal
UNIX_TIMESTAMP ( [ x] )
If x is specified as timestamp then the number of seconds since the UNIX epoch and the timestamp x is returned.
If x is not specified then it returns the number of seconds since the UNIX epoch (January 1, 1970 at 00:00:00).
Apache Drill supports JSON format for querying data. Drill treats a JSON object as SQL record. One object equals one row in a Drill table.
Let us query the sample file, “employee.json” packaged as part of the drill. This sample file is Foodmart data packaged as JAR in Drill's classpath: ./jars/3rdparty/foodmart-data-json.0.4.jar. The sample file can be accessed using namespace, cp.
Start the Drill shell, and select the first row of data from the “employee.json” file installed.
0: jdbc:drill:zk = local> select * from cp.`employee.json` limit 1;
+--------------+--------------+------------+------------+--------------+----------------+-----------+----------------+------------+-----------------------+---------+---------------+-----------------+----------------+--------+-------------------+
| employee_id | full_name | first_name | last_name | position_id | position_title | store_id | department_id | birth_date | hire_date | salary | supervisor_id | education_level | marital_status | gender | management_role |
+--------------+--------------+------------+------------+--------------+----------------+-----------+----------------+------------+-----------------------+---------+---------------+-----------------+----------------+--------+-------------------+
| 1 | Sheri Nowmer | Sheri | Nowmer | 1 | President | 0 | 1 | 1961-08-26 | 1994-12-01 00:00:00.0 | 80000.0 | 0 | Graduate Degree | S | F | Senior Management |
+--------------+--------------+------------+------------+--------------+----------------+-----------+----------------+------------+-----------------------+---------+---------------+-----------------+----------------+--------+-------------------+
The same result can be viewed in the web console as −
You can connect Drill to a file system through a storage plugin. On the Storage tab of the Drill Web Console (http://localhost:8047), you can view and reconfigure a storage plugin.
The Drill installation contains the following default storage plugin configurations.
cp − Points to the JAR files in the Drill classpath.
cp − Points to the JAR files in the Drill classpath.
dfs − Points to the local file system, but you can configure this storage plugin to point to any distributed file system, such as a Hadoop or S3 file system.
dfs − Points to the local file system, but you can configure this storage plugin to point to any distributed file system, such as a Hadoop or S3 file system.
hbase − Provides a connection to the HBase.
hbase − Provides a connection to the HBase.
hive − Integrates Drill with the Hive metadata abstraction of files, HBase, and libraries to read data and operate on SerDes and UDFs.
hive − Integrates Drill with the Hive metadata abstraction of files, HBase, and libraries to read data and operate on SerDes and UDFs.
mongo − Provides a connection to MongoDB data.
mongo − Provides a connection to MongoDB data.
Embedded mode − Apache Drill saves the storage plugin configurations in a temporary directory. The temporary directory clears when you reboot.
Embedded mode − Apache Drill saves the storage plugin configurations in a temporary directory. The temporary directory clears when you reboot.
Distributed mode − Drill saves storage plugin configurations in ZooKeeper.
Distributed mode − Drill saves storage plugin configurations in ZooKeeper.
The workspace defines the location of files in subdirectories of a local or distributed file system. One or more workspaces can be defined in a plugin.
As of now we have queried an already packaged “employee.json” file. Let us create a new JSON file named “student_list.json” as shown in the following program.
{
"ID" : "001",
"name" : "Adam",
"age" : 12,
"gender" : "male",
"standard" : "six",
"mark1" : 70,
"mark2" : 50,
"mark3" : 60,
"addr" : "23 new street",
"pincode" : 111222
}
{
"ID" : "002",
"name" : "Amit",
"age" : 12,
"gender" : "male",
"standard" : "six",
"mark1" : 40,
"mark2" : 50,
"mark3" : 40,
"addr" : "12 old street",
"pincode" : 111222
}
{
"ID" : "003",
"name" : "Bob",
"age" : 12,
"gender" : "male",
"standard" : "six",
"mark1" : 60,
"mark2" : 80,
"mark3" : 70,
"addr" : "10 cross street",
"pincode" : 111222
}
{
"ID" : "004",
"name" : "David",
"age" : 12,
"gender" : "male",
"standard" : "six",
"mark1" : 50,
"mark2" : 70,
"mark3" : 70,
"addr" : "15 express avenue",
"pincode" : 111222
}
{
"ID" : "005",
"name" : "Esha",
"age" : 12,
"gender" : "female",
"standard" : "six",
"mark1" : 70,
"mark2" : 60,
"mark3" : 65,
"addr" : "20 garden street",
"pincode" : 111222
}
{
"ID" : "006",
"name" : "Ganga",
"age" : 12,
"gender" : "female",
"standard" : "six",
"mark1" : 100,
"mark2" : 95,
"mark3" : 98,
"addr" : "25 north street",
"pincode" : 111222
}
{
"ID" : "007",
"name" : "Jack",
"age" : 13,
"gender" : "male",
"standard" : "six",
"mark1" : 55,
"mark2" : 45,
"mark3" : 45,
"addr" : "2 park street",
"pincode" : 111222
}
{
"ID" : "008",
"name" : "Leena",
"age" : 12,
"gender" : "female",
"standard" : "six",
"mark1" : 90,
"mark2" : 85,
"mark3" : 95,
"addr" : "24 south street",
"pincode" : 111222
}
{
"ID" : "009",
"name" : "Mary",
"age" : 13,
"gender" : "female",
"standard" : "six",
"mark1" : 75,
"mark2" : 85,
"mark3" : 90,
"addr" : "5 west street",
"pincode" : 111222
}
{
"ID" : "010",
"name" : "Peter",
"age" : 13,
"gender" : "female",
"standard" : "six",
"mark1" : 80,
"mark2" : 85,
"mark3" : 88,
"addr" : "16 park avenue",
"pincode" : 111222
}
Now, let us query the file to view its full records.
0: jdbc:drill:zk = local> select * from dfs.`/Users/../workspace/Drill-samples/student_list.json`;
ID name age gender standard mark1 mark2 mark3 addr pincode
001 Adam 12 male six 70 50 60 23 new street 111222
002 Amit 12 male six 40 50 40 12 old street 111222
003 Bob 12 male six 60 80 70 10 cross street 111222
004 David 12 male six 50 70 70 15 express avenue 111222
005 Esha 12 female six 70 60 65 20 garden street 111222
006 Ganga 12 female six 100 95 98 25 north street 111222
007 Jack 13 male six 55 45 45 2 park street 111222
008 Leena 12 female six 90 85 95 24 south street 111222
009 Mary 13 female six 75 85 90 5 west street 111222
010 Peter 13 female six 80 85 88 16 park avenue 111222
This section will cover the operations on SQL operators using JSON.
AND
The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
OR
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
IN
The IN operator is used to compare a value to a list of literal values that have been specified.
BETWEEN
The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value.
LIKE
The LIKE operator is used to compare a value to similar values using wildcard operators.
NOT
The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
The aggregate functions produce a single result from a set of input values. The following table lists out the functions in further detail.
AVG(expression)
Averages a column of all records in a data source.
COUNT(*)
Returns the number of rows that match the given criteria.
COUNT([DISTINCT] expression)
Returns the number of distinct values in the column.
MAX(expression)
Returns the largest value of the selected column.
MIN(expression)
Returns the smallest value of the selected column.
SUM(expression)
Return the sum of given column.
The following program shows the query for this function −
0: jdbc:drill:zk = local> select stddev(mark2) from dfs.`/Users/../workspace/Drill-samples/student_list.json`;
EXPR$0
18.020050561034015
0: jdbc:drill:zk = local> select variance(mark2) from dfs.`/Users/../workspace/Drill-samples/student_list.json`;
EXPR$0
324.7222222222223
Variance of mark2 column result is returned as the output.
Window functions execute on a set of rows and return a single value for each row from the query. The term window has the meaning of the set of rows for the function.
A Window function in a query, defines the window using the OVER() clause. This OVER() clause has the following capabilities −
Defines window partitions to form groups of rows. (PARTITION BY clause)
Orders rows within a partition. (ORDER BY clause)
The Aggregate window function can be defined over a partition by and order by clause.
The following program shows the query for this function −
Query
0: jdbc:drill:zk = local> select mark1,gender,
avg(mark1) over (partition by gender ) as avgmark1 from
dfs.`/Users/../workspace/Drill-samples/student_list.json`;
Result
mark1 gender avgmark1
70 female 83.0
100 female 83.0
90 female 83.0
75 female 83.0
80 female 83.0
70 male 55.0
40 male 55.0
60 male 55.0
50 male 55.0
55 male 55.0
This result shows that partition by clause is used for the gender column. So, it takes the average of mark1 from female gender which is 83.0 and then replaces that value to all the male and female gender. The mark1 avg result is now 55.0 and hence it replaces the same to all genders.
The following program shows the query for this function −
Query
0: jdbc:drill:zk = local> select name, gender, mark1, age,
count(*) over(partition by age) as cnt from
dfs.`/Users/../workspace/Drill-samples/student_list.json`;
Result
name gender mark1 age cnt
Adam male 70 12 7
Amit male 40 12 7
Bob male 60 12 7
David male 50 12 7
Esha female 70 12 7
Ganga female 100 12 7
Leena female 90 12 7
Jack male 55 13 3
Mary female 75 13 3
Peter female 80 13 3
Here, there are two age groups 12 and 13. The age count of 12 is for 7 students and 13 age count is for 3 students. Hence count(*) over partition by age replaces 7 for 12 age group and 3 for 13 age group.
The following program shows the query for this function −
Query
0: jdbc:drill:zk = local> select name,age,gender,mark3,
max(mark3) over (partition by gender) as maximum from
dfs.`/Users/../workspace/Drill-samples/student_list.json`;
Result
name age gender mark3 maximum
Esha 12 female 65 98
Ganga 12 female 98 98
Leena 12 female 95 98
Mary 13 female 90 98
Peter 13 female 88 98
Adam 12 male 60 70
Amit 12 male 40 70
Bob 12 male 70 70
David 12 male 70 70
Jack 13 male 45 70
From the above query, maximum mark3 is partitioned by gender, hence female gender max mark 98 is replaced to all female students and male gender max mark 70 is replaced to all male students.
The following program shows the query for this function −
Query
0: jdbc:drill:zk = local> select mark2,min(mark2)
over (partition by age ) as minimum from
dfs.`/Users/../workspace/Drill-samples/student_list.json`;
Result
mark2 minimum
50 50
50 50
80 50
70 50
60 50
95 50
85 50
45 45
85 45
85 45
The following program shows the query for this function −
Query
0: jdbc:drill:zk = local> select name,age,sum(mark1+mark2)
over (order by age ) as summation from
dfs.`/Users/../workspace/Drill-samples/student_list.json`;
Result
name age summation
Adam 12 970
Amit 12 970
Bob 12 970
David 12 970
Esha 12 970
Ganga 12 970
Leena 12 970
Jack 13 1395
Mary 13 1395
Peter 13 1395
Here mark1+mark2 result is replaced separately to each male and female student.
Following is the table listed out with ranking window functions.
CUME_DIST()
DENSE_RANK()
NTILE()
PERCENT_RANK()
RANK()
ROW_NUMBER()
In this chapter, we will discuss in detail about which all composite data types does Apache Drill supports.
Array − An array is a repeated list of values. A value in an array can be a scalar type, such as string or int, or an array can be a complex type, such as a map or another array.
Array − An array is a repeated list of values. A value in an array can be a scalar type, such as string or int, or an array can be a complex type, such as a map or another array.
Map − A map is a set of name/value pairs. A value in a map can be a scalar type, such as string or int, or a complex type, such as an array or another map.
Map − A map is a set of name/value pairs. A value in a map can be a scalar type, such as string or int, or a complex type, such as an array or another map.
Apache Drill uses map and array data types internally for reading complex and nested data structures from data sources.
FLATTEN
FLATTEN separates the elements in a repeated field into individual records.
KVGEN
This function returns a list of the keys that exist in the map.
REPEATED_COUNT
This function counts the values in an array.
REPEATED CONTAINS
Searches for a keyword in an array. If the keyword is present in an array, the result will be true otherwise false.
This section will cover Data definition statements. Let’s go through each of these commands in detail.
You can create tables in Apache Drill by using the following two CTAS commands.
Syntax
CREATE TABLE name [ (column list) ] AS query;
Where,
Query − select statement.
Syntax
CREATE TABLE name [ ( <column list> ) ] [ PARTITION BY ( <column_name> [ , ... ] ) ] AS <select statement>
Where,
name − unique directory name.
name − unique directory name.
column list − optional list of column names or aliases in the new table.
column list − optional list of column names or aliases in the new table.
PARTITION BY − partitions the data by the first column_name.
PARTITION BY − partitions the data by the first column_name.
To create a table, you should adhere to the following steps −
Set the workspace to a writable workspace.
Set the workspace to a writable workspace.
You can only create new tables in df.tmp workspace. You cannot create tables using storage plugins, such as Hive and HBase.
You can only create new tables in df.tmp workspace. You cannot create tables using storage plugins, such as Hive and HBase.
"tmp": {
"location": "/tmp",
"writable": true,
}
0: jdbc:drill:zk = local> use dfs.tmp;
+-------+--------------------------------------+
| ok | summary |
+-------+--------------------------------------+
| true | Default schema changed to [dfs.tmp] |
+-------+--------------------------------------+
0: jdbc:drill:zk = local> create table students as select * from
dfs.`/Users/../workspace/Drill-samples/student_list.json`;
+-----------+----------------------------+
| Fragment | Number of records written |
+-----------+----------------------------+
| 0_0 | 10 |
+-----------+----------------------------+
Query
0: jdbc:drill:zk = local> select * from students;
Result
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+
| ID | name | age | gender | standard | mark1 | mark2 | mark3 | addr | pincode |
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+
| 001 | Adam | 12 | male | six | 70 | 50 | 60 | 23 new street | 111222 |
| 002 | Amit | 12 | male | six | 40 | 50 | 40 | 12 old street | 111222 |
| 003 | Bob | 12 | male | six | 60 | 80 | 70 | 10 cross street | 111222 |
| 004 | David | 12 | male | six | 50 | 70 | 70 | 15 express avenue | 111222 |
| 005 | Esha | 12 | female | six | 70 | 60 | 65 | 20 garden street | 111222 |
| 006 | Ganga | 12 | female | six | 100 | 95 | 98 | 25 north street | 111222 |
| 007 | Jack | 13 | male | six | 55 | 45 | 45 | 2 park street | 111222 |
| 008 | Leena | 12 | female | six | 90 | 85 | 95 | 24 south street | 111222 |
| 009 | Mary | 13 | female | six | 75 | 85 | 90 | 5 west street | 111222 |
| 010 | Peter | 13 | female | six | 80 | 85 | 88 | 16 park avenue | 111222 |
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+
The following program shows the query for this function −
Query
0: jdbc:drill:zk = local> create table student_new partition by (gender) as select * from
dfs.`/Users/../workspace/Drill-samples/student_list.json`;
Result
+-----------+----------------------------+
| Fragment | Number of records written |
+-----------+----------------------------+
| 0_0 | 10 |
+-----------+----------------------------+
To view the records of the table −
Query
0: jdbc:drill:zk = local> select * from student_new;
Result
+------+--------+------+--------+----------+-------+-------+-------+-------------------+---------+
| ID | name | age | gender | standard | mark1 | mark2 | mark3 | addr | pincode |
+------+--------+------+--------+----------+-------+-------+-------+-------------------+---------+
| 005 | Esha | 12 | female | six | 70 | 60 | 65 | 20 garden street | 111222 |
| 006 | Ganga | 12 | female | six | 100 | 95 | 98 | 25 north street | 111222 |
| 008 | Leena | 12 | female | six | 90 | 85 | 95 | 24 south street | 111222 |
| 009 | Mary | 13 | female | six | 75 | 85 | 90 | 5 west street | 111222 |
| 010 | Peter | 13 | female | six | 80 | 85 | 88 | 16 park avenue | 111222 |
| 001 | Adam | 12 | male | six | 70 | 50 | 60 | 23 new street | 111222 |
| 002 | Amit | 12 | male | six | 40 | 50 | 40 | 12 old street | 111222 |
| 003 | Bob | 12 | male | six | 60 | 80 | 70 | 10 cross street | 111222 |
| 004 | David | 12 | male | six | 50 | 70 | 70 | 15 express avenue | 111222 |
| 007 | Jack | 13 | male | six | 55 | 45 | 45 | 2 park street | 111222 |
+------+--------+------+--------+----------+-------+-------+-------+-------------------+---------+
Here the table records are partitioned by gender.
The ALTER SYSTEM command permanently changes a system setting.
ALTER SYSTEM SET `option_name` = value;
To reset the system settings, use the following syntax.
ALTER SYSTEM RESET `option_name`;
ALTER SYSTEM RESET ALL;
Here is the sample query that enables the Decimal data type −
0: jdbc:drill:zk = local> ALTER SYSTEM SET `planner.enable_decimal_data_type` = true;
+-------+--------------------------------------------+
| ok | summary |
+-------+--------------------------------------------+
| true | planner.enable_decimal_data_type updated. |
+-------+--------------------------------------------+
By default, Apache Drill disables the decimal data type. To reset all the changes, you will need to key-in the following command −
0: jdbc:drill:zk = local> ALTER SYSTEM RESET all;
+-------+---------------+
| ok | summary |
+-------+---------------+
| true | ALL updated. |
+-------+---------------+
The CREATE VIEW command creates a virtual structure for the result set of a stored query. A view can combine data from multiple underlying data sources and provide the illusion that all of the data is from one source.
CREATE [OR REPLACE] VIEW [workspace.]view_name [ (column_name [, ...]) ] AS query;
Where,
workspace − The location where you want the view to exist. By default, the view can be created in “dfs.tmp”.
workspace − The location where you want the view to exist. By default, the view can be created in “dfs.tmp”.
view_name − The name that you give to the view. This view must have a unique name.
view_name − The name that you give to the view. This view must have a unique name.
0: jdbc:drill:zk = local> create view student_view as select * from
dfs.`/Users/../workspace/Drill-samples/student_list.json`;
+------+--------------------------------------------------------------+
| ok | summary |
+------+--------------------------------------------------------------+
| true | View 'student_view' created successfully in 'dfs.tmp' schema |
+------+--------------------------------------------------------------+
To see the records, you can use the following query.
0: jdbc:drill:zk = local> select * from student_view;
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+
| ID | name | age | gender | standard | mark1 | mark2 | mark3 | addr | pincode |
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+
| 001 | Adam | 12 | male | six | 70 | 50 | 60 | 23 new street | 111222 |
| 002 | Amit | 12 | male | six | 40 | 50 | 40 | 12 old street | 111222 |
| 003 | Bob | 12 | male | six | 60 | 80 | 70 | 10 cross street | 111222 |
| 004 | David | 12 | male | six | 50 | 70 | 70 | 15 express avenue | 111222 |
| 005 | Esha | 12 | female | six | 70 | 60 | 65 | 20 garden street | 111222 |
| 006 | Ganga | 12 | female | six | 100 | 95 | 98 | 25 north street | 111222 |
| 007 | Jack | 13 | male | six | 55 | 45 | 45 | 2 park street | 111222 |
| 008 | Leena | 12 | female | six | 90 | 85 | 95 | 24 south street | 111222 |
| 009 | Mary | 13 | female | six | 75 | 85 | 90 | 5 west street | 111222 |
| 010 | Peter | 13 | female | six | 80 | 85 | 88 | 16 park avenue | 111222 |
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+
The drop table statement is used to drop the table from a DFS storage plugin.
DROP TABLE [workspace.]name;
0: jdbc:drill:zk = local> drop table student_new;
+------+------------------------------+
| ok | summary |
+------+------------------------------+
| true | Table [student_new] dropped |
+------+------------------------------+
Similar to the table, a view can be dropped by using the following command −
0: jdbc:drill:zk = local> drop view student_view;
+------+-----------------------------------------------------------------+
| ok | summary |
+------+-----------------------------------------------------------------+
| true | View [student_view] deleted successfully from schema [dfs.tmp]. |
+------+-----------------------------------------------------------------+
In this chapter, we will learn about how Apache Drill allows us to query plain text files such as CSV, TSV and PSV.
Create a CSV file named “students.csv” as shown in the following program −
001,Adam,23 new street
002,Amit,12 old street
003,Bob,10 cross street
004,David,15 express avenue
005,Esha,20 garden street
006,Ganga,25 north street
007,Jack,2 park street
008,Leena,24 south street
009,Mary,5 west street
010,Peter,16 park avenue
After saving the file, you can return to the terminal again and type the following query to view that CSV file.
0: jdbc:drill:zk = local> select * from dfs.`/Users/../workspace/Drill-samples/students.csv`;
+-------------------------------------+
| columns |
+-------------------------------------+
| ["001","Adam","23 new street"] |
| ["002","Amit","12 old street"] |
| ["003","Bob","10 cross street"] |
| ["004","David","15 express avenue"] |
| ["005","Esha","20 garden street"] |
| ["006","Ganga","25 north street"] |
| ["007","Jack","2 park street"] |
| ["008","Leena","24 south street"] |
| ["009","Mary","5 west street"] |
| ["010","Peter","16 park avenue"] |
+—————————————————————————————————————+
From this output we can conclude that, Apache Drill recognizes each row as an array of values and returns one column for each row.
The COLUMNS[n] syntax is used to return CSV rows in a column by the column format, where n starts from 0 to n-1.
Query
0: jdbc:drill:zk = local>select columns[0],columns[1],columns[2] from
dfs.`/Users/../workspace/Drill-samples/students.csv`;
Result
+---------+---------+--------------------+
| EXPR$0 | EXPR$1 | EXPR$2 |
+---------+---------+--------------------+
| 001 | Adam | 23 new street |
| 002 | Amit | 12 old street |
| 003 | Bob | 10 cross street |
| 004 | David | 15 express avenue |
| 005 | Esha | 20 garden street |
| 006 | Ganga | 25 north street |
| 007 | Jack | 2 park street |
| 008 | Leena | 24 south street |
| 009 | Mary | 5 west street |
| 010 | Peter | 16 park avenue |
+---------+---------+--------------------+
If you want to assign an alias name for columns, use the following query −
Query
0: jdbc:drill:zk = local>select columns[0] as ID,columns[1] as Name,columns[2] as Address from
dfs.`/Users/../workspace/Drill-samples/students.csv`;
Result
+------+-------+--------------------+
| ID | Name | Address |
+------+-------+--------------------+
| 001 | Adam | 23 new street |
| 002 | Amit | 12 old street |
| 003 | Bob | 10 cross street |
| 004 | David | 15 express avenue |
| 005 | Esha | 20 garden street |
| 006 | Ganga | 25 north street |
| 007 | Jack | 2 park street |
| 008 | Leena | 24 south street |
| 009 | Mary | 5 west street |
| 010 | Peter | 16 park avenue |
+------+-------+--------------------+
Like in JSON, you can create table for plain text files. Following is a sample query −
0: jdbc:drill:zk = local> create table CSV as select * from
dfs.`/Users/../workspace/Drill-samples/students.csv`;
Result
+----------+----------------------------+
| Fragment | Number of records written |
+----------+----------------------------+
| 0_0 | 10 |
+-----------+---------------------------+
To view the file contents, type the following query −
Query
0: jdbc:drill:zk = local> select * from CSV;
Result
+-------------------------------------+
| columns |
+-------------------------------------+
| ["001","Adam","23 new street"] |
| ["002","Amit","12 old street"] |
| ["003","Bob","10 cross street"] |
| ["004","David","15 express avenue"] |
| ["005","Esha","20 garden street"] |
| ["006","Ganga","25 north street"] |
| ["007","Jack","2 park street"] |
| ["008","Leena","24 south street"] |
| ["009","Mary","5 west street"] |
| ["010","Peter","16 park avenue"] |
+-------------------------------------+
Create a TSV file named “students.tsv” as shown in the following program −
ID Name Age Standard Remark
001 id "name is Adam" "for the age of 12" "studying sixth std" "Having good marks"
Now we can execute this TSV file in Apache Drill by using the following query −
0: jdbc:drill:zk = local> select * from dfs.`/Users/../workspace/Drill-samples/student.tsv`;
+-------------------------------------------------------------------------------------------------------------------+
| columns |
+-------------------------------------------------------------------------------------------------------------------+
| [ "ID" , "Name" , "Age" , "Standard" , "Marks" , "Addr", "pincode"] |
| ["001 id ", "name is adam", "for the age of 12", "studying sxith std\" \"Having good marks"] |
+-------------------------------------------------------------------------------------------------------------------+
As shown in the CSV file above, you can also create a table for the TSV file.
Query
0: jdbc:drill:zk = local> select * from dfs.`/Users/../workspace/Drill-samples/student.tsv`;
Result
+-----------+----------------------------+
| Fragment | Number of records written |
+-----------+----------------------------+
| 0_0 | 2 |
+-----------+----------------------------+
1 row selected (0.347 seconds)
Query
0: jdbc:drill:zk = local> select * from TSV;
Result
+------------------------------------------------------------------------------------------------------------------+
| columns |
+------------------------------------------------------------------------------------------------------------------+
| [ "ID" , "Name" , "Age" , "Standard" , "Marks" , "Addr", "pincode"] |
| ["001 id ", "name is adam", "for the age of 12", "studying sxith std\" \"Having good marks"] |
+------------------------------------------------------------------------------------------------------------------+
Create a psv file named “sample.tbl” as shown in the following program.
Tutorialspoint|Apache|Drill|article
Now we can execute this PSV file in Drill,
0: jdbc:drill:zk = local> select * from dfs.`/Users/../workspace/Drill-samples/sample.tbl`;
+------------------------------------------------+
| columns |
+------------------------------------------------+
| ["Tutorialspoint","Apache","Drill","article"] |
+------------------------------------------------+
Now, similar to the CSV and TSV files, try for yourself to create a table for PSV file.
HBase is a distributed column-oriented database built on top of the Hadoop file system. It is a part of the Hadoop ecosystem that provides random real-time read/write access to data in the Hadoop File System. One can store the data in HDFS either directly or through HBase. The following steps are used to query HBase data in Apache Drill.
Before moving on to querying HBase data, you must need to install the following −
Java installed version 1.7 or greater
Hadoop
HBase
After successful installation navigate to Apache Drill web console and select the storage menu option as shown in the following screenshot.
Then choose HBase Enable option, after that go to the update option and now you will see the response as shown in the following program.
{
"type": "hbase",
"config": {
"hbase.zookeeper.quorum": "localhost",
"hbase.zookeeper.property.clientPort": "2181"
},
"size.calculator.enabled": false,
"enabled": true
}
Here the config settings “hbase.zookeeper.property.clientPort” : “2181” indicates ZooKeeper port id. In the embedded mode, it will automatically assign it to the ZooKeeper, but in the distributed mode, you must specify the ZooKeeper port id’s separately. Now, HBase plugin is enabled in Apache Drill.
After enabling the plugin, first start your Hadoop server then start HBase.
After Hadoop and HBase has been started, you can start the HBase interactive shell using “hbase shell” command as shown in the following query.
/bin/hbase shell
Then you will see the response as shown in the following program.
hbase(main):001:0>
To query HBase, you should complete the following steps −
Pipe the following commands to the HBase shell to create a “customer” table.
hbase(main):001:0> create 'customers','account','address'
Create a simple text file named “hbase-customers.txt” as shown in the following program.
put 'customers','Alice','account:name','Alice'
put 'customers','Alice','address:street','123 Ballmer Av'
put 'customers','Alice','address:zipcode','12345'
put 'customers','Alice','address:state','CA'
put 'customers','Bob','account:name','Bob'
put 'customers','Bob','address:street','1 Infinite Loop'
put 'customers','Bob','address:zipcode','12345'
put 'customers','Bob','address:state','CA'
put 'customers','Frank','account:name','Frank'
put 'customers','Frank','address:street','435 Walker Ct'
put 'customers','Frank','address:zipcode','12345'
put 'customers','Frank','address:state','CA'
put 'customers','Mary','account:name','Mary'
put 'customers','Mary','address:street','56 Southern Pkwy'
put 'customers','Mary','address:zipcode','12345'
put 'customers','Mary','address:state','CA'
Now, issue the following command in hbase shell to load the data into a table.
hbase(main):001:0> cat ../drill_sample/hbase/hbase-customers.txt | bin/hbase shell
Now switch to Apache Drill shell and issue the following command.
0: jdbc:drill:zk = local> select * from hbase.customers;
+------------+---------------------+---------------------------------------------------------------------------+
| row_key | account | address |
+------------+---------------------+---------------------------------------------------------------------------+
| 416C696365 | {"name":"QWxpY2U="} | {"state":"Q0E=","street":"MTIzIEJhbGxtZXIgQXY=","zipcode":"MTIzNDU="} |
| 426F62 | {"name":"Qm9i"} | {"state":"Q0E=","street":"MSBJbmZpbml0ZSBMb29w","zipcode":"MTIzNDU="} |
| 4672616E6B | {"name":"RnJhbms="} | {"state":"Q0E=","street":"NDM1IFdhbGtlciBDdA==","zipcode":"MTIzNDU="} |
| 4D617279 | {"name":"TWFyeQ=="} | {"state":"Q0E=","street":"NTYgU291dGhlcm4gUGt3eQ==","zipcode":"MTIzNDU="} |
+------------+---------------------+---------------------------------------------------------------------------+
The output will be 4 rows selected in 1.211 seconds.
Apache Drill fetches the HBase data as a binary format, which we can convert into readable data using CONVERT_FROM function available in drill. Check and use the following query to get proper data from drill.
0: jdbc:drill:zk = local> SELECT CONVERT_FROM(row_key, 'UTF8') AS customer_id,
. . . . . . . . . . . > CONVERT_FROM(customers.account.name, 'UTF8') AS customers_name,
. . . . . . . . . . . > CONVERT_FROM(customers.address.state, 'UTF8') AS customers_state,
. . . . . . . . . . . > CONVERT_FROM(customers.address.street, 'UTF8') AS customers_street,
. . . . . . . . . . . > CONVERT_FROM(customers.address.zipcode, 'UTF8') AS customers_zipcode
. . . . . . . . . . . > FROM hbase.customers;
+--------------+----------------+-----------------+------------------+--------------------+
| customer_id | customers_name | customers_state | customers_street | customers_zipcode |
+--------------+----------------+-----------------+------------------+--------------------+
| Alice | Alice | CA | 123 Ballmer Av | 12345 |
| Bob | Bob | CA | 1 Infinite Loop | 12345 |
| Frank | Frank | CA | 435 Walker Ct | 12345 |
| Mary | Mary | CA | 56 Southern Pkwy | 12345 |
+--------------+----------------+-----------------+------------------+--------------------+
Hive is a data warehouse infrastructure tool to process structured data in Hadoop. It resides on top of Hadoop to summarize Big Data, and makes querying and analyzing easy. Hive stores schema in a database and processed data into HDFS.
Following are the steps that are used to query Hive data in Apache Drill.
You must need to install the following components first −
Java installed version 1.7 or greater
Hadoop
Hive
ZooKeeper
After the installation, start all the services (Hadoop, ZooKeeper and Hive) one by one in a new terminal.
You can start the Hive metastore using the following command −
Query
hive --service metastore
Apache Drill uses Hive metastore service to get hive table’s details.
To start Drill shell in a distributed mode, you can issue the following command −
Query
bin/drillbit.sh start
Like HBase, open Apache Drill web console and choose Hive storage plugin enable option then add the following changes to hive storage plugin “update” option,
{
"type": "hive",
"enabled": false,
"configProps": {
"hive.metastore.uris": "thrift://localhost:9083",
"hive.metastore.sasl.enabled": "false",
"fs.default.name": "hdfs://localhost/"
}
}
Create a table in hive shell using the following command.
Query
create table customers (Name string, address string) row format delimited fields terminated by ',' stored as textfile;
Load data in the hive shell using the following command.
Query
load data local inpath '/path/to/file/customers.csv' overwrite into table customers;
You can query data in the hive shell using the following command.
Query
select * from hive.`customers`;
Result
'Alice','123 Ballmer Av'
'Bob','1 Infinite Loop'
'Frank','435 Walker Ct'
'Mary','56 Southern Pkwy'
Parquet is a columnar storage format. Apache Drill uses Parquet format for easy, fast and efficient access.
Before moving to create a table in parquet, you must change the Drill storage format using the following command.
0: jdbc:drill:zk = local> alter session set `store.format`= 'parquet';
+-------+------------------------+
| ok | summary |
+-------+------------------------+
| true | store.format updated. |
+———----+------------------------+
You can create a table using the following syntax.
0: jdbc:drill:zk = local> create table dfs.tmp.`/Users/../workspace` as select * from
dfs.`/Users/../workspace/Drill-samples/student_list.json`;
+----------+---------------------------+
| Fragment | Number of records written |
+----------+---------------------------+
| 0_0 | 10 |
+----------+---------------------------+
To see the table contents, type-in the following query −
0: jdbc:drill:zk = local> select * from dfs.tmp.`/Users/../workspace`;
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+
| ID | name | age | gender | standard | mark1 | mark2 | mark3 | addr | pincode |
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+
| 001 | Adam | 12 | male | six | 70 | 50 | 60 | 23 new street | 111222 |
| 002 | Amit | 12 | male | six | 40 | 50 | 40 | 12 old street | 111222 |
| 003 | Bob | 12 | male | six | 60 | 80 | 70 | 10 cross street | 111222 |
| 004 | David | 12 | male | six | 50 | 70 | 70 | 15 express avenue | 111222 |
| 005 | Esha | 12 | female | six | 70 | 60 | 65 | 20 garden street | 111222 |
| 006 | Ganga | 12 | female | six | 100 | 95 | 98 | 25 north street | 111222 |
| 007 | Jack | 13 | male | six | 55 | 45 | 45 | 2 park street | 111222 |
| 008 | Leena | 12 | female | six | 90 | 85 | 95 | 24 south street | 111222 |
| 009 | Mary | 13 | female | six | 75 | 85 | 90 | 5 west street | 111222 |
| 010 | Peter | 13 | female | six | 80 | 85 | 88 | 16 park avenue | 111222 |
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+
Apache Drill provides JDBC interface to connect and execute queries. We can use JDBC interface in JDBC based SQL Client like “SquirreL SQL Client” and work on all the features of drill. We can use the same JDBC interface to connect drill from our Java based application. Let us see how to connect drill and execute commands in our sample Java application using JDBC interface in this section.
Apache Drill provides a JDBC driver as a single jar file and it is available @ /path/to/drill/jars/jdbc-driver/drill-jdbc-all-1.6.0.jar. The connection string to connect the drill is of the following format −
jdbc:drill:zk = <zk_host>:<zk_port>
jdbc:drill:zk = <zk_host>:<zk_port>/<zk_drill_path>/<zk_drillbit_name
jdbc:drill:zk = <zk_host>:<zk_port>/<zk_drill_path>/<zk_drillbit_name;schema = hive
Considering ZooKeeper is installed in the local system, the port configured is 2181, the drill path is “drill” and drillbit name is “drillbits1”, the connection string may be among the following commands.
jdbc:drill:zk = localhost:2181
jdbc:drill:zk = localhost:2181/drill/dillbits1
jdbc:drill:zk = localhost:2181/drill/dillbits1;schema = hive
if the drill is installed in a distributed mode, we can replace the “localhost” with the list of drill installed system IP/name as shown in the following command.
jdbc:drill:zk = 1.2.3.4:2181,5.6.7.8:2181/drill/dillbits1;schema = hive
The connection to drill is just like any other JDBC interface. Now, create a new maven project with "com.tutorialspoint.drill.samples" as the package name and “connect-drill” as the application name.
Then, update the following code in “App.java” file. The coding is simple and self-explanatory. The query used in the application is the default JSON file packaged into drill.
package com.tutorialspoint.drill.samples;
import java.sql.*;
import java.lang.*;
public class App{
public static void main( String[] args ) throws SQLException, ClassNotFoundException{
// load the JDBC driver
Class.forName("org.apache.drill.jdbc.Driver");
// Connect the drill using zookeeper drill path
Connection connection = DriverManager.getConnection("jdbc:drill:zk = localhost:2181/drill/drillbits1");
// Query drill
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT * from cp.`employee.json` LIMIT 3");
// Fetch and show the result
while(rs.next()){
System.out.println("Name: " + rs.getString(2));
}
}
}
Now add following drill dependency tag to “pom.xml” file.
<dependency>
<groupId>org.apache.drill.exec</groupId>
<artifactId>drill-jdbc-all</artifactId>
<version>1.1.0</version>
</dependency>
Now, you can compile the application by using the following command.
mvn clean package
Once the application is compiled, execute it using the following command.
java -cp target/connect-drill-1.0.jar:/path/to/apache-drill-1.6.0/jars/
jdbc-driver/drill-jdbc-all-1.6.0.jar com.tutorialspoint.drill.samples.App
The output of this application list is the name of the first three employees available in “employee.json” file and it will show in the console as shown in the following program.
Name: Sheri Nowmer
Name: Derrick Whelply
Name: Michael Spence
Apache Drill has an option to create custom functions. These custom functions are reusable SQL functions that you develop in Java to encapsulate the code that processes column values during a query.
Custom functions can perform calculations and transformations that the built-in SQL operators and functions do not provide. Custom functions are called from within a SQL statement, like a regular function, and return a single value. Apache Drill has custom aggregate function as well and it is still evolving. Let us see how to create a simple custom function in this section.
Apache Drill provides a simple interface, “DrillSimpleFunc”, which we have to implement to create a new custom function. The “DrillSimpleFunc” interface has two methods, “setup” and “eval”. The “setup” method is to initialize necessary variables. “eval” method is actual method used to incorporate the custom function logic. The “eval” method has certain attributes to set function name, input and output variables.
Apache Drill provide a list of datatype to hold input and output variable like BitHolder, VarCharHolder, BigIntHolder, IntHolder, etc. We can use these datatypes to pass on information between drill and custom function. Now, let us create a new application using Maven with “com.tutorialspoint.drill.function” as the package name and “is-pass” as the library name.
mvn archetype:generate -DgroupId = com.tutorialspoint.drill.function -DartifactId =
is-pass -DarchetypeArtifactId = maven-archetype-quickstart -DinteractiveMode = false
Here,
-DgroupId &minus package name
-DgroupId &minus package name
-DartifactId &minus argument
-DartifactId &minus argument
Then remove the App.java file and create new java file and name it as “IsPassFunc.java”. This java file will hold out custom function logic. The custom function logic is to check whether the particular student is secured pass in a particular subject by checking his mark with cutoff mark. The student mark will be first input and it will change according to the record.
The second input is the cutoff mark, which will be a constant and does not change for different records. The custom function will implement “DrillSimpleFunc” interface and just check whether the given input is higher than the cutoff. If the input is higher, then if returns true, otherwise false.
The coding is as follows −
package com.tutorialspoint.drill.function;
import com.google.common.base.Strings;
import io.netty.buffer.DrillBuf;
import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.holders.BigIntHolder;
import org.apache.drill.exec.expr.holders.BitHolder;
import org.apache.drill.exec.expr.holders.NullableVarCharHolder;
import org.apache.drill.exec.expr.holders.VarCharHolder;
import javax.inject.Inject;
// name of the function to be used in drill
@FunctionTemplate(
name = “ispass",
scope = FunctionTemplate.FunctionScope.SIMPLE,
nulls = FunctionTemplate.NullHandling.NULL_IF_NULL
)
public class IsPassFunc implements DrillSimpleFunc {
// input - student mark
@Param
BigIntHolder input;
// input - cutoff mark, constant value
@Param(constant = true)
BigIntHolder inputCutOff;
// output - true / false
@Output
BitHolder out;
public void setup() { }
// main logic of the function. checks mark with cutoff and returns true / false.
public void eval() {
int mark = (int) input.value;
int cutOffMark = (int) inputCutOff.value;
if(mark >= cutOffMark)
out.value = 1;
else
out.value = 0;
}
}
Now, you can create a resource file @ is-pass/src/main/resources/drill-module.conf and place the following code into it.
drill {
classpath.scanning {
base.classes : ${?drill.classpath.scanning.base.classes} [
com.tutorialspoint.drill.function.IsPassFunc
],
packages : ${?drill.classpath.scanning.packages} [
com.tutorialspoint.drill.function
]
}
}
Apache Drill uses this configuration file to find the custom function class in the jar file. A jar file can have any number of custom function and it should be properly configured here.
Finally, add the following configuration in “pom.xml” to properly compile the custom function in maven.
Change the following settings in “pom.xml” file.
<dependencies>
<dependency>
<groupId>org.apache.drill.exec</groupId>
<artifactId>drill-java-exec</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<verbose>true</verbose>
<compilerVersion>1.7</compilerVersion>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
After making all the changes, create a package using the following command.
mvn clean package
Maven will create the necessary jars, is-pass-1.0.jar & is-pass-1.0-sources.jar in the "target" folder. Now, copy the jar files and place it @ /path/to/apache-drill/jars/3rdparty in all the drill nodes.
After jar files are place properly in all the drillbits, restart all the drillbits, open a new drill shell and then execute the query as shown in the following program.
select name, ispass(mark1, 35) as is_pass from dfs.`/Users/../Workspace/drill_sample/student_list.json` limit 3;
name is_pass
Adam true
Amit true
Bob true
Apache Drill custom functions are simple to create and provides great extension capabilities to drill query language.
Apache Drill supports many of today's best industrial applications. Some of these contributors are −
Oracle
IBM Netezza
Clustrix
Pentaho
Apache Drill is a schema free SQL engine and scales up to 10,000 servers or more to process petabytes of data and trillions of records in less than a second. Apache Drill uses pure data flow through the memory and extensible architecture.
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": 2248,
"s": 2069,
"text": "In this chapter, we will discuss about the basic overview of Apache Drill, its benefits and key features. Apart from this, we will also get some basic knowledge on Google Dremel."
},
{
"code": null,
"e": 2605,
"s": 2248,
"text": "Google manages big data every second of every day to provide services like Search, YouTube, Gmail and Google Docs. Google uses an efficient technology to scan big data at a blazing speed which is called as “Dremel”. Well, Dremel is a query service that allows you to run SQL-like queries against very large data sets and return accurate results in seconds."
},
{
"code": null,
"e": 3001,
"s": 2605,
"text": "Dremel can scan 35 billion rows without an index within ten-seconds. Dremel stores data in a columnar storage model, which means that it separates a record into column values and then stores each value on a different storage volume. But at the same time, traditional databases store the whole record on one volume. This columnar approach is the main reason that it makes Dremel drastically fast."
},
{
"code": null,
"e": 3373,
"s": 3001,
"text": "Google has been using Dremel in production since year 2006 and has been continuously evolving it for the applications like Spam analysis, Debugging of map tiles on Google Maps, etc. For this reason, Drill is inspired by Dremel. Recently, Google released BigQuery and it is the public implementation of Dremel that was launched for general businesses or developers to use."
},
{
"code": null,
"e": 3814,
"s": 3373,
"text": "Apache Drill is a low latency schema-free query engine for big data. Drill uses a JSON document model internally which allows it to query data of any structure. Drill works with a variety of non-relational data stores, including Hadoop, NoSQL databases (MongoDB, HBase) and cloud storage like Amazon S3, Azure Blob Storage, etc. Users can query the data using a standard SQL and BI Tools, which doesn’t require to create and manage schemas."
},
{
"code": null,
"e": 3882,
"s": 3814,
"text": "Following are some of the most important benefits of Apache Drill −"
},
{
"code": null,
"e": 3988,
"s": 3882,
"text": "Drill can scale data from a single node to thousands of nodes and query petabytes of data within seconds."
},
{
"code": null,
"e": 4094,
"s": 3988,
"text": "Drill can scale data from a single node to thousands of nodes and query petabytes of data within seconds."
},
{
"code": null,
"e": 4133,
"s": 4094,
"text": "Drill supports user defined functions."
},
{
"code": null,
"e": 4172,
"s": 4133,
"text": "Drill supports user defined functions."
},
{
"code": null,
"e": 4286,
"s": 4172,
"text": "Drill's symmetrical architecture and simple installation makes it easy to deploy and operate very large clusters."
},
{
"code": null,
"e": 4400,
"s": 4286,
"text": "Drill's symmetrical architecture and simple installation makes it easy to deploy and operate very large clusters."
},
{
"code": null,
"e": 4459,
"s": 4400,
"text": "Drill has flexible data model and extensible architecture."
},
{
"code": null,
"e": 4518,
"s": 4459,
"text": "Drill has flexible data model and extensible architecture."
},
{
"code": null,
"e": 4619,
"s": 4518,
"text": "Drill columnar execution model performs SQL processing on complex data without flattening into rows."
},
{
"code": null,
"e": 4720,
"s": 4619,
"text": "Drill columnar execution model performs SQL processing on complex data without flattening into rows."
},
{
"code": null,
"e": 4744,
"s": 4720,
"text": "Supports large datasets"
},
{
"code": null,
"e": 4768,
"s": 4744,
"text": "Supports large datasets"
},
{
"code": null,
"e": 4842,
"s": 4768,
"text": "Following are some of the most significant key features of Apache Drill −"
},
{
"code": null,
"e": 4918,
"s": 4842,
"text": "Drill’s pluggable architecture enables connectivity to multiple datastores."
},
{
"code": null,
"e": 4994,
"s": 4918,
"text": "Drill’s pluggable architecture enables connectivity to multiple datastores."
},
{
"code": null,
"e": 5113,
"s": 4994,
"text": "Drill has a distributed execution engine for processing queries. Users can submit requests to any node in the cluster."
},
{
"code": null,
"e": 5232,
"s": 5113,
"text": "Drill has a distributed execution engine for processing queries. Users can submit requests to any node in the cluster."
},
{
"code": null,
"e": 5284,
"s": 5232,
"text": "Drill supports complex/multi-structured data types."
},
{
"code": null,
"e": 5336,
"s": 5284,
"text": "Drill supports complex/multi-structured data types."
},
{
"code": null,
"e": 5487,
"s": 5336,
"text": "Drill uses self-describing data where a schema is specified as a part of the data itself, so no need for centralized schema definitions or management."
},
{
"code": null,
"e": 5638,
"s": 5487,
"text": "Drill uses self-describing data where a schema is specified as a part of the data itself, so no need for centralized schema definitions or management."
},
{
"code": null,
"e": 5696,
"s": 5638,
"text": "Flexible deployment options either local node or cluster."
},
{
"code": null,
"e": 5754,
"s": 5696,
"text": "Flexible deployment options either local node or cluster."
},
{
"code": null,
"e": 5907,
"s": 5754,
"text": "Specialized memory management that reduces the amount of main memory that a program uses or references while running and eliminates garbage collections."
},
{
"code": null,
"e": 6060,
"s": 5907,
"text": "Specialized memory management that reduces the amount of main memory that a program uses or references while running and eliminates garbage collections."
},
{
"code": null,
"e": 6091,
"s": 6060,
"text": "Decentralized data management."
},
{
"code": null,
"e": 6122,
"s": 6091,
"text": "Decentralized data management."
},
{
"code": null,
"e": 6198,
"s": 6122,
"text": "Apache Drill can work along with a few other softwares, some of which are −"
},
{
"code": null,
"e": 6362,
"s": 6198,
"text": "Cloud JSON and Sensor Analytics − Drill’s columnar approach leverages to access JSON data and expose those data via REST API to apply sensor analytics information."
},
{
"code": null,
"e": 6526,
"s": 6362,
"text": "Cloud JSON and Sensor Analytics − Drill’s columnar approach leverages to access JSON data and expose those data via REST API to apply sensor analytics information."
},
{
"code": null,
"e": 6715,
"s": 6526,
"text": "Works well with Hive − Apache Drill serves as a complement to Hive deployments with low latency queries. Drill’s hive metastore integration exposes existing datasets at interactive speeds."
},
{
"code": null,
"e": 6904,
"s": 6715,
"text": "Works well with Hive − Apache Drill serves as a complement to Hive deployments with low latency queries. Drill’s hive metastore integration exposes existing datasets at interactive speeds."
},
{
"code": null,
"e": 7022,
"s": 6904,
"text": "SQL for NoSQL − Drill’s ODBC driver and powerful parallelization capabilities provide interactive query capabilities."
},
{
"code": null,
"e": 7140,
"s": 7022,
"text": "SQL for NoSQL − Drill’s ODBC driver and powerful parallelization capabilities provide interactive query capabilities."
},
{
"code": null,
"e": 7586,
"s": 7140,
"text": "Apache Drill comes with a flexible JSON-like data model to natively query and process complex/multi-structured data. The data does not need to be flattened or transformed either at the design time or runtime, which provides high performance for queries. Drill exposes an easy and high performance Java API to build custom functions. Apache Drill is built to scale to big data needs and is not restricted by memory available on the cluster nodes."
},
{
"code": null,
"e": 7745,
"s": 7586,
"text": "Drill has to integrate with a variety of data stores like relational data stores or non-relational data stores. It has the flexibility to add new data stores."
},
{
"code": null,
"e": 7818,
"s": 7745,
"text": "Traditional file system − Local files and NAS (Network Attached Storage)"
},
{
"code": null,
"e": 7891,
"s": 7818,
"text": "Traditional file system − Local files and NAS (Network Attached Storage)"
},
{
"code": null,
"e": 7936,
"s": 7891,
"text": "Hadoop − HDFS and MAPR-FS (MAPR-File System)"
},
{
"code": null,
"e": 7981,
"s": 7936,
"text": "Hadoop − HDFS and MAPR-FS (MAPR-File System)"
},
{
"code": null,
"e": 8049,
"s": 7981,
"text": "Cloud storage − Amazon S3, Google Cloud Storage, Azure Blob Storage"
},
{
"code": null,
"e": 8117,
"s": 8049,
"text": "Cloud storage − Amazon S3, Google Cloud Storage, Azure Blob Storage"
},
{
"code": null,
"e": 8125,
"s": 8117,
"text": "MongoDB"
},
{
"code": null,
"e": 8131,
"s": 8125,
"text": "HBase"
},
{
"code": null,
"e": 8136,
"s": 8131,
"text": "HIVE"
},
{
"code": null,
"e": 8144,
"s": 8136,
"text": "MapR-DB"
},
{
"code": null,
"e": 8291,
"s": 8144,
"text": "In this chapter, we will discuss about the nested data model, JSON, Apache Avro, nested query language along with some other components in detail."
},
{
"code": null,
"e": 8531,
"s": 8291,
"text": "Apache Drill supports various data models. The initial goal is to support the column-based format used by Dremel, then it is designed to support schema less models such as JSON, BSON (Binary JSON) and schema based models like Avro and CSV."
},
{
"code": null,
"e": 8986,
"s": 8531,
"text": "JSON (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. JSON format is used for serializing and transmitting structured data over network connection. It is primarily used to transmit data between a server and web applications. JSON is typically perceived as a format whose main advantage is that it is simple and lean. It can be used without knowing or caring about any underlying schema."
},
{
"code": null,
"e": 9075,
"s": 8986,
"text": "Following is a basic JSON schema, which covers a classical product catalog description −"
},
{
"code": null,
"e": 9611,
"s": 9075,
"text": "{\n \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n \"title\": \"Product\",\n \"description\": “Classical product catalog\",\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"description\": \"The unique identifier for a product\",\n \"type\": \"integer\"\n },\n \"name\": {\n \"description\": \"Name of the product\",\n \"type\": \"string\"\n },\n \"price\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"exclusiveMinimum\": true\n }\n },\n \"required\": [\"id\", \"name\", \"price\"]\n}"
},
{
"code": null,
"e": 9844,
"s": 9611,
"text": "The JSON Schema has the capability to express basic definitions and constraints for data types contained in objects, and it also supports some more advanced features such as properties typed as other objects, inheritance, and links."
},
{
"code": null,
"e": 10456,
"s": 9844,
"text": "Avro is an Apache open source project that provides data serialization and data exchange services for Hadoop. These services can be used together or independently. Avro is a schema-based system. A language-independent schema is associated with its read and write operations. Using Avro, big data can be exchanged between programs written in any language. Avro supports a rich set of primitive data types including numeric, binary data and strings, and a number of complex types including arrays, maps, enumerations and records. A key feature of Avro is the robust support for data schemas that change over time."
},
{
"code": null,
"e": 10592,
"s": 10456,
"text": "Avro schema is created in JavaScript Object Notation (JSON) document format, which is a lightweight text-based data interchange format."
},
{
"code": null,
"e": 10604,
"s": 10592,
"text": "For example"
},
{
"code": null,
"e": 10764,
"s": 10604,
"text": "The given schema defines a (record type) document within \"AvroSample\" namespace. The name of document is \"Employee\" which contains two \"Fields\" → Name and Age."
},
{
"code": null,
"e": 10964,
"s": 10764,
"text": "{\n \" type \" : \"record\",\n \" namespace \" : \"AvroSample\",\n \" name \" : \"Employee\",\n \" fields \" : [\n { \"name\" : \" Name\" , \"type\" : \"string\" },\n { \"name\" : \"age\" , \"type\" : \"int\" }\n ]\n}"
},
{
"code": null,
"e": 11047,
"s": 10964,
"text": "The above schema contains four attributes, they have been briefly described here −"
},
{
"code": null,
"e": 11103,
"s": 11047,
"text": "type − Describes document type, in this case a “record\""
},
{
"code": null,
"e": 11159,
"s": 11103,
"text": "type − Describes document type, in this case a “record\""
},
{
"code": null,
"e": 11235,
"s": 11159,
"text": "namespace − Describes the name of the namespace in which the object resides"
},
{
"code": null,
"e": 11311,
"s": 11235,
"text": "namespace − Describes the name of the namespace in which the object resides"
},
{
"code": null,
"e": 11344,
"s": 11311,
"text": "name − Describes the schema name"
},
{
"code": null,
"e": 11377,
"s": 11344,
"text": "name − Describes the schema name"
},
{
"code": null,
"e": 11442,
"s": 11377,
"text": "fields − This is an attribute array which contains the following"
},
{
"code": null,
"e": 11507,
"s": 11442,
"text": "fields − This is an attribute array which contains the following"
},
{
"code": null,
"e": 11542,
"s": 11507,
"text": "name − Describes the name of field"
},
{
"code": null,
"e": 11577,
"s": 11542,
"text": "name − Describes the name of field"
},
{
"code": null,
"e": 11613,
"s": 11577,
"text": "type − Describes data type of field"
},
{
"code": null,
"e": 11649,
"s": 11613,
"text": "type − Describes data type of field"
},
{
"code": null,
"e": 11865,
"s": 11649,
"text": "Apache Drill supports various query languages. The initial goal is to support the SQL-like language used by Dremel and Google BigQuery. DrQL and Mongo query languages are an examples of Drill nested query languages."
},
{
"code": null,
"e": 12035,
"s": 11865,
"text": "The DrQL (Drill Query Language) is a nested query language. DrQL is SQL like query language for nested data. It is designed to support efficient column-based processing."
},
{
"code": null,
"e": 12327,
"s": 12035,
"text": "The MongoDB is an open-source document database, and leading NoSQL database. MongoDB is written in C++ and it is a cross-platform, document-oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on the concept of collection and documenting."
},
{
"code": null,
"e": 12506,
"s": 12327,
"text": "Wherein, collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. A document is a set of key-value pairs."
},
{
"code": null,
"e": 12739,
"s": 12506,
"text": "Drill supports various file formats such as CSV, TSV, PSV, JSON and Parquet. Wherein, “Parquet” is the special file format which helps Drill to run faster and its data representation is almost identical to Drill data representation."
},
{
"code": null,
"e": 13078,
"s": 12739,
"text": "Parquet is a columnar storage format in the Hadoop ecosystem. Compared to a traditional row-oriented format, it is much more efficient in storage and has better query performance. Parquet stores binary data in a column-oriented way, where the values of each column are organized so that they are all adjacent, enabling better compression."
},
{
"code": null,
"e": 13127,
"s": 13078,
"text": "It has the following important characteristics −"
},
{
"code": null,
"e": 13155,
"s": 13127,
"text": "Self-describing data format"
},
{
"code": null,
"e": 13171,
"s": 13155,
"text": "Columnar format"
},
{
"code": null,
"e": 13200,
"s": 13171,
"text": "Flexible compression options"
},
{
"code": null,
"e": 13216,
"s": 13200,
"text": "Large file size"
},
{
"code": null,
"e": 13344,
"s": 13216,
"text": "The Apache Drill allows access to structured file types and plain text files (flat files). It consists of the following types −"
},
{
"code": null,
"e": 13379,
"s": 13344,
"text": "CSV files (comma-separated values)"
},
{
"code": null,
"e": 13412,
"s": 13379,
"text": "TSV files (tab-separated values)"
},
{
"code": null,
"e": 13446,
"s": 13412,
"text": "PSV files (pipe-separated values)"
},
{
"code": null,
"e": 13673,
"s": 13446,
"text": "CSV file format − A CSV is a comma separated values file, which allows data to be saved in a table structured format. CSV data fields are often separated or delimited by comma (,). The following example refers to a CSV format."
},
{
"code": null,
"e": 13707,
"s": 13673,
"text": "firstname, age\nAlice,21\nPeter,34\n"
},
{
"code": null,
"e": 13775,
"s": 13707,
"text": "This CSV format can be defined as follows in a drill configuration."
},
{
"code": null,
"e": 13899,
"s": 13775,
"text": "\"formats\": {\n \"csv\": {\n \"type\": \"text\",\n \"extensions\": [\n “csv2\"\n ],\n \"delimiter\": “,”\n }\n}"
},
{
"code": null,
"e": 14071,
"s": 13899,
"text": "TSV file format − The TSV data fields are often separated or delimited by a tab and saved with an extension of “.tsv\" format. The following example refers to a TSV format."
},
{
"code": null,
"e": 14104,
"s": 14071,
"text": "firstname age\nAlice 21\nPeter 34\n"
},
{
"code": null,
"e": 14171,
"s": 14104,
"text": "The TSV format can be defined as follows in a drill configuration."
},
{
"code": null,
"e": 14260,
"s": 14171,
"text": "\"tsv\": {\n \"type\": \"text\",\n \"extensions\": [\n \"tsv\"\n ],\n \"delimiter\": “\\t\"\n},"
},
{
"code": null,
"e": 14393,
"s": 14260,
"text": "PSV file format − The PSV data fields are separated or delimited by a pipe (|) symbol. The following example refers to a PSV format."
},
{
"code": null,
"e": 14426,
"s": 14393,
"text": "firstname|age\nAlice|21\nPeter|34\n"
},
{
"code": null,
"e": 14493,
"s": 14426,
"text": "The PSV format can be defined as follows in a drill configuration."
},
{
"code": null,
"e": 14616,
"s": 14493,
"text": "\"formats\": {\n \"psv\": {\n \"type\": \"text\",\n \"extensions\": [\n \"tbl\"\n ],\n \"delimiter\": \"|\"\n }\n}"
},
{
"code": null,
"e": 14678,
"s": 14616,
"text": "These PSV files are saved with an extension of “.tbl” format."
},
{
"code": null,
"e": 14990,
"s": 14678,
"text": "Managing millions of data from multiple data sources requires a great deal of planning. When creating your data model, you need to consider the key goals such as the impact on speed of processing, how you can optimize memory usage and performance, scalability when handling growing volumes of data and requests."
},
{
"code": null,
"e": 15160,
"s": 14990,
"text": "Apache Drill provides the flexibility to immediately query complex data in native formats, such as schema-less data, nested data, and data with rapidly evolving schemas."
},
{
"code": null,
"e": 15292,
"s": 15160,
"text": "High-performance analysis of data in its native format including self-describing data such as Parquet, JSON files and HBase tables."
},
{
"code": null,
"e": 15424,
"s": 15292,
"text": "High-performance analysis of data in its native format including self-describing data such as Parquet, JSON files and HBase tables."
},
{
"code": null,
"e": 15529,
"s": 15424,
"text": "Direct querying of data in HBase tables without defining and maintaining a schema in the Hive metastore."
},
{
"code": null,
"e": 15634,
"s": 15529,
"text": "Direct querying of data in HBase tables without defining and maintaining a schema in the Hive metastore."
},
{
"code": null,
"e": 15756,
"s": 15634,
"text": "SQL to query and work with semi-structured/nested data, such as data from NoSQL stores like MongoDB and online REST APIs."
},
{
"code": null,
"e": 15878,
"s": 15756,
"text": "SQL to query and work with semi-structured/nested data, such as data from NoSQL stores like MongoDB and online REST APIs."
},
{
"code": null,
"e": 15930,
"s": 15878,
"text": "Apache Drill can connect to the following clients −"
},
{
"code": null,
"e": 15995,
"s": 15930,
"text": "Multiple interfaces such as JDBC, ODBC, C++ API, REST using JSON"
},
{
"code": null,
"e": 16007,
"s": 15995,
"text": "Drill shell"
},
{
"code": null,
"e": 16049,
"s": 16007,
"text": "Drill web console (http://localhost:8047)"
},
{
"code": null,
"e": 16095,
"s": 16049,
"text": "BI tools such as Tableau, MicroStrategy, etc."
},
{
"code": null,
"e": 16101,
"s": 16095,
"text": "Excel"
},
{
"code": null,
"e": 16290,
"s": 16101,
"text": "As of now, you are aware of the Apache Drill fundamentals. This chapter will explain about its architecture in detail. Following is a diagram that illustrates the Apache Drill core module."
},
{
"code": null,
"e": 16399,
"s": 16290,
"text": "The above diagram consists of different components. Let’s take a look at each of these components in detail."
},
{
"code": null,
"e": 16634,
"s": 16399,
"text": "DrillBit − Apache Drill consists of a Daemon service called the DrillBit. It is responsible for accepting requests from the client, processing queries, and returning results to the client. There is no master-slave concept in DrillBit."
},
{
"code": null,
"e": 16869,
"s": 16634,
"text": "DrillBit − Apache Drill consists of a Daemon service called the DrillBit. It is responsible for accepting requests from the client, processing queries, and returning results to the client. There is no master-slave concept in DrillBit."
},
{
"code": null,
"e": 16980,
"s": 16869,
"text": "SQL Parser − The SQL parser parses all the incoming queries based on the open source framework called Calcite."
},
{
"code": null,
"e": 17091,
"s": 16980,
"text": "SQL Parser − The SQL parser parses all the incoming queries based on the open source framework called Calcite."
},
{
"code": null,
"e": 17383,
"s": 17091,
"text": "Logical Plan − A Logical plan describes the abstract data flow of a query. Once a query is parsed into a logical plan, the Drill optimizer determines the most efficient execution plan using a variety of rule-based and cost-based techniques, translating the logical plan into a physical plan."
},
{
"code": null,
"e": 17675,
"s": 17383,
"text": "Logical Plan − A Logical plan describes the abstract data flow of a query. Once a query is parsed into a logical plan, the Drill optimizer determines the most efficient execution plan using a variety of rule-based and cost-based techniques, translating the logical plan into a physical plan."
},
{
"code": null,
"e": 18050,
"s": 17675,
"text": "Optimizer − Apache Drill uses various database optimizations such as rule based/cost based, as well as other optimization rules exposed by the storage engine to re-write and split the query. The output of the optimizer is a distributed physical query plan. Optimization in Drill is pluggable so you can provide rules for optimization at various parts of the query execution."
},
{
"code": null,
"e": 18425,
"s": 18050,
"text": "Optimizer − Apache Drill uses various database optimizations such as rule based/cost based, as well as other optimization rules exposed by the storage engine to re-write and split the query. The output of the optimizer is a distributed physical query plan. Optimization in Drill is pluggable so you can provide rules for optimization at various parts of the query execution."
},
{
"code": null,
"e": 18760,
"s": 18425,
"text": "Physical Plan − A Physical plan is also called as the execution plan. It represents the most efficient and fastest way to execute the query across the different nodes in the cluster. The physical plan is a DAG (directed acyclic graph) of physical operators, and each parent-child relationship implies how data flows through the graph."
},
{
"code": null,
"e": 19095,
"s": 18760,
"text": "Physical Plan − A Physical plan is also called as the execution plan. It represents the most efficient and fastest way to execute the query across the different nodes in the cluster. The physical plan is a DAG (directed acyclic graph) of physical operators, and each parent-child relationship implies how data flows through the graph."
},
{
"code": null,
"e": 19332,
"s": 19095,
"text": "Storage Engine interface − A Storage plugin interfaces in Drill represent the abstractions that Drill uses to interact with the data sources. The plugins are extensible, allowing you to write new plugins for any additional data sources."
},
{
"code": null,
"e": 19569,
"s": 19332,
"text": "Storage Engine interface − A Storage plugin interfaces in Drill represent the abstractions that Drill uses to interact with the data sources. The plugins are extensible, allowing you to write new plugins for any additional data sources."
},
{
"code": null,
"e": 19632,
"s": 19569,
"text": "The following image shows a DrillBit query execution diagram −"
},
{
"code": null,
"e": 19681,
"s": 19632,
"text": "The above diagram involves the following steps −"
},
{
"code": null,
"e": 19775,
"s": 19681,
"text": "The Drill client issues a query. Any Drillbit in the cluster can accept queries from clients."
},
{
"code": null,
"e": 19869,
"s": 19775,
"text": "The Drill client issues a query. Any Drillbit in the cluster can accept queries from clients."
},
{
"code": null,
"e": 20001,
"s": 19869,
"text": "A Drillbit then parses the query, optimizes it, and generates an optimized distributed query plan for fast and efficient execution."
},
{
"code": null,
"e": 20133,
"s": 20001,
"text": "A Drillbit then parses the query, optimizes it, and generates an optimized distributed query plan for fast and efficient execution."
},
{
"code": null,
"e": 20307,
"s": 20133,
"text": "The Drillbit that accepts the initial query becomes the Foreman (driving Drillbit) for the request. It gets a list of available Drillbit nodes in the cluster from ZooKeeper."
},
{
"code": null,
"e": 20481,
"s": 20307,
"text": "The Drillbit that accepts the initial query becomes the Foreman (driving Drillbit) for the request. It gets a list of available Drillbit nodes in the cluster from ZooKeeper."
},
{
"code": null,
"e": 20663,
"s": 20481,
"text": "The foreman gets a list of available Drillbit nodes in the cluster from ZooKeeper and schedules the execution of query fragments on individual nodes according to the execution plan."
},
{
"code": null,
"e": 20845,
"s": 20663,
"text": "The foreman gets a list of available Drillbit nodes in the cluster from ZooKeeper and schedules the execution of query fragments on individual nodes according to the execution plan."
},
{
"code": null,
"e": 20921,
"s": 20845,
"text": "The individual nodes finish their execution and return data to the foreman."
},
{
"code": null,
"e": 20997,
"s": 20921,
"text": "The individual nodes finish their execution and return data to the foreman."
},
{
"code": null,
"e": 21057,
"s": 20997,
"text": "The foreman finally returns the results back to the client."
},
{
"code": null,
"e": 21117,
"s": 21057,
"text": "The foreman finally returns the results back to the client."
},
{
"code": null,
"e": 21230,
"s": 21117,
"text": "This chapter will cover how to install Apache Drill on your machine. We have two modes of installation in Drill."
},
{
"code": null,
"e": 21358,
"s": 21230,
"text": "Embedded mode − This mode refers to install Drill on a single node (local) on your machine. It doesn’t require ZooKeeper setup."
},
{
"code": null,
"e": 21486,
"s": 21358,
"text": "Embedded mode − This mode refers to install Drill on a single node (local) on your machine. It doesn’t require ZooKeeper setup."
},
{
"code": null,
"e": 21754,
"s": 21486,
"text": "Distributed mode − Install Apache Drill on a distributed environment. ZooKeeper is mandatory for this mode because it co-ordinates clusters. Once you installed successfully, then you will be able to connect and query Hive, HBase or any other distributed data sources."
},
{
"code": null,
"e": 22022,
"s": 21754,
"text": "Distributed mode − Install Apache Drill on a distributed environment. ZooKeeper is mandatory for this mode because it co-ordinates clusters. Once you installed successfully, then you will be able to connect and query Hive, HBase or any other distributed data sources."
},
{
"code": null,
"e": 22088,
"s": 22022,
"text": "Now let’s continue with the embedded mode steps for installation."
},
{
"code": null,
"e": 22225,
"s": 22088,
"text": "Embedded mode is a quick way to install. You can install Apache Drill in the embedded mode on Linux, Mac OS or Windows Operating System."
},
{
"code": null,
"e": 22336,
"s": 22225,
"text": "Hopefully, you have already installed java on your machine, so you just verify it using the following command."
},
{
"code": null,
"e": 22353,
"s": 22336,
"text": "$ java -version\n"
},
{
"code": null,
"e": 22527,
"s": 22353,
"text": "If Java is successfully installed on your machine, you could see the version of installed Java. Otherwise download the latest version of JDK by visiting the following link −"
},
{
"code": null,
"e": 22594,
"s": 22527,
"text": "http://www.oracle.com/technetwork/java/javase/downloads/index.html"
},
{
"code": null,
"e": 22770,
"s": 22594,
"text": "After downloading the latest version, extract those files, move to the directory after setting the path and add Java alternatives. Then Java will be installed on your machine."
},
{
"code": null,
"e": 22847,
"s": 22770,
"text": "Download the latest version of Apache Drill by visiting the following link −"
},
{
"code": null,
"e": 22928,
"s": 22847,
"text": "http://www.apache.org/dyn/closer.cgi/drill/drill-1.6.0/apache-drill-1.6.0.tar.gz"
},
{
"code": null,
"e": 22994,
"s": 22928,
"text": "Now apache-drill-1.6.0.tar.gz will be downloaded on your machine."
},
{
"code": null,
"e": 23058,
"s": 22994,
"text": "You can then extract the tar file using the following program −"
},
{
"code": null,
"e": 23125,
"s": 23058,
"text": "$ cd opt/\n$ tar apache-drill-1.6.0.tar.gz\n$ cd apache-drill-1.6.0\n"
},
{
"code": null,
"e": 23306,
"s": 23125,
"text": "To start the Drill shell in the embedded mode, use the following command. Internally, the command uses a jdbc connection string and identifies the local node as the ZooKeeper node."
},
{
"code": null,
"e": 23328,
"s": 23306,
"text": "$ bin/drill-embedded\n"
},
{
"code": null,
"e": 23384,
"s": 23328,
"text": "After the command, you can see the following response −"
},
{
"code": null,
"e": 23413,
"s": 23384,
"text": "$ 0: jdbc:drill:zk = local>\n"
},
{
"code": null,
"e": 23420,
"s": 23413,
"text": "Where,"
},
{
"code": null,
"e": 23502,
"s": 23420,
"text": "0 − is the number of connections to Drill, which can be only one in embedded node"
},
{
"code": null,
"e": 23584,
"s": 23502,
"text": "0 − is the number of connections to Drill, which can be only one in embedded node"
},
{
"code": null,
"e": 23614,
"s": 23584,
"text": "jdbc − is the connection type"
},
{
"code": null,
"e": 23644,
"s": 23614,
"text": "jdbc − is the connection type"
},
{
"code": null,
"e": 23713,
"s": 23644,
"text": "zk = local − means the local node substitutes for the ZooKeeper node"
},
{
"code": null,
"e": 23782,
"s": 23713,
"text": "zk = local − means the local node substitutes for the ZooKeeper node"
},
{
"code": null,
"e": 23855,
"s": 23782,
"text": "Once you get this prompt, you will be able to run your queries on Drill."
},
{
"code": null,
"e": 23910,
"s": 23855,
"text": "To exit the Drill shell, issue the following command −"
},
{
"code": null,
"e": 23919,
"s": 23910,
"text": "$ !quit\n"
},
{
"code": null,
"e": 24029,
"s": 23919,
"text": "You will have to follow the subsequent steps to ensure a proper Distributed Mode Installation on your system."
},
{
"code": null,
"e": 24046,
"s": 24029,
"text": "$ java -version\n"
},
{
"code": null,
"e": 24216,
"s": 24046,
"text": "If java is successfully installed on your machine, you could see the version of installed Java. Otherwise download latest version of JDK by visiting the following link −"
},
{
"code": null,
"e": 24284,
"s": 24216,
"text": "\nhttp://www.oracle.com/technetwork/java/javase/downloads/index.html"
},
{
"code": null,
"e": 24471,
"s": 24284,
"text": "After downloading the latest version, extract those files and move them to the directory after setting the path and adding Java alternatives. Then Java will be installed on your machine."
},
{
"code": null,
"e": 24601,
"s": 24471,
"text": "Hopefully, you have installed Apache ZooKeeper on your machine. To verify the installation, you can issue the following command −"
},
{
"code": null,
"e": 24626,
"s": 24601,
"text": "$ bin/zkServer.sh start\n"
},
{
"code": null,
"e": 24683,
"s": 24626,
"text": "Then you will get the following program on your screen −"
},
{
"code": null,
"e": 24804,
"s": 24683,
"text": "$ JMX enabled by default\n$ Using config: /Users/../zookeeper-3.4.6/bin/../conf/zoo.cfg\n$ Starting zookeeper ... STARTED\n"
},
{
"code": null,
"e": 24886,
"s": 24804,
"text": "\nhttp://www.apache.org/dyn/closer.cgi/drill/drill-1.6.0/apache-drill-1.6.0.tar.gz"
},
{
"code": null,
"e": 24952,
"s": 24886,
"text": "Now apache-drill-1.6.0.tar.gz will be downloaded on your machine."
},
{
"code": null,
"e": 25028,
"s": 24952,
"text": "The next step is to extract the tar file by issuing the following command −"
},
{
"code": null,
"e": 25095,
"s": 25028,
"text": "$ cd opt/\n$ tar apache-drill-1.6.0.tar.gz\n$ cd apache-drill-1.6.0\n"
},
{
"code": null,
"e": 25156,
"s": 25095,
"text": "Open the drill-override file by using the following command."
},
{
"code": null,
"e": 25187,
"s": 25156,
"text": "$ vi conf/drill-override.conf\n"
},
{
"code": null,
"e": 25230,
"s": 25187,
"text": "Then you will see the following response −"
},
{
"code": null,
"e": 25308,
"s": 25230,
"text": "drill.exec: {\n cluster-id: \"drillbits1\",\n zk.connect: \"localhost:2181\"\n}\n"
},
{
"code": null,
"e": 25447,
"s": 25308,
"text": "Here cluster-id: “drillbits1” indicates we have one instance running. If two or more instances are running, then drillbits also increases."
},
{
"code": null,
"e": 25510,
"s": 25447,
"text": "To start the drillbit shell you can use the following command."
},
{
"code": null,
"e": 25535,
"s": 25510,
"text": "$ bin/drillbit.sh start\n"
},
{
"code": null,
"e": 25578,
"s": 25535,
"text": "Then you will see the following response −"
},
{
"code": null,
"e": 25611,
"s": 25578,
"text": "$ 0: jdbc:drill:zk = <zk1host>:\n"
},
{
"code": null,
"e": 25674,
"s": 25611,
"text": "To exit the Drill shell, you can issue the following command −"
},
{
"code": null,
"e": 25713,
"s": 25674,
"text": "$ 0: jdbc:drill:zk = <zk1host>: !quit\n"
},
{
"code": null,
"e": 25811,
"s": 25713,
"text": "Navigate to the Drill installation directory, and issue the following command to stop a Drillbit."
},
{
"code": null,
"e": 25835,
"s": 25811,
"text": "$ bin/drillbit.sh stop\n"
},
{
"code": null,
"e": 25909,
"s": 25835,
"text": "Apache Drill Web Console is one of the client interfaces to access Drill."
},
{
"code": null,
"e": 26019,
"s": 25909,
"text": "To open this Drill Web Console, launch a web browser, and then type the following URL –\nhttp://localhost:8047"
},
{
"code": null,
"e": 26095,
"s": 26019,
"text": "Now you will see the following screen which is similar to the Query option."
},
{
"code": null,
"e": 26295,
"s": 26095,
"text": "Apache Drill is an open-source SQL-On-Everything engine. It allows SQL queries to be executed on any kind of data source, ranging from a simple CSV file to an advanced SQL and NoSQL database servers."
},
{
"code": null,
"e": 26426,
"s": 26295,
"text": "To execute a query in a Drill shell, open your terminal move to the Drill installed directory and then type the following command."
},
{
"code": null,
"e": 26448,
"s": 26426,
"text": "$ bin/drill-embedded\n"
},
{
"code": null,
"e": 26514,
"s": 26448,
"text": "Then you will see the response as shown in the following program."
},
{
"code": null,
"e": 26541,
"s": 26514,
"text": "0: jdbc:drill:zk = local>\n"
},
{
"code": null,
"e": 26733,
"s": 26541,
"text": "Now you can execute your queries. Otherwise you can run your queries through web console application to the url of http://localhost:8047. If you need any help info type the following command."
},
{
"code": null,
"e": 26768,
"s": 26733,
"text": "$ 0: jdbc:drill:zk = local> !help\n"
},
{
"code": null,
"e": 26824,
"s": 26768,
"text": "Apache Drill supports the following list of data types."
},
{
"code": null,
"e": 26831,
"s": 26824,
"text": "BIGINT"
},
{
"code": null,
"e": 26922,
"s": 26831,
"text": "8-byte signed integer in the range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807"
},
{
"code": null,
"e": 26929,
"s": 26922,
"text": "BINARY"
},
{
"code": null,
"e": 26957,
"s": 26929,
"text": "Variable-length byte string"
},
{
"code": null,
"e": 26965,
"s": 26957,
"text": "BOOLEAN"
},
{
"code": null,
"e": 26979,
"s": 26965,
"text": "True or false"
},
{
"code": null,
"e": 26984,
"s": 26979,
"text": "DATE"
},
{
"code": null,
"e": 27043,
"s": 26984,
"text": "Years, months, and days in YYYY-MM-DD format since 4713 BC"
},
{
"code": null,
"e": 27084,
"s": 27043,
"text": "DECIMAL(p,s), DEC(p,s), or NUMERIC(p,s)*"
},
{
"code": null,
"e": 27142,
"s": 27084,
"text": "38-digit precision number, precision is p, and scale is s"
},
{
"code": null,
"e": 27157,
"s": 27142,
"text": "INTEGER or INT"
},
{
"code": null,
"e": 27224,
"s": 27157,
"text": "4-byte signed integer in the range -2,147,483,648 to 2,147,483,647"
},
{
"code": null,
"e": 27233,
"s": 27224,
"text": "INTERVAL"
},
{
"code": null,
"e": 27267,
"s": 27233,
"text": "A day-time or year-month interval"
},
{
"code": null,
"e": 27276,
"s": 27267,
"text": "SMALLINT"
},
{
"code": null,
"e": 27329,
"s": 27276,
"text": "2-byte signed integer in the range -32,768 to 32,767"
},
{
"code": null,
"e": 27335,
"s": 27329,
"text": "FLOAT"
},
{
"code": null,
"e": 27364,
"s": 27335,
"text": "4-byte floating point number"
},
{
"code": null,
"e": 27371,
"s": 27364,
"text": "DOUBLE"
},
{
"code": null,
"e": 27400,
"s": 27371,
"text": "8-byte floating point number"
},
{
"code": null,
"e": 27405,
"s": 27400,
"text": "TIME"
},
{
"code": null,
"e": 27468,
"s": 27405,
"text": "24-hour based time in hours, minutes, seconds format: HH:mm:ss"
},
{
"code": null,
"e": 27478,
"s": 27468,
"text": "TIMESTAMP"
},
{
"code": null,
"e": 27594,
"s": 27478,
"text": "JDBC timestamp in year, month, date hour, minute, second, and optional milliseconds format: yyyy-MM-dd HH:mm:ss.SSS"
},
{
"code": null,
"e": 27629,
"s": 27594,
"text": "CHARACTER VARYING, CHAR or VARCHAR"
},
{
"code": null,
"e": 27733,
"s": 27629,
"text": "variable-length string. The default limit is 1 character. The maximum character limit is 2,147,483,647."
},
{
"code": null,
"e": 27789,
"s": 27733,
"text": "Let us continue with simple examples on the data types."
},
{
"code": null,
"e": 28014,
"s": 27789,
"text": "Apache Drill supports time functions in the range from 1971 to 2037. The processing logic of data types can be easily tested by “VALUES()” statement. The following query returns date, time and timestamp for the given values."
},
{
"code": null,
"e": 28135,
"s": 28014,
"text": "0: jdbc:drill:zk = local> select DATE '2016-04-07',\n TIME '12:12:23',TIMESTAMP '2016-04-07 12:12:23' from (values(1));"
},
{
"code": null,
"e": 28401,
"s": 28135,
"text": "+-------------+-----------+------------------------+\n| EXPR$0 | EXPR$1 | EXPR$2 |\n+-------------+-----------+------------------------+\n| 2016-04-07 | 12:12:23 | 2016-04-07 12:12:23.0 |\n+-------------+-----------+------------------------+\n"
},
{
"code": null,
"e": 28477,
"s": 28401,
"text": "The INTERVALYEAR and INTERVALDAY internal types represent a period of time."
},
{
"code": null,
"e": 28540,
"s": 28477,
"text": "The INTERVALYEAR type specifies values from a year to a month."
},
{
"code": null,
"e": 28601,
"s": 28540,
"text": "The INTERVALDAY type specifies values from a day to seconds."
},
{
"code": null,
"e": 28711,
"s": 28601,
"text": "0: jdbc:drill:zk = local> select timestamp '2016-04-07 12:45:50' +\n interval '10' year(2) from (values(1));"
},
{
"code": null,
"e": 28878,
"s": 28711,
"text": "+------------------------+\n| EXPR$0 |\n+------------------------+\n| 2026-04-07 12:45:50.0 |\n+———————————————————————-+\n1 row selected (0.251 seconds)\n"
},
{
"code": null,
"e": 29091,
"s": 28878,
"text": "In the above query, INTERVAL keyword followed by 10 adds 10 years to the timestamp. The 2 in parentheses in YEAR(2) specifies the precision of the year interval, 2 digits in this case to support the ten interval."
},
{
"code": null,
"e": 29199,
"s": 29091,
"text": "0: jdbc:drill:zk = local> select timestamp '2016-04-07 12:45:52' +\n interval '1' day(1) from (values(1));"
},
{
"code": null,
"e": 29335,
"s": 29199,
"text": "+------------------------+\n| EXPR$0 |\n+------------------------+\n| 2016-04-08 12:45:52.0 |\n+———————————————————————-+\n"
},
{
"code": null,
"e": 29416,
"s": 29335,
"text": "Here INTERVAL ‘1’ indicates that two days will be added from that specified day."
},
{
"code": null,
"e": 29500,
"s": 29416,
"text": "The following operators are used in Apache Drill to perform the desired operations."
},
{
"code": null,
"e": 29518,
"s": 29500,
"text": "Logical Operators"
},
{
"code": null,
"e": 29553,
"s": 29518,
"text": "AND, BETWEEN, IN , LIKE , NOT , OR"
},
{
"code": null,
"e": 29574,
"s": 29553,
"text": "Comparison Operators"
},
{
"code": null,
"e": 29706,
"s": 29574,
"text": "<, > , <= , >= , = , <> , IS NULL , IS NOT NULL , IS FALSE , IS NOT FALSE , IS TRUE , IS NOT TRUE,\nPattern Matching Operator - LIKE"
},
{
"code": null,
"e": 29721,
"s": 29706,
"text": "Math Operators"
},
{
"code": null,
"e": 29729,
"s": 29721,
"text": "+,-,*,/"
},
{
"code": null,
"e": 29748,
"s": 29729,
"text": "Subquery Operators"
},
{
"code": null,
"e": 29759,
"s": 29748,
"text": "EXISTS, IN"
},
{
"code": null,
"e": 29903,
"s": 29759,
"text": "Apache Drill scalar functions supports Math and Trig functions. Most scalar functions use data types such as INTEGER, BIGINT, FLOAT and DOUBLE."
},
{
"code": null,
"e": 29979,
"s": 29903,
"text": "The following table describes the list of “Math functions” in Apache Drill."
},
{
"code": null,
"e": 29986,
"s": 29979,
"text": "ABS(x)"
},
{
"code": null,
"e": 30038,
"s": 29986,
"text": "Returns the absolute value of the input argument x."
},
{
"code": null,
"e": 30046,
"s": 30038,
"text": "CBRT(x)"
},
{
"code": null,
"e": 30075,
"s": 30046,
"text": "Returns the cubic root of x."
},
{
"code": null,
"e": 30083,
"s": 30075,
"text": "CEIL(x)"
},
{
"code": null,
"e": 30129,
"s": 30083,
"text": "Returns the smallest integer not less than x."
},
{
"code": null,
"e": 30140,
"s": 30129,
"text": "CEILING(x)"
},
{
"code": null,
"e": 30154,
"s": 30140,
"text": "Same as CEIL."
},
{
"code": null,
"e": 30165,
"s": 30154,
"text": "DEGREES(x)"
},
{
"code": null,
"e": 30196,
"s": 30165,
"text": "Converts x radians to degrees."
},
{
"code": null,
"e": 30203,
"s": 30196,
"text": "EXP(x)"
},
{
"code": null,
"e": 30249,
"s": 30203,
"text": "Returns e (Euler's number) to the power of x."
},
{
"code": null,
"e": 30258,
"s": 30249,
"text": "FLOOR(x)"
},
{
"code": null,
"e": 30306,
"s": 30258,
"text": "Returns the largest integer not greater than x."
},
{
"code": null,
"e": 30316,
"s": 30306,
"text": "LOG(x, y)"
},
{
"code": null,
"e": 30351,
"s": 30316,
"text": "Returns log base x to the y power."
},
{
"code": null,
"e": 30523,
"s": 30351,
"text": "Now let’s run queries for the scalar functions. The Drill scalar functions can be easily tested by the values() statement, otherwise you can also use the select statement."
},
{
"code": null,
"e": 30634,
"s": 30523,
"text": "Apache Drill supports the following trig functions and these functions’ return type is a floating point value."
},
{
"code": null,
"e": 30641,
"s": 30634,
"text": "SIN(x)"
},
{
"code": null,
"e": 30668,
"s": 30641,
"text": "Sine of angle x in radians"
},
{
"code": null,
"e": 30676,
"s": 30668,
"text": "ACOS(x)"
},
{
"code": null,
"e": 30713,
"s": 30676,
"text": "Inverse cosine of angle x in radians"
},
{
"code": null,
"e": 30720,
"s": 30713,
"text": "COSH()"
},
{
"code": null,
"e": 30771,
"s": 30720,
"text": "Hyperbolic cosine of hyperbolic angle x in radians"
},
{
"code": null,
"e": 30971,
"s": 30771,
"text": "In Apache Drill, you can cast or convert data to the required type for moving data from one data source to another. Drill also supports the following functions for casting and converting data types −"
},
{
"code": null,
"e": 30984,
"s": 30971,
"text": "CAST(x AS y)"
},
{
"code": null,
"e": 31000,
"s": 30984,
"text": "CONVERT_TO(x,y)"
},
{
"code": null,
"e": 31018,
"s": 31000,
"text": "CONVERT_FROM(x,y)"
},
{
"code": null,
"e": 31186,
"s": 31018,
"text": "Apache Drill supports time functions based on the Gregorian calendar and in the range from 1971 to 2037. The following table describes the list of Date/Time functions."
},
{
"code": null,
"e": 31201,
"s": 31186,
"text": "AGE(x [, y ] )"
},
{
"code": null,
"e": 31213,
"s": 31201,
"text": "INTERVALDAY"
},
{
"code": null,
"e": 31216,
"s": 31213,
"text": "or"
},
{
"code": null,
"e": 31229,
"s": 31216,
"text": "INTERVALYEAR"
},
{
"code": null,
"e": 31242,
"s": 31229,
"text": "CURRENT_DATE"
},
{
"code": null,
"e": 31255,
"s": 31242,
"text": "CURRENT_TIME"
},
{
"code": null,
"e": 31273,
"s": 31255,
"text": "CURRENT_TIMESTAMP"
},
{
"code": null,
"e": 31287,
"s": 31273,
"text": "DATE_SUB(x,y)"
},
{
"code": null,
"e": 31305,
"s": 31287,
"text": "EXTRACT(x FROM y)"
},
{
"code": null,
"e": 31367,
"s": 31305,
"text": "Extracts a time unit from a date or timestamp expression (y)."
},
{
"code": null,
"e": 31453,
"s": 31367,
"text": "This must be one of the following values: SECOND, MINUTE, HOUR, DAY, MONTH, and YEAR."
},
{
"code": null,
"e": 31463,
"s": 31453,
"text": "LOCALTIME"
},
{
"code": null,
"e": 31478,
"s": 31463,
"text": "LOCALTIMESTAMP"
},
{
"code": null,
"e": 31484,
"s": 31478,
"text": "NOW()"
},
{
"code": null,
"e": 31496,
"s": 31484,
"text": "TIMEOFDAY()"
},
{
"code": null,
"e": 31558,
"s": 31496,
"text": "Apache Drill supports the following list of string functions."
},
{
"code": null,
"e": 31583,
"s": 31558,
"text": "BYTE_SUBSTR(x,y [, z ] )"
},
{
"code": null,
"e": 31598,
"s": 31583,
"text": "CHAR_LENGTH(x)"
},
{
"code": null,
"e": 31610,
"s": 31598,
"text": "CONCAT(x,y)"
},
{
"code": null,
"e": 31621,
"s": 31610,
"text": "INITCAP(x)"
},
{
"code": null,
"e": 31631,
"s": 31621,
"text": "LENGTH(x)"
},
{
"code": null,
"e": 31640,
"s": 31631,
"text": "LOWER(x)"
},
{
"code": null,
"e": 31659,
"s": 31640,
"text": "LPAD(x,y [ , z ] )"
},
{
"code": null,
"e": 31795,
"s": 31659,
"text": "The value of x is filled in the front (the left-hand side) with the value of z until the total length of the value is equal y’s length."
},
{
"code": null,
"e": 31852,
"s": 31795,
"text": "If no z value then blanks are used to fill the position."
},
{
"code": null,
"e": 31861,
"s": 31852,
"text": "LTRIM(x)"
},
{
"code": null,
"e": 31879,
"s": 31861,
"text": "POSITION( x IN y)"
},
{
"code": null,
"e": 31901,
"s": 31879,
"text": "REGEXP_REPLACE(x,y,z)"
},
{
"code": null,
"e": 31913,
"s": 31901,
"text": "RPAD(x,y,z)"
},
{
"code": null,
"e": 31922,
"s": 31913,
"text": "RTRIM(x)"
},
{
"code": null,
"e": 31934,
"s": 31922,
"text": "STRPOS(x,y)"
},
{
"code": null,
"e": 31948,
"s": 31934,
"text": "SUBSTR(x,y,z)"
},
{
"code": null,
"e": 31957,
"s": 31948,
"text": "UPPER(x)"
},
{
"code": null,
"e": 32026,
"s": 31957,
"text": "Apache Drill supports the following list of null handling functions."
},
{
"code": null,
"e": 32053,
"s": 32026,
"text": "COALESCE(x, y [ , y ]... )"
},
{
"code": null,
"e": 32066,
"s": 32053,
"text": "NULLIF(x,y )"
},
{
"code": null,
"e": 32142,
"s": 32066,
"text": "The following table describes the list of “Math functions” in Apache Drill."
},
{
"code": null,
"e": 32146,
"s": 32142,
"text": "E()"
},
{
"code": null,
"e": 32173,
"s": 32146,
"text": "Returns 2.718281828459045."
},
{
"code": null,
"e": 32180,
"s": 32173,
"text": "LOG(x)"
},
{
"code": null,
"e": 32219,
"s": 32180,
"text": "Returns the natural log (base e) of x."
},
{
"code": null,
"e": 32228,
"s": 32219,
"text": "LOG10(x)"
},
{
"code": null,
"e": 32257,
"s": 32228,
"text": "Returns the common log of x."
},
{
"code": null,
"e": 32270,
"s": 32257,
"text": "LSHIFT(x, y)"
},
{
"code": null,
"e": 32314,
"s": 32270,
"text": "Shifts the binary x by y times to the left."
},
{
"code": null,
"e": 32324,
"s": 32314,
"text": "MOD(x, y)"
},
{
"code": null,
"e": 32365,
"s": 32324,
"text": "Returns the remainder of x divided by y."
},
{
"code": null,
"e": 32377,
"s": 32365,
"text": "NEGATIVE(x)"
},
{
"code": null,
"e": 32409,
"s": 32377,
"text": "Returns x as a negative number."
},
{
"code": null,
"e": 32412,
"s": 32409,
"text": "PI"
},
{
"code": null,
"e": 32424,
"s": 32412,
"text": "Returns pi."
},
{
"code": null,
"e": 32434,
"s": 32424,
"text": "POW(x, y)"
},
{
"code": null,
"e": 32473,
"s": 32434,
"text": "Returns the value of x to the y power."
},
{
"code": null,
"e": 32481,
"s": 32473,
"text": "RADIANS"
},
{
"code": null,
"e": 32512,
"s": 32481,
"text": "Converts x degrees to radians."
},
{
"code": null,
"e": 32517,
"s": 32512,
"text": "RAND"
},
{
"code": null,
"e": 32551,
"s": 32517,
"text": "Returns a random number from 0-1."
},
{
"code": null,
"e": 32560,
"s": 32551,
"text": "ROUND(x)"
},
{
"code": null,
"e": 32591,
"s": 32560,
"text": "Rounds to the nearest integer."
},
{
"code": null,
"e": 32603,
"s": 32591,
"text": "ROUND(x, y)"
},
{
"code": null,
"e": 32657,
"s": 32603,
"text": "Rounds x to y decimal places. Return type is decimal."
},
{
"code": null,
"e": 32670,
"s": 32657,
"text": "RSHIFT(x, y)"
},
{
"code": null,
"e": 32715,
"s": 32670,
"text": "Shifts the binary x by y times to the right."
},
{
"code": null,
"e": 32723,
"s": 32715,
"text": "SIGN(x)"
},
{
"code": null,
"e": 32746,
"s": 32723,
"text": "Returns the sign of x."
},
{
"code": null,
"e": 32754,
"s": 32746,
"text": "SQRT(x)"
},
{
"code": null,
"e": 32784,
"s": 32754,
"text": "Returns the square root of x."
},
{
"code": null,
"e": 32793,
"s": 32784,
"text": "TRUNC(x)"
},
{
"code": null,
"e": 32904,
"s": 32793,
"text": "Apache Drill supports the following trig functions and these functions’ return type is a floating point value."
},
{
"code": null,
"e": 32911,
"s": 32904,
"text": "COS(x)"
},
{
"code": null,
"e": 32940,
"s": 32911,
"text": "Cosine of angle x in radians"
},
{
"code": null,
"e": 32947,
"s": 32940,
"text": "TAN(x)"
},
{
"code": null,
"e": 32977,
"s": 32947,
"text": "Tangent of angle x in radians"
},
{
"code": null,
"e": 32985,
"s": 32977,
"text": "ASIN(x)"
},
{
"code": null,
"e": 33020,
"s": 32985,
"text": "Inverse sine of angle x in radians"
},
{
"code": null,
"e": 33028,
"s": 33020,
"text": "ATAN(x)"
},
{
"code": null,
"e": 33066,
"s": 33028,
"text": "Inverse tangent of angle x in radians"
},
{
"code": null,
"e": 33073,
"s": 33066,
"text": "SINH()"
},
{
"code": null,
"e": 33122,
"s": 33073,
"text": "Hyperbolic sine of hyperbolic angle x in radians"
},
{
"code": null,
"e": 33129,
"s": 33122,
"text": "TANH()"
},
{
"code": null,
"e": 33181,
"s": 33129,
"text": "Hyperbolic tangent of hyperbolic angle x in radians"
},
{
"code": null,
"e": 33244,
"s": 33181,
"text": "The following table describes the list of Date/Time functions."
},
{
"code": null,
"e": 33258,
"s": 33244,
"text": "DATE_ADD(x,y)"
},
{
"code": null,
"e": 33370,
"s": 33258,
"text": "Returns the sum of the sum of a date/time and a number of days/hours, or of a date/time and date/time interval."
},
{
"code": null,
"e": 33377,
"s": 33370,
"text": "Where,"
},
{
"code": null,
"e": 33405,
"s": 33377,
"text": "x - date, time or timestamp"
},
{
"code": null,
"e": 33444,
"s": 33405,
"text": "y - integer or an interval expression."
},
{
"code": null,
"e": 33459,
"s": 33444,
"text": "DATE_PART(x,y)"
},
{
"code": null,
"e": 33516,
"s": 33459,
"text": "Returns a field of a date, time, timestamp, or interval."
},
{
"code": null,
"e": 33523,
"s": 33516,
"text": "where,"
},
{
"code": null,
"e": 33569,
"s": 33523,
"text": "x - year, month, day, hour, minute, or second"
},
{
"code": null,
"e": 33616,
"s": 33569,
"text": "y - date, time, timestamp, or interval literal"
},
{
"code": null,
"e": 33640,
"s": 33616,
"text": "UNIX_TIMESTAMP ( [ x] )"
},
{
"code": null,
"e": 33752,
"s": 33640,
"text": "If x is specified as timestamp then the number of seconds since the UNIX epoch and the timestamp x is returned."
},
{
"code": null,
"e": 33864,
"s": 33752,
"text": "If x is not specified then it returns the number of seconds since the UNIX epoch (January 1, 1970 at 00:00:00)."
},
{
"code": null,
"e": 34003,
"s": 33864,
"text": "Apache Drill supports JSON format for querying data. Drill treats a JSON object as SQL record. One object equals one row in a Drill table."
},
{
"code": null,
"e": 34249,
"s": 34003,
"text": "Let us query the sample file, “employee.json” packaged as part of the drill. This sample file is Foodmart data packaged as JAR in Drill's classpath: ./jars/3rdparty/foodmart-data-json.0.4.jar. The sample file can be accessed using namespace, cp."
},
{
"code": null,
"e": 34346,
"s": 34249,
"text": "Start the Drill shell, and select the first row of data from the “employee.json” file installed."
},
{
"code": null,
"e": 34414,
"s": 34346,
"text": "0: jdbc:drill:zk = local> select * from cp.`employee.json` limit 1;"
},
{
"code": null,
"e": 35645,
"s": 34414,
"text": "+--------------+--------------+------------+------------+--------------+----------------+-----------+----------------+------------+-----------------------+---------+---------------+-----------------+----------------+--------+-------------------+\n| employee_id | full_name | first_name | last_name | position_id | position_title | store_id | department_id | birth_date | hire_date | salary | supervisor_id | education_level | marital_status | gender | management_role |\n+--------------+--------------+------------+------------+--------------+----------------+-----------+----------------+------------+-----------------------+---------+---------------+-----------------+----------------+--------+-------------------+\n| 1 | Sheri Nowmer | Sheri | Nowmer | 1 | President | 0 | 1 | 1961-08-26 | 1994-12-01 00:00:00.0 | 80000.0 | 0 | Graduate Degree | S | F | Senior Management |\n+--------------+--------------+------------+------------+--------------+----------------+-----------+----------------+------------+-----------------------+---------+---------------+-----------------+----------------+--------+-------------------+\n"
},
{
"code": null,
"e": 35699,
"s": 35645,
"text": "The same result can be viewed in the web console as −"
},
{
"code": null,
"e": 35880,
"s": 35699,
"text": "You can connect Drill to a file system through a storage plugin. On the Storage tab of the Drill Web Console (http://localhost:8047), you can view and reconfigure a storage plugin."
},
{
"code": null,
"e": 35965,
"s": 35880,
"text": "The Drill installation contains the following default storage plugin configurations."
},
{
"code": null,
"e": 36018,
"s": 35965,
"text": "cp − Points to the JAR files in the Drill classpath."
},
{
"code": null,
"e": 36071,
"s": 36018,
"text": "cp − Points to the JAR files in the Drill classpath."
},
{
"code": null,
"e": 36229,
"s": 36071,
"text": "dfs − Points to the local file system, but you can configure this storage plugin to point to any distributed file system, such as a Hadoop or S3 file system."
},
{
"code": null,
"e": 36387,
"s": 36229,
"text": "dfs − Points to the local file system, but you can configure this storage plugin to point to any distributed file system, such as a Hadoop or S3 file system."
},
{
"code": null,
"e": 36431,
"s": 36387,
"text": "hbase − Provides a connection to the HBase."
},
{
"code": null,
"e": 36475,
"s": 36431,
"text": "hbase − Provides a connection to the HBase."
},
{
"code": null,
"e": 36610,
"s": 36475,
"text": "hive − Integrates Drill with the Hive metadata abstraction of files, HBase, and libraries to read data and operate on SerDes and UDFs."
},
{
"code": null,
"e": 36745,
"s": 36610,
"text": "hive − Integrates Drill with the Hive metadata abstraction of files, HBase, and libraries to read data and operate on SerDes and UDFs."
},
{
"code": null,
"e": 36792,
"s": 36745,
"text": "mongo − Provides a connection to MongoDB data."
},
{
"code": null,
"e": 36839,
"s": 36792,
"text": "mongo − Provides a connection to MongoDB data."
},
{
"code": null,
"e": 36982,
"s": 36839,
"text": "Embedded mode − Apache Drill saves the storage plugin configurations in a temporary directory. The temporary directory clears when you reboot."
},
{
"code": null,
"e": 37125,
"s": 36982,
"text": "Embedded mode − Apache Drill saves the storage plugin configurations in a temporary directory. The temporary directory clears when you reboot."
},
{
"code": null,
"e": 37200,
"s": 37125,
"text": "Distributed mode − Drill saves storage plugin configurations in ZooKeeper."
},
{
"code": null,
"e": 37275,
"s": 37200,
"text": "Distributed mode − Drill saves storage plugin configurations in ZooKeeper."
},
{
"code": null,
"e": 37427,
"s": 37275,
"text": "The workspace defines the location of files in subdirectories of a local or distributed file system. One or more workspaces can be defined in a plugin."
},
{
"code": null,
"e": 37586,
"s": 37427,
"text": "As of now we have queried an already packaged “employee.json” file. Let us create a new JSON file named “student_list.json” as shown in the following program."
},
{
"code": null,
"e": 39644,
"s": 37586,
"text": "{\n \"ID\" : \"001\",\n \"name\" : \"Adam\",\n \"age\" : 12,\n \"gender\" : \"male\",\n \"standard\" : \"six\",\n \"mark1\" : 70,\n \"mark2\" : 50,\n \"mark3\" : 60,\n \"addr\" : \"23 new street\",\n \"pincode\" : 111222\n}\n{\n \"ID\" : \"002\",\n \"name\" : \"Amit\",\n \"age\" : 12,\n \"gender\" : \"male\",\n \"standard\" : \"six\",\n \"mark1\" : 40,\n \"mark2\" : 50,\n \"mark3\" : 40,\n \"addr\" : \"12 old street\",\n \"pincode\" : 111222\n}\n{\n \"ID\" : \"003\",\n \"name\" : \"Bob\",\n \"age\" : 12,\n \"gender\" : \"male\",\n \"standard\" : \"six\",\n \"mark1\" : 60,\n \"mark2\" : 80,\n \"mark3\" : 70,\n \"addr\" : \"10 cross street\",\n \"pincode\" : 111222\n}\n{\n \"ID\" : \"004\",\n \"name\" : \"David\",\n \"age\" : 12,\n \"gender\" : \"male\",\n \"standard\" : \"six\",\n \"mark1\" : 50,\n \"mark2\" : 70,\n \"mark3\" : 70,\n \"addr\" : \"15 express avenue\",\n \"pincode\" : 111222\n}\n{\n \"ID\" : \"005\",\n \"name\" : \"Esha\",\n \"age\" : 12,\n \"gender\" : \"female\",\n \"standard\" : \"six\",\n \"mark1\" : 70,\n \"mark2\" : 60,\n \"mark3\" : 65,\n \"addr\" : \"20 garden street\",\n \"pincode\" : 111222\n}\n{\n \"ID\" : \"006\",\n \"name\" : \"Ganga\",\n \"age\" : 12,\n \"gender\" : \"female\",\n \"standard\" : \"six\",\n \"mark1\" : 100,\n \"mark2\" : 95,\n \"mark3\" : 98,\n \"addr\" : \"25 north street\",\n \"pincode\" : 111222\n}\n{\n \"ID\" : \"007\",\n \"name\" : \"Jack\",\n \"age\" : 13,\n \"gender\" : \"male\",\n \"standard\" : \"six\",\n \"mark1\" : 55,\n \"mark2\" : 45,\n \"mark3\" : 45,\n \"addr\" : \"2 park street\",\n \"pincode\" : 111222\n}\n{\n \"ID\" : \"008\",\n \"name\" : \"Leena\",\n \"age\" : 12,\n \"gender\" : \"female\",\n \"standard\" : \"six\",\n \"mark1\" : 90,\n \"mark2\" : 85,\n \"mark3\" : 95,\n \"addr\" : \"24 south street\",\n \"pincode\" : 111222\n}\n{\n \"ID\" : \"009\",\n \"name\" : \"Mary\",\n \"age\" : 13,\n \"gender\" : \"female\",\n \"standard\" : \"six\",\n \"mark1\" : 75,\n \"mark2\" : 85,\n \"mark3\" : 90,\n \"addr\" : \"5 west street\",\n \"pincode\" : 111222\n}\n{\n \"ID\" : \"010\",\n \"name\" : \"Peter\",\n \"age\" : 13,\n \"gender\" : \"female\",\n \"standard\" : \"six\",\n \"mark1\" : 80,\n \"mark2\" : 85,\n \"mark3\" : 88,\n \"addr\" : \"16 park avenue\",\n \"pincode\" : 111222\n}"
},
{
"code": null,
"e": 39697,
"s": 39644,
"text": "Now, let us query the file to view its full records."
},
{
"code": null,
"e": 39796,
"s": 39697,
"text": "0: jdbc:drill:zk = local> select * from dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 40689,
"s": 39796,
"text": "ID name age gender standard mark1 mark2 mark3 addr pincode\n001 Adam 12 male six 70 50 60 23 new street 111222\n002 Amit 12 male six 40 50 40 12 old street 111222\n003 Bob 12 male six 60 80 70 10 cross street 111222\n004 David 12 male six 50 70 70 15 express avenue 111222\n005 Esha 12 female six 70 60 65 20 garden street 111222\n006 Ganga 12 female six 100 95 98 25 north street 111222\n007 Jack 13 male six 55 45 45 2 park street 111222\n008 Leena 12 female six 90 85 95 24 south street 111222\n009 Mary 13 female six 75 85 90 5 west street 111222\n010 Peter 13 female six 80 85 88 16 park avenue 111222\n"
},
{
"code": null,
"e": 40757,
"s": 40689,
"text": "This section will cover the operations on SQL operators using JSON."
},
{
"code": null,
"e": 40761,
"s": 40757,
"text": "AND"
},
{
"code": null,
"e": 40858,
"s": 40761,
"text": "The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause."
},
{
"code": null,
"e": 40861,
"s": 40858,
"text": "OR"
},
{
"code": null,
"e": 40952,
"s": 40861,
"text": "The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause."
},
{
"code": null,
"e": 40955,
"s": 40952,
"text": "IN"
},
{
"code": null,
"e": 41052,
"s": 40955,
"text": "The IN operator is used to compare a value to a list of literal values that have been specified."
},
{
"code": null,
"e": 41060,
"s": 41052,
"text": "BETWEEN"
},
{
"code": null,
"e": 41190,
"s": 41060,
"text": "The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value."
},
{
"code": null,
"e": 41195,
"s": 41190,
"text": "LIKE"
},
{
"code": null,
"e": 41284,
"s": 41195,
"text": "The LIKE operator is used to compare a value to similar values using wildcard operators."
},
{
"code": null,
"e": 41288,
"s": 41284,
"text": "NOT"
},
{
"code": null,
"e": 41442,
"s": 41288,
"text": "The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator."
},
{
"code": null,
"e": 41581,
"s": 41442,
"text": "The aggregate functions produce a single result from a set of input values. The following table lists out the functions in further detail."
},
{
"code": null,
"e": 41597,
"s": 41581,
"text": "AVG(expression)"
},
{
"code": null,
"e": 41648,
"s": 41597,
"text": "Averages a column of all records in a data source."
},
{
"code": null,
"e": 41657,
"s": 41648,
"text": "COUNT(*)"
},
{
"code": null,
"e": 41715,
"s": 41657,
"text": "Returns the number of rows that match the given criteria."
},
{
"code": null,
"e": 41744,
"s": 41715,
"text": "COUNT([DISTINCT] expression)"
},
{
"code": null,
"e": 41797,
"s": 41744,
"text": "Returns the number of distinct values in the column."
},
{
"code": null,
"e": 41813,
"s": 41797,
"text": "MAX(expression)"
},
{
"code": null,
"e": 41863,
"s": 41813,
"text": "Returns the largest value of the selected column."
},
{
"code": null,
"e": 41879,
"s": 41863,
"text": "MIN(expression)"
},
{
"code": null,
"e": 41930,
"s": 41879,
"text": "Returns the smallest value of the selected column."
},
{
"code": null,
"e": 41946,
"s": 41930,
"text": "SUM(expression)"
},
{
"code": null,
"e": 41978,
"s": 41946,
"text": "Return the sum of given column."
},
{
"code": null,
"e": 42036,
"s": 41978,
"text": "The following program shows the query for this function −"
},
{
"code": null,
"e": 42147,
"s": 42036,
"text": "0: jdbc:drill:zk = local> select stddev(mark2) from dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 42174,
"s": 42147,
"text": "EXPR$0\n18.020050561034015\n"
},
{
"code": null,
"e": 42287,
"s": 42174,
"text": "0: jdbc:drill:zk = local> select variance(mark2) from dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 42313,
"s": 42287,
"text": "EXPR$0\n324.7222222222223\n"
},
{
"code": null,
"e": 42372,
"s": 42313,
"text": "Variance of mark2 column result is returned as the output."
},
{
"code": null,
"e": 42538,
"s": 42372,
"text": "Window functions execute on a set of rows and return a single value for each row from the query. The term window has the meaning of the set of rows for the function."
},
{
"code": null,
"e": 42664,
"s": 42538,
"text": "A Window function in a query, defines the window using the OVER() clause. This OVER() clause has the following capabilities −"
},
{
"code": null,
"e": 42736,
"s": 42664,
"text": "Defines window partitions to form groups of rows. (PARTITION BY clause)"
},
{
"code": null,
"e": 42786,
"s": 42736,
"text": "Orders rows within a partition. (ORDER BY clause)"
},
{
"code": null,
"e": 42872,
"s": 42786,
"text": "The Aggregate window function can be defined over a partition by and order by clause."
},
{
"code": null,
"e": 42930,
"s": 42872,
"text": "The following program shows the query for this function −"
},
{
"code": null,
"e": 42936,
"s": 42930,
"text": "Query"
},
{
"code": null,
"e": 43104,
"s": 42936,
"text": "0: jdbc:drill:zk = local> select mark1,gender,\n avg(mark1) over (partition by gender ) as avgmark1 from\n dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 43111,
"s": 43104,
"text": "Result"
},
{
"code": null,
"e": 43334,
"s": 43111,
"text": "mark1 gender avgmark1\n70 female 83.0\n100 female 83.0\n90 female 83.0\n75 female 83.0\n80 female 83.0\n70 male 55.0\n40 male 55.0\n60 male 55.0\n50 male 55.0\n55 male 55.0\n"
},
{
"code": null,
"e": 43619,
"s": 43334,
"text": "This result shows that partition by clause is used for the gender column. So, it takes the average of mark1 from female gender which is 83.0 and then replaces that value to all the male and female gender. The mark1 avg result is now 55.0 and hence it replaces the same to all genders."
},
{
"code": null,
"e": 43677,
"s": 43619,
"text": "The following program shows the query for this function −"
},
{
"code": null,
"e": 43683,
"s": 43677,
"text": "Query"
},
{
"code": null,
"e": 43851,
"s": 43683,
"text": "0: jdbc:drill:zk = local> select name, gender, mark1, age,\n count(*) over(partition by age) as cnt from\n dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 43858,
"s": 43851,
"text": "Result"
},
{
"code": null,
"e": 44157,
"s": 43858,
"text": "name gender mark1 age cnt\nAdam male 70 12 7\nAmit male 40 12 7\nBob male 60 12 7\nDavid male 50 12 7\nEsha female 70 12 7\nGanga female 100 12 7\nLeena female 90 12 7\nJack male 55 13 3\nMary female 75 13 3\nPeter female 80 13 3\n"
},
{
"code": null,
"e": 44362,
"s": 44157,
"text": "Here, there are two age groups 12 and 13. The age count of 12 is for 7 students and 13 age count is for 3 students. Hence count(*) over partition by age replaces 7 for 12 age group and 3 for 13 age group."
},
{
"code": null,
"e": 44420,
"s": 44362,
"text": "The following program shows the query for this function −"
},
{
"code": null,
"e": 44426,
"s": 44420,
"text": "Query"
},
{
"code": null,
"e": 44601,
"s": 44426,
"text": "0: jdbc:drill:zk = local> select name,age,gender,mark3,\n max(mark3) over (partition by gender) as maximum from\n dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 44608,
"s": 44601,
"text": "Result"
},
{
"code": null,
"e": 44920,
"s": 44608,
"text": "name age gender mark3 maximum\nEsha 12 female 65 98\nGanga 12 female 98 98\nLeena 12 female 95 98\nMary 13 female 90 98\nPeter 13 female 88 98\nAdam 12 male 60 70\nAmit 12 male 40 70\nBob 12 male 70 70\nDavid 12 male 70 70\nJack 13 male 45 70\n"
},
{
"code": null,
"e": 45111,
"s": 44920,
"text": "From the above query, maximum mark3 is partitioned by gender, hence female gender max mark 98 is replaced to all female students and male gender max mark 70 is replaced to all male students."
},
{
"code": null,
"e": 45169,
"s": 45111,
"text": "The following program shows the query for this function −"
},
{
"code": null,
"e": 45175,
"s": 45169,
"text": "Query"
},
{
"code": null,
"e": 45331,
"s": 45175,
"text": "0: jdbc:drill:zk = local> select mark2,min(mark2)\n over (partition by age ) as minimum from\n dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 45338,
"s": 45331,
"text": "Result"
},
{
"code": null,
"e": 45463,
"s": 45338,
"text": "mark2 minimum\n 50 50\n 50 50\n 80 50\n 70 50\n 60 50\n 95 50\n 85 50\n 45 45\n 85 45\n 85 45\n"
},
{
"code": null,
"e": 45521,
"s": 45463,
"text": "The following program shows the query for this function −"
},
{
"code": null,
"e": 45527,
"s": 45521,
"text": "Query"
},
{
"code": null,
"e": 45690,
"s": 45527,
"text": "0: jdbc:drill:zk = local> select name,age,sum(mark1+mark2)\n over (order by age ) as summation from\n dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 45697,
"s": 45690,
"text": "Result"
},
{
"code": null,
"e": 45892,
"s": 45697,
"text": "name age summation\nAdam 12 970\nAmit 12 970\nBob 12 970\nDavid 12 970\nEsha 12 970\nGanga 12 970\nLeena 12 970\nJack 13 1395\nMary 13 1395\nPeter 13 1395\n"
},
{
"code": null,
"e": 45972,
"s": 45892,
"text": "Here mark1+mark2 result is replaced separately to each male and female student."
},
{
"code": null,
"e": 46037,
"s": 45972,
"text": "Following is the table listed out with ranking window functions."
},
{
"code": null,
"e": 46049,
"s": 46037,
"text": "CUME_DIST()"
},
{
"code": null,
"e": 46062,
"s": 46049,
"text": "DENSE_RANK()"
},
{
"code": null,
"e": 46070,
"s": 46062,
"text": "NTILE()"
},
{
"code": null,
"e": 46085,
"s": 46070,
"text": "PERCENT_RANK()"
},
{
"code": null,
"e": 46092,
"s": 46085,
"text": "RANK()"
},
{
"code": null,
"e": 46105,
"s": 46092,
"text": "ROW_NUMBER()"
},
{
"code": null,
"e": 46213,
"s": 46105,
"text": "In this chapter, we will discuss in detail about which all composite data types does Apache Drill supports."
},
{
"code": null,
"e": 46392,
"s": 46213,
"text": "Array − An array is a repeated list of values. A value in an array can be a scalar type, such as string or int, or an array can be a complex type, such as a map or another array."
},
{
"code": null,
"e": 46571,
"s": 46392,
"text": "Array − An array is a repeated list of values. A value in an array can be a scalar type, such as string or int, or an array can be a complex type, such as a map or another array."
},
{
"code": null,
"e": 46727,
"s": 46571,
"text": "Map − A map is a set of name/value pairs. A value in a map can be a scalar type, such as string or int, or a complex type, such as an array or another map."
},
{
"code": null,
"e": 46883,
"s": 46727,
"text": "Map − A map is a set of name/value pairs. A value in a map can be a scalar type, such as string or int, or a complex type, such as an array or another map."
},
{
"code": null,
"e": 47003,
"s": 46883,
"text": "Apache Drill uses map and array data types internally for reading complex and nested data structures from data sources."
},
{
"code": null,
"e": 47011,
"s": 47003,
"text": "FLATTEN"
},
{
"code": null,
"e": 47087,
"s": 47011,
"text": "FLATTEN separates the elements in a repeated field into individual records."
},
{
"code": null,
"e": 47093,
"s": 47087,
"text": "KVGEN"
},
{
"code": null,
"e": 47157,
"s": 47093,
"text": "This function returns a list of the keys that exist in the map."
},
{
"code": null,
"e": 47172,
"s": 47157,
"text": "REPEATED_COUNT"
},
{
"code": null,
"e": 47217,
"s": 47172,
"text": "This function counts the values in an array."
},
{
"code": null,
"e": 47235,
"s": 47217,
"text": "REPEATED CONTAINS"
},
{
"code": null,
"e": 47351,
"s": 47235,
"text": "Searches for a keyword in an array. If the keyword is present in an array, the result will be true otherwise false."
},
{
"code": null,
"e": 47454,
"s": 47351,
"text": "This section will cover Data definition statements. Let’s go through each of these commands in detail."
},
{
"code": null,
"e": 47534,
"s": 47454,
"text": "You can create tables in Apache Drill by using the following two CTAS commands."
},
{
"code": null,
"e": 47541,
"s": 47534,
"text": "Syntax"
},
{
"code": null,
"e": 47588,
"s": 47541,
"text": "CREATE TABLE name [ (column list) ] AS query;\n"
},
{
"code": null,
"e": 47595,
"s": 47588,
"text": "Where,"
},
{
"code": null,
"e": 47621,
"s": 47595,
"text": "Query − select statement."
},
{
"code": null,
"e": 47628,
"s": 47621,
"text": "Syntax"
},
{
"code": null,
"e": 47736,
"s": 47628,
"text": "CREATE TABLE name [ ( <column list> ) ] [ PARTITION BY ( <column_name> [ , ... ] ) ] AS <select statement>\n"
},
{
"code": null,
"e": 47743,
"s": 47736,
"text": "Where,"
},
{
"code": null,
"e": 47773,
"s": 47743,
"text": "name − unique directory name."
},
{
"code": null,
"e": 47803,
"s": 47773,
"text": "name − unique directory name."
},
{
"code": null,
"e": 47876,
"s": 47803,
"text": "column list − optional list of column names or aliases in the new table."
},
{
"code": null,
"e": 47949,
"s": 47876,
"text": "column list − optional list of column names or aliases in the new table."
},
{
"code": null,
"e": 48010,
"s": 47949,
"text": "PARTITION BY − partitions the data by the first column_name."
},
{
"code": null,
"e": 48071,
"s": 48010,
"text": "PARTITION BY − partitions the data by the first column_name."
},
{
"code": null,
"e": 48133,
"s": 48071,
"text": "To create a table, you should adhere to the following steps −"
},
{
"code": null,
"e": 48176,
"s": 48133,
"text": "Set the workspace to a writable workspace."
},
{
"code": null,
"e": 48219,
"s": 48176,
"text": "Set the workspace to a writable workspace."
},
{
"code": null,
"e": 48343,
"s": 48219,
"text": "You can only create new tables in df.tmp workspace. You cannot create tables using storage plugins, such as Hive and HBase."
},
{
"code": null,
"e": 48467,
"s": 48343,
"text": "You can only create new tables in df.tmp workspace. You cannot create tables using storage plugins, such as Hive and HBase."
},
{
"code": null,
"e": 48523,
"s": 48467,
"text": "\"tmp\": {\n \"location\": \"/tmp\",\n \"writable\": true,\n}\n"
},
{
"code": null,
"e": 48562,
"s": 48523,
"text": "0: jdbc:drill:zk = local> use dfs.tmp;"
},
{
"code": null,
"e": 48808,
"s": 48562,
"text": "+-------+--------------------------------------+\n| ok | summary |\n+-------+--------------------------------------+\n| true | Default schema changed to [dfs.tmp] |\n+-------+--------------------------------------+\n"
},
{
"code": null,
"e": 48935,
"s": 48808,
"text": "0: jdbc:drill:zk = local> create table students as select * from\n dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 49151,
"s": 48935,
"text": "+-----------+----------------------------+\n| Fragment | Number of records written |\n+-----------+----------------------------+\n| 0_0 | 10 |\n+-----------+----------------------------+\n"
},
{
"code": null,
"e": 49157,
"s": 49151,
"text": "Query"
},
{
"code": null,
"e": 49207,
"s": 49157,
"text": "0: jdbc:drill:zk = local> select * from students;"
},
{
"code": null,
"e": 49214,
"s": 49207,
"text": "Result"
},
{
"code": null,
"e": 50559,
"s": 49214,
"text": "+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+\n| ID | name | age | gender | standard | mark1 | mark2 | mark3 | addr | pincode |\n+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+\n| 001 | Adam | 12 | male | six | 70 | 50 | 60 | 23 new street | 111222 |\n| 002 | Amit | 12 | male | six | 40 | 50 | 40 | 12 old street | 111222 |\n| 003 | Bob | 12 | male | six | 60 | 80 | 70 | 10 cross street | 111222 |\n| 004 | David | 12 | male | six | 50 | 70 | 70 | 15 express avenue | 111222 |\n| 005 | Esha | 12 | female | six | 70 | 60 | 65 | 20 garden street | 111222 |\n| 006 | Ganga | 12 | female | six | 100 | 95 | 98 | 25 north street | 111222 |\n| 007 | Jack | 13 | male | six | 55 | 45 | 45 | 2 park street | 111222 |\n| 008 | Leena | 12 | female | six | 90 | 85 | 95 | 24 south street | 111222 |\n| 009 | Mary | 13 | female | six | 75 | 85 | 90 | 5 west street | 111222 |\n| 010 | Peter | 13 | female | six | 80 | 85 | 88 | 16 park avenue | 111222 |\n+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+\n"
},
{
"code": null,
"e": 50617,
"s": 50559,
"text": "The following program shows the query for this function −"
},
{
"code": null,
"e": 50623,
"s": 50617,
"text": "Query"
},
{
"code": null,
"e": 50775,
"s": 50623,
"text": "0: jdbc:drill:zk = local> create table student_new partition by (gender) as select * from\n dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 50782,
"s": 50775,
"text": "Result"
},
{
"code": null,
"e": 50998,
"s": 50782,
"text": "+-----------+----------------------------+\n| Fragment | Number of records written |\n+-----------+----------------------------+\n| 0_0 | 10 |\n+-----------+----------------------------+\n"
},
{
"code": null,
"e": 51033,
"s": 50998,
"text": "To view the records of the table −"
},
{
"code": null,
"e": 51039,
"s": 51033,
"text": "Query"
},
{
"code": null,
"e": 51092,
"s": 51039,
"text": "0: jdbc:drill:zk = local> select * from student_new;"
},
{
"code": null,
"e": 51099,
"s": 51092,
"text": "Result"
},
{
"code": null,
"e": 52486,
"s": 51099,
"text": "+------+--------+------+--------+----------+-------+-------+-------+-------------------+---------+\n| ID | name | age | gender | standard | mark1 | mark2 | mark3 | addr | pincode |\n+------+--------+------+--------+----------+-------+-------+-------+-------------------+---------+\n| 005 | Esha | 12 | female | six | 70 | 60 | 65 | 20 garden street | 111222 |\n| 006 | Ganga | 12 | female | six | 100 | 95 | 98 | 25 north street | 111222 |\n| 008 | Leena | 12 | female | six | 90 | 85 | 95 | 24 south street | 111222 |\n| 009 | Mary | 13 | female | six | 75 | 85 | 90 | 5 west street | 111222 |\n| 010 | Peter | 13 | female | six | 80 | 85 | 88 | 16 park avenue | 111222 |\n| 001 | Adam | 12 | male | six | 70 | 50 | 60 | 23 new street | 111222 |\n| 002 | Amit | 12 | male | six | 40 | 50 | 40 | 12 old street | 111222 |\n| 003 | Bob | 12 | male | six | 60 | 80 | 70 | 10 cross street | 111222 |\n| 004 | David | 12 | male | six | 50 | 70 | 70 | 15 express avenue | 111222 |\n| 007 | Jack | 13 | male | six | 55 | 45 | 45 | 2 park street | 111222 |\n+------+--------+------+--------+----------+-------+-------+-------+-------------------+---------+\n"
},
{
"code": null,
"e": 52536,
"s": 52486,
"text": "Here the table records are partitioned by gender."
},
{
"code": null,
"e": 52599,
"s": 52536,
"text": "The ALTER SYSTEM command permanently changes a system setting."
},
{
"code": null,
"e": 52640,
"s": 52599,
"text": "ALTER SYSTEM SET `option_name` = value;\n"
},
{
"code": null,
"e": 52696,
"s": 52640,
"text": "To reset the system settings, use the following syntax."
},
{
"code": null,
"e": 52755,
"s": 52696,
"text": "ALTER SYSTEM RESET `option_name`;\nALTER SYSTEM RESET ALL;\n"
},
{
"code": null,
"e": 52817,
"s": 52755,
"text": "Here is the sample query that enables the Decimal data type −"
},
{
"code": null,
"e": 52903,
"s": 52817,
"text": "0: jdbc:drill:zk = local> ALTER SYSTEM SET `planner.enable_decimal_data_type` = true;"
},
{
"code": null,
"e": 53179,
"s": 52903,
"text": "+-------+--------------------------------------------+\n| ok | summary |\n+-------+--------------------------------------------+\n| true | planner.enable_decimal_data_type updated. |\n+-------+--------------------------------------------+\n"
},
{
"code": null,
"e": 53310,
"s": 53179,
"text": "By default, Apache Drill disables the decimal data type. To reset all the changes, you will need to key-in the following command −"
},
{
"code": null,
"e": 53360,
"s": 53310,
"text": "0: jdbc:drill:zk = local> ALTER SYSTEM RESET all;"
},
{
"code": null,
"e": 53491,
"s": 53360,
"text": "+-------+---------------+\n| ok | summary |\n+-------+---------------+\n| true | ALL updated. |\n+-------+---------------+\n"
},
{
"code": null,
"e": 53709,
"s": 53491,
"text": "The CREATE VIEW command creates a virtual structure for the result set of a stored query. A view can combine data from multiple underlying data sources and provide the illusion that all of the data is from one source."
},
{
"code": null,
"e": 53793,
"s": 53709,
"text": "CREATE [OR REPLACE] VIEW [workspace.]view_name [ (column_name [, ...]) ] AS query;\n"
},
{
"code": null,
"e": 53800,
"s": 53793,
"text": "Where,"
},
{
"code": null,
"e": 53909,
"s": 53800,
"text": "workspace − The location where you want the view to exist. By default, the view can be created in “dfs.tmp”."
},
{
"code": null,
"e": 54018,
"s": 53909,
"text": "workspace − The location where you want the view to exist. By default, the view can be created in “dfs.tmp”."
},
{
"code": null,
"e": 54101,
"s": 54018,
"text": "view_name − The name that you give to the view. This view must have a unique name."
},
{
"code": null,
"e": 54184,
"s": 54101,
"text": "view_name − The name that you give to the view. This view must have a unique name."
},
{
"code": null,
"e": 54314,
"s": 54184,
"text": "0: jdbc:drill:zk = local> create view student_view as select * from\n dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 54675,
"s": 54314,
"text": "+------+--------------------------------------------------------------+\n| ok | summary |\n+------+--------------------------------------------------------------+\n| true | View 'student_view' created successfully in 'dfs.tmp' schema |\n+------+--------------------------------------------------------------+\n"
},
{
"code": null,
"e": 54728,
"s": 54675,
"text": "To see the records, you can use the following query."
},
{
"code": null,
"e": 54782,
"s": 54728,
"text": "0: jdbc:drill:zk = local> select * from student_view;"
},
{
"code": null,
"e": 56127,
"s": 54782,
"text": "+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+\n| ID | name | age | gender | standard | mark1 | mark2 | mark3 | addr | pincode |\n+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+\n| 001 | Adam | 12 | male | six | 70 | 50 | 60 | 23 new street | 111222 |\n| 002 | Amit | 12 | male | six | 40 | 50 | 40 | 12 old street | 111222 |\n| 003 | Bob | 12 | male | six | 60 | 80 | 70 | 10 cross street | 111222 |\n| 004 | David | 12 | male | six | 50 | 70 | 70 | 15 express avenue | 111222 |\n| 005 | Esha | 12 | female | six | 70 | 60 | 65 | 20 garden street | 111222 |\n| 006 | Ganga | 12 | female | six | 100 | 95 | 98 | 25 north street | 111222 |\n| 007 | Jack | 13 | male | six | 55 | 45 | 45 | 2 park street | 111222 |\n| 008 | Leena | 12 | female | six | 90 | 85 | 95 | 24 south street | 111222 |\n| 009 | Mary | 13 | female | six | 75 | 85 | 90 | 5 west street | 111222 |\n| 010 | Peter | 13 | female | six | 80 | 85 | 88 | 16 park avenue | 111222 |\n+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+\n"
},
{
"code": null,
"e": 56205,
"s": 56127,
"text": "The drop table statement is used to drop the table from a DFS storage plugin."
},
{
"code": null,
"e": 56235,
"s": 56205,
"text": "DROP TABLE [workspace.]name;\n"
},
{
"code": null,
"e": 56285,
"s": 56235,
"text": "0: jdbc:drill:zk = local> drop table student_new;"
},
{
"code": null,
"e": 56486,
"s": 56285,
"text": "+------+------------------------------+\n| ok | summary |\n+------+------------------------------+\n| true | Table [student_new] dropped |\n+------+------------------------------+\n"
},
{
"code": null,
"e": 56563,
"s": 56486,
"text": "Similar to the table, a view can be dropped by using the following command −"
},
{
"code": null,
"e": 56613,
"s": 56563,
"text": "0: jdbc:drill:zk = local> drop view student_view;"
},
{
"code": null,
"e": 56989,
"s": 56613,
"text": "+------+-----------------------------------------------------------------+\n| ok | summary |\n+------+-----------------------------------------------------------------+\n| true | View [student_view] deleted successfully from schema [dfs.tmp]. |\n+------+-----------------------------------------------------------------+\n"
},
{
"code": null,
"e": 57105,
"s": 56989,
"text": "In this chapter, we will learn about how Apache Drill allows us to query plain text files such as CSV, TSV and PSV."
},
{
"code": null,
"e": 57180,
"s": 57105,
"text": "Create a CSV file named “students.csv” as shown in the following program −"
},
{
"code": null,
"e": 57428,
"s": 57180,
"text": "001,Adam,23 new street\n002,Amit,12 old street\n003,Bob,10 cross street\n004,David,15 express avenue\n005,Esha,20 garden street\n006,Ganga,25 north street\n007,Jack,2 park street\n008,Leena,24 south street\n009,Mary,5 west street\n010,Peter,16 park avenue\n"
},
{
"code": null,
"e": 57540,
"s": 57428,
"text": "After saving the file, you can return to the terminal again and type the following query to view that CSV file."
},
{
"code": null,
"e": 57634,
"s": 57540,
"text": "0: jdbc:drill:zk = local> select * from dfs.`/Users/../workspace/Drill-samples/students.csv`;"
},
{
"code": null,
"e": 58196,
"s": 57634,
"text": "+-------------------------------------+\n| columns |\n+-------------------------------------+\n| [\"001\",\"Adam\",\"23 new street\"] |\n| [\"002\",\"Amit\",\"12 old street\"] |\n| [\"003\",\"Bob\",\"10 cross street\"] |\n| [\"004\",\"David\",\"15 express avenue\"] |\n| [\"005\",\"Esha\",\"20 garden street\"] |\n| [\"006\",\"Ganga\",\"25 north street\"] |\n| [\"007\",\"Jack\",\"2 park street\"] |\n| [\"008\",\"Leena\",\"24 south street\"] |\n| [\"009\",\"Mary\",\"5 west street\"] |\n| [\"010\",\"Peter\",\"16 park avenue\"] |\n+—————————————————————————————————————+\n"
},
{
"code": null,
"e": 58327,
"s": 58196,
"text": "From this output we can conclude that, Apache Drill recognizes each row as an array of values and returns one column for each row."
},
{
"code": null,
"e": 58440,
"s": 58327,
"text": "The COLUMNS[n] syntax is used to return CSV rows in a column by the column format, where n starts from 0 to n-1."
},
{
"code": null,
"e": 58446,
"s": 58440,
"text": "Query"
},
{
"code": null,
"e": 58573,
"s": 58446,
"text": "0: jdbc:drill:zk = local>select columns[0],columns[1],columns[2] from\n dfs.`/Users/../workspace/Drill-samples/students.csv`;"
},
{
"code": null,
"e": 58580,
"s": 58573,
"text": "Result"
},
{
"code": null,
"e": 59183,
"s": 58580,
"text": "+---------+---------+--------------------+\n| EXPR$0 | EXPR$1 | EXPR$2 |\n+---------+---------+--------------------+\n| 001 | Adam | 23 new street |\n| 002 | Amit | 12 old street |\n| 003 | Bob | 10 cross street |\n| 004 | David | 15 express avenue |\n| 005 | Esha | 20 garden street |\n| 006 | Ganga | 25 north street |\n| 007 | Jack | 2 park street |\n| 008 | Leena | 24 south street |\n| 009 | Mary | 5 west street |\n| 010 | Peter | 16 park avenue |\n+---------+---------+--------------------+\n"
},
{
"code": null,
"e": 59258,
"s": 59183,
"text": "If you want to assign an alias name for columns, use the following query −"
},
{
"code": null,
"e": 59264,
"s": 59258,
"text": "Query"
},
{
"code": null,
"e": 59416,
"s": 59264,
"text": "0: jdbc:drill:zk = local>select columns[0] as ID,columns[1] as Name,columns[2] as Address from\n dfs.`/Users/../workspace/Drill-samples/students.csv`;"
},
{
"code": null,
"e": 59423,
"s": 59416,
"text": "Result"
},
{
"code": null,
"e": 59957,
"s": 59423,
"text": "+------+-------+--------------------+\n| ID | Name | Address |\n+------+-------+--------------------+\n| 001 | Adam | 23 new street |\n| 002 | Amit | 12 old street |\n| 003 | Bob | 10 cross street |\n| 004 | David | 15 express avenue |\n| 005 | Esha | 20 garden street |\n| 006 | Ganga | 25 north street | \n| 007 | Jack | 2 park street |\n| 008 | Leena | 24 south street |\n| 009 | Mary | 5 west street |\n| 010 | Peter | 16 park avenue |\n+------+-------+--------------------+\n"
},
{
"code": null,
"e": 60044,
"s": 59957,
"text": "Like in JSON, you can create table for plain text files. Following is a sample query −"
},
{
"code": null,
"e": 60161,
"s": 60044,
"text": "0: jdbc:drill:zk = local> create table CSV as select * from\n dfs.`/Users/../workspace/Drill-samples/students.csv`;"
},
{
"code": null,
"e": 60168,
"s": 60161,
"text": "Result"
},
{
"code": null,
"e": 60379,
"s": 60168,
"text": "+----------+----------------------------+\n| Fragment | Number of records written |\n+----------+----------------------------+\n| 0_0 | 10 |\n+-----------+---------------------------+\n"
},
{
"code": null,
"e": 60433,
"s": 60379,
"text": "To view the file contents, type the following query −"
},
{
"code": null,
"e": 60439,
"s": 60433,
"text": "Query"
},
{
"code": null,
"e": 60484,
"s": 60439,
"text": "0: jdbc:drill:zk = local> select * from CSV;"
},
{
"code": null,
"e": 60491,
"s": 60484,
"text": "Result"
},
{
"code": null,
"e": 61053,
"s": 60491,
"text": "+-------------------------------------+\n| columns |\n+-------------------------------------+\n| [\"001\",\"Adam\",\"23 new street\"] |\n| [\"002\",\"Amit\",\"12 old street\"] |\n| [\"003\",\"Bob\",\"10 cross street\"] |\n| [\"004\",\"David\",\"15 express avenue\"] |\n| [\"005\",\"Esha\",\"20 garden street\"] |\n| [\"006\",\"Ganga\",\"25 north street\"] | \n| [\"007\",\"Jack\",\"2 park street\"] |\n| [\"008\",\"Leena\",\"24 south street\"] |\n| [\"009\",\"Mary\",\"5 west street\"] |\n| [\"010\",\"Peter\",\"16 park avenue\"] |\n+-------------------------------------+\n"
},
{
"code": null,
"e": 61128,
"s": 61053,
"text": "Create a TSV file named “students.tsv” as shown in the following program −"
},
{
"code": null,
"e": 61283,
"s": 61128,
"text": " ID Name Age Standard Remark\n001 id \"name is Adam\" \"for the age of 12\" \"studying sixth std\" \"Having good marks\"\n"
},
{
"code": null,
"e": 61363,
"s": 61283,
"text": "Now we can execute this TSV file in Apache Drill by using the following query −"
},
{
"code": null,
"e": 61456,
"s": 61363,
"text": "0: jdbc:drill:zk = local> select * from dfs.`/Users/../workspace/Drill-samples/student.tsv`;"
},
{
"code": null,
"e": 62164,
"s": 61456,
"text": "+-------------------------------------------------------------------------------------------------------------------+\n| columns |\n+-------------------------------------------------------------------------------------------------------------------+\n| [ \"ID\" , \"Name\" , \"Age\" , \"Standard\" , \"Marks\" , \"Addr\", \"pincode\"] |\n| [\"001 id \", \"name is adam\", \"for the age of 12\", \"studying sxith std\\\" \\\"Having good marks\"] |\n+-------------------------------------------------------------------------------------------------------------------+\n"
},
{
"code": null,
"e": 62242,
"s": 62164,
"text": "As shown in the CSV file above, you can also create a table for the TSV file."
},
{
"code": null,
"e": 62248,
"s": 62242,
"text": "Query"
},
{
"code": null,
"e": 62341,
"s": 62248,
"text": "0: jdbc:drill:zk = local> select * from dfs.`/Users/../workspace/Drill-samples/student.tsv`;"
},
{
"code": null,
"e": 62348,
"s": 62341,
"text": "Result"
},
{
"code": null,
"e": 62595,
"s": 62348,
"text": "+-----------+----------------------------+\n| Fragment | Number of records written |\n+-----------+----------------------------+\n| 0_0 | 2 |\n+-----------+----------------------------+\n1 row selected (0.347 seconds)\n"
},
{
"code": null,
"e": 62601,
"s": 62595,
"text": "Query"
},
{
"code": null,
"e": 62646,
"s": 62601,
"text": "0: jdbc:drill:zk = local> select * from TSV;"
},
{
"code": null,
"e": 62653,
"s": 62646,
"text": "Result"
},
{
"code": null,
"e": 63356,
"s": 62653,
"text": "+------------------------------------------------------------------------------------------------------------------+\n| columns |\n+------------------------------------------------------------------------------------------------------------------+\n| [ \"ID\" , \"Name\" , \"Age\" , \"Standard\" , \"Marks\" , \"Addr\", \"pincode\"] |\n| [\"001 id \", \"name is adam\", \"for the age of 12\", \"studying sxith std\\\" \\\"Having good marks\"] |\n+------------------------------------------------------------------------------------------------------------------+\n"
},
{
"code": null,
"e": 63428,
"s": 63356,
"text": "Create a psv file named “sample.tbl” as shown in the following program."
},
{
"code": null,
"e": 63465,
"s": 63428,
"text": "Tutorialspoint|Apache|Drill|article\n"
},
{
"code": null,
"e": 63508,
"s": 63465,
"text": "Now we can execute this PSV file in Drill,"
},
{
"code": null,
"e": 63601,
"s": 63508,
"text": "0: jdbc:drill:zk = local> select * from dfs.`/Users/../workspace/Drill-samples/sample.tbl`;\n"
},
{
"code": null,
"e": 63857,
"s": 63601,
"text": "+------------------------------------------------+\n| columns |\n+------------------------------------------------+\n| [\"Tutorialspoint\",\"Apache\",\"Drill\",\"article\"] |\n+------------------------------------------------+\n"
},
{
"code": null,
"e": 63945,
"s": 63857,
"text": "Now, similar to the CSV and TSV files, try for yourself to create a table for PSV file."
},
{
"code": null,
"e": 64285,
"s": 63945,
"text": "HBase is a distributed column-oriented database built on top of the Hadoop file system. It is a part of the Hadoop ecosystem that provides random real-time read/write access to data in the Hadoop File System. One can store the data in HDFS either directly or through HBase. The following steps are used to query HBase data in Apache Drill."
},
{
"code": null,
"e": 64367,
"s": 64285,
"text": "Before moving on to querying HBase data, you must need to install the following −"
},
{
"code": null,
"e": 64405,
"s": 64367,
"text": "Java installed version 1.7 or greater"
},
{
"code": null,
"e": 64412,
"s": 64405,
"text": "Hadoop"
},
{
"code": null,
"e": 64418,
"s": 64412,
"text": "HBase"
},
{
"code": null,
"e": 64558,
"s": 64418,
"text": "After successful installation navigate to Apache Drill web console and select the storage menu option as shown in the following screenshot."
},
{
"code": null,
"e": 64695,
"s": 64558,
"text": "Then choose HBase Enable option, after that go to the update option and now you will see the response as shown in the following program."
},
{
"code": null,
"e": 64894,
"s": 64695,
"text": "{\n \"type\": \"hbase\",\n \"config\": {\n \"hbase.zookeeper.quorum\": \"localhost\",\n \"hbase.zookeeper.property.clientPort\": \"2181\"\n },\n \"size.calculator.enabled\": false,\n \"enabled\": true\n}\n"
},
{
"code": null,
"e": 65195,
"s": 64894,
"text": "Here the config settings “hbase.zookeeper.property.clientPort” : “2181” indicates ZooKeeper port id. In the embedded mode, it will automatically assign it to the ZooKeeper, but in the distributed mode, you must specify the ZooKeeper port id’s separately. Now, HBase plugin is enabled in Apache Drill."
},
{
"code": null,
"e": 65271,
"s": 65195,
"text": "After enabling the plugin, first start your Hadoop server then start HBase."
},
{
"code": null,
"e": 65415,
"s": 65271,
"text": "After Hadoop and HBase has been started, you can start the HBase interactive shell using “hbase shell” command as shown in the following query."
},
{
"code": null,
"e": 65432,
"s": 65415,
"text": "/bin/hbase shell"
},
{
"code": null,
"e": 65498,
"s": 65432,
"text": "Then you will see the response as shown in the following program."
},
{
"code": null,
"e": 65518,
"s": 65498,
"text": "hbase(main):001:0>\n"
},
{
"code": null,
"e": 65576,
"s": 65518,
"text": "To query HBase, you should complete the following steps −"
},
{
"code": null,
"e": 65653,
"s": 65576,
"text": "Pipe the following commands to the HBase shell to create a “customer” table."
},
{
"code": null,
"e": 65711,
"s": 65653,
"text": "hbase(main):001:0> create 'customers','account','address'"
},
{
"code": null,
"e": 65800,
"s": 65711,
"text": "Create a simple text file named “hbase-customers.txt” as shown in the following program."
},
{
"code": null,
"e": 66587,
"s": 65800,
"text": "put 'customers','Alice','account:name','Alice'\nput 'customers','Alice','address:street','123 Ballmer Av'\nput 'customers','Alice','address:zipcode','12345'\nput 'customers','Alice','address:state','CA'\nput 'customers','Bob','account:name','Bob'\nput 'customers','Bob','address:street','1 Infinite Loop'\nput 'customers','Bob','address:zipcode','12345'\nput 'customers','Bob','address:state','CA'\nput 'customers','Frank','account:name','Frank'\nput 'customers','Frank','address:street','435 Walker Ct'\nput 'customers','Frank','address:zipcode','12345'\nput 'customers','Frank','address:state','CA'\nput 'customers','Mary','account:name','Mary'\nput 'customers','Mary','address:street','56 Southern Pkwy'\nput 'customers','Mary','address:zipcode','12345'\nput 'customers','Mary','address:state','CA'"
},
{
"code": null,
"e": 66666,
"s": 66587,
"text": "Now, issue the following command in hbase shell to load the data into a table."
},
{
"code": null,
"e": 66749,
"s": 66666,
"text": "hbase(main):001:0> cat ../drill_sample/hbase/hbase-customers.txt | bin/hbase shell"
},
{
"code": null,
"e": 66815,
"s": 66749,
"text": "Now switch to Apache Drill shell and issue the following command."
},
{
"code": null,
"e": 66872,
"s": 66815,
"text": "0: jdbc:drill:zk = local> select * from hbase.customers;"
},
{
"code": null,
"e": 67777,
"s": 66872,
"text": "+------------+---------------------+---------------------------------------------------------------------------+\n| row_key | account | address |\n+------------+---------------------+---------------------------------------------------------------------------+\n| 416C696365 | {\"name\":\"QWxpY2U=\"} | {\"state\":\"Q0E=\",\"street\":\"MTIzIEJhbGxtZXIgQXY=\",\"zipcode\":\"MTIzNDU=\"} |\n| 426F62 | {\"name\":\"Qm9i\"} | {\"state\":\"Q0E=\",\"street\":\"MSBJbmZpbml0ZSBMb29w\",\"zipcode\":\"MTIzNDU=\"} |\n| 4672616E6B | {\"name\":\"RnJhbms=\"} | {\"state\":\"Q0E=\",\"street\":\"NDM1IFdhbGtlciBDdA==\",\"zipcode\":\"MTIzNDU=\"} |\n| 4D617279 | {\"name\":\"TWFyeQ==\"} | {\"state\":\"Q0E=\",\"street\":\"NTYgU291dGhlcm4gUGt3eQ==\",\"zipcode\":\"MTIzNDU=\"} |\n+------------+---------------------+---------------------------------------------------------------------------+\n"
},
{
"code": null,
"e": 67830,
"s": 67777,
"text": "The output will be 4 rows selected in 1.211 seconds."
},
{
"code": null,
"e": 68039,
"s": 67830,
"text": "Apache Drill fetches the HBase data as a binary format, which we can convert into readable data using CONVERT_FROM function available in drill. Check and use the following query to get proper data from drill."
},
{
"code": null,
"e": 68527,
"s": 68039,
"text": "0: jdbc:drill:zk = local> SELECT CONVERT_FROM(row_key, 'UTF8') AS customer_id,\n. . . . . . . . . . . > CONVERT_FROM(customers.account.name, 'UTF8') AS customers_name,\n. . . . . . . . . . . > CONVERT_FROM(customers.address.state, 'UTF8') AS customers_state,\n. . . . . . . . . . . > CONVERT_FROM(customers.address.street, 'UTF8') AS customers_street,\n. . . . . . . . . . . > CONVERT_FROM(customers.address.zipcode, 'UTF8') AS customers_zipcode\n. . . . . . . . . . . > FROM hbase.customers;"
},
{
"code": null,
"e": 69264,
"s": 68527,
"text": "+--------------+----------------+-----------------+------------------+--------------------+\n| customer_id | customers_name | customers_state | customers_street | customers_zipcode |\n+--------------+----------------+-----------------+------------------+--------------------+\n| Alice | Alice | CA | 123 Ballmer Av | 12345 |\n| Bob | Bob | CA | 1 Infinite Loop | 12345 |\n| Frank | Frank | CA | 435 Walker Ct | 12345 |\n| Mary | Mary | CA | 56 Southern Pkwy | 12345 |\n+--------------+----------------+-----------------+------------------+--------------------+\n"
},
{
"code": null,
"e": 69500,
"s": 69264,
"text": "Hive is a data warehouse infrastructure tool to process structured data in Hadoop. It resides on top of Hadoop to summarize Big Data, and makes querying and analyzing easy. Hive stores schema in a database and processed data into HDFS."
},
{
"code": null,
"e": 69574,
"s": 69500,
"text": "Following are the steps that are used to query Hive data in Apache Drill."
},
{
"code": null,
"e": 69632,
"s": 69574,
"text": "You must need to install the following components first −"
},
{
"code": null,
"e": 69670,
"s": 69632,
"text": "Java installed version 1.7 or greater"
},
{
"code": null,
"e": 69677,
"s": 69670,
"text": "Hadoop"
},
{
"code": null,
"e": 69682,
"s": 69677,
"text": "Hive"
},
{
"code": null,
"e": 69692,
"s": 69682,
"text": "ZooKeeper"
},
{
"code": null,
"e": 69798,
"s": 69692,
"text": "After the installation, start all the services (Hadoop, ZooKeeper and Hive) one by one in a new terminal."
},
{
"code": null,
"e": 69861,
"s": 69798,
"text": "You can start the Hive metastore using the following command −"
},
{
"code": null,
"e": 69867,
"s": 69861,
"text": "Query"
},
{
"code": null,
"e": 69892,
"s": 69867,
"text": "hive --service metastore"
},
{
"code": null,
"e": 69962,
"s": 69892,
"text": "Apache Drill uses Hive metastore service to get hive table’s details."
},
{
"code": null,
"e": 70044,
"s": 69962,
"text": "To start Drill shell in a distributed mode, you can issue the following command −"
},
{
"code": null,
"e": 70050,
"s": 70044,
"text": "Query"
},
{
"code": null,
"e": 70072,
"s": 70050,
"text": "bin/drillbit.sh start"
},
{
"code": null,
"e": 70230,
"s": 70072,
"text": "Like HBase, open Apache Drill web console and choose Hive storage plugin enable option then add the following changes to hive storage plugin “update” option,"
},
{
"code": null,
"e": 70447,
"s": 70230,
"text": "{\n \"type\": \"hive\",\n \"enabled\": false,\n \"configProps\": {\n \"hive.metastore.uris\": \"thrift://localhost:9083\",\n \"hive.metastore.sasl.enabled\": \"false\",\n \"fs.default.name\": \"hdfs://localhost/\"\n }\n}\n"
},
{
"code": null,
"e": 70505,
"s": 70447,
"text": "Create a table in hive shell using the following command."
},
{
"code": null,
"e": 70511,
"s": 70505,
"text": "Query"
},
{
"code": null,
"e": 70630,
"s": 70511,
"text": "create table customers (Name string, address string) row format delimited fields terminated by ',' stored as textfile;"
},
{
"code": null,
"e": 70687,
"s": 70630,
"text": "Load data in the hive shell using the following command."
},
{
"code": null,
"e": 70693,
"s": 70687,
"text": "Query"
},
{
"code": null,
"e": 70778,
"s": 70693,
"text": "load data local inpath '/path/to/file/customers.csv' overwrite into table customers;"
},
{
"code": null,
"e": 70844,
"s": 70778,
"text": "You can query data in the hive shell using the following command."
},
{
"code": null,
"e": 70850,
"s": 70844,
"text": "Query"
},
{
"code": null,
"e": 70882,
"s": 70850,
"text": "select * from hive.`customers`;"
},
{
"code": null,
"e": 70889,
"s": 70882,
"text": "Result"
},
{
"code": null,
"e": 70989,
"s": 70889,
"text": "'Alice','123 Ballmer Av'\n'Bob','1 Infinite Loop'\n'Frank','435 Walker Ct'\n'Mary','56 Southern Pkwy'\n"
},
{
"code": null,
"e": 71097,
"s": 70989,
"text": "Parquet is a columnar storage format. Apache Drill uses Parquet format for easy, fast and efficient access."
},
{
"code": null,
"e": 71211,
"s": 71097,
"text": "Before moving to create a table in parquet, you must change the Drill storage format using the following command."
},
{
"code": null,
"e": 71282,
"s": 71211,
"text": "0: jdbc:drill:zk = local> alter session set `store.format`= 'parquet';"
},
{
"code": null,
"e": 71458,
"s": 71282,
"text": "+-------+------------------------+\n| ok | summary |\n+-------+------------------------+\n| true | store.format updated. |\n+———----+------------------------+\n"
},
{
"code": null,
"e": 71509,
"s": 71458,
"text": "You can create a table using the following syntax."
},
{
"code": null,
"e": 71657,
"s": 71509,
"text": "0: jdbc:drill:zk = local> create table dfs.tmp.`/Users/../workspace` as select * from\n dfs.`/Users/../workspace/Drill-samples/student_list.json`;"
},
{
"code": null,
"e": 71863,
"s": 71657,
"text": "+----------+---------------------------+\n| Fragment | Number of records written |\n+----------+---------------------------+\n| 0_0 | 10 |\n+----------+---------------------------+\n"
},
{
"code": null,
"e": 71920,
"s": 71863,
"text": "To see the table contents, type-in the following query −"
},
{
"code": null,
"e": 71991,
"s": 71920,
"text": "0: jdbc:drill:zk = local> select * from dfs.tmp.`/Users/../workspace`;"
},
{
"code": null,
"e": 73336,
"s": 71991,
"text": "+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+\n| ID | name | age | gender | standard | mark1 | mark2 | mark3 | addr | pincode |\n+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+\n| 001 | Adam | 12 | male | six | 70 | 50 | 60 | 23 new street | 111222 |\n| 002 | Amit | 12 | male | six | 40 | 50 | 40 | 12 old street | 111222 |\n| 003 | Bob | 12 | male | six | 60 | 80 | 70 | 10 cross street | 111222 |\n| 004 | David | 12 | male | six | 50 | 70 | 70 | 15 express avenue | 111222 |\n| 005 | Esha | 12 | female | six | 70 | 60 | 65 | 20 garden street | 111222 |\n| 006 | Ganga | 12 | female | six | 100 | 95 | 98 | 25 north street | 111222 |\n| 007 | Jack | 13 | male | six | 55 | 45 | 45 | 2 park street | 111222 |\n| 008 | Leena | 12 | female | six | 90 | 85 | 95 | 24 south street | 111222 |\n| 009 | Mary | 13 | female | six | 75 | 85 | 90 | 5 west street | 111222 |\n| 010 | Peter | 13 | female | six | 80 | 85 | 88 | 16 park avenue | 111222 |\n+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+\n"
},
{
"code": null,
"e": 73729,
"s": 73336,
"text": "Apache Drill provides JDBC interface to connect and execute queries. We can use JDBC interface in JDBC based SQL Client like “SquirreL SQL Client” and work on all the features of drill. We can use the same JDBC interface to connect drill from our Java based application. Let us see how to connect drill and execute commands in our sample Java application using JDBC interface in this section."
},
{
"code": null,
"e": 73938,
"s": 73729,
"text": "Apache Drill provides a JDBC driver as a single jar file and it is available @ /path/to/drill/jars/jdbc-driver/drill-jdbc-all-1.6.0.jar. The connection string to connect the drill is of the following format −"
},
{
"code": null,
"e": 74129,
"s": 73938,
"text": "jdbc:drill:zk = <zk_host>:<zk_port>\njdbc:drill:zk = <zk_host>:<zk_port>/<zk_drill_path>/<zk_drillbit_name\njdbc:drill:zk = <zk_host>:<zk_port>/<zk_drill_path>/<zk_drillbit_name;schema = hive\n"
},
{
"code": null,
"e": 74334,
"s": 74129,
"text": "Considering ZooKeeper is installed in the local system, the port configured is 2181, the drill path is “drill” and drillbit name is “drillbits1”, the connection string may be among the following commands."
},
{
"code": null,
"e": 74474,
"s": 74334,
"text": "jdbc:drill:zk = localhost:2181\njdbc:drill:zk = localhost:2181/drill/dillbits1\njdbc:drill:zk = localhost:2181/drill/dillbits1;schema = hive\n"
},
{
"code": null,
"e": 74637,
"s": 74474,
"text": "if the drill is installed in a distributed mode, we can replace the “localhost” with the list of drill installed system IP/name as shown in the following command."
},
{
"code": null,
"e": 74710,
"s": 74637,
"text": "jdbc:drill:zk = 1.2.3.4:2181,5.6.7.8:2181/drill/dillbits1;schema = hive\n"
},
{
"code": null,
"e": 74910,
"s": 74710,
"text": "The connection to drill is just like any other JDBC interface. Now, create a new maven project with \"com.tutorialspoint.drill.samples\" as the package name and “connect-drill” as the application name."
},
{
"code": null,
"e": 75085,
"s": 74910,
"text": "Then, update the following code in “App.java” file. The coding is simple and self-explanatory. The query used in the application is the default JSON file packaged into drill."
},
{
"code": null,
"e": 75831,
"s": 75085,
"text": "package com.tutorialspoint.drill.samples;\nimport java.sql.*;\nimport java.lang.*;\npublic class App{\n\n public static void main( String[] args ) throws SQLException, ClassNotFoundException{\n \n // load the JDBC driver\n Class.forName(\"org.apache.drill.jdbc.Driver\");\n \n // Connect the drill using zookeeper drill path\n Connection connection = DriverManager.getConnection(\"jdbc:drill:zk = localhost:2181/drill/drillbits1\");\n \n // Query drill\n Statement st = connection.createStatement();\n ResultSet rs = st.executeQuery(\"SELECT * from cp.`employee.json` LIMIT 3\");\n \n // Fetch and show the result\n while(rs.next()){\n System.out.println(\"Name: \" + rs.getString(2));\n }\n }\n}"
},
{
"code": null,
"e": 75889,
"s": 75831,
"text": "Now add following drill dependency tag to “pom.xml” file."
},
{
"code": null,
"e": 76031,
"s": 75889,
"text": "<dependency>\n <groupId>org.apache.drill.exec</groupId>\n <artifactId>drill-jdbc-all</artifactId>\n <version>1.1.0</version>\n</dependency>"
},
{
"code": null,
"e": 76100,
"s": 76031,
"text": "Now, you can compile the application by using the following command."
},
{
"code": null,
"e": 76118,
"s": 76100,
"text": "mvn clean package"
},
{
"code": null,
"e": 76192,
"s": 76118,
"text": "Once the application is compiled, execute it using the following command."
},
{
"code": null,
"e": 76341,
"s": 76192,
"text": "java -cp target/connect-drill-1.0.jar:/path/to/apache-drill-1.6.0/jars/\n jdbc-driver/drill-jdbc-all-1.6.0.jar com.tutorialspoint.drill.samples.App"
},
{
"code": null,
"e": 76519,
"s": 76341,
"text": "The output of this application list is the name of the first three employees available in “employee.json” file and it will show in the console as shown in the following program."
},
{
"code": null,
"e": 76582,
"s": 76519,
"text": "Name: Sheri Nowmer\nName: Derrick Whelply\nName: Michael Spence\n"
},
{
"code": null,
"e": 76781,
"s": 76582,
"text": "Apache Drill has an option to create custom functions. These custom functions are reusable SQL functions that you develop in Java to encapsulate the code that processes column values during a query."
},
{
"code": null,
"e": 77158,
"s": 76781,
"text": "Custom functions can perform calculations and transformations that the built-in SQL operators and functions do not provide. Custom functions are called from within a SQL statement, like a regular function, and return a single value. Apache Drill has custom aggregate function as well and it is still evolving. Let us see how to create a simple custom function in this section."
},
{
"code": null,
"e": 77574,
"s": 77158,
"text": "Apache Drill provides a simple interface, “DrillSimpleFunc”, which we have to implement to create a new custom function. The “DrillSimpleFunc” interface has two methods, “setup” and “eval”. The “setup” method is to initialize necessary variables. “eval” method is actual method used to incorporate the custom function logic. The “eval” method has certain attributes to set function name, input and output variables."
},
{
"code": null,
"e": 77939,
"s": 77574,
"text": "Apache Drill provide a list of datatype to hold input and output variable like BitHolder, VarCharHolder, BigIntHolder, IntHolder, etc. We can use these datatypes to pass on information between drill and custom function. Now, let us create a new application using Maven with “com.tutorialspoint.drill.function” as the package name and “is-pass” as the library name."
},
{
"code": null,
"e": 78112,
"s": 77939,
"text": "mvn archetype:generate -DgroupId = com.tutorialspoint.drill.function -DartifactId =\n is-pass -DarchetypeArtifactId = maven-archetype-quickstart -DinteractiveMode = false\n"
},
{
"code": null,
"e": 78118,
"s": 78112,
"text": "Here,"
},
{
"code": null,
"e": 78148,
"s": 78118,
"text": "-DgroupId &minus package name"
},
{
"code": null,
"e": 78178,
"s": 78148,
"text": "-DgroupId &minus package name"
},
{
"code": null,
"e": 78207,
"s": 78178,
"text": "-DartifactId &minus argument"
},
{
"code": null,
"e": 78236,
"s": 78207,
"text": "-DartifactId &minus argument"
},
{
"code": null,
"e": 78606,
"s": 78236,
"text": "Then remove the App.java file and create new java file and name it as “IsPassFunc.java”. This java file will hold out custom function logic. The custom function logic is to check whether the particular student is secured pass in a particular subject by checking his mark with cutoff mark. The student mark will be first input and it will change according to the record."
},
{
"code": null,
"e": 78903,
"s": 78606,
"text": "The second input is the cutoff mark, which will be a constant and does not change for different records. The custom function will implement “DrillSimpleFunc” interface and just check whether the given input is higher than the cutoff. If the input is higher, then if returns true, otherwise false."
},
{
"code": null,
"e": 78930,
"s": 78903,
"text": "The coding is as follows −"
},
{
"code": null,
"e": 80323,
"s": 78930,
"text": "package com.tutorialspoint.drill.function;\n\nimport com.google.common.base.Strings;\nimport io.netty.buffer.DrillBuf;\n\nimport org.apache.drill.exec.expr.DrillSimpleFunc;\n\nimport org.apache.drill.exec.expr.annotations.FunctionTemplate;\nimport org.apache.drill.exec.expr.annotations.Output;\nimport org.apache.drill.exec.expr.annotations.Param;\n\nimport org.apache.drill.exec.expr.holders.BigIntHolder;\nimport org.apache.drill.exec.expr.holders.BitHolder;\nimport org.apache.drill.exec.expr.holders.NullableVarCharHolder;\nimport org.apache.drill.exec.expr.holders.VarCharHolder;\n\nimport javax.inject.Inject;\n\n// name of the function to be used in drill\n@FunctionTemplate(\n name = “ispass\",\n scope = FunctionTemplate.FunctionScope.SIMPLE,\n nulls = FunctionTemplate.NullHandling.NULL_IF_NULL\n)\n\npublic class IsPassFunc implements DrillSimpleFunc {\n\n // input - student mark\n @Param\n BigIntHolder input;\n \n // input - cutoff mark, constant value\n @Param(constant = true)\n BigIntHolder inputCutOff;\n \n // output - true / false\n @Output\n BitHolder out;\n \n public void setup() { }\n \n // main logic of the function. checks mark with cutoff and returns true / false.\n \n public void eval() {\n \n int mark = (int) input.value;\n int cutOffMark = (int) inputCutOff.value;\n if(mark >= cutOffMark)\n out.value = 1;\n else\n out.value = 0;\n }\n}"
},
{
"code": null,
"e": 80444,
"s": 80323,
"text": "Now, you can create a resource file @ is-pass/src/main/resources/drill-module.conf and place the following code into it."
},
{
"code": null,
"e": 80719,
"s": 80444,
"text": "drill {\n classpath.scanning {\n base.classes : ${?drill.classpath.scanning.base.classes} [\n com.tutorialspoint.drill.function.IsPassFunc\n ],\n packages : ${?drill.classpath.scanning.packages} [\n com.tutorialspoint.drill.function\n ]\n }\n}"
},
{
"code": null,
"e": 80905,
"s": 80719,
"text": "Apache Drill uses this configuration file to find the custom function class in the jar file. A jar file can have any number of custom function and it should be properly configured here."
},
{
"code": null,
"e": 81009,
"s": 80905,
"text": "Finally, add the following configuration in “pom.xml” to properly compile the custom function in maven."
},
{
"code": null,
"e": 81058,
"s": 81009,
"text": "Change the following settings in “pom.xml” file."
},
{
"code": null,
"e": 82053,
"s": 81058,
"text": "<dependencies>\n <dependency>\n <groupId>org.apache.drill.exec</groupId>\n <artifactId>drill-java-exec</artifactId>\n <version>1.1.0</version>\n </dependency>\n</dependencies>\n\n<build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-source-plugin</artifactId>\n <version>2.4</version>\n <executions>\n <execution>\n <id>attach-sources</id>\n <phase>package</phase>\n <goals>\n <goal>jar-no-fork</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n \n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.0</version>\n <configuration>\n <verbose>true</verbose>\n <compilerVersion>1.7</compilerVersion>\n <source>1.7</source>\n <target>1.7</target>\n </configuration>\n </plugin>\n </plugins>\n</build>"
},
{
"code": null,
"e": 82129,
"s": 82053,
"text": "After making all the changes, create a package using the following command."
},
{
"code": null,
"e": 82147,
"s": 82129,
"text": "mvn clean package"
},
{
"code": null,
"e": 82350,
"s": 82147,
"text": "Maven will create the necessary jars, is-pass-1.0.jar & is-pass-1.0-sources.jar in the \"target\" folder. Now, copy the jar files and place it @ /path/to/apache-drill/jars/3rdparty in all the drill nodes."
},
{
"code": null,
"e": 82519,
"s": 82350,
"text": "After jar files are place properly in all the drillbits, restart all the drillbits, open a new drill shell and then execute the query as shown in the following program."
},
{
"code": null,
"e": 82632,
"s": 82519,
"text": "select name, ispass(mark1, 35) as is_pass from dfs.`/Users/../Workspace/drill_sample/student_list.json` limit 3;"
},
{
"code": null,
"e": 82675,
"s": 82632,
"text": "name is_pass\nAdam true\nAmit true\nBob true\n"
},
{
"code": null,
"e": 82793,
"s": 82675,
"text": "Apache Drill custom functions are simple to create and provides great extension capabilities to drill query language."
},
{
"code": null,
"e": 82894,
"s": 82793,
"text": "Apache Drill supports many of today's best industrial applications. Some of these contributors are −"
},
{
"code": null,
"e": 82901,
"s": 82894,
"text": "Oracle"
},
{
"code": null,
"e": 82913,
"s": 82901,
"text": "IBM Netezza"
},
{
"code": null,
"e": 82922,
"s": 82913,
"text": "Clustrix"
},
{
"code": null,
"e": 82930,
"s": 82922,
"text": "Pentaho"
},
{
"code": null,
"e": 83169,
"s": 82930,
"text": "Apache Drill is a schema free SQL engine and scales up to 10,000 servers or more to process petabytes of data and trillions of records in less than a second. Apache Drill uses pure data flow through the memory and extensible architecture."
},
{
"code": null,
"e": 83204,
"s": 83169,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 83223,
"s": 83204,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 83258,
"s": 83223,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 83279,
"s": 83258,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 83312,
"s": 83279,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 83325,
"s": 83312,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 83360,
"s": 83325,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 83378,
"s": 83360,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 83411,
"s": 83378,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 83429,
"s": 83411,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 83462,
"s": 83429,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 83480,
"s": 83462,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 83487,
"s": 83480,
"text": " Print"
},
{
"code": null,
"e": 83498,
"s": 83487,
"text": " Add Notes"
}
] |
How to interact with APIs in Python | by Dan Root | Towards Data Science
|
APIs (Application Programming Interface) have an enormous impact on the development, software, and programming communities. Not only are APIs useful, but a good amount of them are surprisingly simple to conduct basic interactions with. Programming languages can interact with APIs and perform tasks to achieve specific outcomes. We will use Python for this purpose in this article. Python is one of my preferred languages, and has especially useful modules for interacting with APIs. If you haven’t already looked at some of my articles talking about the history, overview, basics, and IDEs associated to the Python language I will include them below.
I will include my GitHub repository for the code involved here.
medium.com
medium.com
medium.com
medium.com
If you haven’t ever worked with an API before you should learn about HTTP methods. I will only go into the basics for this article. I would also recommend Postman to learn and do basic tasks when beginning with HTTP methods. Postman is useful for several other purposes, as well.
www.postman.com
GET — HTTP Client uses GET method to retrieve data from a Server in a one-way direction to the Client.
POST — HTTP Client uses POST method to send data to a Server in a one-way direction to the Server. (Although, we use a Python method to achieve this)
This article will only cover the basics to get started with using HTTP methods with Python. We will also only be covering REST APIs. I am going to be using the JetBrains PyCharm IDE for this project.
www.jetbrains.com
So, say we want to get weather for the next day once per day and automatically get an email containing that content.
For this we will use the OpenWeatherMap API and the Google Gmail API:
openweathermap.org
developers.google.com
To start things off you are going to have to make an account with OpenWeatherMap, which means you must be eligible according to their policies. After making an account you will be brought to the home dashboard. Navigate to the API keys tab. This is the key you will need when we code out the GET request in Python. Then go to the API section of their website. Click the One Call API.
https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API key}
Now I import the requests module into Python. I will also need the pandas module.
import requestsimport pandas as pd
I will then use a GET request from the requests module to retrieve data about the weather I want to get information from. Using the OpenWeatherMap One Call API you can put together a query string. A query string is a piece of the URL (Uniform Resource Locator) that uses keys and values to perform a large amount of processes and functions. Everything after the ? is the query string.
response = requests.get("https://api.openweathermap.org/data/2.5/onecall?lat=42.937084&lon=-75.6107&exclude=current,minutely,hourly,alerts&appid=redacted&units=imperial").json()
I’m asking the server for daily data by using the parameter exclude= and the values current,minutely,hourly,alerts to filter my results down. I am going to use the coordinates of New York for this example, but you can use whatever latitude and longitude you choose.
I will now use the json_normalize() method from the pandas module to format our data correctly into a Pandas DataFrame. I will also use the record_path= parameter to focus in on the metadata that is important to what I need.
responseData = pd.json_normalize(response, record_path="daily")
You can figure out the metadata that you need by looking for it in the API documentation’s response data section. I will now grab the info I need by slicing our data down.
# get only tomorrows dataresponseData = responseData[1:2]# convert the precipitation to a percentageresponseData[’pop’][1] *100
Print the results. I used alt commands to get the degree symbol. ALT 248 | ALT 0176.
print(f"Tomorrow will have a low of: {responseData['temp.min'][1]}°.")print(f"Tomorrow will have a high of: {responseData['temp.max'][1]}°.")print(f"Tomorrow will have a {responseData['pop'][1]}% chance of precipitation.")msg_text = f"Tomorrow will have a low of: {responseData[’temp.min’][1]}°, a high of: {responseData[’temp.max’][1]}°, and a {responseData[’pop’][1]}% chance of precipitation."[out]Tomorrow will have a low of: 56.95°.Tomorrow will have a high of: 75.43°.Tomorrow will have a 20.0% chance of precipitation.
So, I now have my weather data in a format that I will use the Gmail API to send to myself once a day at 7:00 AM in the morning detailing the next day's weather for me. To do this we will need to conduct a few actions in your google account to allow this. Make sure you follow the guide on the Gmail API QuickStart Guide about authenticating your access and downloading your credentials.
developers.google.com
First you will need to import the proper packages
import pickleimport osimport base64import googleapiclient.discoveryfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport pickleimport osfrom google_auth_oauthlib.flow import InstalledAppFlow
Next you will need to set permissions:
# set permissionsSCOPES = ['https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.modify']
Then I will set up the credentials:
home_dir = os.path.expanduser('~')json_path = os.path.join(home_dir, 'Downloads', 'credentials.json')flow = InstalledAppFlow.from_client_secrets_file(json_path, SCOPES)creds = flow.run_local_server(port=0)pickle_path = os.path.join(home_dir, 'gmail.pickle')with open(pickle_path, 'wb') as token: pickle.dump(creds, token)home_dir = os.path.expanduser('~')pickle_path = os.path.join(home_dir, 'gmail.pickle')creds = pickle.load(open(pickle_path, 'rb'))
I can build the service now:
service = googleapiclient.discovery.build('gmail', 'v1', credentials=creds)
Last you need to send the message:
message = MIMEMultipart('alternative')message['Subject'] = "Tomorrow's daily weather alert"message['From'] = '<youremail@email.com>'message['To'] = '<youremail@email.com'messagePlain = msg_textmessageHtml = '<b>Weather Update!</b>'message.attach(MIMEText(messagePlain, 'plain'))message.attach(MIMEText(messageHtml, 'html'))raw = base64.urlsafe_b64encode(message.as_bytes())raw = raw.decode()body = {'raw': raw}message_first = bodymessage_full = ( service.users().messages().send( userId="me", body=message_first).execute())print('Message sent!')
This should open your bowser asking you to log into your account and then asks for permissions and access for your application to send and modify messages on your account. If you don’t want this annoying message, then you will want to give your app permission in the Google Cloud Developer Platform.
cloud.google.com
I recommend reading the docs for this.
cloud.google.com
I will also want to automate the script with the Task Scheduler.
I start by typing task scheduler in my search bar on the task bar. This will open an application that can schedule out different programs.
Click the Action menu and select Create Basic Task... from the list.
I proceed to then fill in the basic information about the application. Select Next when finished.
Then select the trigger as Daily. Select Next.
I entered this to be the day after I am currently authoring this article. Select Next.
Leave it on Start a program and select Next.
Program/script: should be going to the python.exe file. Add arguments should be to your Python script’s path. Select Next.
I click Finished and check to see if my task is in the Task Scheduler Library.
The script should now be automated to run every day at 7:00 AM.
Python with HTTP and APIs goes much further than this, but hopefully, this will serve as a good entry point if you are interested in this type of project or topic. If you have any questions, comments, or corrections go ahead and leave them in the responses below. Thank you for reading this article and I hope it helps.
|
[
{
"code": null,
"e": 699,
"s": 47,
"text": "APIs (Application Programming Interface) have an enormous impact on the development, software, and programming communities. Not only are APIs useful, but a good amount of them are surprisingly simple to conduct basic interactions with. Programming languages can interact with APIs and perform tasks to achieve specific outcomes. We will use Python for this purpose in this article. Python is one of my preferred languages, and has especially useful modules for interacting with APIs. If you haven’t already looked at some of my articles talking about the history, overview, basics, and IDEs associated to the Python language I will include them below."
},
{
"code": null,
"e": 763,
"s": 699,
"text": "I will include my GitHub repository for the code involved here."
},
{
"code": null,
"e": 774,
"s": 763,
"text": "medium.com"
},
{
"code": null,
"e": 785,
"s": 774,
"text": "medium.com"
},
{
"code": null,
"e": 796,
"s": 785,
"text": "medium.com"
},
{
"code": null,
"e": 807,
"s": 796,
"text": "medium.com"
},
{
"code": null,
"e": 1087,
"s": 807,
"text": "If you haven’t ever worked with an API before you should learn about HTTP methods. I will only go into the basics for this article. I would also recommend Postman to learn and do basic tasks when beginning with HTTP methods. Postman is useful for several other purposes, as well."
},
{
"code": null,
"e": 1103,
"s": 1087,
"text": "www.postman.com"
},
{
"code": null,
"e": 1206,
"s": 1103,
"text": "GET — HTTP Client uses GET method to retrieve data from a Server in a one-way direction to the Client."
},
{
"code": null,
"e": 1356,
"s": 1206,
"text": "POST — HTTP Client uses POST method to send data to a Server in a one-way direction to the Server. (Although, we use a Python method to achieve this)"
},
{
"code": null,
"e": 1556,
"s": 1356,
"text": "This article will only cover the basics to get started with using HTTP methods with Python. We will also only be covering REST APIs. I am going to be using the JetBrains PyCharm IDE for this project."
},
{
"code": null,
"e": 1574,
"s": 1556,
"text": "www.jetbrains.com"
},
{
"code": null,
"e": 1691,
"s": 1574,
"text": "So, say we want to get weather for the next day once per day and automatically get an email containing that content."
},
{
"code": null,
"e": 1761,
"s": 1691,
"text": "For this we will use the OpenWeatherMap API and the Google Gmail API:"
},
{
"code": null,
"e": 1780,
"s": 1761,
"text": "openweathermap.org"
},
{
"code": null,
"e": 1802,
"s": 1780,
"text": "developers.google.com"
},
{
"code": null,
"e": 2186,
"s": 1802,
"text": "To start things off you are going to have to make an account with OpenWeatherMap, which means you must be eligible according to their policies. After making an account you will be brought to the home dashboard. Navigate to the API keys tab. This is the key you will need when we code out the GET request in Python. Then go to the API section of their website. Click the One Call API."
},
{
"code": null,
"e": 2285,
"s": 2186,
"text": "https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API key}"
},
{
"code": null,
"e": 2367,
"s": 2285,
"text": "Now I import the requests module into Python. I will also need the pandas module."
},
{
"code": null,
"e": 2402,
"s": 2367,
"text": "import requestsimport pandas as pd"
},
{
"code": null,
"e": 2787,
"s": 2402,
"text": "I will then use a GET request from the requests module to retrieve data about the weather I want to get information from. Using the OpenWeatherMap One Call API you can put together a query string. A query string is a piece of the URL (Uniform Resource Locator) that uses keys and values to perform a large amount of processes and functions. Everything after the ? is the query string."
},
{
"code": null,
"e": 2965,
"s": 2787,
"text": "response = requests.get(\"https://api.openweathermap.org/data/2.5/onecall?lat=42.937084&lon=-75.6107&exclude=current,minutely,hourly,alerts&appid=redacted&units=imperial\").json()"
},
{
"code": null,
"e": 3231,
"s": 2965,
"text": "I’m asking the server for daily data by using the parameter exclude= and the values current,minutely,hourly,alerts to filter my results down. I am going to use the coordinates of New York for this example, but you can use whatever latitude and longitude you choose."
},
{
"code": null,
"e": 3456,
"s": 3231,
"text": "I will now use the json_normalize() method from the pandas module to format our data correctly into a Pandas DataFrame. I will also use the record_path= parameter to focus in on the metadata that is important to what I need."
},
{
"code": null,
"e": 3520,
"s": 3456,
"text": "responseData = pd.json_normalize(response, record_path=\"daily\")"
},
{
"code": null,
"e": 3692,
"s": 3520,
"text": "You can figure out the metadata that you need by looking for it in the API documentation’s response data section. I will now grab the info I need by slicing our data down."
},
{
"code": null,
"e": 3820,
"s": 3692,
"text": "# get only tomorrows dataresponseData = responseData[1:2]# convert the precipitation to a percentageresponseData[’pop’][1] *100"
},
{
"code": null,
"e": 3905,
"s": 3820,
"text": "Print the results. I used alt commands to get the degree symbol. ALT 248 | ALT 0176."
},
{
"code": null,
"e": 4431,
"s": 3905,
"text": "print(f\"Tomorrow will have a low of: {responseData['temp.min'][1]}°.\")print(f\"Tomorrow will have a high of: {responseData['temp.max'][1]}°.\")print(f\"Tomorrow will have a {responseData['pop'][1]}% chance of precipitation.\")msg_text = f\"Tomorrow will have a low of: {responseData[’temp.min’][1]}°, a high of: {responseData[’temp.max’][1]}°, and a {responseData[’pop’][1]}% chance of precipitation.\"[out]Tomorrow will have a low of: 56.95°.Tomorrow will have a high of: 75.43°.Tomorrow will have a 20.0% chance of precipitation."
},
{
"code": null,
"e": 4819,
"s": 4431,
"text": "So, I now have my weather data in a format that I will use the Gmail API to send to myself once a day at 7:00 AM in the morning detailing the next day's weather for me. To do this we will need to conduct a few actions in your google account to allow this. Make sure you follow the guide on the Gmail API QuickStart Guide about authenticating your access and downloading your credentials."
},
{
"code": null,
"e": 4841,
"s": 4819,
"text": "developers.google.com"
},
{
"code": null,
"e": 4891,
"s": 4841,
"text": "First you will need to import the proper packages"
},
{
"code": null,
"e": 5117,
"s": 4891,
"text": "import pickleimport osimport base64import googleapiclient.discoveryfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport pickleimport osfrom google_auth_oauthlib.flow import InstalledAppFlow"
},
{
"code": null,
"e": 5156,
"s": 5117,
"text": "Next you will need to set permissions:"
},
{
"code": null,
"e": 5286,
"s": 5156,
"text": "# set permissionsSCOPES = ['https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.modify']"
},
{
"code": null,
"e": 5322,
"s": 5286,
"text": "Then I will set up the credentials:"
},
{
"code": null,
"e": 5777,
"s": 5322,
"text": "home_dir = os.path.expanduser('~')json_path = os.path.join(home_dir, 'Downloads', 'credentials.json')flow = InstalledAppFlow.from_client_secrets_file(json_path, SCOPES)creds = flow.run_local_server(port=0)pickle_path = os.path.join(home_dir, 'gmail.pickle')with open(pickle_path, 'wb') as token: pickle.dump(creds, token)home_dir = os.path.expanduser('~')pickle_path = os.path.join(home_dir, 'gmail.pickle')creds = pickle.load(open(pickle_path, 'rb'))"
},
{
"code": null,
"e": 5806,
"s": 5777,
"text": "I can build the service now:"
},
{
"code": null,
"e": 5882,
"s": 5806,
"text": "service = googleapiclient.discovery.build('gmail', 'v1', credentials=creds)"
},
{
"code": null,
"e": 5917,
"s": 5882,
"text": "Last you need to send the message:"
},
{
"code": null,
"e": 6473,
"s": 5917,
"text": "message = MIMEMultipart('alternative')message['Subject'] = \"Tomorrow's daily weather alert\"message['From'] = '<youremail@email.com>'message['To'] = '<youremail@email.com'messagePlain = msg_textmessageHtml = '<b>Weather Update!</b>'message.attach(MIMEText(messagePlain, 'plain'))message.attach(MIMEText(messageHtml, 'html'))raw = base64.urlsafe_b64encode(message.as_bytes())raw = raw.decode()body = {'raw': raw}message_first = bodymessage_full = ( service.users().messages().send( userId=\"me\", body=message_first).execute())print('Message sent!')"
},
{
"code": null,
"e": 6773,
"s": 6473,
"text": "This should open your bowser asking you to log into your account and then asks for permissions and access for your application to send and modify messages on your account. If you don’t want this annoying message, then you will want to give your app permission in the Google Cloud Developer Platform."
},
{
"code": null,
"e": 6790,
"s": 6773,
"text": "cloud.google.com"
},
{
"code": null,
"e": 6829,
"s": 6790,
"text": "I recommend reading the docs for this."
},
{
"code": null,
"e": 6846,
"s": 6829,
"text": "cloud.google.com"
},
{
"code": null,
"e": 6911,
"s": 6846,
"text": "I will also want to automate the script with the Task Scheduler."
},
{
"code": null,
"e": 7050,
"s": 6911,
"text": "I start by typing task scheduler in my search bar on the task bar. This will open an application that can schedule out different programs."
},
{
"code": null,
"e": 7119,
"s": 7050,
"text": "Click the Action menu and select Create Basic Task... from the list."
},
{
"code": null,
"e": 7217,
"s": 7119,
"text": "I proceed to then fill in the basic information about the application. Select Next when finished."
},
{
"code": null,
"e": 7264,
"s": 7217,
"text": "Then select the trigger as Daily. Select Next."
},
{
"code": null,
"e": 7351,
"s": 7264,
"text": "I entered this to be the day after I am currently authoring this article. Select Next."
},
{
"code": null,
"e": 7396,
"s": 7351,
"text": "Leave it on Start a program and select Next."
},
{
"code": null,
"e": 7519,
"s": 7396,
"text": "Program/script: should be going to the python.exe file. Add arguments should be to your Python script’s path. Select Next."
},
{
"code": null,
"e": 7598,
"s": 7519,
"text": "I click Finished and check to see if my task is in the Task Scheduler Library."
},
{
"code": null,
"e": 7662,
"s": 7598,
"text": "The script should now be automated to run every day at 7:00 AM."
}
] |
Python program to remove duplicate elements index from other list - GeeksforGeeks
|
13 Sep, 2021
Given two lists, the task is to write a Python program to remove all the index elements from 2nd list which are duplicate element indices from 1st list.
Examples:
Input : test_list1 = [3, 5, 6, 5, 3, 7, 8, 6], test_list2 = [1, 7, 6, 3, 7, 9, 10, 11] Output : [1, 7, 6, 9, 10] Explanation : 3, 7 and 11 correspond to 2nd occurrence of 5, 3 and 6, hence removed.
Input : test_list1 = [3, 5, 6, 5, 3, 7, 8], test_list2 = [1, 7, 6, 3, 7, 9, 10] Output : [1, 7, 6, 9, 10] Explanation : 3 and 7 correspond to 2nd occurrence of 5 and 3 hence removed.
Method 1: Using list comprehension + loop + enumerate()
In this, we perform task of getting all the indices using enumerate() and loop using set to store already occurred elements. Then, same indices from other list are omitted.
Python3
# Python3 code to demonstrate working of# Remove duplicate elements index from other list# Using list comprehension + loop + enumerate() # initializing liststest_list1 = [3, 5, 6, 5, 3, 7, 8, 6]test_list2 = [1, 7, 6, 3, 7, 9, 10, 11] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) oc_set = set() temp = [] # getting duplicate elements listfor idx, val in enumerate(test_list1): if val not in oc_set: oc_set.add(val) else: temp.append(idx) # excluding duplicate indices from other listres = [ele for idx, ele in enumerate(test_list2) if idx not in temp] # printing resultprint("The list after removing duplicate indices : " + str(res))
Output:
The original list 1 is : [3, 5, 6, 5, 3, 7, 8, 6]
The original list 2 is : [1, 7, 6, 3, 7, 9, 10, 11]
The list after removing duplicate indices : [1, 7, 6, 9, 10]
Method 2: Using list comprehension + enumerate()
In this, we perform similar task as above just in a shorthand manner, extracting indices using enumerate() and list comprehension.
Python3
# Python3 code to demonstrate working of# Remove duplicate elements index from other list# Using list comprehension + enumerate() # initializing liststest_list1 = [3, 5, 6, 5, 3, 7, 8, 6]test_list2 = [1, 7, 6, 3, 7, 9, 10, 11] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # getting duplicate elements list using list comprehensiontemp = [idx for idx, val in enumerate(test_list1) if val in test_list1[:idx]] # excluding duplicate indices from other listres = [ele for idx, ele in enumerate(test_list2) if idx not in temp] # printing resultprint("The list after removing duplicate indices : " + str(res))
Output:
The original list 1 is : [3, 5, 6, 5, 3, 7, 8, 6]
The original list 2 is : [1, 7, 6, 3, 7, 9, 10, 11]
The list after removing duplicate indices : [1, 7, 6, 9, 10]
varshagumber28
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 25708,
"s": 25555,
"text": "Given two lists, the task is to write a Python program to remove all the index elements from 2nd list which are duplicate element indices from 1st list."
},
{
"code": null,
"e": 25718,
"s": 25708,
"text": "Examples:"
},
{
"code": null,
"e": 25916,
"s": 25718,
"text": "Input : test_list1 = [3, 5, 6, 5, 3, 7, 8, 6], test_list2 = [1, 7, 6, 3, 7, 9, 10, 11] Output : [1, 7, 6, 9, 10] Explanation : 3, 7 and 11 correspond to 2nd occurrence of 5, 3 and 6, hence removed."
},
{
"code": null,
"e": 26101,
"s": 25916,
"text": "Input : test_list1 = [3, 5, 6, 5, 3, 7, 8], test_list2 = [1, 7, 6, 3, 7, 9, 10] Output : [1, 7, 6, 9, 10] Explanation : 3 and 7 correspond to 2nd occurrence of 5 and 3 hence removed. "
},
{
"code": null,
"e": 26157,
"s": 26101,
"text": "Method 1: Using list comprehension + loop + enumerate()"
},
{
"code": null,
"e": 26330,
"s": 26157,
"text": "In this, we perform task of getting all the indices using enumerate() and loop using set to store already occurred elements. Then, same indices from other list are omitted."
},
{
"code": null,
"e": 26338,
"s": 26330,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Remove duplicate elements index from other list# Using list comprehension + loop + enumerate() # initializing liststest_list1 = [3, 5, 6, 5, 3, 7, 8, 6]test_list2 = [1, 7, 6, 3, 7, 9, 10, 11] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) oc_set = set() temp = [] # getting duplicate elements listfor idx, val in enumerate(test_list1): if val not in oc_set: oc_set.add(val) else: temp.append(idx) # excluding duplicate indices from other listres = [ele for idx, ele in enumerate(test_list2) if idx not in temp] # printing resultprint(\"The list after removing duplicate indices : \" + str(res))",
"e": 27109,
"s": 26338,
"text": null
},
{
"code": null,
"e": 27118,
"s": 27109,
"text": " Output:"
},
{
"code": null,
"e": 27281,
"s": 27118,
"text": "The original list 1 is : [3, 5, 6, 5, 3, 7, 8, 6]\nThe original list 2 is : [1, 7, 6, 3, 7, 9, 10, 11]\nThe list after removing duplicate indices : [1, 7, 6, 9, 10]"
},
{
"code": null,
"e": 27331,
"s": 27281,
"text": " Method 2: Using list comprehension + enumerate()"
},
{
"code": null,
"e": 27462,
"s": 27331,
"text": "In this, we perform similar task as above just in a shorthand manner, extracting indices using enumerate() and list comprehension."
},
{
"code": null,
"e": 27470,
"s": 27462,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Remove duplicate elements index from other list# Using list comprehension + enumerate() # initializing liststest_list1 = [3, 5, 6, 5, 3, 7, 8, 6]test_list2 = [1, 7, 6, 3, 7, 9, 10, 11] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # getting duplicate elements list using list comprehensiontemp = [idx for idx, val in enumerate(test_list1) if val in test_list1[:idx]] # excluding duplicate indices from other listres = [ele for idx, ele in enumerate(test_list2) if idx not in temp] # printing resultprint(\"The list after removing duplicate indices : \" + str(res))",
"e": 28177,
"s": 27470,
"text": null
},
{
"code": null,
"e": 28185,
"s": 28177,
"text": "Output:"
},
{
"code": null,
"e": 28348,
"s": 28185,
"text": "The original list 1 is : [3, 5, 6, 5, 3, 7, 8, 6]\nThe original list 2 is : [1, 7, 6, 3, 7, 9, 10, 11]\nThe list after removing duplicate indices : [1, 7, 6, 9, 10]"
},
{
"code": null,
"e": 28363,
"s": 28348,
"text": "varshagumber28"
},
{
"code": null,
"e": 28384,
"s": 28363,
"text": "Python list-programs"
},
{
"code": null,
"e": 28391,
"s": 28384,
"text": "Python"
},
{
"code": null,
"e": 28407,
"s": 28391,
"text": "Python Programs"
},
{
"code": null,
"e": 28505,
"s": 28407,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28537,
"s": 28505,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28579,
"s": 28537,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28621,
"s": 28579,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28677,
"s": 28621,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28704,
"s": 28677,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28726,
"s": 28704,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28765,
"s": 28726,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28811,
"s": 28765,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28849,
"s": 28811,
"text": "Python | Convert a list to dictionary"
}
] |
Ant - Data Types
|
Ant provides a number of predefined data types. Do not confuse the term "data types" with those that are available in the programming language. Instead, consider them as a set of services that are built into the product already.
The following data types are provided by Apache Ant.
The fileset data type represents a collection of files. It is used as a filter to include or exclude files that match a particular pattern.
For example, refer the following code. Here, the src attribute points to the source folder of the project.
<fileset dir="${src}" casesensitive="yes">
<include name="**/*.java"/>
<exclude name="**/*Stub*"/>
</fileset>
The fileset selects all .java files in the source folder except those contain the word 'Stub'.The case-sensitive filter is applied to the fileset, which means a file with the name Samplestub.java will not be excluded from the fileset.
A pattern set is a pattern that allows to filter files or folders easily based on certain patterns. The patterns can be created using the following meta characters −
? - Matches one character only.
? - Matches one character only.
- Matches zero or many characters.
- Matches zero or many characters.
** - Matches zero or many directories recursively.
** - Matches zero or many directories recursively.
The following example depicts the usage of a pattern set.
<patternset id="java.files.without.stubs">
<include name="src/**/*.java"/>
<exclude name="src/**/*Stub*"/>
</patternset>
The patternset can then be reused with a fileset as follows −
<fileset dir="${src}" casesensitive="yes">
<patternset refid="java.files.without.stubs"/>
</fileset>
The filelist data type is similar to the file set except the following differences −
It contains explicitly named lists of files and it does not support wild cards.
It contains explicitly named lists of files and it does not support wild cards.
This data type can be applied for existing or non-existing files.
This data type can be applied for existing or non-existing files.
Let us see the following example of the filelist data type. Here, the attribute webapp.src.folder points to the web application source folder of the project.
<filelist id="config.files" dir="${webapp.src.folder}">
<file name="applicationConfig.xml"/>
<file name="faces-config.xml"/>
<file name="web.xml"/>
<file name="portlet.xml"/>
</filelist>
By using a filterset data type along with the copy task, you can replace certain text in all the files that matches the pattern with a replacement value.
A common example is to append the version number to the release notes file, as shown in the following code.
<copy todir="${output.dir}">
<fileset dir="${releasenotes.dir}" includes="**/*.txt"/>
<filterset>
<filter token="VERSION" value="${current.version}"/>
</filterset>
</copy>
In the above mentioned code −
The attribute output.dir points to the output folder of the project.
The attribute output.dir points to the output folder of the project.
The attribute releasenotes.dir points to the release notes folder of the project.
The attribute releasenotes.dir points to the release notes folder of the project.
The attribute current.version points to the current version folder of the project.
The attribute current.version points to the current version folder of the project.
The copy task, as the name suggests, is used to copy files from one location to another.
The copy task, as the name suggests, is used to copy files from one location to another.
The path data type is commonly used to represent a class-path. Entries in the path are separated using semicolons or colons. However, these characters are replaced at the runtime by the executing system's path separator character.
The classpath is set to the list of jar files and classes in the project, as shown in the example below.
<path id="build.classpath.jar">
<pathelement path="${env.J2EE_HOME}/${j2ee.jar}"/>
<fileset dir="lib">
<include name="**/*.jar"/>
</fileset>
</path>
In the code given above −
The attribute env.J2EE_HOME points to the environment variable J2EE_HOME.
The attribute env.J2EE_HOME points to the environment variable J2EE_HOME.
The attribute j2ee.jar points to the name of the J2EE jar file in the J2EE base folder.
The attribute j2ee.jar points to the name of the J2EE jar file in the J2EE base folder.
20 Lectures
2 hours
Deepti Trivedi
19 Lectures
2.5 hours
Deepti Trivedi
139 Lectures
14 hours
Er. Himanshu Vasishta
30 Lectures
1.5 hours
Pushpendu Mondal
65 Lectures
6.5 hours
Ridhi Arora
10 Lectures
2 hours
Manish Gupta
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2326,
"s": 2097,
"text": "Ant provides a number of predefined data types. Do not confuse the term \"data types\" with those that are available in the programming language. Instead, consider them as a set of services that are built into the product already."
},
{
"code": null,
"e": 2379,
"s": 2326,
"text": "The following data types are provided by Apache Ant."
},
{
"code": null,
"e": 2519,
"s": 2379,
"text": "The fileset data type represents a collection of files. It is used as a filter to include or exclude files that match a particular pattern."
},
{
"code": null,
"e": 2626,
"s": 2519,
"text": "For example, refer the following code. Here, the src attribute points to the source folder of the project."
},
{
"code": null,
"e": 2742,
"s": 2626,
"text": "<fileset dir=\"${src}\" casesensitive=\"yes\">\n <include name=\"**/*.java\"/>\n <exclude name=\"**/*Stub*\"/>\n</fileset>"
},
{
"code": null,
"e": 2977,
"s": 2742,
"text": "The fileset selects all .java files in the source folder except those contain the word 'Stub'.The case-sensitive filter is applied to the fileset, which means a file with the name Samplestub.java will not be excluded from the fileset."
},
{
"code": null,
"e": 3143,
"s": 2977,
"text": "A pattern set is a pattern that allows to filter files or folders easily based on certain patterns. The patterns can be created using the following meta characters −"
},
{
"code": null,
"e": 3175,
"s": 3143,
"text": "? - Matches one character only."
},
{
"code": null,
"e": 3207,
"s": 3175,
"text": "? - Matches one character only."
},
{
"code": null,
"e": 3242,
"s": 3207,
"text": "- Matches zero or many characters."
},
{
"code": null,
"e": 3277,
"s": 3242,
"text": "- Matches zero or many characters."
},
{
"code": null,
"e": 3328,
"s": 3277,
"text": "** - Matches zero or many directories recursively."
},
{
"code": null,
"e": 3379,
"s": 3328,
"text": "** - Matches zero or many directories recursively."
},
{
"code": null,
"e": 3437,
"s": 3379,
"text": "The following example depicts the usage of a pattern set."
},
{
"code": null,
"e": 3564,
"s": 3437,
"text": "<patternset id=\"java.files.without.stubs\">\n <include name=\"src/**/*.java\"/>\n <exclude name=\"src/**/*Stub*\"/>\n</patternset>"
},
{
"code": null,
"e": 3626,
"s": 3564,
"text": "The patternset can then be reused with a fileset as follows −"
},
{
"code": null,
"e": 3730,
"s": 3626,
"text": "<fileset dir=\"${src}\" casesensitive=\"yes\">\n <patternset refid=\"java.files.without.stubs\"/>\n</fileset>"
},
{
"code": null,
"e": 3815,
"s": 3730,
"text": "The filelist data type is similar to the file set except the following differences −"
},
{
"code": null,
"e": 3895,
"s": 3815,
"text": "It contains explicitly named lists of files and it does not support wild cards."
},
{
"code": null,
"e": 3975,
"s": 3895,
"text": "It contains explicitly named lists of files and it does not support wild cards."
},
{
"code": null,
"e": 4041,
"s": 3975,
"text": "This data type can be applied for existing or non-existing files."
},
{
"code": null,
"e": 4107,
"s": 4041,
"text": "This data type can be applied for existing or non-existing files."
},
{
"code": null,
"e": 4265,
"s": 4107,
"text": "Let us see the following example of the filelist data type. Here, the attribute webapp.src.folder points to the web application source folder of the project."
},
{
"code": null,
"e": 4464,
"s": 4265,
"text": "<filelist id=\"config.files\" dir=\"${webapp.src.folder}\">\n <file name=\"applicationConfig.xml\"/>\n <file name=\"faces-config.xml\"/>\n <file name=\"web.xml\"/>\n <file name=\"portlet.xml\"/>\n</filelist>"
},
{
"code": null,
"e": 4618,
"s": 4464,
"text": "By using a filterset data type along with the copy task, you can replace certain text in all the files that matches the pattern with a replacement value."
},
{
"code": null,
"e": 4726,
"s": 4618,
"text": "A common example is to append the version number to the release notes file, as shown in the following code."
},
{
"code": null,
"e": 4913,
"s": 4726,
"text": "<copy todir=\"${output.dir}\">\n <fileset dir=\"${releasenotes.dir}\" includes=\"**/*.txt\"/>\n <filterset>\n <filter token=\"VERSION\" value=\"${current.version}\"/>\n </filterset>\n</copy>"
},
{
"code": null,
"e": 4943,
"s": 4913,
"text": "In the above mentioned code −"
},
{
"code": null,
"e": 5012,
"s": 4943,
"text": "The attribute output.dir points to the output folder of the project."
},
{
"code": null,
"e": 5081,
"s": 5012,
"text": "The attribute output.dir points to the output folder of the project."
},
{
"code": null,
"e": 5163,
"s": 5081,
"text": "The attribute releasenotes.dir points to the release notes folder of the project."
},
{
"code": null,
"e": 5245,
"s": 5163,
"text": "The attribute releasenotes.dir points to the release notes folder of the project."
},
{
"code": null,
"e": 5328,
"s": 5245,
"text": "The attribute current.version points to the current version folder of the project."
},
{
"code": null,
"e": 5411,
"s": 5328,
"text": "The attribute current.version points to the current version folder of the project."
},
{
"code": null,
"e": 5500,
"s": 5411,
"text": "The copy task, as the name suggests, is used to copy files from one location to another."
},
{
"code": null,
"e": 5589,
"s": 5500,
"text": "The copy task, as the name suggests, is used to copy files from one location to another."
},
{
"code": null,
"e": 5820,
"s": 5589,
"text": "The path data type is commonly used to represent a class-path. Entries in the path are separated using semicolons or colons. However, these characters are replaced at the runtime by the executing system's path separator character."
},
{
"code": null,
"e": 5925,
"s": 5820,
"text": "The classpath is set to the list of jar files and classes in the project, as shown in the example below."
},
{
"code": null,
"e": 6089,
"s": 5925,
"text": "<path id=\"build.classpath.jar\">\n <pathelement path=\"${env.J2EE_HOME}/${j2ee.jar}\"/>\n <fileset dir=\"lib\">\n <include name=\"**/*.jar\"/>\n </fileset>\n</path>"
},
{
"code": null,
"e": 6115,
"s": 6089,
"text": "In the code given above −"
},
{
"code": null,
"e": 6189,
"s": 6115,
"text": "The attribute env.J2EE_HOME points to the environment variable J2EE_HOME."
},
{
"code": null,
"e": 6263,
"s": 6189,
"text": "The attribute env.J2EE_HOME points to the environment variable J2EE_HOME."
},
{
"code": null,
"e": 6351,
"s": 6263,
"text": "The attribute j2ee.jar points to the name of the J2EE jar file in the J2EE base folder."
},
{
"code": null,
"e": 6439,
"s": 6351,
"text": "The attribute j2ee.jar points to the name of the J2EE jar file in the J2EE base folder."
},
{
"code": null,
"e": 6472,
"s": 6439,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6488,
"s": 6472,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 6523,
"s": 6488,
"text": "\n 19 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6539,
"s": 6523,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 6574,
"s": 6539,
"text": "\n 139 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 6597,
"s": 6574,
"text": " Er. Himanshu Vasishta"
},
{
"code": null,
"e": 6632,
"s": 6597,
"text": "\n 30 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6650,
"s": 6632,
"text": " Pushpendu Mondal"
},
{
"code": null,
"e": 6685,
"s": 6650,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6698,
"s": 6685,
"text": " Ridhi Arora"
},
{
"code": null,
"e": 6731,
"s": 6698,
"text": "\n 10 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6745,
"s": 6731,
"text": " Manish Gupta"
},
{
"code": null,
"e": 6752,
"s": 6745,
"text": " Print"
},
{
"code": null,
"e": 6763,
"s": 6752,
"text": " Add Notes"
}
] |
Lean Six Sigma with Python — Logistic Regression | by Samir Saci | Towards Data Science
|
Lean Six Sigma is a method that can be defined as a stepwise approach to process improvements.
In a previous article, we used the Kruskal-Wallis Test to verify the hypothesis that a specific training positively impacts operators Inbound VAS productivity. (Link)
In this article, we will implement Logistic Regression with Python to estimate the impact of a daily productivity bonus on your warehouse operators picking productivity.
SUMMARYI. Problem StatementWhat should be the minimum amount of daily incentive to get 75% of workers that reach their productivity target?II. Data Analysis1. Exploratory Data AnalysisAnalysis with Python sample data from experiment 2. Fitted Line Plot of your Logistic RegressionWhat is the probability of reaching the target for each value of daily incentive?3. Validation with the p-valueValidate that your results are significant and not due to random fluctuationIII. Conclusion
You are Reginal Director of a Logistic Company (3PL) and you have 22 warehouses in your scope.
In each warehouse, the site manager has fixed a picking productivity target for the operators; your objective is to find the right incentive policy to reach 75% of this target.
P.S: Picking Productivity is defined by the number of cartons picked per hour paid.
Currently, productive operators (operators that reach their daily productivity target) receive 5 euros per day in addition to their daily salary of 64 euros (after-tax).
However, this incentive policy applied in 2 warehouses is not that effective; only 20% of the operators are reaching this target.
QuestionWhat should be the minimum daily bonus needed to reach 75% of the picking productivity target?
Experiment
Randomly select operators in your 22 warehousesImplement a daily incentive amount varying between 1 to 20 eurosCheck if the operators reached their target
Randomly select operators in your 22 warehouses
Implement a daily incentive amount varying between 1 to 20 euros
Check if the operators reached their target
Edit: You can find a Youtube version of this article with animations in the link below.
You can find the full code in this Github (Follow Me :D) repository: Link.My portfolio with other projects: Samir Saci
Box plot of the sample distribution
The median value of incentive for reached target’s day is more than 2 times higher than the one for the days below this target.
Logistic Regression will provide us with a probability plot. We can estimate the probability of reaching the target for each value of the daily incentive.
Confirmation of the current trend: 5 euros -> 20% of the productivity target reached
We need at leat 15 euros incentive per day to ensure 75% of probability to reach the target
Code
MinitabMenu Stat > Binary Fitted Line Plot
In order to check that these results, based on sample data, are significant we need to compute the p-value.
p-value: 2.1327739857133364e-141p-value < 5%
The p-value is below 5% so we can conclude that the difference of means is statically significant.
ConclusionIf you fix a value of 15 euros per day of incentives, you will reach 75% of your target.
Code
MinitabMenu Stat > Binary Fitted Line Plot
If you are interested in other applications of Lean Six Sigma Methodology using Python you can have a look at the articles below:
www.samirsaci.com
www.samirsaci.com
Based on this experiment we have fixed a minimum amount of 15 euros/day for the bonus incentives to reach 75% of your productivity target.
Before implementing this new incentive policy you need to check that you have a positive return on investment:
What is the total cost to company (CTC)(Basic Salary + Social Contributions) per hour paid for picking operators? (Euros/Hour)
What is the total amount of hours earned after the productivity increase? (Hours)
What would be the CTC of hiring temporary workers for this number of hours? (Euros)
What is the total CTC of incentives?
After answering these questions you’ll be able to estimate the return on investment of this new incentive policy. Depending on the hourly cost of the operators you may lose or save money.
However, the operator's productivity may not be only driven by their motivation but can be also impacted by the warehouse layout, the picking process or the order profile.
Therefore, this analysis should be completed with a process optimization study to ensure that operators can exploit their full potential motivated by the right amount of incentives. (for more information you can check my previous series about warehouse picking productivity: link)
Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com
[1] P values for sklearn logistic regression, Rob Speare
[2] Improve Warehouse Productivity using Order Batching with Python, Samir Saci, Link
[3] Lean Six Sigma with Python — Kruskal Wallis Test, Samir Saci, Link
|
[
{
"code": null,
"e": 267,
"s": 172,
"text": "Lean Six Sigma is a method that can be defined as a stepwise approach to process improvements."
},
{
"code": null,
"e": 434,
"s": 267,
"text": "In a previous article, we used the Kruskal-Wallis Test to verify the hypothesis that a specific training positively impacts operators Inbound VAS productivity. (Link)"
},
{
"code": null,
"e": 604,
"s": 434,
"text": "In this article, we will implement Logistic Regression with Python to estimate the impact of a daily productivity bonus on your warehouse operators picking productivity."
},
{
"code": null,
"e": 1087,
"s": 604,
"text": "SUMMARYI. Problem StatementWhat should be the minimum amount of daily incentive to get 75% of workers that reach their productivity target?II. Data Analysis1. Exploratory Data AnalysisAnalysis with Python sample data from experiment 2. Fitted Line Plot of your Logistic RegressionWhat is the probability of reaching the target for each value of daily incentive?3. Validation with the p-valueValidate that your results are significant and not due to random fluctuationIII. Conclusion"
},
{
"code": null,
"e": 1182,
"s": 1087,
"text": "You are Reginal Director of a Logistic Company (3PL) and you have 22 warehouses in your scope."
},
{
"code": null,
"e": 1359,
"s": 1182,
"text": "In each warehouse, the site manager has fixed a picking productivity target for the operators; your objective is to find the right incentive policy to reach 75% of this target."
},
{
"code": null,
"e": 1443,
"s": 1359,
"text": "P.S: Picking Productivity is defined by the number of cartons picked per hour paid."
},
{
"code": null,
"e": 1613,
"s": 1443,
"text": "Currently, productive operators (operators that reach their daily productivity target) receive 5 euros per day in addition to their daily salary of 64 euros (after-tax)."
},
{
"code": null,
"e": 1743,
"s": 1613,
"text": "However, this incentive policy applied in 2 warehouses is not that effective; only 20% of the operators are reaching this target."
},
{
"code": null,
"e": 1846,
"s": 1743,
"text": "QuestionWhat should be the minimum daily bonus needed to reach 75% of the picking productivity target?"
},
{
"code": null,
"e": 1857,
"s": 1846,
"text": "Experiment"
},
{
"code": null,
"e": 2012,
"s": 1857,
"text": "Randomly select operators in your 22 warehousesImplement a daily incentive amount varying between 1 to 20 eurosCheck if the operators reached their target"
},
{
"code": null,
"e": 2060,
"s": 2012,
"text": "Randomly select operators in your 22 warehouses"
},
{
"code": null,
"e": 2125,
"s": 2060,
"text": "Implement a daily incentive amount varying between 1 to 20 euros"
},
{
"code": null,
"e": 2169,
"s": 2125,
"text": "Check if the operators reached their target"
},
{
"code": null,
"e": 2257,
"s": 2169,
"text": "Edit: You can find a Youtube version of this article with animations in the link below."
},
{
"code": null,
"e": 2376,
"s": 2257,
"text": "You can find the full code in this Github (Follow Me :D) repository: Link.My portfolio with other projects: Samir Saci"
},
{
"code": null,
"e": 2412,
"s": 2376,
"text": "Box plot of the sample distribution"
},
{
"code": null,
"e": 2540,
"s": 2412,
"text": "The median value of incentive for reached target’s day is more than 2 times higher than the one for the days below this target."
},
{
"code": null,
"e": 2695,
"s": 2540,
"text": "Logistic Regression will provide us with a probability plot. We can estimate the probability of reaching the target for each value of the daily incentive."
},
{
"code": null,
"e": 2780,
"s": 2695,
"text": "Confirmation of the current trend: 5 euros -> 20% of the productivity target reached"
},
{
"code": null,
"e": 2872,
"s": 2780,
"text": "We need at leat 15 euros incentive per day to ensure 75% of probability to reach the target"
},
{
"code": null,
"e": 2877,
"s": 2872,
"text": "Code"
},
{
"code": null,
"e": 2920,
"s": 2877,
"text": "MinitabMenu Stat > Binary Fitted Line Plot"
},
{
"code": null,
"e": 3028,
"s": 2920,
"text": "In order to check that these results, based on sample data, are significant we need to compute the p-value."
},
{
"code": null,
"e": 3073,
"s": 3028,
"text": "p-value: 2.1327739857133364e-141p-value < 5%"
},
{
"code": null,
"e": 3172,
"s": 3073,
"text": "The p-value is below 5% so we can conclude that the difference of means is statically significant."
},
{
"code": null,
"e": 3271,
"s": 3172,
"text": "ConclusionIf you fix a value of 15 euros per day of incentives, you will reach 75% of your target."
},
{
"code": null,
"e": 3276,
"s": 3271,
"text": "Code"
},
{
"code": null,
"e": 3319,
"s": 3276,
"text": "MinitabMenu Stat > Binary Fitted Line Plot"
},
{
"code": null,
"e": 3449,
"s": 3319,
"text": "If you are interested in other applications of Lean Six Sigma Methodology using Python you can have a look at the articles below:"
},
{
"code": null,
"e": 3467,
"s": 3449,
"text": "www.samirsaci.com"
},
{
"code": null,
"e": 3485,
"s": 3467,
"text": "www.samirsaci.com"
},
{
"code": null,
"e": 3624,
"s": 3485,
"text": "Based on this experiment we have fixed a minimum amount of 15 euros/day for the bonus incentives to reach 75% of your productivity target."
},
{
"code": null,
"e": 3735,
"s": 3624,
"text": "Before implementing this new incentive policy you need to check that you have a positive return on investment:"
},
{
"code": null,
"e": 3862,
"s": 3735,
"text": "What is the total cost to company (CTC)(Basic Salary + Social Contributions) per hour paid for picking operators? (Euros/Hour)"
},
{
"code": null,
"e": 3944,
"s": 3862,
"text": "What is the total amount of hours earned after the productivity increase? (Hours)"
},
{
"code": null,
"e": 4028,
"s": 3944,
"text": "What would be the CTC of hiring temporary workers for this number of hours? (Euros)"
},
{
"code": null,
"e": 4065,
"s": 4028,
"text": "What is the total CTC of incentives?"
},
{
"code": null,
"e": 4253,
"s": 4065,
"text": "After answering these questions you’ll be able to estimate the return on investment of this new incentive policy. Depending on the hourly cost of the operators you may lose or save money."
},
{
"code": null,
"e": 4425,
"s": 4253,
"text": "However, the operator's productivity may not be only driven by their motivation but can be also impacted by the warehouse layout, the picking process or the order profile."
},
{
"code": null,
"e": 4706,
"s": 4425,
"text": "Therefore, this analysis should be completed with a process optimization study to ensure that operators can exploit their full potential motivated by the right amount of incentives. (for more information you can check my previous series about warehouse picking productivity: link)"
},
{
"code": null,
"e": 4860,
"s": 4706,
"text": "Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com"
},
{
"code": null,
"e": 4917,
"s": 4860,
"text": "[1] P values for sklearn logistic regression, Rob Speare"
},
{
"code": null,
"e": 5003,
"s": 4917,
"text": "[2] Improve Warehouse Productivity using Order Batching with Python, Samir Saci, Link"
}
] |
Python 3 - File writelines() Method
|
The method writelines() writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value.
Following is the syntax for writelines() method −
fileObject.writelines( sequence )
sequence − This is the Sequence of the strings.
This method does not return any value.
The following example shows the usage of writelines() method.
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
#!/usr/bin/python3
# Open a file in read/write mode
fo = open("abc.txt", "r+")
print ("Name of the file: ", fo.name)
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
line = next(fo)
print ("Line No %d - %s" % (index, line))
# Close opened file
fo.close()
When we run the above program, it produces the following result −
Name of the file: foo.txt
Line No 0 - This is 1st line
Line No 1 - This is 2nd line
Line No 2 - This is 3rd line
Line No 3 - This is 4th line
Line No 4 - This is 5th line
Line No 5 - This is 6th line
Line No 6 - This is 7th line
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2520,
"s": 2340,
"text": "The method writelines() writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value."
},
{
"code": null,
"e": 2570,
"s": 2520,
"text": "Following is the syntax for writelines() method −"
},
{
"code": null,
"e": 2605,
"s": 2570,
"text": "fileObject.writelines( sequence )\n"
},
{
"code": null,
"e": 2653,
"s": 2605,
"text": "sequence − This is the Sequence of the strings."
},
{
"code": null,
"e": 2692,
"s": 2653,
"text": "This method does not return any value."
},
{
"code": null,
"e": 2754,
"s": 2692,
"text": "The following example shows the usage of writelines() method."
},
{
"code": null,
"e": 2894,
"s": 2754,
"text": "Assuming that 'foo.txt' file contains following text:\nThis is 1st line\nThis is 2nd line\nThis is 3rd line\nThis is 4th line\nThis is 5th line\n"
},
{
"code": null,
"e": 3337,
"s": 2894,
"text": "#!/usr/bin/python3\n\n# Open a file in read/write mode\nfo = open(\"abc.txt\", \"r+\")\nprint (\"Name of the file: \", fo.name)\n\nseq = [\"This is 6th line\\n\", \"This is 7th line\"]\n# Write sequence of lines at the end of the file.\nfo.seek(0, 2)\nline = fo.writelines( seq )\n\n# Now read complete file from beginning.\nfo.seek(0,0)\n for index in range(7):\n line = next(fo)\n print (\"Line No %d - %s\" % (index, line))\n\n# Close opened file\nfo.close()"
},
{
"code": null,
"e": 3403,
"s": 3337,
"text": "When we run the above program, it produces the following result −"
},
{
"code": null,
"e": 3635,
"s": 3403,
"text": "Name of the file: foo.txt\n\nLine No 0 - This is 1st line\nLine No 1 - This is 2nd line\nLine No 2 - This is 3rd line\nLine No 3 - This is 4th line\nLine No 4 - This is 5th line\nLine No 5 - This is 6th line\nLine No 6 - This is 7th line\n"
},
{
"code": null,
"e": 3672,
"s": 3635,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3688,
"s": 3672,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3721,
"s": 3688,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3740,
"s": 3721,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3775,
"s": 3740,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3797,
"s": 3775,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3831,
"s": 3797,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3859,
"s": 3831,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3894,
"s": 3859,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3908,
"s": 3894,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3941,
"s": 3908,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3958,
"s": 3941,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3965,
"s": 3958,
"text": " Print"
},
{
"code": null,
"e": 3976,
"s": 3965,
"text": " Add Notes"
}
] |
Matrix Multiplication and Normalization in C program
|
Now procedure of Matrix Multiplication is discussed. The Matrix Multiplication can only be performed, if it satisfies certain condition. Suppose two matrices are P and Q, and their dimensions are P (a x b) and Q (z x y) the resultant matrix can be found if and only if b = x. Then the order of the resultant matrix R will be (m x q).
matrixMultiply(P, Q):
Assume dimension of P is (a x b), dimension of Q is (z x y)
Begin
if b is not same as z, then exit
otherwise define R matrix as (a x y)
for i in range 0 to a - 1, do
for j in range 0 to y – 1, do
for k in range 0 to z, do
R[i, j] = R[i, j] + (P[i, k] * Q[k, j])
done
done
done
End
Suppose we have a 2x3 matrix:
4 5 6
1 2 3 The normalized matrix would be:
4/sqrt(pow(5,2) + pow(6,2)) 5/sqrt(pow(5,2) + pow(6,2)) 6/sqrt(pow(5,2) + pow(6,2))
1/sqrt(pow(2,2) + pow(3,2)) 2/sqrt(pow(2,2) + pow(3,2)) 3/sqrt(pow(2,2) + pow(3,2))
#include <stdio.h>
#include <math.h>
int main() {
int row, col, row1, col1;
int assignMatrix[50][50], rowAdd[100] = {0};
long long int a, square[50] = {0};
double norm[50][50], k;
printf("Enter size of a matrix\n");
scanf("%d %d", &row, &col);
printf("Enter matrix of size %dX%d\n", row, col);
for ( row1 = 0; row1 < row; row1++) {
for (col1 = 0; col1 < col; col1++) {
scanf("%d", &assignMatrix[row1][col1]);
}
}
printf("\nrows: %d cols: %d elements:\n",row,col);
for( row1 = 0; row1 < row; row1++) {
for( col1 = 0; col1 < col; col1++) {
printf("%d ", assignMatrix[row1][col1]);
}
printf("\n");
}
for (row1 = 0; row1 < row; row1++) {
for (col1 = 1; col1 < col; col1++) {
a = assignMatrix[r][c];
square[row1] += a * a;
}
printf("Sum of squares of row %d: %lld\n",row1,square[row1]);
}
for ( row1 = 0; row1 < row; row1++ ) {
k = 1.0 / sqrt(square[row1]);
for( col1 = 0; col1 < col; col1++ ) {
norm[row1][col1] = k * assignMatrix[row1][col1] ;
}
}
printf("\nNormalized Matrix:\n");
for( row1 = 0; row1 < row; row1++) {
for( col1 = 0; col1 < col; col1++) {
printf("%.3lf ", norm[row1][col1]);
}
printf("\n");
}
return 0;
}
Enter size of a matrix
2
3
Enter matrix of size 2X3
4 5 6
1 2 3
rows: 2 cols: 3 elements:
4 5 6
1 2 3
Sum of squares of row 0: 61
Sum of squares of row 1: 13
Normalized Matrix:
0.512 0.640 0.768
0.277 0.555 0.832
Process returned 0 (0x0) execution time : 12.446 s
Press any key to continue.
|
[
{
"code": null,
"e": 1396,
"s": 1062,
"text": "Now procedure of Matrix Multiplication is discussed. The Matrix Multiplication can only be performed, if it satisfies certain condition. Suppose two matrices are P and Q, and their dimensions are P (a x b) and Q (z x y) the resultant matrix can be found if and only if b = x. Then the order of the resultant matrix R will be (m x q)."
},
{
"code": null,
"e": 1753,
"s": 1396,
"text": "matrixMultiply(P, Q):\nAssume dimension of P is (a x b), dimension of Q is (z x y)\nBegin\n if b is not same as z, then exit\n otherwise define R matrix as (a x y)\n for i in range 0 to a - 1, do\n for j in range 0 to y – 1, do\n for k in range 0 to z, do\n R[i, j] = R[i, j] + (P[i, k] * Q[k, j])\n done\n done\n done\nEnd"
},
{
"code": null,
"e": 1995,
"s": 1753,
"text": "Suppose we have a 2x3 matrix:\n4 5 6\n1 2 3 The normalized matrix would be:\n4/sqrt(pow(5,2) + pow(6,2)) 5/sqrt(pow(5,2) + pow(6,2)) 6/sqrt(pow(5,2) + pow(6,2))\n1/sqrt(pow(2,2) + pow(3,2)) 2/sqrt(pow(2,2) + pow(3,2)) 3/sqrt(pow(2,2) + pow(3,2))"
},
{
"code": null,
"e": 3312,
"s": 1995,
"text": "#include <stdio.h>\n#include <math.h>\nint main() {\n int row, col, row1, col1;\n int assignMatrix[50][50], rowAdd[100] = {0};\n long long int a, square[50] = {0};\n double norm[50][50], k;\n printf(\"Enter size of a matrix\\n\");\n scanf(\"%d %d\", &row, &col);\n printf(\"Enter matrix of size %dX%d\\n\", row, col);\n for ( row1 = 0; row1 < row; row1++) {\n for (col1 = 0; col1 < col; col1++) {\n scanf(\"%d\", &assignMatrix[row1][col1]);\n }\n }\n printf(\"\\nrows: %d cols: %d elements:\\n\",row,col);\n for( row1 = 0; row1 < row; row1++) {\n for( col1 = 0; col1 < col; col1++) {\n printf(\"%d \", assignMatrix[row1][col1]);\n }\n printf(\"\\n\");\n }\n for (row1 = 0; row1 < row; row1++) {\n for (col1 = 1; col1 < col; col1++) {\n a = assignMatrix[r][c];\n square[row1] += a * a;\n }\n printf(\"Sum of squares of row %d: %lld\\n\",row1,square[row1]);\n }\n for ( row1 = 0; row1 < row; row1++ ) {\n k = 1.0 / sqrt(square[row1]);\n for( col1 = 0; col1 < col; col1++ ) {\n norm[row1][col1] = k * assignMatrix[row1][col1] ;\n }\n }\n printf(\"\\nNormalized Matrix:\\n\");\n for( row1 = 0; row1 < row; row1++) {\n for( col1 = 0; col1 < col; col1++) {\n printf(\"%.3lf \", norm[row1][col1]);\n }\n printf(\"\\n\");\n }\n return 0;\n}"
},
{
"code": null,
"e": 3603,
"s": 3312,
"text": "Enter size of a matrix\n2\n3\nEnter matrix of size 2X3\n4 5 6\n1 2 3\nrows: 2 cols: 3 elements:\n4 5 6\n1 2 3\nSum of squares of row 0: 61\nSum of squares of row 1: 13\nNormalized Matrix:\n0.512 0.640 0.768\n0.277 0.555 0.832\nProcess returned 0 (0x0) execution time : 12.446 s\nPress any key to continue."
}
] |
How to restrict the number of digits inside JPasswordField in Java?
|
A JPasswordField is a subclass of JTextField and each character entered in a JPasswordField can be replaced by an echo character. This allows confidential input for passwords. The important methods of JPasswordField are getPassword(), getText(), getAccessibleContext() and etc. By default, we can enter any number of digits inside JPasswordField. If we want to restrict the digits entered by a user by implementing a DocumentFilter class and need to override the replace() method.
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException
import java.awt.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JPasswordFieldDigitLimitTest extends JFrame {
private JPasswordField passwordField;
private JPanel panel;
public JPasswordFieldDigitLimitTest() {
panel = new JPanel();
((FlowLayout) panel.getLayout()).setHgap(2);
panel.add(new JLabel("Enter Pin: "));
passwordField = new JPasswordField(4);
PlainDocument document = (PlainDocument) passwordField.getDocument();
document.setDocumentFilter(new DocumentFilter() {
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
String string = fb.getDocument().getText(0, fb.getDocument().getLength()) + text;
if (string.length() <= 4) {
super.replace(fb, offset, length, text, attrs);
}
}
});
panel.add(passwordField);
add(panel);
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JPasswordFieldDigitLimitTest();
}
}
|
[
{
"code": null,
"e": 1543,
"s": 1062,
"text": "A JPasswordField is a subclass of JTextField and each character entered in a JPasswordField can be replaced by an echo character. This allows confidential input for passwords. The important methods of JPasswordField are getPassword(), getText(), getAccessibleContext() and etc. By default, we can enter any number of digits inside JPasswordField. If we want to restrict the digits entered by a user by implementing a DocumentFilter class and need to override the replace() method."
},
{
"code": null,
"e": 1680,
"s": 1543,
"text": "public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException"
},
{
"code": null,
"e": 2922,
"s": 1680,
"text": "import java.awt.*;\nimport java.awt.*;\nimport javax.swing.*;\nimport javax.swing.text.*;\npublic class JPasswordFieldDigitLimitTest extends JFrame {\n private JPasswordField passwordField;\n private JPanel panel;\n public JPasswordFieldDigitLimitTest() {\n panel = new JPanel();\n ((FlowLayout) panel.getLayout()).setHgap(2);\n panel.add(new JLabel(\"Enter Pin: \"));\n passwordField = new JPasswordField(4);\n PlainDocument document = (PlainDocument) passwordField.getDocument();\n document.setDocumentFilter(new DocumentFilter() {\n @Override\n public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {\n String string = fb.getDocument().getText(0, fb.getDocument().getLength()) + text;\n if (string.length() <= 4) {\n super.replace(fb, offset, length, text, attrs);\n }\n }\n });\n panel.add(passwordField);\n add(panel);\n setSize(400, 300);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[] args) {\n new JPasswordFieldDigitLimitTest();\n }\n}"
}
] |
Multithreading in Java
|
Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program.
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread.
Following are the stages of the life cycle −
New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.
Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.
If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps.
As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method.
public void run( )
As a second step, you will instantiate a Thread object using the following constructor.
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.
Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method.
void start();
Here is an example that creates a new thread and starts running it.
Live Demo
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.
You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method.
public void run( )
Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method.
void start( );
Here is the preceding program rewritten to extend the Thread.
Live Demo
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
}
}
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Following is the list of important methods available in the Thread class.
The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread.
The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable.
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
public class DisplayMessage implements Runnable {
private String message;
public DisplayMessage(String message) {
this.message = message;
}
public void run() {
while(true) {
System.out.println(message);
}
}
}
Following is another class which extends the Thread class.
// File Name : GuessANumber.java
// Create a thread to extentd Thread
public class GuessANumber extends Thread {
private int number;
public GuessANumber(int number) {
this.number = number;
}
public void run() {
int counter = 0;
int guess = 0;
do {
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName() + " guesses " + guess);
counter++;
} while(guess != number);
System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**");
}
}
Following is the main program, which makes use of the above-defined classes.
// File Name : ThreadClassDemo.java
public class ThreadClassDemo {
public static void main(String [] args) {
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
Runnable bye = new DisplayMessage("Goodbye");
Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try {
thread3.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
This will produce the following result. You can try this example again and again and you will get a different result every time.
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......
While doing Multithreading programming in Java, you would need to have the following concepts very handy.
What is thread synchronization?
What is thread synchronization?
Handling interthread communication
Handling interthread communication
Handling thread deadlock
Handling thread deadlock
Major thread operations
Major thread operations
|
[
{
"code": null,
"e": 1401,
"s": 1062,
"text": "Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs."
},
{
"code": null,
"e": 1830,
"s": 1401,
"text": "By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application."
},
{
"code": null,
"e": 1948,
"s": 1830,
"text": "Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program."
},
{
"code": null,
"e": 2130,
"s": 1948,
"text": "A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread."
},
{
"code": null,
"e": 2175,
"s": 2130,
"text": "Following are the stages of the life cycle −"
},
{
"code": null,
"e": 2337,
"s": 2175,
"text": "New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread."
},
{
"code": null,
"e": 2499,
"s": 2337,
"text": "New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread."
},
{
"code": null,
"e": 2640,
"s": 2499,
"text": "Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task."
},
{
"code": null,
"e": 2781,
"s": 2640,
"text": "Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task."
},
{
"code": null,
"e": 3028,
"s": 2781,
"text": "Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing."
},
{
"code": null,
"e": 3275,
"s": 3028,
"text": "Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing."
},
{
"code": null,
"e": 3515,
"s": 3275,
"text": "Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs."
},
{
"code": null,
"e": 3755,
"s": 3515,
"text": "Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs."
},
{
"code": null,
"e": 3873,
"s": 3755,
"text": "Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates."
},
{
"code": null,
"e": 3991,
"s": 3873,
"text": "Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates."
},
{
"code": null,
"e": 4108,
"s": 3991,
"text": "Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled."
},
{
"code": null,
"e": 4300,
"s": 4108,
"text": "Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5)."
},
{
"code": null,
"e": 4548,
"s": 4300,
"text": "Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent."
},
{
"code": null,
"e": 4708,
"s": 4548,
"text": "If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps."
},
{
"code": null,
"e": 4963,
"s": 4708,
"text": "As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method."
},
{
"code": null,
"e": 4982,
"s": 4963,
"text": "public void run( )"
},
{
"code": null,
"e": 5070,
"s": 4982,
"text": "As a second step, you will instantiate a Thread object using the following constructor."
},
{
"code": null,
"e": 5117,
"s": 5070,
"text": "Thread(Runnable threadObj, String threadName);"
},
{
"code": null,
"e": 5251,
"s": 5117,
"text": "Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread."
},
{
"code": null,
"e": 5416,
"s": 5251,
"text": "Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method."
},
{
"code": null,
"e": 5430,
"s": 5416,
"text": "void start();"
},
{
"code": null,
"e": 5498,
"s": 5430,
"text": "Here is an example that creates a new thread and starts running it."
},
{
"code": null,
"e": 5509,
"s": 5498,
"text": " Live Demo"
},
{
"code": null,
"e": 6593,
"s": 5509,
"text": "class RunnableDemo implements Runnable {\n private Thread t;\n private String threadName;\n RunnableDemo( String name) {\n threadName = name;\n System.out.println(\"Creating \" + threadName );\n }\n public void run() {\n System.out.println(\"Running \" + threadName );\n try {\n for(int i = 4; i > 0; i--) {\n System.out.println(\"Thread: \" + threadName + \", \" + i);\n // Let the thread sleep for a while.\n Thread.sleep(50);\n }\n } catch (InterruptedException e) {\n System.out.println(\"Thread \" + threadName + \" interrupted.\");\n }\n System.out.println(\"Thread \" + threadName + \" exiting.\");\n }\n public void start () {\n System.out.println(\"Starting \" + threadName );\n if (t == null) {\n t = new Thread (this, threadName);\n t.start ();\n }\n }\n}\npublic class TestThread {\n public static void main(String args[]) {\n RunnableDemo R1 = new RunnableDemo( \"Thread-1\");\n R1.start();\n RunnableDemo R2 = new RunnableDemo( \"Thread-2\");\n R2.start();\n }\n}"
},
{
"code": null,
"e": 6909,
"s": 6593,
"text": "Creating Thread-1\nStarting Thread-1\nCreating Thread-2\nStarting Thread-2\nRunning Thread-1\nThread: Thread-1, 4\nRunning Thread-2\nThread: Thread-2, 4\nThread: Thread-1, 3\nThread: Thread-2, 3\nThread: Thread-1, 2\nThread: Thread-2, 2\nThread: Thread-1, 1\nThread: Thread-2, 1\nThread Thread-1 exiting.\nThread Thread-2 exiting."
},
{
"code": null,
"e": 7150,
"s": 6909,
"text": "The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class."
},
{
"code": null,
"e": 7380,
"s": 7150,
"text": "You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method."
},
{
"code": null,
"e": 7399,
"s": 7380,
"text": "public void run( )"
},
{
"code": null,
"e": 7562,
"s": 7399,
"text": "Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method."
},
{
"code": null,
"e": 7577,
"s": 7562,
"text": "void start( );"
},
{
"code": null,
"e": 7639,
"s": 7577,
"text": "Here is the preceding program rewritten to extend the Thread."
},
{
"code": null,
"e": 7650,
"s": 7639,
"text": " Live Demo"
},
{
"code": null,
"e": 8717,
"s": 7650,
"text": "class ThreadDemo extends Thread {\n private Thread t;\n private String threadName;\n ThreadDemo( String name) {\n threadName = name;\n System.out.println(\"Creating \" + threadName );\n }\n public void run() {\n System.out.println(\"Running \" + threadName );\n try {\n for(int i = 4; i > 0; i--) {\n System.out.println(\"Thread: \" + threadName + \", \" + i);\n // Let the thread sleep for a while.\n Thread.sleep(50);\n }\n } catch (InterruptedException e) {\n System.out.println(\"Thread \" + threadName + \" interrupted.\");\n }\n System.out.println(\"Thread \" + threadName + \" exiting.\");\n }\n public void start () {\n System.out.println(\"Starting \" + threadName );\n if (t == null) {\n t = new Thread (this, threadName);\n t.start ();\n }\n }\n}\npublic class TestThread {\n public static void main(String args[]) {\n ThreadDemo T1 = new ThreadDemo( \"Thread-1\");\n T1.start();\n ThreadDemo T2 = new ThreadDemo( \"Thread-2\");\n T2.start();\n }\n}"
},
{
"code": null,
"e": 9033,
"s": 8717,
"text": "Creating Thread-1\nStarting Thread-1\nCreating Thread-2\nStarting Thread-2\nRunning Thread-1\nThread: Thread-1, 4\nRunning Thread-2\nThread: Thread-2, 4\nThread: Thread-1, 3\nThread: Thread-2, 3\nThread: Thread-1, 2\nThread: Thread-2, 2\nThread: Thread-1, 1\nThread: Thread-2, 1\nThread Thread-1 exiting.\nThread Thread-2 exiting."
},
{
"code": null,
"e": 9107,
"s": 9033,
"text": "Following is the list of important methods available in the Thread class."
},
{
"code": null,
"e": 9316,
"s": 9107,
"text": "The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread."
},
{
"code": null,
"e": 9469,
"s": 9316,
"text": "The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable."
},
{
"code": null,
"e": 9796,
"s": 9469,
"text": "// File Name : DisplayMessage.java\n// Create a thread to implement Runnable\npublic class DisplayMessage implements Runnable {\n private String message;\n public DisplayMessage(String message) {\n this.message = message;\n }\n public void run() {\n while(true) {\n System.out.println(message);\n }\n }\n}"
},
{
"code": null,
"e": 9855,
"s": 9796,
"text": "Following is another class which extends the Thread class."
},
{
"code": null,
"e": 10405,
"s": 9855,
"text": "// File Name : GuessANumber.java\n// Create a thread to extentd Thread\npublic class GuessANumber extends Thread {\n private int number;\n public GuessANumber(int number) {\n this.number = number;\n }\n public void run() {\n int counter = 0;\n int guess = 0;\n do {\n guess = (int) (Math.random() * 100 + 1);\n System.out.println(this.getName() + \" guesses \" + guess);\n counter++;\n } while(guess != number);\n System.out.println(\"** Correct!\" + this.getName() + \"in\" + counter + \"guesses.**\");\n }\n}"
},
{
"code": null,
"e": 10482,
"s": 10405,
"text": "Following is the main program, which makes use of the above-defined classes."
},
{
"code": null,
"e": 11506,
"s": 10482,
"text": "// File Name : ThreadClassDemo.java\npublic class ThreadClassDemo {\n public static void main(String [] args) {\n Runnable hello = new DisplayMessage(\"Hello\");\n Thread thread1 = new Thread(hello);\n thread1.setDaemon(true);\n thread1.setName(\"hello\");\n System.out.println(\"Starting hello thread...\");\n thread1.start();\n Runnable bye = new DisplayMessage(\"Goodbye\");\n Thread thread2 = new Thread(bye);\n thread2.setPriority(Thread.MIN_PRIORITY);\n thread2.setDaemon(true);\n System.out.println(\"Starting goodbye thread...\");\n thread2.start();\n System.out.println(\"Starting thread3...\");\n Thread thread3 = new GuessANumber(27);\n thread3.start();\n try {\n thread3.join();\n } catch (InterruptedException e) {\n System.out.println(\"Thread interrupted.\");\n }\n System.out.println(\"Starting thread4...\");\n Thread thread4 = new GuessANumber(75);\n thread4.start();\n System.out.println(\"main() is ending...\");\n }\n}"
},
{
"code": null,
"e": 11635,
"s": 11506,
"text": "This will produce the following result. You can try this example again and again and you will get a different result every time."
},
{
"code": null,
"e": 11771,
"s": 11635,
"text": "Starting hello thread...\nStarting goodbye thread...\nHello\nHello\nHello\nHello\nHello\nHello\nGoodbye\nGoodbye\nGoodbye\nGoodbye\nGoodbye\n......."
},
{
"code": null,
"e": 11877,
"s": 11771,
"text": "While doing Multithreading programming in Java, you would need to have the following concepts very handy."
},
{
"code": null,
"e": 11909,
"s": 11877,
"text": "What is thread synchronization?"
},
{
"code": null,
"e": 11941,
"s": 11909,
"text": "What is thread synchronization?"
},
{
"code": null,
"e": 11976,
"s": 11941,
"text": "Handling interthread communication"
},
{
"code": null,
"e": 12011,
"s": 11976,
"text": "Handling interthread communication"
},
{
"code": null,
"e": 12036,
"s": 12011,
"text": "Handling thread deadlock"
},
{
"code": null,
"e": 12061,
"s": 12036,
"text": "Handling thread deadlock"
},
{
"code": null,
"e": 12085,
"s": 12061,
"text": "Major thread operations"
},
{
"code": null,
"e": 12109,
"s": 12085,
"text": "Major thread operations"
}
] |
How To Show Mean Value in Boxplots with ggplot2?
|
10 Oct, 2021
In this article, we will discuss how to show mean value in Boxplot with ggplot2 using R programming language.
Firstly, we will create a basic boxplot using the geom_boxplot() function of the ggplot2 package and then do the needful, so that the difference is apparent.
Syntax:
ggplot() + geom_boxplot()
Example: Basic boxplot
R
# load library tidyverselibrary(tidyverse)library(ggplot2) # basic boxplotggplot(diamonds, aes(x=cut, y=price)) + # geom_boxplot is used to plot the boxplot geom_boxplot()
Output:
In order to show mean values in boxplot using ggplot2, we use the stat_summary() function to compute new summary statistics and add them to the plot. We use stat_summary() function with ggplot() function.
Syntax:
stat_summary(mapping = NULL, data = NULL, geom = “pointrange”, position = “identity”, color=”value”, shape=”value”,...)
Example: Adding mean value to boxplot
R
# load librarieslibrary(ggplot2)library(tidyverse) # basic boxplotggplot(diamonds, aes(x=cut, y=price)) + # geom_boxplot is used to plot the boxplot geom_boxplot() + # stat_summary computes the statistics summary# fun.y arguments as mean determines that # statistical summary will be mean of y-axisstat_summary(fun.y="mean")
Output:
In the output produced above, the point in the center of the boxplot shows the variation of the mean of the y-axis for each category of data on the x-axis.
We can also change the color and shape of the mean mark using the color and shape parameter of the stat_summary() function. This helps us visualize the data better by distinguishing the mark from other symbols.
Example: Customizing added mean values
R
# load library tidyverselibrary(tidyverse)library(ggplot2) # basic boxplotggplot(diamonds, aes(x=cut, y=price)) + # geom_boxplot is used to plot the boxplot geom_boxplot() + # stat_summary computes the statistics summarystat_summary(fun.y="mean",color="red", shape=13)
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
Logistic Regression in R Programming
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Oct, 2021"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "In this article, we will discuss how to show mean value in Boxplot with ggplot2 using R programming language."
},
{
"code": null,
"e": 296,
"s": 138,
"text": "Firstly, we will create a basic boxplot using the geom_boxplot() function of the ggplot2 package and then do the needful, so that the difference is apparent."
},
{
"code": null,
"e": 304,
"s": 296,
"text": "Syntax:"
},
{
"code": null,
"e": 330,
"s": 304,
"text": "ggplot() + geom_boxplot()"
},
{
"code": null,
"e": 353,
"s": 330,
"text": "Example: Basic boxplot"
},
{
"code": null,
"e": 355,
"s": 353,
"text": "R"
},
{
"code": "# load library tidyverselibrary(tidyverse)library(ggplot2) # basic boxplotggplot(diamonds, aes(x=cut, y=price)) + # geom_boxplot is used to plot the boxplot geom_boxplot()",
"e": 530,
"s": 355,
"text": null
},
{
"code": null,
"e": 538,
"s": 530,
"text": "Output:"
},
{
"code": null,
"e": 743,
"s": 538,
"text": "In order to show mean values in boxplot using ggplot2, we use the stat_summary() function to compute new summary statistics and add them to the plot. We use stat_summary() function with ggplot() function."
},
{
"code": null,
"e": 751,
"s": 743,
"text": "Syntax:"
},
{
"code": null,
"e": 871,
"s": 751,
"text": "stat_summary(mapping = NULL, data = NULL, geom = “pointrange”, position = “identity”, color=”value”, shape=”value”,...)"
},
{
"code": null,
"e": 909,
"s": 871,
"text": "Example: Adding mean value to boxplot"
},
{
"code": null,
"e": 911,
"s": 909,
"text": "R"
},
{
"code": "# load librarieslibrary(ggplot2)library(tidyverse) # basic boxplotggplot(diamonds, aes(x=cut, y=price)) + # geom_boxplot is used to plot the boxplot geom_boxplot() + # stat_summary computes the statistics summary# fun.y arguments as mean determines that # statistical summary will be mean of y-axisstat_summary(fun.y=\"mean\")",
"e": 1240,
"s": 911,
"text": null
},
{
"code": null,
"e": 1248,
"s": 1240,
"text": "Output:"
},
{
"code": null,
"e": 1404,
"s": 1248,
"text": "In the output produced above, the point in the center of the boxplot shows the variation of the mean of the y-axis for each category of data on the x-axis."
},
{
"code": null,
"e": 1615,
"s": 1404,
"text": "We can also change the color and shape of the mean mark using the color and shape parameter of the stat_summary() function. This helps us visualize the data better by distinguishing the mark from other symbols."
},
{
"code": null,
"e": 1654,
"s": 1615,
"text": "Example: Customizing added mean values"
},
{
"code": null,
"e": 1656,
"s": 1654,
"text": "R"
},
{
"code": "# load library tidyverselibrary(tidyverse)library(ggplot2) # basic boxplotggplot(diamonds, aes(x=cut, y=price)) + # geom_boxplot is used to plot the boxplot geom_boxplot() + # stat_summary computes the statistics summarystat_summary(fun.y=\"mean\",color=\"red\", shape=13)",
"e": 1929,
"s": 1656,
"text": null
},
{
"code": null,
"e": 1937,
"s": 1929,
"text": "Output:"
},
{
"code": null,
"e": 1944,
"s": 1937,
"text": "Picked"
},
{
"code": null,
"e": 1953,
"s": 1944,
"text": "R-ggplot"
},
{
"code": null,
"e": 1964,
"s": 1953,
"text": "R Language"
},
{
"code": null,
"e": 2062,
"s": 1964,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2114,
"s": 2062,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2172,
"s": 2114,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2207,
"s": 2172,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2245,
"s": 2207,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2262,
"s": 2245,
"text": "R - if statement"
},
{
"code": null,
"e": 2299,
"s": 2262,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 2348,
"s": 2299,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2391,
"s": 2348,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2428,
"s": 2391,
"text": "How to import an Excel File into R ?"
}
] |
Inventory Management with JSON in Python
|
15 Feb, 2022
The Inventory Management system is used to manage store products and keep track of all goods stock and also we can use it to check the purchases history of the store. Basically, we are developing a system to manage/automate some processes of any retail store by using the computer. So by using this system we can keep record data of products and even all purchases happened in-store.
So here we are going to develop an inventory management system using python and for storing data we are going to use JSON files. First of all, we will create sample data by using python code itself and then developing all functions one by one.
We have to open JSON files on each function and loading JSON data in python dictionary format and again reverse the process of converting dictionary data back to JSON format then closing the file.
Let’s generate data in a Python dictionary.
Python3
import json # Creating Dictionary to store dataavailable_products = {1001: {"name": "avocado", "price": 230, "category": "grocery", "quantity": 10, "date": "10/03/2021"}, 1002: {"name": "lotion", "price": 250, "category": "beauty & personal", "quantity": 100, "date": "15/07/2021"}, 1003: {"name": "pain reliever", "price": 500, "category": "health", "quantity": 200, "date": "12/04/2021"}, 1004: {"name": "dry pasta", "price": 20, "category": "grocery", "quantity": 50, "date": "27/06/2021"}, 1005: {"name": "toothbrush", "price": 700, "category": "beauty & personal", "quantity": 100, "date": "30/01/2021"}, 1006: {"name": "halloween candy", "price": 33, "category": "grocery", "quantity": 56, "date": "22/02/2021"}, 1007: {"name": "mascara", "price": 765, "category": "beauty & personal", "quantity": 70, "date": "11/03/2021"}, 1008: {"name": "capsicum", "price": 764, "category": "grocery", "quantity": 90, "date": "16/02/2021"}, 1009: {"name": "blush", "price": 87, "category": "beauty & personal", "quantity": 50, "date": "17/07/2021"}, 1010: {"name": "granola bars", "price": 24, "category": "grocery", "quantity": 60, "date": "20/05/2021"}, } # Formatting Dictionary into JSON formatjs = json.dumps(available_products)''' json.dumps() function converts a Python object into a json string '''js # so we got all data in json string format here # Create Jason File for DataBase and Write data Into Filefd = open("data.json", 'w') fd.write(js) # writing string into filefd.close() # Close File After Inserting Data
So we have created data for our inventory management system now we have to create functions to access this data and process various functionalities on it.
Admin Level Functionality. (used for Administrator of the system to operate)
User Level Functionality. (will be used by Customers)
Basically, This is just for managing the Inventory for a person having extra permissions like inserting, updating, and deleting product details which are should be at the owner or manager level only.
Following Function will help to coordinate between admin Functions
Python3
def admin(): print("============= Welcome to the Admin Inventory Management System =====") while (1): print("1)Display DataBase/All Products with there details") print("2)Display Specific Product with its details") print("3)Insert Data Into DataBase") print("4)Update Product in Database") print("5)Delete Product in DataBase") print("6)Display User Purchase Reports") print("7)Exit") print("Enter Your Choice :- ") n = int(input()) if (n == 1): display_data() elif (n == 2): display_specific_data() elif (n == 3): add_new() elif (n == 4): update_prod_data() elif (n == 5): delete_prod() elif (n == 6): display_reports_admin() elif (n == 7): break else: print("Invalid Choice...!!!")
This level will provide the following Functions
In This Function, Admin Will have two options either he wants all list as it is in Database or else he wants to have a look at all products by their categories.
Note: To make it look good in the tabular format we will use pandas.
Python3
def display_data(): import pandas as pd import json fd = open("data.json", 'r') # Open file in read mode txt = fd.read() # reading data from file data = json.loads(txt) # This will parse the JSON data, # populates a Python dictionary with the data fd.close() print("Enter '0' To Display Data Category Wise or '1' \ To Show Data As its Sequence Of Insertion :- ") n = int(input()) # Display All Records if (n == 1): table = pd.DataFrame( columns=['ID', 'name', 'price', 'category', 'quantity', 'date']) # Creating Pandas dataframe to show data in table # format later for i in data.keys(): '''Fetch all keys in dictionary''' temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] table = table.append(temp) table = table.reset_index(drop=True) # This will reset index of dataframe from IPython.display import display display(table) elif (n == 0): # Display Records by Category table = pd.DataFrame( columns=['ID', 'name', 'price', 'category', 'quantity', 'date']) cat = [] for i in data.keys(): temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] if (j == 'category'): cat.append(data[i][j]) table = table.append(temp) table = table.reset_index(drop=True) cat = set(cat) cat = list(cat) for k in cat: temp = pd.DataFrame() temp = table[table['category'] == k] print("Data Of Products Of Category "+k+" is:- ") from IPython.display import display display(temp) else: print("Enter Valid Choice...!!!") # display_data() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data
In this Function, Admin will have to enter the Product ID of the product to see the details he wants to check he will get all details regarding that particular product.
Python3
def display_specific_data(): import pandas as pd import json fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() print("Enter Product ID Whoes Details You Want to Have a Look on :- ") i = input() # Following Code will Filter out Product ID from Records if i in data.keys(): temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] from IPython.display import display display(temp) else: print("You Have Entered Wrong Product ID \ that is not Present in DataBase...!!!") # display_specific_data() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data
This Function will allow Admin to Add New Product Details in Inventory. Also provides Functionality to add new attribute property for a specific product if Admin wants to add other than basic 5 properties/details.
Note: Here program is more specific regarding data we have inserted we can make changes to make it applicable to all types
Python3
def add_new(): import json fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() print("Enter New Product ID :- ") id = input() if id not in data.keys(): print("Enter Product Name :- ") name = input() print("Enter Price of Product(price for product quantity as 1) :- ") price = input() print("Enter Category of Product :- ") category = input() print("Enter Quantity of Product :- ") quantity = input() print("Enter The Date on Which Product is Added in Inventory :- ") date = input() data[id] = {'name': name, 'price': price, 'category': category, 'quantity': quantity, 'date': date} print("Please Press '0' to Add New Attributes\ /Properties of Product or Press '1' to Continue :- ") z = int(input()) if(z == 0): print("Enter Number of New Attributes/Properties of Product :- ") n = int(input()) for i in range(n): print("Enter Attribute Name That you Want To Add :- ") nam = input() print("Enter The "+str(nam)+" of Product :- ") pro = input() data[id][nam] = pro print("Product ID "+str(id)+" Added Successfully...!!!") else: print("The Product ID you Have Entered Is Already Present\ t in DataBase Please Check...!!!") js = json.dumps(data) fd = open("data.json", 'w') fd.write(js) fd.close() # add_new() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data
Here Admin can remove products that are out of stock or want to delete. Also, it will Throw an Error on an invalid product ID.
Python3
def delete_prod(): import json fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() print("Enter The Product ID of The Product Which You Want To Delete :- ") temp = input() if temp in data.keys(): # here we are removing that particular data data.pop(temp) print("Product ID "+str(temp)+" Deleted Successfully...!!!") else: print("Invalid Product ID...!!!") js = json.dumps(data) fd = open("data.json", 'w') fd.write(js) fd.close() # delete_prod() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data
This Function will provide Admin two options either he wants to update all details of the product or he wants to edit any specific detail/attribute of the product. Also, it will Throw an Error on an invalid product ID.
Python3
def update_prod_data(): import json fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() print("Enter The Product ID of The Product\ Which You Want To Update :- ") temp = input() if temp in data.keys(): print("Want to update whole product data\ press '0' else '1' for specific data :- ") q = int(input()) if (q == 0): print("Enter Product Name :- ") name = input() print("Enter Price of Product(price for product quantity as 1) :- ") price = input() print("Enter Category of Product :- ") category = input() print("Enter Quantity of Product :- ") quantity = input() print("Enter The Date on Which Product is Added in Inventory :- ") date = input() data[temp] = {'name': name, 'price': price, 'category': category, 'quantity': quantity, 'date': date} print( "Please Press '0' to Add more Attributes\ /Properties of Product or Press '1' to Continue :- ") z = int(input()) if(z == 0): print("Enter Number of New Attributes/Properties of Product :- ") n = int(input()) for i in range(n): print("Enter Attribute Name That you Want To Add :- ") nam = input() print("Enter The "+str(nam)+" of Product :- ") pro = input() data[temp][nam] = pro print("Product ID "+str(temp)+" Updated Successfully...!!!") elif(q == 1): print("Enter Which Attribute of Product You want to Update :- ") p = input() if p in data[temp].keys(): print("Enter "+str(p)+" of Product :- ") u = input() data[temp][p] = u print("Product ID "+str(temp)+"'s attribute " + str(p)+" is Updated Successfully...!!!") else: print("Invalid Product Attribute...!!!") else: print("Invalid Choice...!!!") else: print("Invalid Product ID...!!!") js = json.dumps(data) fd = open("data.json", 'w') fd.write(js) fd.close() # update_prod_data() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data
Admin can have a look at user purchases with two options like either he wants to check all purchase reports or want to check the purchase report of any specific customer/user. This Also Provide Functionality to show a message that no reports are present if no purchase happened by any user. Also, it will Throw an Error on an invalid User ID.
Python3
def display_reports_admin(): import os.path import pandas as pd import json if (os.path.isfile("user_data.json") is False): # Check for if file is present or not # File will be generated only # if any user will do some purchase print("No User Reports are Present") return fd = open("user_data.json", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() print("Enter '0' to Check All Bills/Reports and \ '1' To Check Specific User Bills/Reports :- ") n = int(input()) if (n == 1): print("Enter User ID Whoes Details You Want to Have a Look on") i = input() temp = pd.DataFrame() if i in user_data.keys(): for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() temp = temp.reset_index(drop=True) from IPython.display import display display(temp) else: print("You Have Entered Wrong User ID that is not Present in DataBase...!!!") elif (n == 0): table = pd.DataFrame() for i in user_data.keys(): temp = pd.DataFrame() for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() table = table.append(temp) table = table.reset_index(drop=True) from IPython.display import display display(table) else: print("Please Enter Valid Choice...!!!") # display_reports_admin() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data
Admin Can Delete the Whole Database also if he wants to clear it all.
Python3
def delete_all(): fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() data = {} # Replacing Data with NULL Dictionary js = json.dumps(data) fd = open("data.json", 'w') fd.write(js) fd.close()
This is basically something like a customer can operate to buy products and get his bill and previous bills record too have no functionally or access to the product to either insert or modify or delete it.
Following Function will help to coordinate between admin Functions
Python3
def user(): print("===============\ Welcome to the User Inventory Management System\ ===============================================") while (1): print("1)Display All Products With Details") print("2)Display Specific Product With Details") print("3)Display All Purchase Bills") print("4)Buy The Product") print("5)Exit") print("Enter Your Choice :- ") n = int(input()) if (n == 1): display_data() elif (n == 2): display_specific_data() elif (n == 3): display_user_data() elif (n == 4): buy_product() elif (n == 5): break else: print("Invalid Choice...!!!")
Following Are The Functions at User Level
Note: Before the user buys something we should show him a list of all products available in inventory so we can use the same function we have created for admin for displaying products.
This Function will help the user to track his purchase and all bills reports till today. Also, This Function Provides Information Only to the User if he enters User ID. (we can add password features also here to increase more functionality)
Python3
def display_user_data(): import os.path import json if (os.path.isfile("user_data.json") is False): print("No User Reports are Present") return fd = open("user_data.json", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() print("Enter your User ID to Display All your Bills :- ") i = input() temp = pd.DataFrame() if i in user_data.keys(): for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() temp = temp.reset_index(drop=True) from IPython.display import display display(temp) else: print("You Have Entered Wrong User ID that is not Present in DataBase...!!!")
User/Customer will get his bill regarding purchases done by him just after the purchase with a unique 10 digit Transaction ID. If a user buys multiple products in one go it will give an aggregate bill.
Python3
def generate_bill(user_id, prod_id, price, time_date, purchase_no, name, category, quantity_all, transaction_id): print("================================\ ================= Bill ================\ =================================") print("########################################") print(" User ID :-", user_id) print("############################################") amount = 0 n = len(purchase_no) for i in range(n): print("--------------------------------------") amount = amount+float(price[i])*float(quantity_all[i]) print("Purchase number", purchase_no[i], "\nPurchase Time :-", time_date[i], "\nProduct ID :-", prod_id[i], "\nName Of Product :-", name[i], "\nCategory Of Product :-", category[i], "\nPrice of Product per Item :-", price[i], "\nPurchase Quantity :-", quantity_all[i]) print("-------------------------------------------------") print("*********************************************************") print(" Total Payable Bill :-", amount, "Transaction ID :-", transaction_id) print("*************************************")
This is the main function of this part this will allow user/customer to buy products it will give an error if the customer buys a product with high quantity than in stock also user will get one more chance to correct quantity if he wants to save efforts or restarting the process or he can skip that product too. Also, Customer will get messages out of stock if the product is not present in inventory (quantity=0). Customers can buy multiple products simultaneously by using product IDs (we can add buying product by its name also) user/customer will error messages if he enters wrong choices.
Python3
def buy_product(): import time import random import os.path if (os.path.isfile("user_data.json") is False): user_data = {} else: fd = open("user_data.json", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() print("Enter Your User ID if You are Old Customer\ else press '0' To New User ID :- ") p = int(input()) if (p == 0): if (len(user_data.keys()) == 0): user_id = 1000 else: user_id = int(list(user_data.keys())[-1])+1 else: if str(p) in user_data.keys(): user_id = p else: user_id = -1 if (user_id != -1): user_id = str(user_id) price = [] time_date = [] purchase_no = [] name = [] category = [] quantity_all = [] prod_id = [] transaction_id = ''.join(random.choice( '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(10)) print("Enter Number of Products You Want To Buy :- ") n = int(input()) print("Enter Data As Follows :- ") if user_id not in user_data.keys(): user_data[user_id] = {} g = 0 else: g = int(list(user_data[user_id].keys())[-1])+1 for i in range(n): print("Enter Product ID of Product " + str(i+1)+" that you want to buy") id = input() if id in data.keys(): user_data[user_id][str(i+1+g)] = {} user_data[user_id][str(i+1+g)]['time_date'] = str(time.ctime()) time_date.append(str(time.ctime())) if(float(data[id]['quantity']) == 0): print("Product You Want is Currenty Out Of Stock...!!!") continue purchase_no.append(i+1+g) name.append(data[id]['name']) user_data[user_id][str(i+1+g)]['name'] = data[id]['name'] prod_id.append(id) user_data[user_id][str(i+1+g)]['product_id'] = id category.append(data[id]['category']) user_data[user_id][str( i+1+g)]['category'] = data[id]['category'] print("For Product "+str(data[id]['name']) + " Available Quantity is :- "+str(data[id]['quantity'])) print("Enter Quantity of Product " + str(i+1)+" that you want to buy") quantity = input() if (float(quantity) <= float(data[id]['quantity'])): data[id]['quantity'] = str( float(data[id]['quantity'])-float(quantity)) quantity_all.append(quantity) user_data[user_id][str(i+1+g)]['quantity'] = str(quantity) price.append(data[id]['price']) user_data[user_id][str(i+1+g)]['price'] = data[id]['price'] user_data[user_id][str( i+1+g)]['Transaction ID'] = str(transaction_id) else: print( "The Quantity You Have Asked is Quite High\ Than That is Available in Stock") print( "Did you Want To buy According to The Quantity\ Available in Stock then Enter '0' Else '1'\ to skip This Product") key = int(input()) if (key == 0): print("Enter Quantity of Product " + str(i+1)+" that you want to buy") quantity = intput() if (float(quantity) <= float(data[id]['quantity'])): data[id]['quantity'] = str( float(data[id]['quantity'])-float(quantity)) quantity_all.append(quantity) user_data[user_id][str( i+1)]['quantity'] = str(quantity) price.append(data[id]['price']) user_data[user_id][str( i+1)]['price'] = data[id]['price'] user_data[user_id][str( i+1+g)]['Transaction ID'] = str(transaction_id) else: print("Invalid Operation Got Repeated...!!!") elif (key == 1): continue else: print("Invalid Choice...!!!") else: print("Invalid Product ID...!!!") if(len(purchase_no) != 0): generate_bill(user_id, prod_id, price, time_date, purchase_no, name, category, quantity_all, transaction_id) else: print("User ID Doesn't Exists...!!!") js = json.dumps(data) fd = open("data.json", 'w') fd.write(js) fd.close() js = json.dumps(user_data) fd = open("user_data.json", 'w') fd.write(js) fd.close()
After all, we have to manage user and admin-level functionalities. So, code for that is,
Python3
import jsonimport pandas as pd while (1): print("Choose Any One of The Following :- ") print("1)Admin") print("2)User") print("3)Exit") print("Enter Your Choice Here :- ") n = int(input()) if (n == 1): admin() elif (n == 2): user() elif (n == 3): break else: print("Invalid Choice...!!!")
This was all complete Inventory Management System with Admin and User Functionalities.
Python3
import pandas as pdimport jsonimport os.pathimport timeimport random # Creating Dictionary to store dataavailable_products = {1001: {"name": "avocado", "price": 230, "category": "grocery", "quantity": 10, "date": "10/03/2021"}, 1002: {"name": "lotion", "price": 250, "category": "beauty & personal", "quantity": 100, "date": "15/07/2021"}, 1003: {"name": "pain reliever", "price": 500, "category": "health", "quantity": 200, "date": "12/04/2021"}, 1004: {"name": "dry pasta", "price": 20, "category": "grocery", "quantity": 50, "date": "27/06/2021"}, 1005: {"name": "toothbrush", "price": 700, "category": "beauty & personal", "quantity": 100, "date": "30/01/2021"}, 1006: {"name": "halloween candy", "price": 33, "category": "grocery", "quantity": 56, "date": "22/02/2021"}, 1007: {"name": "mascara", "price": 765, "category": "beauty & personal", "quantity": 70, "date": "11/03/2021"}, 1008: {"name": "capsicum", "price": 764, "category": "grocery", "quantity": 90, "date": "16/02/2021"}, 1009: {"name": "blush", "price": 87, "category": "beauty & personal", "quantity": 50, "date": "17/07/2021"}, 1010: {"name": "granola bars", "price": 24, "category": "grocery", "quantity": 60, "date": "20/05/2021"}, } # Formatting Dictionary into JSON formatjs = json.dumps(available_products) # json.dumps() function converts a# Python object into a json stringjs # so we got all data in json string format here # Create Jason File for DataBase and Write data Into Filefd = open("data.json", 'w')# it will open file into write mode if file# does not exists then it will create file too'''fd.write(js) # writing string into filefd.close() # Close File After Inserting Data def admin(): print("========\ Welcome to the Admin Inventory Management System \ ==============") while (1): print("1)Display DataBase/All Products with there details") print("2)Display Specific Product with its details") print("3)Insert Data Into DataBase") print("4)Update Product in Database") print("5)Delete Product in DataBase") print("6)Display User Purchase Reports") print("7)Exit") print("Enter Your Choice :- ") n = int(input()) if (n == 1): display_data() elif (n == 2): display_specific_data() elif (n == 3): add_new() elif (n == 4): update_prod_data() elif (n == 5): delete_prod() elif (n == 6): display_reports_admin() elif (n == 7): break else: print("Invalid Choice...!!!") def display_data(): fd = open("data.json", 'r') txt = fd.read() # reading data from file data = json.loads(txt) # This will parse the JSON data, populates a # Python dictionary with the data fd.close() print("Enter '0' To Display Data Category Wise or '1' \ To Show Data As its Sequence Of Insertion :- ") n = int(input()) # Display All Records if (n == 1): table = pd.DataFrame( columns=['ID', 'name', 'price', 'category', 'quantity', 'date']) # Creating Pandas dataframe to show data in table format later for i in data.keys(): # Fetch all keys in dictionary temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] table = table.append(temp) table = table.reset_index(drop=True) '''This will reset index of dataframe''' from IPython.display import display display(table) elif (n == 0): # Display Records by Category table = pd.DataFrame( columns=['ID', 'name', 'price', 'category', 'quantity', 'date']) cat = [] for i in data.keys(): temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] if (j == 'category'): cat.append(data[i][j]) table = table.append(temp) table = table.reset_index(drop=True) cat = set(cat) cat = list(cat) for k in cat: temp = pd.DataFrame() temp = table[table['category'] == k] print("Data Of Products Of Category "+k+" is:- ") from IPython.display import display display(temp) else: print("Enter Valid Choice...!!!") # display_data() # Uncomment This Line To Run This Functiondef display_specific_data(): fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() print("Enter Product ID Whoes Details You Want to Have a Look on :- ") i = input() # Following Code will Filter out Product ID from Records if i in data.keys(): temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] from IPython.display import display display(temp) else: print("You Have Entered Wrong Product ID\ that is not Present in DataBase...!!!") # display_specific_data() # Uncomment This Line To Run This Functiondef add_new(): fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() print("Enter New Product ID :- ") id = input() if id not in data.keys(): print("Enter Product Name :- ") name = input() print("Enter Price of Product(price for product quantity as 1) :- ") price = input() print("Enter Category of Product :- ") category = input() print("Enter Quantity of Product :- ") quantity = input() print("Enter The Date on Which Product is Added in Inventory :- ") date = input() data[id] = {'name': name, 'price': price, 'category': category, 'quantity': quantity, 'date': date} print("Please Press '0' to Add New\ Attributes/Properties of Product or Press '1' to Continue :- ") z = int(input()) if(z == 0): print("Enter Number of New Attributes/Properties of Product :- ") n = int(input()) for i in range(n): print("Enter Attribute Name That you Want To Add :- ") nam = input() print("Enter The "+str(nam)+" of Product :- ") pro = input() data[id][nam] = pro print("Product ID "+str(id)+" Added Successfully...!!!") else: print("The Product ID you Have Entered Is\ Already Present in DataBase Please Check...!!!") js = json.dumps(data) fd = open("data.json", 'w') fd.write(js) fd.close() # add_new() # Uncomment This Line To Run This Functiondef delete_prod(): fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() print("Enter The Product ID of The Product Which You Want To Delete :- ") temp = input() if temp in data.keys(): data.pop(temp) # here we are removing that particular data print("Product ID "+str(temp)+" Deleted Successfully...!!!") else: print("Invalid Product ID...!!!") js = json.dumps(data) fd = open("data.json", 'w') fd.write(js) fd.close() # delete_prod() # Uncomment This Line To Run This Functiondef update_prod_data(): fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() print("Enter The Product ID of The Product\ Which You Want To Update :- ") temp = input() if temp in data.keys(): print("Want to update whole product data\ press '0' else '1' for specific data :- ") q = int(input()) if (q == 0): print("Enter Product Name :- ") name = input() print("Enter Price of Product(price for\ product quantity as 1) :- ") price = input() print("Enter Category of Product :- ") category = input() print("Enter Quantity of Product :- ") quantity = input() print("Enter The Date on Which Product\ is Added in Inventory :- ") date = input() data[temp] = {'name': name, 'price': price, 'category': category, 'quantity': quantity, 'date': date} print( "Please Press '0' to Add more Attributes/Properties of Product or Press '1' to Continue :- ") z = int(input()) if(z == 0): print("Enter Number of New Attributes/Properties of Product :- ") n = int(input()) for i in range(n): print("Enter Attribute Name That you Want To Add :- ") nam = input() print("Enter The "+str(nam)+" of Product :- ") pro = input() data[temp][nam] = pro print("Product ID "+str(temp)+" Updated Successfully...!!!") elif(q == 1): print("Enter Which Attribute of Product You want to Update :- ") p = input() if p in data[temp].keys(): print("Enter "+str(p)+" of Product :- ") u = input() data[temp][p] = u print("Product ID "+str(temp)+"'s attribute " + str(p)+" is Updated Successfully...!!!") else: print("Invalid Product Attribute...!!!") else: print("Invalid Choice...!!!") else: print("Invalid Product ID...!!!") js = json.dumps(data) fd = open("data.json", 'w') fd.write(js) fd.close() # update_prod_data() # Uncomment This Line To Run This Functiondef display_reports_admin(): if (os.path.isfile("user_data.json") is False): # Check for if file is present or not # File will be generated only if any user will do some purchase print("No User Reports are Present") return fd = open("user_data.json", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() print("Enter '0' to Check All Bills/Reports\ and '1' To Check Specific User Bills/Reports :- ") n = int(input()) if (n == 1): print("Enter User ID Whoes Details You Want to Have a Look on") i = input() temp = pd.DataFrame() if i in user_data.keys(): for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() temp = temp.reset_index(drop=True) from IPython.display import display display(temp) else: print("You Have Entered Wrong User ID that is not Present in DataBase...!!!") elif (n == 0): table = pd.DataFrame() for i in user_data.keys(): temp = pd.DataFrame() for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() table = table.append(temp) table = table.reset_index(drop=True) from IPython.display import display display(table) else: print("Please Enter Valid Choice...!!!") # display_reports_admin() # Uncomment This Line To Run This Functiondef delete_all(): fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() data = {} # Replacing Data with NULL Dictionary js = json.dumps(data) fd = open("data.json", 'w') fd.write(js) fd.close() def user(): print("======= Welcome to the User Inventory Management System ====") while (1): print("1)Display All Products With Details") print("2)Display Specific Product With Details") print("3)Display All Purchase Bills") print("4)Buy The Product") print("5)Exit") print("Enter Your Choice :- ") n = int(input()) if (n == 1): display_data() elif (n == 2): display_specific_data() elif (n == 3): display_user_data() elif (n == 4): buy_product() elif (n == 5): break else: print("Invalid Choice...!!!") def display_user_data(): if (os.path.isfile("user_data.json") is False): print("No User Reports are Present") return fd = open("user_data.json", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() print("Enter your User ID to Display All your Bills :- ") i = input() temp = pd.DataFrame() if i in user_data.keys(): for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() temp = temp.reset_index(drop=True) from IPython.display import display display(temp) else: print("You Have Entered Wrong User ID that is not Present in DataBase...!!!") def generate_bill(user_id, prod_id, price, time_date, purchase_no, name, category, quantity_all, transaction_id): print("========= Bill ========") print("#######################") print(" User ID :-", user_id) print("#################") amount = 0 n = len(purchase_no) for i in range(n): print("-----------------------------------------") amount = amount+float(price[i])*float(quantity_all[i]) print("Purchase number", purchase_no[i], "\nPurchase Time :-", time_date[i], "\nProduct ID :-", prod_id[i], "\nName Of Product :-", name[i], "\nCategory Of Product :-", category[i], "\nPrice of Product per Item :-", price[i], "\nPurchase Quantity :-", quantity_all[i]) print("-----------------------------------") print("*****************************************") print(" Total Payable Bill :-", amount, "Transaction ID :-", transaction_id) print("***************************************") def buy_product(): if (os.path.isfile("user_data.json") is False): user_data = {} else: fd = open("user_data.json", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() fd = open("data.json", 'r') txt = fd.read() data = json.loads(txt) fd.close() print("Enter Your User ID if You are Old \ Customer else press '0' To New User ID :- ") p = int(input()) if (p == 0): if (len(user_data.keys()) == 0): user_id = 1000 else: user_id = int(list(user_data.keys())[-1])+1 else: if str(p) in user_data.keys(): user_id = p else: user_id = -1 if (user_id != -1): user_id = str(user_id) price = [] time_date = [] purchase_no = [] name = [] category = [] quantity_all = [] prod_id = [] transaction_id = ''.join(random.choice( '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(10)) print("Enter Number of Products You Want To Buy :- ") n = int(input()) print("Enter Data As Follows :- ") if user_id not in user_data.keys(): user_data[user_id] = {} g = 0 else: g = int(list(user_data[user_id].keys())[-1])+1 for i in range(n): print("Enter Product ID of Product " + str(i+1)+" that you want to buy") id = input() if id in data.keys(): user_data[user_id][str(i+1+g)] = {} user_data[user_id][str(i+1+g)]['time_date'] = str(time.ctime()) time_date.append(str(time.ctime())) if(float(data[id]['quantity']) == 0.0): print("Product You Want is Currenty Out Of Stock...!!!") continue purchase_no.append(i+1+g) name.append(data[id]['name']) user_data[user_id][str(i+1+g)]['name'] = data[id]['name'] prod_id.append(id) user_data[user_id][str(i+1+g)]['product_id'] = id category.append(data[id]['category']) user_data[user_id][str( i+1+g)]['category'] = data[id]['category'] print("For Product "+str(data[id]['name']) + " Available Quantity is :- "+str(data[id]['quantity'])) print("Enter Quantity of Product " + str(i+1)+" that you want to buy") quantity = input() if (float(quantity) <= float(data[id]['quantity'])): data[id]['quantity'] = str( float(data[id]['quantity'])-float(quantity)) quantity_all.append(quantity) user_data[user_id][str(i+1+g)]['quantity'] = str(quantity) price.append(data[id]['price']) user_data[user_id][str(i+1+g)]['price'] = data[id]['price'] user_data[user_id][str( i+1+g)]['Transaction ID'] = str(transaction_id) else: print( "The Quantity You Have Asked is Quite High Than\ That is Available in Stock") print( "Did you Want To buy According to The Quantity\ Available in Stock then Enter '0' Else '1'\ to skip This Product") key = int(input()) if (key == 0): print("Enter Quantity of Product " + str(i+1)+" that you want to buy") quantity = intput() if (float(quantity) <= float(data[id]['quantity'])): data[id]['quantity'] = str( float(data[id]['quantity'])-float(quantity)) quantity_all.append(quantity) user_data[user_id][str( i+1)]['quantity'] = str(quantity) price.append(data[id]['price']) user_data[user_id][str( i+1)]['price'] = data[id]['price'] user_data[user_id][str( i+1+g)]['Transaction ID'] = str(transaction_id) else: print("Invalid Operation Got Repeated...!!!") elif (key == 1): continue else: print("Invalid Choice...!!!") else: print("Invalid Product ID...!!!") if(len(purchase_no) != 0): generate_bill(user_id, prod_id, price, time_date, purchase_no, name, category, quantity_all, transaction_id) else: print("User ID Doesn't Exists...!!!") js = json.dumps(data) fd = open("data.json", 'w') fd.write(js) fd.close() js = json.dumps(user_data) fd = open("user_data.json", 'w') fd.write(js) fd.close() while (1): print("Choose Any One of The Following :- ") print("1)Admin") print("2)User") print("3)Exit") print("Enter Your Choice Here :- ") n = int(input()) if (n == 1): admin() elif (n == 2): user() elif (n == 3): break else: print("Invalid Choice...!!!")
Output:
simmytarika5
abhishek0719kadiyan
germanshephered48
as5853535
rkbhola5
Picked
Python-json
Python-projects
TrueGeek-2021
Python
TrueGeek
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 redirect to another page in ReactJS ?
Basics of API Testing Using Postman
How to remove duplicate elements from JavaScript Array ?
How to Convert Char to String in Java?
Types of Internet Protocols
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 438,
"s": 54,
"text": "The Inventory Management system is used to manage store products and keep track of all goods stock and also we can use it to check the purchases history of the store. Basically, we are developing a system to manage/automate some processes of any retail store by using the computer. So by using this system we can keep record data of products and even all purchases happened in-store."
},
{
"code": null,
"e": 682,
"s": 438,
"text": "So here we are going to develop an inventory management system using python and for storing data we are going to use JSON files. First of all, we will create sample data by using python code itself and then developing all functions one by one."
},
{
"code": null,
"e": 879,
"s": 682,
"text": "We have to open JSON files on each function and loading JSON data in python dictionary format and again reverse the process of converting dictionary data back to JSON format then closing the file."
},
{
"code": null,
"e": 923,
"s": 879,
"text": "Let’s generate data in a Python dictionary."
},
{
"code": null,
"e": 931,
"s": 923,
"text": "Python3"
},
{
"code": "import json # Creating Dictionary to store dataavailable_products = {1001: {\"name\": \"avocado\", \"price\": 230, \"category\": \"grocery\", \"quantity\": 10, \"date\": \"10/03/2021\"}, 1002: {\"name\": \"lotion\", \"price\": 250, \"category\": \"beauty & personal\", \"quantity\": 100, \"date\": \"15/07/2021\"}, 1003: {\"name\": \"pain reliever\", \"price\": 500, \"category\": \"health\", \"quantity\": 200, \"date\": \"12/04/2021\"}, 1004: {\"name\": \"dry pasta\", \"price\": 20, \"category\": \"grocery\", \"quantity\": 50, \"date\": \"27/06/2021\"}, 1005: {\"name\": \"toothbrush\", \"price\": 700, \"category\": \"beauty & personal\", \"quantity\": 100, \"date\": \"30/01/2021\"}, 1006: {\"name\": \"halloween candy\", \"price\": 33, \"category\": \"grocery\", \"quantity\": 56, \"date\": \"22/02/2021\"}, 1007: {\"name\": \"mascara\", \"price\": 765, \"category\": \"beauty & personal\", \"quantity\": 70, \"date\": \"11/03/2021\"}, 1008: {\"name\": \"capsicum\", \"price\": 764, \"category\": \"grocery\", \"quantity\": 90, \"date\": \"16/02/2021\"}, 1009: {\"name\": \"blush\", \"price\": 87, \"category\": \"beauty & personal\", \"quantity\": 50, \"date\": \"17/07/2021\"}, 1010: {\"name\": \"granola bars\", \"price\": 24, \"category\": \"grocery\", \"quantity\": 60, \"date\": \"20/05/2021\"}, } # Formatting Dictionary into JSON formatjs = json.dumps(available_products)''' json.dumps() function converts a Python object into a json string '''js # so we got all data in json string format here # Create Jason File for DataBase and Write data Into Filefd = open(\"data.json\", 'w') fd.write(js) # writing string into filefd.close() # Close File After Inserting Data",
"e": 3307,
"s": 931,
"text": null
},
{
"code": null,
"e": 3462,
"s": 3307,
"text": "So we have created data for our inventory management system now we have to create functions to access this data and process various functionalities on it."
},
{
"code": null,
"e": 3539,
"s": 3462,
"text": "Admin Level Functionality. (used for Administrator of the system to operate)"
},
{
"code": null,
"e": 3593,
"s": 3539,
"text": "User Level Functionality. (will be used by Customers)"
},
{
"code": null,
"e": 3793,
"s": 3593,
"text": "Basically, This is just for managing the Inventory for a person having extra permissions like inserting, updating, and deleting product details which are should be at the owner or manager level only."
},
{
"code": null,
"e": 3860,
"s": 3793,
"text": "Following Function will help to coordinate between admin Functions"
},
{
"code": null,
"e": 3868,
"s": 3860,
"text": "Python3"
},
{
"code": "def admin(): print(\"============= Welcome to the Admin Inventory Management System =====\") while (1): print(\"1)Display DataBase/All Products with there details\") print(\"2)Display Specific Product with its details\") print(\"3)Insert Data Into DataBase\") print(\"4)Update Product in Database\") print(\"5)Delete Product in DataBase\") print(\"6)Display User Purchase Reports\") print(\"7)Exit\") print(\"Enter Your Choice :- \") n = int(input()) if (n == 1): display_data() elif (n == 2): display_specific_data() elif (n == 3): add_new() elif (n == 4): update_prod_data() elif (n == 5): delete_prod() elif (n == 6): display_reports_admin() elif (n == 7): break else: print(\"Invalid Choice...!!!\")",
"e": 4779,
"s": 3868,
"text": null
},
{
"code": null,
"e": 4827,
"s": 4779,
"text": "This level will provide the following Functions"
},
{
"code": null,
"e": 4988,
"s": 4827,
"text": "In This Function, Admin Will have two options either he wants all list as it is in Database or else he wants to have a look at all products by their categories."
},
{
"code": null,
"e": 5057,
"s": 4988,
"text": "Note: To make it look good in the tabular format we will use pandas."
},
{
"code": null,
"e": 5065,
"s": 5057,
"text": "Python3"
},
{
"code": "def display_data(): import pandas as pd import json fd = open(\"data.json\", 'r') # Open file in read mode txt = fd.read() # reading data from file data = json.loads(txt) # This will parse the JSON data, # populates a Python dictionary with the data fd.close() print(\"Enter '0' To Display Data Category Wise or '1' \\ To Show Data As its Sequence Of Insertion :- \") n = int(input()) # Display All Records if (n == 1): table = pd.DataFrame( columns=['ID', 'name', 'price', 'category', 'quantity', 'date']) # Creating Pandas dataframe to show data in table # format later for i in data.keys(): '''Fetch all keys in dictionary''' temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] table = table.append(temp) table = table.reset_index(drop=True) # This will reset index of dataframe from IPython.display import display display(table) elif (n == 0): # Display Records by Category table = pd.DataFrame( columns=['ID', 'name', 'price', 'category', 'quantity', 'date']) cat = [] for i in data.keys(): temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] if (j == 'category'): cat.append(data[i][j]) table = table.append(temp) table = table.reset_index(drop=True) cat = set(cat) cat = list(cat) for k in cat: temp = pd.DataFrame() temp = table[table['category'] == k] print(\"Data Of Products Of Category \"+k+\" is:- \") from IPython.display import display display(temp) else: print(\"Enter Valid Choice...!!!\") # display_data() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data",
"e": 7209,
"s": 5065,
"text": null
},
{
"code": null,
"e": 7378,
"s": 7209,
"text": "In this Function, Admin will have to enter the Product ID of the product to see the details he wants to check he will get all details regarding that particular product."
},
{
"code": null,
"e": 7386,
"s": 7378,
"text": "Python3"
},
{
"code": "def display_specific_data(): import pandas as pd import json fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() print(\"Enter Product ID Whoes Details You Want to Have a Look on :- \") i = input() # Following Code will Filter out Product ID from Records if i in data.keys(): temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] from IPython.display import display display(temp) else: print(\"You Have Entered Wrong Product ID \\ that is not Present in DataBase...!!!\") # display_specific_data() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data",
"e": 8170,
"s": 7386,
"text": null
},
{
"code": null,
"e": 8384,
"s": 8170,
"text": "This Function will allow Admin to Add New Product Details in Inventory. Also provides Functionality to add new attribute property for a specific product if Admin wants to add other than basic 5 properties/details."
},
{
"code": null,
"e": 8507,
"s": 8384,
"text": "Note: Here program is more specific regarding data we have inserted we can make changes to make it applicable to all types"
},
{
"code": null,
"e": 8515,
"s": 8507,
"text": "Python3"
},
{
"code": "def add_new(): import json fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() print(\"Enter New Product ID :- \") id = input() if id not in data.keys(): print(\"Enter Product Name :- \") name = input() print(\"Enter Price of Product(price for product quantity as 1) :- \") price = input() print(\"Enter Category of Product :- \") category = input() print(\"Enter Quantity of Product :- \") quantity = input() print(\"Enter The Date on Which Product is Added in Inventory :- \") date = input() data[id] = {'name': name, 'price': price, 'category': category, 'quantity': quantity, 'date': date} print(\"Please Press '0' to Add New Attributes\\ /Properties of Product or Press '1' to Continue :- \") z = int(input()) if(z == 0): print(\"Enter Number of New Attributes/Properties of Product :- \") n = int(input()) for i in range(n): print(\"Enter Attribute Name That you Want To Add :- \") nam = input() print(\"Enter The \"+str(nam)+\" of Product :- \") pro = input() data[id][nam] = pro print(\"Product ID \"+str(id)+\" Added Successfully...!!!\") else: print(\"The Product ID you Have Entered Is Already Present\\ t in DataBase Please Check...!!!\") js = json.dumps(data) fd = open(\"data.json\", 'w') fd.write(js) fd.close() # add_new() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data",
"e": 10222,
"s": 8515,
"text": null
},
{
"code": null,
"e": 10349,
"s": 10222,
"text": "Here Admin can remove products that are out of stock or want to delete. Also, it will Throw an Error on an invalid product ID."
},
{
"code": null,
"e": 10357,
"s": 10349,
"text": "Python3"
},
{
"code": "def delete_prod(): import json fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() print(\"Enter The Product ID of The Product Which You Want To Delete :- \") temp = input() if temp in data.keys(): # here we are removing that particular data data.pop(temp) print(\"Product ID \"+str(temp)+\" Deleted Successfully...!!!\") else: print(\"Invalid Product ID...!!!\") js = json.dumps(data) fd = open(\"data.json\", 'w') fd.write(js) fd.close() # delete_prod() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data",
"e": 11012,
"s": 10357,
"text": null
},
{
"code": null,
"e": 11231,
"s": 11012,
"text": "This Function will provide Admin two options either he wants to update all details of the product or he wants to edit any specific detail/attribute of the product. Also, it will Throw an Error on an invalid product ID."
},
{
"code": null,
"e": 11239,
"s": 11231,
"text": "Python3"
},
{
"code": "def update_prod_data(): import json fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() print(\"Enter The Product ID of The Product\\ Which You Want To Update :- \") temp = input() if temp in data.keys(): print(\"Want to update whole product data\\ press '0' else '1' for specific data :- \") q = int(input()) if (q == 0): print(\"Enter Product Name :- \") name = input() print(\"Enter Price of Product(price for product quantity as 1) :- \") price = input() print(\"Enter Category of Product :- \") category = input() print(\"Enter Quantity of Product :- \") quantity = input() print(\"Enter The Date on Which Product is Added in Inventory :- \") date = input() data[temp] = {'name': name, 'price': price, 'category': category, 'quantity': quantity, 'date': date} print( \"Please Press '0' to Add more Attributes\\ /Properties of Product or Press '1' to Continue :- \") z = int(input()) if(z == 0): print(\"Enter Number of New Attributes/Properties of Product :- \") n = int(input()) for i in range(n): print(\"Enter Attribute Name That you Want To Add :- \") nam = input() print(\"Enter The \"+str(nam)+\" of Product :- \") pro = input() data[temp][nam] = pro print(\"Product ID \"+str(temp)+\" Updated Successfully...!!!\") elif(q == 1): print(\"Enter Which Attribute of Product You want to Update :- \") p = input() if p in data[temp].keys(): print(\"Enter \"+str(p)+\" of Product :- \") u = input() data[temp][p] = u print(\"Product ID \"+str(temp)+\"'s attribute \" + str(p)+\" is Updated Successfully...!!!\") else: print(\"Invalid Product Attribute...!!!\") else: print(\"Invalid Choice...!!!\") else: print(\"Invalid Product ID...!!!\") js = json.dumps(data) fd = open(\"data.json\", 'w') fd.write(js) fd.close() # update_prod_data() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data",
"e": 13809,
"s": 11239,
"text": null
},
{
"code": null,
"e": 14152,
"s": 13809,
"text": "Admin can have a look at user purchases with two options like either he wants to check all purchase reports or want to check the purchase report of any specific customer/user. This Also Provide Functionality to show a message that no reports are present if no purchase happened by any user. Also, it will Throw an Error on an invalid User ID."
},
{
"code": null,
"e": 14160,
"s": 14152,
"text": "Python3"
},
{
"code": "def display_reports_admin(): import os.path import pandas as pd import json if (os.path.isfile(\"user_data.json\") is False): # Check for if file is present or not # File will be generated only # if any user will do some purchase print(\"No User Reports are Present\") return fd = open(\"user_data.json\", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() print(\"Enter '0' to Check All Bills/Reports and \\ '1' To Check Specific User Bills/Reports :- \") n = int(input()) if (n == 1): print(\"Enter User ID Whoes Details You Want to Have a Look on\") i = input() temp = pd.DataFrame() if i in user_data.keys(): for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() temp = temp.reset_index(drop=True) from IPython.display import display display(temp) else: print(\"You Have Entered Wrong User ID that is not Present in DataBase...!!!\") elif (n == 0): table = pd.DataFrame() for i in user_data.keys(): temp = pd.DataFrame() for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() table = table.append(temp) table = table.reset_index(drop=True) from IPython.display import display display(table) else: print(\"Please Enter Valid Choice...!!!\") # display_reports_admin() # Uncomment This Line To Run This Function# Note :- Ensure You Have data.json File to Fetch Data",
"e": 16253,
"s": 14160,
"text": null
},
{
"code": null,
"e": 16323,
"s": 16253,
"text": "Admin Can Delete the Whole Database also if he wants to clear it all."
},
{
"code": null,
"e": 16331,
"s": 16323,
"text": "Python3"
},
{
"code": "def delete_all(): fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() data = {} # Replacing Data with NULL Dictionary js = json.dumps(data) fd = open(\"data.json\", 'w') fd.write(js) fd.close()",
"e": 16577,
"s": 16331,
"text": null
},
{
"code": null,
"e": 16783,
"s": 16577,
"text": "This is basically something like a customer can operate to buy products and get his bill and previous bills record too have no functionally or access to the product to either insert or modify or delete it."
},
{
"code": null,
"e": 16850,
"s": 16783,
"text": "Following Function will help to coordinate between admin Functions"
},
{
"code": null,
"e": 16858,
"s": 16850,
"text": "Python3"
},
{
"code": "def user(): print(\"===============\\ Welcome to the User Inventory Management System\\ ===============================================\") while (1): print(\"1)Display All Products With Details\") print(\"2)Display Specific Product With Details\") print(\"3)Display All Purchase Bills\") print(\"4)Buy The Product\") print(\"5)Exit\") print(\"Enter Your Choice :- \") n = int(input()) if (n == 1): display_data() elif (n == 2): display_specific_data() elif (n == 3): display_user_data() elif (n == 4): buy_product() elif (n == 5): break else: print(\"Invalid Choice...!!!\")",
"e": 17589,
"s": 16858,
"text": null
},
{
"code": null,
"e": 17632,
"s": 17589,
"text": "Following Are The Functions at User Level "
},
{
"code": null,
"e": 17817,
"s": 17632,
"text": "Note: Before the user buys something we should show him a list of all products available in inventory so we can use the same function we have created for admin for displaying products."
},
{
"code": null,
"e": 18058,
"s": 17817,
"text": "This Function will help the user to track his purchase and all bills reports till today. Also, This Function Provides Information Only to the User if he enters User ID. (we can add password features also here to increase more functionality)"
},
{
"code": null,
"e": 18066,
"s": 18058,
"text": "Python3"
},
{
"code": "def display_user_data(): import os.path import json if (os.path.isfile(\"user_data.json\") is False): print(\"No User Reports are Present\") return fd = open(\"user_data.json\", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() print(\"Enter your User ID to Display All your Bills :- \") i = input() temp = pd.DataFrame() if i in user_data.keys(): for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() temp = temp.reset_index(drop=True) from IPython.display import display display(temp) else: print(\"You Have Entered Wrong User ID that is not Present in DataBase...!!!\")",
"e": 18971,
"s": 18066,
"text": null
},
{
"code": null,
"e": 19173,
"s": 18971,
"text": "User/Customer will get his bill regarding purchases done by him just after the purchase with a unique 10 digit Transaction ID. If a user buys multiple products in one go it will give an aggregate bill."
},
{
"code": null,
"e": 19181,
"s": 19173,
"text": "Python3"
},
{
"code": "def generate_bill(user_id, prod_id, price, time_date, purchase_no, name, category, quantity_all, transaction_id): print(\"================================\\ ================= Bill ================\\ =================================\") print(\"########################################\") print(\" User ID :-\", user_id) print(\"############################################\") amount = 0 n = len(purchase_no) for i in range(n): print(\"--------------------------------------\") amount = amount+float(price[i])*float(quantity_all[i]) print(\"Purchase number\", purchase_no[i], \"\\nPurchase Time :-\", time_date[i], \"\\nProduct ID :-\", prod_id[i], \"\\nName Of Product :-\", name[i], \"\\nCategory Of Product :-\", category[i], \"\\nPrice of Product per Item :-\", price[i], \"\\nPurchase Quantity :-\", quantity_all[i]) print(\"-------------------------------------------------\") print(\"*********************************************************\") print(\" Total Payable Bill :-\", amount, \"Transaction ID :-\", transaction_id) print(\"*************************************\")",
"e": 20413,
"s": 19181,
"text": null
},
{
"code": null,
"e": 21008,
"s": 20413,
"text": "This is the main function of this part this will allow user/customer to buy products it will give an error if the customer buys a product with high quantity than in stock also user will get one more chance to correct quantity if he wants to save efforts or restarting the process or he can skip that product too. Also, Customer will get messages out of stock if the product is not present in inventory (quantity=0). Customers can buy multiple products simultaneously by using product IDs (we can add buying product by its name also) user/customer will error messages if he enters wrong choices."
},
{
"code": null,
"e": 21016,
"s": 21008,
"text": "Python3"
},
{
"code": "def buy_product(): import time import random import os.path if (os.path.isfile(\"user_data.json\") is False): user_data = {} else: fd = open(\"user_data.json\", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() print(\"Enter Your User ID if You are Old Customer\\ else press '0' To New User ID :- \") p = int(input()) if (p == 0): if (len(user_data.keys()) == 0): user_id = 1000 else: user_id = int(list(user_data.keys())[-1])+1 else: if str(p) in user_data.keys(): user_id = p else: user_id = -1 if (user_id != -1): user_id = str(user_id) price = [] time_date = [] purchase_no = [] name = [] category = [] quantity_all = [] prod_id = [] transaction_id = ''.join(random.choice( '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(10)) print(\"Enter Number of Products You Want To Buy :- \") n = int(input()) print(\"Enter Data As Follows :- \") if user_id not in user_data.keys(): user_data[user_id] = {} g = 0 else: g = int(list(user_data[user_id].keys())[-1])+1 for i in range(n): print(\"Enter Product ID of Product \" + str(i+1)+\" that you want to buy\") id = input() if id in data.keys(): user_data[user_id][str(i+1+g)] = {} user_data[user_id][str(i+1+g)]['time_date'] = str(time.ctime()) time_date.append(str(time.ctime())) if(float(data[id]['quantity']) == 0): print(\"Product You Want is Currenty Out Of Stock...!!!\") continue purchase_no.append(i+1+g) name.append(data[id]['name']) user_data[user_id][str(i+1+g)]['name'] = data[id]['name'] prod_id.append(id) user_data[user_id][str(i+1+g)]['product_id'] = id category.append(data[id]['category']) user_data[user_id][str( i+1+g)]['category'] = data[id]['category'] print(\"For Product \"+str(data[id]['name']) + \" Available Quantity is :- \"+str(data[id]['quantity'])) print(\"Enter Quantity of Product \" + str(i+1)+\" that you want to buy\") quantity = input() if (float(quantity) <= float(data[id]['quantity'])): data[id]['quantity'] = str( float(data[id]['quantity'])-float(quantity)) quantity_all.append(quantity) user_data[user_id][str(i+1+g)]['quantity'] = str(quantity) price.append(data[id]['price']) user_data[user_id][str(i+1+g)]['price'] = data[id]['price'] user_data[user_id][str( i+1+g)]['Transaction ID'] = str(transaction_id) else: print( \"The Quantity You Have Asked is Quite High\\ Than That is Available in Stock\") print( \"Did you Want To buy According to The Quantity\\ Available in Stock then Enter '0' Else '1'\\ to skip This Product\") key = int(input()) if (key == 0): print(\"Enter Quantity of Product \" + str(i+1)+\" that you want to buy\") quantity = intput() if (float(quantity) <= float(data[id]['quantity'])): data[id]['quantity'] = str( float(data[id]['quantity'])-float(quantity)) quantity_all.append(quantity) user_data[user_id][str( i+1)]['quantity'] = str(quantity) price.append(data[id]['price']) user_data[user_id][str( i+1)]['price'] = data[id]['price'] user_data[user_id][str( i+1+g)]['Transaction ID'] = str(transaction_id) else: print(\"Invalid Operation Got Repeated...!!!\") elif (key == 1): continue else: print(\"Invalid Choice...!!!\") else: print(\"Invalid Product ID...!!!\") if(len(purchase_no) != 0): generate_bill(user_id, prod_id, price, time_date, purchase_no, name, category, quantity_all, transaction_id) else: print(\"User ID Doesn't Exists...!!!\") js = json.dumps(data) fd = open(\"data.json\", 'w') fd.write(js) fd.close() js = json.dumps(user_data) fd = open(\"user_data.json\", 'w') fd.write(js) fd.close()",
"e": 26280,
"s": 21016,
"text": null
},
{
"code": null,
"e": 26370,
"s": 26280,
"text": "After all, we have to manage user and admin-level functionalities. So, code for that is,"
},
{
"code": null,
"e": 26378,
"s": 26370,
"text": "Python3"
},
{
"code": "import jsonimport pandas as pd while (1): print(\"Choose Any One of The Following :- \") print(\"1)Admin\") print(\"2)User\") print(\"3)Exit\") print(\"Enter Your Choice Here :- \") n = int(input()) if (n == 1): admin() elif (n == 2): user() elif (n == 3): break else: print(\"Invalid Choice...!!!\")",
"e": 26725,
"s": 26378,
"text": null
},
{
"code": null,
"e": 26812,
"s": 26725,
"text": "This was all complete Inventory Management System with Admin and User Functionalities."
},
{
"code": null,
"e": 26820,
"s": 26812,
"text": "Python3"
},
{
"code": "import pandas as pdimport jsonimport os.pathimport timeimport random # Creating Dictionary to store dataavailable_products = {1001: {\"name\": \"avocado\", \"price\": 230, \"category\": \"grocery\", \"quantity\": 10, \"date\": \"10/03/2021\"}, 1002: {\"name\": \"lotion\", \"price\": 250, \"category\": \"beauty & personal\", \"quantity\": 100, \"date\": \"15/07/2021\"}, 1003: {\"name\": \"pain reliever\", \"price\": 500, \"category\": \"health\", \"quantity\": 200, \"date\": \"12/04/2021\"}, 1004: {\"name\": \"dry pasta\", \"price\": 20, \"category\": \"grocery\", \"quantity\": 50, \"date\": \"27/06/2021\"}, 1005: {\"name\": \"toothbrush\", \"price\": 700, \"category\": \"beauty & personal\", \"quantity\": 100, \"date\": \"30/01/2021\"}, 1006: {\"name\": \"halloween candy\", \"price\": 33, \"category\": \"grocery\", \"quantity\": 56, \"date\": \"22/02/2021\"}, 1007: {\"name\": \"mascara\", \"price\": 765, \"category\": \"beauty & personal\", \"quantity\": 70, \"date\": \"11/03/2021\"}, 1008: {\"name\": \"capsicum\", \"price\": 764, \"category\": \"grocery\", \"quantity\": 90, \"date\": \"16/02/2021\"}, 1009: {\"name\": \"blush\", \"price\": 87, \"category\": \"beauty & personal\", \"quantity\": 50, \"date\": \"17/07/2021\"}, 1010: {\"name\": \"granola bars\", \"price\": 24, \"category\": \"grocery\", \"quantity\": 60, \"date\": \"20/05/2021\"}, } # Formatting Dictionary into JSON formatjs = json.dumps(available_products) # json.dumps() function converts a# Python object into a json stringjs # so we got all data in json string format here # Create Jason File for DataBase and Write data Into Filefd = open(\"data.json\", 'w')# it will open file into write mode if file# does not exists then it will create file too'''fd.write(js) # writing string into filefd.close() # Close File After Inserting Data def admin(): print(\"========\\ Welcome to the Admin Inventory Management System \\ ==============\") while (1): print(\"1)Display DataBase/All Products with there details\") print(\"2)Display Specific Product with its details\") print(\"3)Insert Data Into DataBase\") print(\"4)Update Product in Database\") print(\"5)Delete Product in DataBase\") print(\"6)Display User Purchase Reports\") print(\"7)Exit\") print(\"Enter Your Choice :- \") n = int(input()) if (n == 1): display_data() elif (n == 2): display_specific_data() elif (n == 3): add_new() elif (n == 4): update_prod_data() elif (n == 5): delete_prod() elif (n == 6): display_reports_admin() elif (n == 7): break else: print(\"Invalid Choice...!!!\") def display_data(): fd = open(\"data.json\", 'r') txt = fd.read() # reading data from file data = json.loads(txt) # This will parse the JSON data, populates a # Python dictionary with the data fd.close() print(\"Enter '0' To Display Data Category Wise or '1' \\ To Show Data As its Sequence Of Insertion :- \") n = int(input()) # Display All Records if (n == 1): table = pd.DataFrame( columns=['ID', 'name', 'price', 'category', 'quantity', 'date']) # Creating Pandas dataframe to show data in table format later for i in data.keys(): # Fetch all keys in dictionary temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] table = table.append(temp) table = table.reset_index(drop=True) '''This will reset index of dataframe''' from IPython.display import display display(table) elif (n == 0): # Display Records by Category table = pd.DataFrame( columns=['ID', 'name', 'price', 'category', 'quantity', 'date']) cat = [] for i in data.keys(): temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] if (j == 'category'): cat.append(data[i][j]) table = table.append(temp) table = table.reset_index(drop=True) cat = set(cat) cat = list(cat) for k in cat: temp = pd.DataFrame() temp = table[table['category'] == k] print(\"Data Of Products Of Category \"+k+\" is:- \") from IPython.display import display display(temp) else: print(\"Enter Valid Choice...!!!\") # display_data() # Uncomment This Line To Run This Functiondef display_specific_data(): fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() print(\"Enter Product ID Whoes Details You Want to Have a Look on :- \") i = input() # Following Code will Filter out Product ID from Records if i in data.keys(): temp = pd.DataFrame(columns=['ID']) temp['ID'] = [i] for j in data[i].keys(): temp[j] = [data[i][j]] from IPython.display import display display(temp) else: print(\"You Have Entered Wrong Product ID\\ that is not Present in DataBase...!!!\") # display_specific_data() # Uncomment This Line To Run This Functiondef add_new(): fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() print(\"Enter New Product ID :- \") id = input() if id not in data.keys(): print(\"Enter Product Name :- \") name = input() print(\"Enter Price of Product(price for product quantity as 1) :- \") price = input() print(\"Enter Category of Product :- \") category = input() print(\"Enter Quantity of Product :- \") quantity = input() print(\"Enter The Date on Which Product is Added in Inventory :- \") date = input() data[id] = {'name': name, 'price': price, 'category': category, 'quantity': quantity, 'date': date} print(\"Please Press '0' to Add New\\ Attributes/Properties of Product or Press '1' to Continue :- \") z = int(input()) if(z == 0): print(\"Enter Number of New Attributes/Properties of Product :- \") n = int(input()) for i in range(n): print(\"Enter Attribute Name That you Want To Add :- \") nam = input() print(\"Enter The \"+str(nam)+\" of Product :- \") pro = input() data[id][nam] = pro print(\"Product ID \"+str(id)+\" Added Successfully...!!!\") else: print(\"The Product ID you Have Entered Is\\ Already Present in DataBase Please Check...!!!\") js = json.dumps(data) fd = open(\"data.json\", 'w') fd.write(js) fd.close() # add_new() # Uncomment This Line To Run This Functiondef delete_prod(): fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() print(\"Enter The Product ID of The Product Which You Want To Delete :- \") temp = input() if temp in data.keys(): data.pop(temp) # here we are removing that particular data print(\"Product ID \"+str(temp)+\" Deleted Successfully...!!!\") else: print(\"Invalid Product ID...!!!\") js = json.dumps(data) fd = open(\"data.json\", 'w') fd.write(js) fd.close() # delete_prod() # Uncomment This Line To Run This Functiondef update_prod_data(): fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() print(\"Enter The Product ID of The Product\\ Which You Want To Update :- \") temp = input() if temp in data.keys(): print(\"Want to update whole product data\\ press '0' else '1' for specific data :- \") q = int(input()) if (q == 0): print(\"Enter Product Name :- \") name = input() print(\"Enter Price of Product(price for\\ product quantity as 1) :- \") price = input() print(\"Enter Category of Product :- \") category = input() print(\"Enter Quantity of Product :- \") quantity = input() print(\"Enter The Date on Which Product\\ is Added in Inventory :- \") date = input() data[temp] = {'name': name, 'price': price, 'category': category, 'quantity': quantity, 'date': date} print( \"Please Press '0' to Add more Attributes/Properties of Product or Press '1' to Continue :- \") z = int(input()) if(z == 0): print(\"Enter Number of New Attributes/Properties of Product :- \") n = int(input()) for i in range(n): print(\"Enter Attribute Name That you Want To Add :- \") nam = input() print(\"Enter The \"+str(nam)+\" of Product :- \") pro = input() data[temp][nam] = pro print(\"Product ID \"+str(temp)+\" Updated Successfully...!!!\") elif(q == 1): print(\"Enter Which Attribute of Product You want to Update :- \") p = input() if p in data[temp].keys(): print(\"Enter \"+str(p)+\" of Product :- \") u = input() data[temp][p] = u print(\"Product ID \"+str(temp)+\"'s attribute \" + str(p)+\" is Updated Successfully...!!!\") else: print(\"Invalid Product Attribute...!!!\") else: print(\"Invalid Choice...!!!\") else: print(\"Invalid Product ID...!!!\") js = json.dumps(data) fd = open(\"data.json\", 'w') fd.write(js) fd.close() # update_prod_data() # Uncomment This Line To Run This Functiondef display_reports_admin(): if (os.path.isfile(\"user_data.json\") is False): # Check for if file is present or not # File will be generated only if any user will do some purchase print(\"No User Reports are Present\") return fd = open(\"user_data.json\", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() print(\"Enter '0' to Check All Bills/Reports\\ and '1' To Check Specific User Bills/Reports :- \") n = int(input()) if (n == 1): print(\"Enter User ID Whoes Details You Want to Have a Look on\") i = input() temp = pd.DataFrame() if i in user_data.keys(): for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() temp = temp.reset_index(drop=True) from IPython.display import display display(temp) else: print(\"You Have Entered Wrong User ID that is not Present in DataBase...!!!\") elif (n == 0): table = pd.DataFrame() for i in user_data.keys(): temp = pd.DataFrame() for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() table = table.append(temp) table = table.reset_index(drop=True) from IPython.display import display display(table) else: print(\"Please Enter Valid Choice...!!!\") # display_reports_admin() # Uncomment This Line To Run This Functiondef delete_all(): fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() data = {} # Replacing Data with NULL Dictionary js = json.dumps(data) fd = open(\"data.json\", 'w') fd.write(js) fd.close() def user(): print(\"======= Welcome to the User Inventory Management System ====\") while (1): print(\"1)Display All Products With Details\") print(\"2)Display Specific Product With Details\") print(\"3)Display All Purchase Bills\") print(\"4)Buy The Product\") print(\"5)Exit\") print(\"Enter Your Choice :- \") n = int(input()) if (n == 1): display_data() elif (n == 2): display_specific_data() elif (n == 3): display_user_data() elif (n == 4): buy_product() elif (n == 5): break else: print(\"Invalid Choice...!!!\") def display_user_data(): if (os.path.isfile(\"user_data.json\") is False): print(\"No User Reports are Present\") return fd = open(\"user_data.json\", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() print(\"Enter your User ID to Display All your Bills :- \") i = input() temp = pd.DataFrame() if i in user_data.keys(): for j in user_data[i].keys(): d = dict() d['User ID'] = i d['Purchase Number'] = j for k in user_data[i][j].keys(): d[k] = user_data[i][j][k] temp = temp.append(d, ignore_index=True) d = dict() temp = temp.reset_index(drop=True) from IPython.display import display display(temp) else: print(\"You Have Entered Wrong User ID that is not Present in DataBase...!!!\") def generate_bill(user_id, prod_id, price, time_date, purchase_no, name, category, quantity_all, transaction_id): print(\"========= Bill ========\") print(\"#######################\") print(\" User ID :-\", user_id) print(\"#################\") amount = 0 n = len(purchase_no) for i in range(n): print(\"-----------------------------------------\") amount = amount+float(price[i])*float(quantity_all[i]) print(\"Purchase number\", purchase_no[i], \"\\nPurchase Time :-\", time_date[i], \"\\nProduct ID :-\", prod_id[i], \"\\nName Of Product :-\", name[i], \"\\nCategory Of Product :-\", category[i], \"\\nPrice of Product per Item :-\", price[i], \"\\nPurchase Quantity :-\", quantity_all[i]) print(\"-----------------------------------\") print(\"*****************************************\") print(\" Total Payable Bill :-\", amount, \"Transaction ID :-\", transaction_id) print(\"***************************************\") def buy_product(): if (os.path.isfile(\"user_data.json\") is False): user_data = {} else: fd = open(\"user_data.json\", 'r') txt = fd.read() user_data = json.loads(txt) fd.close() fd = open(\"data.json\", 'r') txt = fd.read() data = json.loads(txt) fd.close() print(\"Enter Your User ID if You are Old \\ Customer else press '0' To New User ID :- \") p = int(input()) if (p == 0): if (len(user_data.keys()) == 0): user_id = 1000 else: user_id = int(list(user_data.keys())[-1])+1 else: if str(p) in user_data.keys(): user_id = p else: user_id = -1 if (user_id != -1): user_id = str(user_id) price = [] time_date = [] purchase_no = [] name = [] category = [] quantity_all = [] prod_id = [] transaction_id = ''.join(random.choice( '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(10)) print(\"Enter Number of Products You Want To Buy :- \") n = int(input()) print(\"Enter Data As Follows :- \") if user_id not in user_data.keys(): user_data[user_id] = {} g = 0 else: g = int(list(user_data[user_id].keys())[-1])+1 for i in range(n): print(\"Enter Product ID of Product \" + str(i+1)+\" that you want to buy\") id = input() if id in data.keys(): user_data[user_id][str(i+1+g)] = {} user_data[user_id][str(i+1+g)]['time_date'] = str(time.ctime()) time_date.append(str(time.ctime())) if(float(data[id]['quantity']) == 0.0): print(\"Product You Want is Currenty Out Of Stock...!!!\") continue purchase_no.append(i+1+g) name.append(data[id]['name']) user_data[user_id][str(i+1+g)]['name'] = data[id]['name'] prod_id.append(id) user_data[user_id][str(i+1+g)]['product_id'] = id category.append(data[id]['category']) user_data[user_id][str( i+1+g)]['category'] = data[id]['category'] print(\"For Product \"+str(data[id]['name']) + \" Available Quantity is :- \"+str(data[id]['quantity'])) print(\"Enter Quantity of Product \" + str(i+1)+\" that you want to buy\") quantity = input() if (float(quantity) <= float(data[id]['quantity'])): data[id]['quantity'] = str( float(data[id]['quantity'])-float(quantity)) quantity_all.append(quantity) user_data[user_id][str(i+1+g)]['quantity'] = str(quantity) price.append(data[id]['price']) user_data[user_id][str(i+1+g)]['price'] = data[id]['price'] user_data[user_id][str( i+1+g)]['Transaction ID'] = str(transaction_id) else: print( \"The Quantity You Have Asked is Quite High Than\\ That is Available in Stock\") print( \"Did you Want To buy According to The Quantity\\ Available in Stock then Enter '0' Else '1'\\ to skip This Product\") key = int(input()) if (key == 0): print(\"Enter Quantity of Product \" + str(i+1)+\" that you want to buy\") quantity = intput() if (float(quantity) <= float(data[id]['quantity'])): data[id]['quantity'] = str( float(data[id]['quantity'])-float(quantity)) quantity_all.append(quantity) user_data[user_id][str( i+1)]['quantity'] = str(quantity) price.append(data[id]['price']) user_data[user_id][str( i+1)]['price'] = data[id]['price'] user_data[user_id][str( i+1+g)]['Transaction ID'] = str(transaction_id) else: print(\"Invalid Operation Got Repeated...!!!\") elif (key == 1): continue else: print(\"Invalid Choice...!!!\") else: print(\"Invalid Product ID...!!!\") if(len(purchase_no) != 0): generate_bill(user_id, prod_id, price, time_date, purchase_no, name, category, quantity_all, transaction_id) else: print(\"User ID Doesn't Exists...!!!\") js = json.dumps(data) fd = open(\"data.json\", 'w') fd.write(js) fd.close() js = json.dumps(user_data) fd = open(\"user_data.json\", 'w') fd.write(js) fd.close() while (1): print(\"Choose Any One of The Following :- \") print(\"1)Admin\") print(\"2)User\") print(\"3)Exit\") print(\"Enter Your Choice Here :- \") n = int(input()) if (n == 1): admin() elif (n == 2): user() elif (n == 3): break else: print(\"Invalid Choice...!!!\")",
"e": 47579,
"s": 26820,
"text": null
},
{
"code": null,
"e": 47587,
"s": 47579,
"text": "Output:"
},
{
"code": null,
"e": 47600,
"s": 47587,
"text": "simmytarika5"
},
{
"code": null,
"e": 47620,
"s": 47600,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 47638,
"s": 47620,
"text": "germanshephered48"
},
{
"code": null,
"e": 47648,
"s": 47638,
"text": "as5853535"
},
{
"code": null,
"e": 47657,
"s": 47648,
"text": "rkbhola5"
},
{
"code": null,
"e": 47664,
"s": 47657,
"text": "Picked"
},
{
"code": null,
"e": 47676,
"s": 47664,
"text": "Python-json"
},
{
"code": null,
"e": 47692,
"s": 47676,
"text": "Python-projects"
},
{
"code": null,
"e": 47706,
"s": 47692,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 47713,
"s": 47706,
"text": "Python"
},
{
"code": null,
"e": 47722,
"s": 47713,
"text": "TrueGeek"
},
{
"code": null,
"e": 47820,
"s": 47722,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47852,
"s": 47820,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 47879,
"s": 47852,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 47900,
"s": 47879,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 47923,
"s": 47900,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 47954,
"s": 47923,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 47999,
"s": 47954,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 48035,
"s": 47999,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 48092,
"s": 48035,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 48131,
"s": 48092,
"text": "How to Convert Char to String in Java?"
}
] |
Check if a value is present in an Array in Java
|
13 Jun, 2022
Given an array, the task is to write a Java program to check whether a specific element is present in this Array or not.
Examples:
Input: arr[] = [5, 1, 1, 9, 7, 2, 6, 10], key = 7
Output: true
Input: arr[] = [-1, 1, 5, 8], key = -2
Output: false
An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be quickly sorted or searched. All the items of the array are stored at contiguous memory locations.
There are numerous approaches to check whether a specific element is present in this Array or not in Java. These are –
Using the Linear Search method
Using the Binary Search method
Using List.contains() method
Using Stream.anyMatch() method
In this, the list or array is traversed sequentially, and every element is checked.
Syntax:
for (int element : arr) {
if (element == toCheckValue) {
return true;
}
}
Example:
Java
// Java program to check whether// an element is present in array or not import java.util.Arrays;import java.util.stream.IntStream; class GFG { // Function return true if given element // found in array private static void check(int[] arr, int toCheckValue) { // check if the specified element // is present in the array or not // using Linear Search method boolean test = false; for (int element : arr) { if (element == toCheckValue) { test = true; break; } } // Print the result System.out.println("Is " + toCheckValue + " present in the array: " + test); } public static void main(String[] args) { // Get the array int arr[] = { 5, 1, 1, 9, 7, 2, 6, 10 }; // Get the value to be checked int toCheckValue = 7; // Print the array System.out.println("Array: " + Arrays.toString(arr)); // Check if this value is // present in the array or not check(arr, toCheckValue); }}
Array: [5, 1, 1, 9, 7, 2, 6, 10]
Is 7 present in the array: true
Time Complexity: O(N)
Auxiliary Space: O(1)
In this, search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.In this example, the Arrays.binarySearch() method is used for Binary Search.
Syntax:
public static int
binarySearch(data_type arr, data_type key)
Example:
Java
// Java program to check whether// an element is present in array or not import java.util.Arrays;import java.util.stream.IntStream; class GFG { // Function return true if given element // found in array private static void check(int[] arr, int toCheckValue) { // sort given array Arrays.sort(arr); // check if the specified element // is present in the array or not // using Binary Search method int res = Arrays.binarySearch(arr, toCheckValue); boolean test = res > 0 ? true : false; // Print the result System.out.println("Is " + toCheckValue + " present in the array: " + test); } public static void main(String[] args) { // Get the array int arr[] = { 5, 1, 1, 9, 7, 2, 6, 10 }; // Get the value to be checked int toCheckValue = 7; // Print the array System.out.println("Array: " + Arrays.toString(arr)); // Check if this value is // present in the array or not check(arr, toCheckValue); }}
Array: [5, 1, 1, 9, 7, 2, 6, 10]
Is 7 present in the array: true
Time Complexity: O(nlog(n))
Auxiliary Space: O(1)
List contains() method in Java is used for checking if the specified element exists in the given list or not.
Syntax:
public boolean contains(Object)
where object-element to be searched for.
Example:
Java
// Java program to check whether// an element is present in array or not import java.util.Arrays; class GFG { // Function return true if given element // found in array private static void check(Integer[] arr, int toCheckValue) { // check if the specified element // is present in the array or not // using contains() method boolean test = Arrays.asList(arr) .contains(toCheckValue); // Print the result System.out.println("Is " + toCheckValue + " present in the array: " + test); } public static void main(String[] args) { // Get the array Integer arr[] = { 5, 1, 1, 9, 7, 2, 6, 10 }; // Get the value to be checked int toCheckValue = 7; // Print the array System.out.println("Array: " + Arrays.toString(arr)); // Check if this value is // present in the array or not check(arr, toCheckValue); }}
Array: [5, 1, 1, 9, 7, 2, 6, 10]
Is 7 present in the array: true
Time Complexity: O(N)
Auxiliary Space: O(1)
Stream anyMatch(Predicate predicate) returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result.
Syntax:
boolean anyMatch(Predicate<T> predicate)
Where T is the type of the input to the predicate
and the function returns true if any elements of
the stream match the provided predicate,
otherwise false.
Example 1: Using Stream.of() method to create Stream
Java
// Java program to check whether// an element is present in array or not import java.util.Arrays;import java.util.stream.IntStream; class GFG { // Function return true if given element // found in array private static void check(int[] arr, int toCheckValue) { // check if the specified element // is present in the array or not // using anyMatch() method boolean test = IntStream.of(arr) .anyMatch(x -> x == toCheckValue); // Print the result System.out.println("Is " + toCheckValue + " present in the array: " + test); } public static void main(String[] args) { // Get the array int arr[] = { 5, 1, 1, 9, 7, 2, 6, 10 }; // Get the value to be checked int toCheckValue = 7; // Print the array System.out.println("Array: " + Arrays.toString(arr)); // Check if this value is // present in the array or not check(arr, toCheckValue); }}
Array: [5, 1, 1, 9, 7, 2, 6, 10]
Is 7 present in the array: true
Time Complexity: O(N)
Auxiliary Space: O(1)
Example 2: Using Arrays.stream() method to create Stream
Java
// Java program to check whether// an element is present in array or not import java.util.Arrays;import java.util.stream.IntStream; class GFG { // Function return true if given element // found in array private static void check(int[] arr, int toCheckValue) { // check if the specified element // is present in the array or not // using anyMatch() method boolean test = IntStream.of(arr) .anyMatch(x -> x == toCheckValue); // Print the result System.out.println("Is " + toCheckValue + " present in the array: " + test); } public static void main(String[] args) { // Get the array int arr[] = { 5, 1, 1, 9, 7, 2, 6, 10 }; // Get the value to be checked int toCheckValue = 7; // Print the array System.out.println("Array: " + Arrays.toString(arr)); // Check if this value is // present in the array or not check(arr, toCheckValue); }}
Array: [5, 1, 1, 9, 7, 2, 6, 10]
Is 7 present in the array: true
Time Complexity: O(N)
Auxiliary Space: O(1)
hritikbhatnagar2182
nishkarshgandhi
ishankhandelwals
Java-Array-Programs
Java-Arrays
Searching Quiz
Technical Scripter 2018
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 175,
"s": 54,
"text": "Given an array, the task is to write a Java program to check whether a specific element is present in this Array or not."
},
{
"code": null,
"e": 186,
"s": 175,
"text": "Examples: "
},
{
"code": null,
"e": 303,
"s": 186,
"text": "Input: arr[] = [5, 1, 1, 9, 7, 2, 6, 10], key = 7\nOutput: true\n\nInput: arr[] = [-1, 1, 5, 8], key = -2\nOutput: false"
},
{
"code": null,
"e": 654,
"s": 303,
"text": "An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be quickly sorted or searched. All the items of the array are stored at contiguous memory locations. "
},
{
"code": null,
"e": 774,
"s": 654,
"text": "There are numerous approaches to check whether a specific element is present in this Array or not in Java. These are – "
},
{
"code": null,
"e": 805,
"s": 774,
"text": "Using the Linear Search method"
},
{
"code": null,
"e": 836,
"s": 805,
"text": "Using the Binary Search method"
},
{
"code": null,
"e": 865,
"s": 836,
"text": "Using List.contains() method"
},
{
"code": null,
"e": 896,
"s": 865,
"text": "Using Stream.anyMatch() method"
},
{
"code": null,
"e": 981,
"s": 896,
"text": "In this, the list or array is traversed sequentially, and every element is checked. "
},
{
"code": null,
"e": 990,
"s": 981,
"text": "Syntax: "
},
{
"code": null,
"e": 1080,
"s": 990,
"text": "for (int element : arr) {\n if (element == toCheckValue) {\n return true;\n }\n}"
},
{
"code": null,
"e": 1090,
"s": 1080,
"text": "Example: "
},
{
"code": null,
"e": 1095,
"s": 1090,
"text": "Java"
},
{
"code": "// Java program to check whether// an element is present in array or not import java.util.Arrays;import java.util.stream.IntStream; class GFG { // Function return true if given element // found in array private static void check(int[] arr, int toCheckValue) { // check if the specified element // is present in the array or not // using Linear Search method boolean test = false; for (int element : arr) { if (element == toCheckValue) { test = true; break; } } // Print the result System.out.println(\"Is \" + toCheckValue + \" present in the array: \" + test); } public static void main(String[] args) { // Get the array int arr[] = { 5, 1, 1, 9, 7, 2, 6, 10 }; // Get the value to be checked int toCheckValue = 7; // Print the array System.out.println(\"Array: \" + Arrays.toString(arr)); // Check if this value is // present in the array or not check(arr, toCheckValue); }}",
"e": 2220,
"s": 1095,
"text": null
},
{
"code": null,
"e": 2285,
"s": 2220,
"text": "Array: [5, 1, 1, 9, 7, 2, 6, 10]\nIs 7 present in the array: true"
},
{
"code": null,
"e": 2307,
"s": 2285,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 2329,
"s": 2307,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2768,
"s": 2329,
"text": "In this, search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.In this example, the Arrays.binarySearch() method is used for Binary Search."
},
{
"code": null,
"e": 2777,
"s": 2768,
"text": "Syntax: "
},
{
"code": null,
"e": 2843,
"s": 2777,
"text": "public static int \n binarySearch(data_type arr, data_type key)"
},
{
"code": null,
"e": 2852,
"s": 2843,
"text": "Example:"
},
{
"code": null,
"e": 2857,
"s": 2852,
"text": "Java"
},
{
"code": "// Java program to check whether// an element is present in array or not import java.util.Arrays;import java.util.stream.IntStream; class GFG { // Function return true if given element // found in array private static void check(int[] arr, int toCheckValue) { // sort given array Arrays.sort(arr); // check if the specified element // is present in the array or not // using Binary Search method int res = Arrays.binarySearch(arr, toCheckValue); boolean test = res > 0 ? true : false; // Print the result System.out.println(\"Is \" + toCheckValue + \" present in the array: \" + test); } public static void main(String[] args) { // Get the array int arr[] = { 5, 1, 1, 9, 7, 2, 6, 10 }; // Get the value to be checked int toCheckValue = 7; // Print the array System.out.println(\"Array: \" + Arrays.toString(arr)); // Check if this value is // present in the array or not check(arr, toCheckValue); }}",
"e": 3963,
"s": 2857,
"text": null
},
{
"code": null,
"e": 4028,
"s": 3963,
"text": "Array: [5, 1, 1, 9, 7, 2, 6, 10]\nIs 7 present in the array: true"
},
{
"code": null,
"e": 4056,
"s": 4028,
"text": "Time Complexity: O(nlog(n))"
},
{
"code": null,
"e": 4078,
"s": 4056,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4188,
"s": 4078,
"text": "List contains() method in Java is used for checking if the specified element exists in the given list or not."
},
{
"code": null,
"e": 4197,
"s": 4188,
"text": "Syntax: "
},
{
"code": null,
"e": 4229,
"s": 4197,
"text": "public boolean contains(Object)"
},
{
"code": null,
"e": 4270,
"s": 4229,
"text": "where object-element to be searched for."
},
{
"code": null,
"e": 4280,
"s": 4270,
"text": "Example: "
},
{
"code": null,
"e": 4285,
"s": 4280,
"text": "Java"
},
{
"code": "// Java program to check whether// an element is present in array or not import java.util.Arrays; class GFG { // Function return true if given element // found in array private static void check(Integer[] arr, int toCheckValue) { // check if the specified element // is present in the array or not // using contains() method boolean test = Arrays.asList(arr) .contains(toCheckValue); // Print the result System.out.println(\"Is \" + toCheckValue + \" present in the array: \" + test); } public static void main(String[] args) { // Get the array Integer arr[] = { 5, 1, 1, 9, 7, 2, 6, 10 }; // Get the value to be checked int toCheckValue = 7; // Print the array System.out.println(\"Array: \" + Arrays.toString(arr)); // Check if this value is // present in the array or not check(arr, toCheckValue); }}",
"e": 5299,
"s": 4285,
"text": null
},
{
"code": null,
"e": 5364,
"s": 5299,
"text": "Array: [5, 1, 1, 9, 7, 2, 6, 10]\nIs 7 present in the array: true"
},
{
"code": null,
"e": 5386,
"s": 5364,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 5408,
"s": 5386,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5614,
"s": 5408,
"text": "Stream anyMatch(Predicate predicate) returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result."
},
{
"code": null,
"e": 5623,
"s": 5614,
"text": "Syntax: "
},
{
"code": null,
"e": 5823,
"s": 5623,
"text": "boolean anyMatch(Predicate<T> predicate)\n\nWhere T is the type of the input to the predicate\nand the function returns true if any elements of\nthe stream match the provided predicate, \notherwise false."
},
{
"code": null,
"e": 5876,
"s": 5823,
"text": "Example 1: Using Stream.of() method to create Stream"
},
{
"code": null,
"e": 5881,
"s": 5876,
"text": "Java"
},
{
"code": "// Java program to check whether// an element is present in array or not import java.util.Arrays;import java.util.stream.IntStream; class GFG { // Function return true if given element // found in array private static void check(int[] arr, int toCheckValue) { // check if the specified element // is present in the array or not // using anyMatch() method boolean test = IntStream.of(arr) .anyMatch(x -> x == toCheckValue); // Print the result System.out.println(\"Is \" + toCheckValue + \" present in the array: \" + test); } public static void main(String[] args) { // Get the array int arr[] = { 5, 1, 1, 9, 7, 2, 6, 10 }; // Get the value to be checked int toCheckValue = 7; // Print the array System.out.println(\"Array: \" + Arrays.toString(arr)); // Check if this value is // present in the array or not check(arr, toCheckValue); }}",
"e": 6930,
"s": 5881,
"text": null
},
{
"code": null,
"e": 6995,
"s": 6930,
"text": "Array: [5, 1, 1, 9, 7, 2, 6, 10]\nIs 7 present in the array: true"
},
{
"code": null,
"e": 7017,
"s": 6995,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 7039,
"s": 7017,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7096,
"s": 7039,
"text": "Example 2: Using Arrays.stream() method to create Stream"
},
{
"code": null,
"e": 7101,
"s": 7096,
"text": "Java"
},
{
"code": "// Java program to check whether// an element is present in array or not import java.util.Arrays;import java.util.stream.IntStream; class GFG { // Function return true if given element // found in array private static void check(int[] arr, int toCheckValue) { // check if the specified element // is present in the array or not // using anyMatch() method boolean test = IntStream.of(arr) .anyMatch(x -> x == toCheckValue); // Print the result System.out.println(\"Is \" + toCheckValue + \" present in the array: \" + test); } public static void main(String[] args) { // Get the array int arr[] = { 5, 1, 1, 9, 7, 2, 6, 10 }; // Get the value to be checked int toCheckValue = 7; // Print the array System.out.println(\"Array: \" + Arrays.toString(arr)); // Check if this value is // present in the array or not check(arr, toCheckValue); }}",
"e": 8150,
"s": 7101,
"text": null
},
{
"code": null,
"e": 8215,
"s": 8150,
"text": "Array: [5, 1, 1, 9, 7, 2, 6, 10]\nIs 7 present in the array: true"
},
{
"code": null,
"e": 8237,
"s": 8215,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 8259,
"s": 8237,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8279,
"s": 8259,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 8295,
"s": 8279,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 8312,
"s": 8295,
"text": "ishankhandelwals"
},
{
"code": null,
"e": 8332,
"s": 8312,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 8344,
"s": 8332,
"text": "Java-Arrays"
},
{
"code": null,
"e": 8359,
"s": 8344,
"text": "Searching Quiz"
},
{
"code": null,
"e": 8383,
"s": 8359,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 8388,
"s": 8383,
"text": "Java"
},
{
"code": null,
"e": 8407,
"s": 8388,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8412,
"s": 8407,
"text": "Java"
},
{
"code": null,
"e": 8510,
"s": 8412,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8561,
"s": 8510,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 8592,
"s": 8561,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 8611,
"s": 8592,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 8641,
"s": 8611,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 8659,
"s": 8641,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 8674,
"s": 8659,
"text": "Stream In Java"
},
{
"code": null,
"e": 8694,
"s": 8674,
"text": "Collections in Java"
},
{
"code": null,
"e": 8726,
"s": 8694,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 8750,
"s": 8726,
"text": "Singleton Class in Java"
}
] |
GATE | GATE-CS-2006 | Question 68
|
12 Apr, 2018
Consider the relation “enrolled(student, course)” in which (student, course) is the primary key, and the relation “paid(student, amount)” where student is the primary key. Assume no null values and no foreign keys or integrity constraints. Given the following four queries:
Query1: select student from enrolled where
student in (select student from paid)
Query2: select student from paid where
student in (select student from enrolled)
Query3: select E.student from enrolled E, paid P
where E.student = P.student
Query4: select student from paid where exists
(select * from enrolled where enrolled.student
= paid.student)
Which one of the following statements is correct?(A) All queries return identical row sets for any database(B) Query2 and Query4 return identical row sets for all databases but there exist databases for which Query1 and Query2 return different row sets.(C) There exist databases for which Query3 returns strictly fewer rows than Query2(D) There exist databases for which Query4 will encounter an integrity violation at runtime.Answer: (B)Explanation: Take an example:
Table enrolled
student course
----------------
abc c1
xyz c1
abc c2
pqr c1
Table paid
student amount
-----------------
abc 20000
xyz 10000
rst 10000
Output of Query 1
abc
abc
xyz
Output of Query 2
abc
xyz
Output of Query 3
abc
xyz
Output of Query 4
abc
xyz
Query 1 and Query 3 may return repetitive student values as “student” is not a key in relation enrolled, however query 2 and query 4 always return same row sets.
So, option (B) is correct.Quiz of this Question
GATE-CS-2006
GATE-GATE-CS-2006
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE CS 2010 | Question 54
GATE | GATE-CS-2015 (Set 1) | Question 19
GATE | GATE CS 2018 | Question 43
GATE | Gate IT 2008 | Question 59
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE-CS-2006 | Question 45
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2013 | Question 25
GATE | GATE-CS-2003 | Question 77
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Apr, 2018"
},
{
"code": null,
"e": 328,
"s": 54,
"text": "Consider the relation “enrolled(student, course)” in which (student, course) is the primary key, and the relation “paid(student, amount)” where student is the primary key. Assume no null values and no foreign keys or integrity constraints. Given the following four queries:"
},
{
"code": null,
"e": 723,
"s": 328,
"text": "Query1: select student from enrolled where \n student in (select student from paid)\nQuery2: select student from paid where \n student in (select student from enrolled)\nQuery3: select E.student from enrolled E, paid P \n where E.student = P.student\nQuery4: select student from paid where exists\n (select * from enrolled where enrolled.student\n = paid.student) "
},
{
"code": null,
"e": 1191,
"s": 723,
"text": "Which one of the following statements is correct?(A) All queries return identical row sets for any database(B) Query2 and Query4 return identical row sets for all databases but there exist databases for which Query1 and Query2 return different row sets.(C) There exist databases for which Query3 returns strictly fewer rows than Query2(D) There exist databases for which Query4 will encounter an integrity violation at runtime.Answer: (B)Explanation: Take an example:"
},
{
"code": null,
"e": 1511,
"s": 1191,
"text": "Table enrolled\nstudent course\n----------------\n abc c1 \n xyz c1\n abc c2\n pqr c1\n\nTable paid\nstudent amount\n-----------------\n abc 20000\n xyz 10000\n rst 10000\n\n\nOutput of Query 1\n abc\n abc\n xyz\n\nOutput of Query 2\n abc\n xyz\n\nOutput of Query 3\n abc\n xyz\n\nOutput of Query 4\n abc\n xyz"
},
{
"code": null,
"e": 1673,
"s": 1511,
"text": "Query 1 and Query 3 may return repetitive student values as “student” is not a key in relation enrolled, however query 2 and query 4 always return same row sets."
},
{
"code": null,
"e": 1721,
"s": 1673,
"text": "So, option (B) is correct.Quiz of this Question"
},
{
"code": null,
"e": 1734,
"s": 1721,
"text": "GATE-CS-2006"
},
{
"code": null,
"e": 1752,
"s": 1734,
"text": "GATE-GATE-CS-2006"
},
{
"code": null,
"e": 1757,
"s": 1752,
"text": "GATE"
},
{
"code": null,
"e": 1855,
"s": 1757,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1897,
"s": 1855,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 1931,
"s": 1897,
"text": "GATE | GATE CS 2010 | Question 54"
},
{
"code": null,
"e": 1973,
"s": 1931,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 19"
},
{
"code": null,
"e": 2007,
"s": 1973,
"text": "GATE | GATE CS 2018 | Question 43"
},
{
"code": null,
"e": 2041,
"s": 2007,
"text": "GATE | Gate IT 2008 | Question 59"
},
{
"code": null,
"e": 2083,
"s": 2041,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 2117,
"s": 2083,
"text": "GATE | GATE-CS-2006 | Question 45"
},
{
"code": null,
"e": 2159,
"s": 2117,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 2193,
"s": 2159,
"text": "GATE | GATE CS 2013 | Question 25"
}
] |
HTML - Progress Tag
|
The HTML <progress> tag specifies a completion progress of a task. It is displayed as a progress bar. The value of progressbar can be manipulated by JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>HTML Progress Tag</title>
</head>
<body>
<h1>Student's Intelligence level</h1>
<progress value = "80" max = "100"/>
</body>
</html>
This will produce the following result −
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <progress> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference
|
[
{
"code": null,
"e": 2669,
"s": 2508,
"text": "The HTML <progress> tag specifies a completion progress of a task. It is displayed as a progress bar. The value of progressbar can be manipulated by JavaScript."
},
{
"code": null,
"e": 2871,
"s": 2669,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Progress Tag</title>\n </head>\n\n <body>\n <h1>Student's Intelligence level</h1>\n <progress value = \"80\" max = \"100\"/>\n </body>\n\n</html>"
},
{
"code": null,
"e": 2912,
"s": 2871,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2996,
"s": 2912,
"text": "This tag supports all the global attributes described in − HTML Attribute Reference"
},
{
"code": null,
"e": 3073,
"s": 2996,
"text": "The HTML <progress> tag also supports the following additional attributes −"
}
] |
Program to find all match of a regex in a string
|
04 Sep, 2018
Prerequisite: smatch | Regex (Regular Expressions) in C++
Given a regex, the task is to find all regex matches in a string.
Without using iterator:// C++ program to find all the matches#include <bits/stdc++.h>using namespace std;int main(){ string subject("My GeeksforGeeks is my " "GeeksforGeeks none of your GeeksforGeeks"); // Template instantiations for // extracting the matching pattern. smatch match; regex r("GeeksforGeeks"); int i = 1; while (regex_search(subject, match, r)) { cout << "\nMatched string is " << match.str(0) << endl << "and it is found at position " << match.position(0)<<endl; i++; // suffix to find the rest of the string. subject = match.suffix().str(); } return 0;}Output:Matched string is GeeksforGeeks
and it is found at position 3
Matched string is GeeksforGeeks
and it is found at position 7
Matched string is GeeksforGeeks
and it is found at position 14
Note: Above code is running perfectly fine but the problem is input string will be lost.
// C++ program to find all the matches#include <bits/stdc++.h>using namespace std;int main(){ string subject("My GeeksforGeeks is my " "GeeksforGeeks none of your GeeksforGeeks"); // Template instantiations for // extracting the matching pattern. smatch match; regex r("GeeksforGeeks"); int i = 1; while (regex_search(subject, match, r)) { cout << "\nMatched string is " << match.str(0) << endl << "and it is found at position " << match.position(0)<<endl; i++; // suffix to find the rest of the string. subject = match.suffix().str(); } return 0;}
Matched string is GeeksforGeeks
and it is found at position 3
Matched string is GeeksforGeeks
and it is found at position 7
Matched string is GeeksforGeeks
and it is found at position 14
Note: Above code is running perfectly fine but the problem is input string will be lost.
Using iterator:Object can be constructed by calling the constructor with three parameters: a string iterator indicating the starting position of the search, a string iterator indicating the ending position of the search, and the regex object. Construct another iterator object using the default constructor to get an end-of-sequence iterator.#include <bits/stdc++.h>using namespace std;int main(){ string subject("geeksforgeeksabcdefghg" "eeksforgeeksabcdgeeksforgeeks"); // regex object. regex re("geeks(for)geeks"); // finding all the match. for (sregex_iterator it = sregex_iterator(subject.begin(), subject.end(), re); it != sregex_iterator(); it++) { smatch match; match = *it; cout << "\nMatched string is = " << match.str(0) << "\nand it is found at position " << match.position(0) << endl; cout << "Capture " << match.str(1) << " at position " << match.position(1) << endl; } return 0;}Output:Matched string is = geeksforgeeks
and it is found at position 0
Capture for at position 5
Matched string is = geeksforgeeks
and it is found at position 21
Capture for at position 26
Matched string is = geeksforgeeks
and it is found at position 38
Capture for at position 43
#include <bits/stdc++.h>using namespace std;int main(){ string subject("geeksforgeeksabcdefghg" "eeksforgeeksabcdgeeksforgeeks"); // regex object. regex re("geeks(for)geeks"); // finding all the match. for (sregex_iterator it = sregex_iterator(subject.begin(), subject.end(), re); it != sregex_iterator(); it++) { smatch match; match = *it; cout << "\nMatched string is = " << match.str(0) << "\nand it is found at position " << match.position(0) << endl; cout << "Capture " << match.str(1) << " at position " << match.position(1) << endl; } return 0;}
Matched string is = geeksforgeeks
and it is found at position 0
Capture for at position 5
Matched string is = geeksforgeeks
and it is found at position 21
Capture for at position 26
Matched string is = geeksforgeeks
and it is found at position 38
Capture for at position 43
CPP-Library
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reverse the substrings of the given String according to the given Array of indices
Check if the given string is shuffled substring of another string
How to validate GUID (Globally Unique Identifier) using Regular Expression
How to check Aadhaar number is valid or not using Regular Expression
How to validate pin code of India using Regular Expression
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Sep, 2018"
},
{
"code": null,
"e": 110,
"s": 52,
"text": "Prerequisite: smatch | Regex (Regular Expressions) in C++"
},
{
"code": null,
"e": 176,
"s": 110,
"text": "Given a regex, the task is to find all regex matches in a string."
},
{
"code": null,
"e": 1137,
"s": 176,
"text": "Without using iterator:// C++ program to find all the matches#include <bits/stdc++.h>using namespace std;int main(){ string subject(\"My GeeksforGeeks is my \" \"GeeksforGeeks none of your GeeksforGeeks\"); // Template instantiations for // extracting the matching pattern. smatch match; regex r(\"GeeksforGeeks\"); int i = 1; while (regex_search(subject, match, r)) { cout << \"\\nMatched string is \" << match.str(0) << endl << \"and it is found at position \" << match.position(0)<<endl; i++; // suffix to find the rest of the string. subject = match.suffix().str(); } return 0;}Output:Matched string is GeeksforGeeks\nand it is found at position 3\n\nMatched string is GeeksforGeeks\nand it is found at position 7\n\nMatched string is GeeksforGeeks\nand it is found at position 14\nNote: Above code is running perfectly fine but the problem is input string will be lost."
},
{
"code": "// C++ program to find all the matches#include <bits/stdc++.h>using namespace std;int main(){ string subject(\"My GeeksforGeeks is my \" \"GeeksforGeeks none of your GeeksforGeeks\"); // Template instantiations for // extracting the matching pattern. smatch match; regex r(\"GeeksforGeeks\"); int i = 1; while (regex_search(subject, match, r)) { cout << \"\\nMatched string is \" << match.str(0) << endl << \"and it is found at position \" << match.position(0)<<endl; i++; // suffix to find the rest of the string. subject = match.suffix().str(); } return 0;}",
"e": 1791,
"s": 1137,
"text": null
},
{
"code": null,
"e": 1981,
"s": 1791,
"text": "Matched string is GeeksforGeeks\nand it is found at position 3\n\nMatched string is GeeksforGeeks\nand it is found at position 7\n\nMatched string is GeeksforGeeks\nand it is found at position 14\n"
},
{
"code": null,
"e": 2070,
"s": 1981,
"text": "Note: Above code is running perfectly fine but the problem is input string will be lost."
},
{
"code": null,
"e": 3367,
"s": 2070,
"text": "Using iterator:Object can be constructed by calling the constructor with three parameters: a string iterator indicating the starting position of the search, a string iterator indicating the ending position of the search, and the regex object. Construct another iterator object using the default constructor to get an end-of-sequence iterator.#include <bits/stdc++.h>using namespace std;int main(){ string subject(\"geeksforgeeksabcdefghg\" \"eeksforgeeksabcdgeeksforgeeks\"); // regex object. regex re(\"geeks(for)geeks\"); // finding all the match. for (sregex_iterator it = sregex_iterator(subject.begin(), subject.end(), re); it != sregex_iterator(); it++) { smatch match; match = *it; cout << \"\\nMatched string is = \" << match.str(0) << \"\\nand it is found at position \" << match.position(0) << endl; cout << \"Capture \" << match.str(1) << \" at position \" << match.position(1) << endl; } return 0;}Output:Matched string is = geeksforgeeks\nand it is found at position 0\nCapture for at position 5\n\nMatched string is = geeksforgeeks\nand it is found at position 21\nCapture for at position 26\n\nMatched string is = geeksforgeeks\nand it is found at position 38\nCapture for at position 43\n"
},
{
"code": "#include <bits/stdc++.h>using namespace std;int main(){ string subject(\"geeksforgeeksabcdefghg\" \"eeksforgeeksabcdgeeksforgeeks\"); // regex object. regex re(\"geeks(for)geeks\"); // finding all the match. for (sregex_iterator it = sregex_iterator(subject.begin(), subject.end(), re); it != sregex_iterator(); it++) { smatch match; match = *it; cout << \"\\nMatched string is = \" << match.str(0) << \"\\nand it is found at position \" << match.position(0) << endl; cout << \"Capture \" << match.str(1) << \" at position \" << match.position(1) << endl; } return 0;}",
"e": 4036,
"s": 3367,
"text": null
},
{
"code": null,
"e": 4316,
"s": 4036,
"text": "Matched string is = geeksforgeeks\nand it is found at position 0\nCapture for at position 5\n\nMatched string is = geeksforgeeks\nand it is found at position 21\nCapture for at position 26\n\nMatched string is = geeksforgeeks\nand it is found at position 38\nCapture for at position 43\n"
},
{
"code": null,
"e": 4328,
"s": 4316,
"text": "CPP-Library"
},
{
"code": null,
"e": 4346,
"s": 4328,
"text": "Pattern Searching"
},
{
"code": null,
"e": 4354,
"s": 4346,
"text": "Strings"
},
{
"code": null,
"e": 4362,
"s": 4354,
"text": "Strings"
},
{
"code": null,
"e": 4380,
"s": 4362,
"text": "Pattern Searching"
},
{
"code": null,
"e": 4478,
"s": 4380,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4561,
"s": 4478,
"text": "Reverse the substrings of the given String according to the given Array of indices"
},
{
"code": null,
"e": 4627,
"s": 4561,
"text": "Check if the given string is shuffled substring of another string"
},
{
"code": null,
"e": 4702,
"s": 4627,
"text": "How to validate GUID (Globally Unique Identifier) using Regular Expression"
},
{
"code": null,
"e": 4771,
"s": 4702,
"text": "How to check Aadhaar number is valid or not using Regular Expression"
},
{
"code": null,
"e": 4830,
"s": 4771,
"text": "How to validate pin code of India using Regular Expression"
},
{
"code": null,
"e": 4876,
"s": 4830,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 4901,
"s": 4876,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4961,
"s": 4901,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4976,
"s": 4961,
"text": "C++ Data Types"
}
] |
Switch case calculator in JavaScript
|
Let’s say, we are required to write a JavaScript function that takes in a string like these to create a calculator −
"4 add 6"
"6 divide 7"
"23 modulo 8"
Basically, the idea is that the string will contain two numbers on either sides and a string representing the operation in the middle.
The string in the middle can take one of these five values −
"add", "divide", "multiply", "modulo", "subtract"
Our job is to return the correct result based on the string
Let’s write the code for this function −
const problem = "3 add 16";
const calculate = opr => {
const [num1, operation, num2] = opr.split(" ");
switch (operation) {
case "add":
return +num1 + +num2;
case "divide":
return +num1 / +num2;
case "subtract":
return +num1 - +num2;
case "multiply":
return +num1 * +num2;
case "modulo":
return +num1 % +num2;
default:
return 0;
}
}
console.log(calculate(problem));
The output in the console: −
19
|
[
{
"code": null,
"e": 1304,
"s": 1187,
"text": "Let’s say, we are required to write a JavaScript function that takes in a string like these to create a calculator −"
},
{
"code": null,
"e": 1341,
"s": 1304,
"text": "\"4 add 6\"\n\"6 divide 7\"\n\"23 modulo 8\""
},
{
"code": null,
"e": 1476,
"s": 1341,
"text": "Basically, the idea is that the string will contain two numbers on either sides and a string representing the operation in the middle."
},
{
"code": null,
"e": 1537,
"s": 1476,
"text": "The string in the middle can take one of these five values −"
},
{
"code": null,
"e": 1587,
"s": 1537,
"text": "\"add\", \"divide\", \"multiply\", \"modulo\", \"subtract\""
},
{
"code": null,
"e": 1647,
"s": 1587,
"text": "Our job is to return the correct result based on the string"
},
{
"code": null,
"e": 1688,
"s": 1647,
"text": "Let’s write the code for this function −"
},
{
"code": null,
"e": 2153,
"s": 1688,
"text": "const problem = \"3 add 16\";\nconst calculate = opr => {\n const [num1, operation, num2] = opr.split(\" \");\n switch (operation) {\n case \"add\":\n return +num1 + +num2;\n case \"divide\":\n return +num1 / +num2;\n case \"subtract\":\n return +num1 - +num2;\n case \"multiply\":\n return +num1 * +num2;\n case \"modulo\":\n return +num1 % +num2;\n default:\n return 0;\n }\n}\nconsole.log(calculate(problem));"
},
{
"code": null,
"e": 2182,
"s": 2153,
"text": "The output in the console: −"
},
{
"code": null,
"e": 2185,
"s": 2182,
"text": "19"
}
] |
Output of C programs | Set 61 (Loops)
|
04 Oct, 2017
Prerequisite : Loops in CQ.1 What is the output of this program?
#include <iostream>using namespace std;int main(){ int i, j, var = 'A'; for (i = 5; i >= 1; i--) { for (j = 0; j < i; j++) printf("%c ", (var + j)); printf("\n"); } return 0;}
Optionsa)A B C D EA B C D EA B C D EA B C D EA B C D E
b)A B C DA B C DA B C DA B C D
c)A B C DA B CA BA
d)A B C D EA B C DA B CA BA
ans:- d
Explanation :- inner loop iterates for value less than equal to i, thus printingA B C D EA B C DA B CA BA
Q.2 What is the output of this program?
#include <iostream>using namespace std;int main(){ int counter = 1; do { printf("%d, ", counter); counter += 1; } while (counter >= 10); printf("\nAfter loop counter=%d", counter); printf("\n"); return 0;}
Options
a) After loop counter=1b) 1,After loop counter=2c) 1,After loop counter=1d) After loop counter=2
ans:- b
Explanation :- do while is an exit controlled loop, here loop body executed first, then condition will be checked.
Q.3 What is the output of this program?
#include <iostream>using namespace std;int main(){ int counter = 1; while (counter >= 10) { printf("%d, ", counter); counter += 1; } printf("\nAfter loop counter=%d", counter); printf("\n"); return 0;}
Optionsa)After loop counter=1b)1,After loop counter=2c)1,After loop counter=1d)After loop counter=2
ans:- a
Explanation :- since while is an entry controlled loop so, here condition will be checked first.
Q.4 What is the output of this program?
#include <iostream>using namespace std;int main(){ int loopvar = 10; while (printf("Hello ") && loopvar--) ; return 0;}
Optionsa)Hellob)Hello Hello Hello Hello .......c)Hello Hello Hello Hello Hello Hello Hello Hello Hello Hellod)Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
ans:- d
Explanation :- since post decrement operator is used so value is decremented after expression loopvar – – is evaluated. Thus, Hello is printed 11 times.
Q.5 What is the output of this program?
#include <iostream>#include <string.h>using namespace std;int main(){ int counter = 1; while (counter <= 10 && 1 ++) printf("Hello"); return 0;}
Options
a)compilation errorb)HelloHello ... 10 timesc)HelloHello ... 11 timesd)Hello
ans:- a
Explanation :- Error: lvalue required as increment operand. It is a compile time error.
This article is contributed by Pragya Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Loops & Control Statements
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of C++ programs | Set 50
Runtime Errors
C++ Programming Multiple Choice Questions
Output of C Programs | Set 2
Different ways to copy a string in C/C++
Output of C++ Program | Set 1
Output of Python Program | Set 1
Output of Java Program | Set 2
Output of Java Program | Set 3
Output of C++ programs | Set 47 (Pointers)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Oct, 2017"
},
{
"code": null,
"e": 117,
"s": 52,
"text": "Prerequisite : Loops in CQ.1 What is the output of this program?"
},
{
"code": "#include <iostream>using namespace std;int main(){ int i, j, var = 'A'; for (i = 5; i >= 1; i--) { for (j = 0; j < i; j++) printf(\"%c \", (var + j)); printf(\"\\n\"); } return 0;}",
"e": 332,
"s": 117,
"text": null
},
{
"code": null,
"e": 387,
"s": 332,
"text": "Optionsa)A B C D EA B C D EA B C D EA B C D EA B C D E"
},
{
"code": null,
"e": 418,
"s": 387,
"text": "b)A B C DA B C DA B C DA B C D"
},
{
"code": null,
"e": 437,
"s": 418,
"text": "c)A B C DA B CA BA"
},
{
"code": null,
"e": 465,
"s": 437,
"text": "d)A B C D EA B C DA B CA BA"
},
{
"code": null,
"e": 474,
"s": 465,
"text": "ans:- d "
},
{
"code": null,
"e": 580,
"s": 474,
"text": "Explanation :- inner loop iterates for value less than equal to i, thus printingA B C D EA B C DA B CA BA"
},
{
"code": null,
"e": 620,
"s": 580,
"text": "Q.2 What is the output of this program?"
},
{
"code": "#include <iostream>using namespace std;int main(){ int counter = 1; do { printf(\"%d, \", counter); counter += 1; } while (counter >= 10); printf(\"\\nAfter loop counter=%d\", counter); printf(\"\\n\"); return 0;}",
"e": 858,
"s": 620,
"text": null
},
{
"code": null,
"e": 866,
"s": 858,
"text": "Options"
},
{
"code": null,
"e": 963,
"s": 866,
"text": "a) After loop counter=1b) 1,After loop counter=2c) 1,After loop counter=1d) After loop counter=2"
},
{
"code": null,
"e": 971,
"s": 963,
"text": "ans:- b"
},
{
"code": null,
"e": 1086,
"s": 971,
"text": "Explanation :- do while is an exit controlled loop, here loop body executed first, then condition will be checked."
},
{
"code": null,
"e": 1126,
"s": 1086,
"text": "Q.3 What is the output of this program?"
},
{
"code": "#include <iostream>using namespace std;int main(){ int counter = 1; while (counter >= 10) { printf(\"%d, \", counter); counter += 1; } printf(\"\\nAfter loop counter=%d\", counter); printf(\"\\n\"); return 0;}",
"e": 1360,
"s": 1126,
"text": null
},
{
"code": null,
"e": 1460,
"s": 1360,
"text": "Optionsa)After loop counter=1b)1,After loop counter=2c)1,After loop counter=1d)After loop counter=2"
},
{
"code": null,
"e": 1468,
"s": 1460,
"text": "ans:- a"
},
{
"code": null,
"e": 1565,
"s": 1468,
"text": "Explanation :- since while is an entry controlled loop so, here condition will be checked first."
},
{
"code": null,
"e": 1605,
"s": 1565,
"text": "Q.4 What is the output of this program?"
},
{
"code": "#include <iostream>using namespace std;int main(){ int loopvar = 10; while (printf(\"Hello \") && loopvar--) ; return 0;}",
"e": 1741,
"s": 1605,
"text": null
},
{
"code": null,
"e": 1917,
"s": 1741,
"text": "Optionsa)Hellob)Hello Hello Hello Hello .......c)Hello Hello Hello Hello Hello Hello Hello Hello Hello Hellod)Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello"
},
{
"code": null,
"e": 1925,
"s": 1917,
"text": "ans:- d"
},
{
"code": null,
"e": 2078,
"s": 1925,
"text": "Explanation :- since post decrement operator is used so value is decremented after expression loopvar – – is evaluated. Thus, Hello is printed 11 times."
},
{
"code": null,
"e": 2118,
"s": 2078,
"text": "Q.5 What is the output of this program?"
},
{
"code": "#include <iostream>#include <string.h>using namespace std;int main(){ int counter = 1; while (counter <= 10 && 1 ++) printf(\"Hello\"); return 0;}",
"e": 2279,
"s": 2118,
"text": null
},
{
"code": null,
"e": 2287,
"s": 2279,
"text": "Options"
},
{
"code": null,
"e": 2364,
"s": 2287,
"text": "a)compilation errorb)HelloHello ... 10 timesc)HelloHello ... 11 timesd)Hello"
},
{
"code": null,
"e": 2372,
"s": 2364,
"text": "ans:- a"
},
{
"code": null,
"e": 2460,
"s": 2372,
"text": "Explanation :- Error: lvalue required as increment operand. It is a compile time error."
},
{
"code": null,
"e": 2760,
"s": 2460,
"text": "This article is contributed by Pragya Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2885,
"s": 2760,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2914,
"s": 2885,
"text": "C-Loops & Control Statements"
},
{
"code": null,
"e": 2923,
"s": 2914,
"text": "C-Output"
},
{
"code": null,
"e": 2938,
"s": 2923,
"text": "Program Output"
},
{
"code": null,
"e": 3036,
"s": 2938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3068,
"s": 3036,
"text": "Output of C++ programs | Set 50"
},
{
"code": null,
"e": 3083,
"s": 3068,
"text": "Runtime Errors"
},
{
"code": null,
"e": 3125,
"s": 3083,
"text": "C++ Programming Multiple Choice Questions"
},
{
"code": null,
"e": 3154,
"s": 3125,
"text": "Output of C Programs | Set 2"
},
{
"code": null,
"e": 3195,
"s": 3154,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 3225,
"s": 3195,
"text": "Output of C++ Program | Set 1"
},
{
"code": null,
"e": 3258,
"s": 3225,
"text": "Output of Python Program | Set 1"
},
{
"code": null,
"e": 3289,
"s": 3258,
"text": "Output of Java Program | Set 2"
},
{
"code": null,
"e": 3320,
"s": 3289,
"text": "Output of Java Program | Set 3"
}
] |
Print leftmost and rightmost nodes of a Binary Tree
|
30 Jun, 2022
Given a Binary Tree, Print the corner nodes at each level. The node at the leftmost and the node at the rightmost. For example, output for following is 15, 10, 20, 8, 25.
A Simple Solution is to do two traversals using the approaches discussed for printing left view and right view.
Can we print all corner nodes using one traversal? The idea is to use Level Order Traversal. Every time we store the size of the queue in a variable n, which is the number of nodes at that level. For every level, we check whether the current node is the first (i.e node at index 0) and the node at the last index (i.e node at index n-1) If it is either of them, we print the value of that node.
Implementation:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C++
Java
Python3
C#
// C/C++ program to print corner node at each level// of binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */struct Node{ int key; struct Node* left, *right;}; /* To create a newNode of tree and return pointer */struct Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} /* Function to print corner node at each level */void printCorner(Node *root){ //If the root is null then simply return if(root == NULL) return; //Do level order traversal using a single queue queue<Node*> q; q.push(root); while(!q.empty()) { //n denotes the size of the current level in the queue int n = q.size(); for(int i =0;i<n;i++) { Node *temp = q.front(); q.pop(); //If it is leftmost corner value or rightmost corner value then print it if(i==0 || i==n-1) cout<<temp->key<<" "; //push the left and right children of the temp node if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); } }}// Driver program to test above functionint main (){ Node *root = newNode(15); root->left = newNode(10); root->right = newNode(20); root->left->left = newNode(8); root->left->right = newNode(12); root->right->left = newNode(16); root->right->right = newNode(25); printCorner(root); return 0;} // This code is contributed by Tapeshdua420.
// Java program to print corner node at each level in a binary tree import java.util.*; /* A binary tree node has key, pointer to left child and a pointer to right child */class Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} class BinaryTree{ Node root; /* Function to print corner node at each level */ void printCorner(Node root) { // star node is for keeping track of levels Queue<Node> q = new LinkedList<Node>(); // pushing root node and star node q.add(root); // Do level order traversal of Binary Tree while (!q.isEmpty()) { // n is the no of nodes in current Level int n = q.size(); for(int i = 0 ; i < n ; i++){ // dequeue the front node from the queue Node temp = q.peek(); q.poll(); //If it is leftmost corner value or rightmost corner value then print it if(i==0 || i==n-1) System.out.print(temp.key + " "); //push the left and right children of the temp node if (temp.left != null) q.add(temp.left); if (temp.right != null) q.add(temp.right); } } } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(15); tree.root.left = new Node(10); tree.root.right = new Node(20); tree.root.left.left = new Node(8); tree.root.left.right = new Node(12); tree.root.right.left = new Node(16); tree.root.right.right = new Node(25); tree.printCorner(tree.root); }} // This code has been contributed by Utkarsh Choubey
# Python3 program to print corner# node at each level of binary treefrom collections import deque # A binary tree node has key, pointer to left# child and a pointer to right childclass Node: def __init__(self, key): self.key = key self.left = None self.right = None # Function to print corner node at each leveldef printCorner(root: Node): # If the root is null then simply return if root == None: return # Do level order traversal # using a single queue q = deque() q.append(root) while q: # n denotes the size of the current # level in the queue n = len(q) for i in range(n): temp = q[0] q.popleft() # If it is leftmost corner value or # rightmost corner value then print it if i == 0 or i == n - 1: print(temp.key, end = " ") # push the left and right children # of the temp node if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) # Driver Codeif __name__ == "__main__": root = Node(15) root.left = Node(10) root.right = Node(20) root.left.left = Node(8) root.left.right = Node(12) root.right.left = Node(16) root.right.right = Node(25) printCorner(root) # This code is contributed by sanjeev2552
// C# program to print corner node// at each level in a binary treeusing System;using System.Collections.Generic; /* A binary tree node has key, pointer to leftchild and a pointer to right child */public class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} public class BinaryTree{ Node root; /* Function to print corner node at each level */ void printCorner(Node root) { // star node is for keeping track of levels Queue<Node> q = new Queue<Node>(); // pushing root node and star node q.Enqueue(root); // Do level order traversal of Binary Tree while (q.Count != 0) { // n is the no of nodes in current Level int n = q.Count; for(int i = 0 ; i < n ; i++){ Node temp = q.Peek(); q.Dequeue(); //If it is leftmost corner value or rightmost corner value then print it if(i==0||i==n-1) Console.Write(temp.key + " "); //push the left and right children of the temp node if (temp.left != null) q.Enqueue(temp.left); if (temp.right != null) q.Enqueue(temp.right); } } } // Driver code public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(15); tree.root.left = new Node(10); tree.root.right = new Node(20); tree.root.left.left = new Node(8); tree.root.left.right = new Node(12); tree.root.right.left = new Node(16); tree.root.right.right = new Node(25); tree.printCorner(tree.root); }} // This code is contributed by Utkarsh Choubey
15 10 20 8 25
Time Complexity: O(n) where n is number of nodes in Binary Tree.
This article is contributed by Utkarsh Choubey.
simplex
Rajput-Ji
UtkarshChoubey
sanjeev2552
ajiteshawasthi
tapeshdua420
hardikkoriintern
Amazon
Tree
Amazon
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
A program to check if a binary tree is BST or not
Lowest Common Ancestor in a Binary Tree | Set 1
Diameter of a Binary Tree
Decision Tree
Construct Tree from given Inorder and Preorder traversals
Diagonal Traversal of Binary Tree
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 226,
"s": 54,
"text": "Given a Binary Tree, Print the corner nodes at each level. The node at the leftmost and the node at the rightmost. For example, output for following is 15, 10, 20, 8, 25. "
},
{
"code": null,
"e": 339,
"s": 226,
"text": "A Simple Solution is to do two traversals using the approaches discussed for printing left view and right view. "
},
{
"code": null,
"e": 736,
"s": 339,
"text": "Can we print all corner nodes using one traversal? The idea is to use Level Order Traversal. Every time we store the size of the queue in a variable n, which is the number of nodes at that level. For every level, we check whether the current node is the first (i.e node at index 0) and the node at the last index (i.e node at index n-1) If it is either of them, we print the value of that node. "
},
{
"code": null,
"e": 752,
"s": 736,
"text": "Implementation:"
},
{
"code": null,
"e": 761,
"s": 752,
"text": "Chapters"
},
{
"code": null,
"e": 788,
"s": 761,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 838,
"s": 788,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 861,
"s": 838,
"text": "captions off, selected"
},
{
"code": null,
"e": 869,
"s": 861,
"text": "English"
},
{
"code": null,
"e": 893,
"s": 869,
"text": "This is a modal window."
},
{
"code": null,
"e": 962,
"s": 893,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 984,
"s": 962,
"text": "End of dialog window."
},
{
"code": null,
"e": 988,
"s": 984,
"text": "C++"
},
{
"code": null,
"e": 993,
"s": 988,
"text": "Java"
},
{
"code": null,
"e": 1001,
"s": 993,
"text": "Python3"
},
{
"code": null,
"e": 1004,
"s": 1001,
"text": "C#"
},
{
"code": "// C/C++ program to print corner node at each level// of binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */struct Node{ int key; struct Node* left, *right;}; /* To create a newNode of tree and return pointer */struct Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} /* Function to print corner node at each level */void printCorner(Node *root){ //If the root is null then simply return if(root == NULL) return; //Do level order traversal using a single queue queue<Node*> q; q.push(root); while(!q.empty()) { //n denotes the size of the current level in the queue int n = q.size(); for(int i =0;i<n;i++) { Node *temp = q.front(); q.pop(); //If it is leftmost corner value or rightmost corner value then print it if(i==0 || i==n-1) cout<<temp->key<<\" \"; //push the left and right children of the temp node if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); } }}// Driver program to test above functionint main (){ Node *root = newNode(15); root->left = newNode(10); root->right = newNode(20); root->left->left = newNode(8); root->left->right = newNode(12); root->right->left = newNode(16); root->right->right = newNode(25); printCorner(root); return 0;} // This code is contributed by Tapeshdua420.",
"e": 2639,
"s": 1004,
"text": null
},
{
"code": "// Java program to print corner node at each level in a binary tree import java.util.*; /* A binary tree node has key, pointer to left child and a pointer to right child */class Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} class BinaryTree{ Node root; /* Function to print corner node at each level */ void printCorner(Node root) { // star node is for keeping track of levels Queue<Node> q = new LinkedList<Node>(); // pushing root node and star node q.add(root); // Do level order traversal of Binary Tree while (!q.isEmpty()) { // n is the no of nodes in current Level int n = q.size(); for(int i = 0 ; i < n ; i++){ // dequeue the front node from the queue Node temp = q.peek(); q.poll(); //If it is leftmost corner value or rightmost corner value then print it if(i==0 || i==n-1) System.out.print(temp.key + \" \"); //push the left and right children of the temp node if (temp.left != null) q.add(temp.left); if (temp.right != null) q.add(temp.right); } } } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(15); tree.root.left = new Node(10); tree.root.right = new Node(20); tree.root.left.left = new Node(8); tree.root.left.right = new Node(12); tree.root.right.left = new Node(16); tree.root.right.right = new Node(25); tree.printCorner(tree.root); }} // This code has been contributed by Utkarsh Choubey",
"e": 4448,
"s": 2639,
"text": null
},
{
"code": "# Python3 program to print corner# node at each level of binary treefrom collections import deque # A binary tree node has key, pointer to left# child and a pointer to right childclass Node: def __init__(self, key): self.key = key self.left = None self.right = None # Function to print corner node at each leveldef printCorner(root: Node): # If the root is null then simply return if root == None: return # Do level order traversal # using a single queue q = deque() q.append(root) while q: # n denotes the size of the current # level in the queue n = len(q) for i in range(n): temp = q[0] q.popleft() # If it is leftmost corner value or # rightmost corner value then print it if i == 0 or i == n - 1: print(temp.key, end = \" \") # push the left and right children # of the temp node if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) # Driver Codeif __name__ == \"__main__\": root = Node(15) root.left = Node(10) root.right = Node(20) root.left.left = Node(8) root.left.right = Node(12) root.right.left = Node(16) root.right.right = Node(25) printCorner(root) # This code is contributed by sanjeev2552",
"e": 5840,
"s": 4448,
"text": null
},
{
"code": "// C# program to print corner node// at each level in a binary treeusing System;using System.Collections.Generic; /* A binary tree node has key, pointer to leftchild and a pointer to right child */public class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} public class BinaryTree{ Node root; /* Function to print corner node at each level */ void printCorner(Node root) { // star node is for keeping track of levels Queue<Node> q = new Queue<Node>(); // pushing root node and star node q.Enqueue(root); // Do level order traversal of Binary Tree while (q.Count != 0) { // n is the no of nodes in current Level int n = q.Count; for(int i = 0 ; i < n ; i++){ Node temp = q.Peek(); q.Dequeue(); //If it is leftmost corner value or rightmost corner value then print it if(i==0||i==n-1) Console.Write(temp.key + \" \"); //push the left and right children of the temp node if (temp.left != null) q.Enqueue(temp.left); if (temp.right != null) q.Enqueue(temp.right); } } } // Driver code public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(15); tree.root.left = new Node(10); tree.root.right = new Node(20); tree.root.left.left = new Node(8); tree.root.left.right = new Node(12); tree.root.right.left = new Node(16); tree.root.right.right = new Node(25); tree.printCorner(tree.root); }} // This code is contributed by Utkarsh Choubey",
"e": 7654,
"s": 5840,
"text": null
},
{
"code": null,
"e": 7669,
"s": 7654,
"text": "15 10 20 8 25 "
},
{
"code": null,
"e": 7734,
"s": 7669,
"text": "Time Complexity: O(n) where n is number of nodes in Binary Tree."
},
{
"code": null,
"e": 7782,
"s": 7734,
"text": "This article is contributed by Utkarsh Choubey."
},
{
"code": null,
"e": 7790,
"s": 7782,
"text": "simplex"
},
{
"code": null,
"e": 7800,
"s": 7790,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7815,
"s": 7800,
"text": "UtkarshChoubey"
},
{
"code": null,
"e": 7827,
"s": 7815,
"text": "sanjeev2552"
},
{
"code": null,
"e": 7842,
"s": 7827,
"text": "ajiteshawasthi"
},
{
"code": null,
"e": 7855,
"s": 7842,
"text": "tapeshdua420"
},
{
"code": null,
"e": 7872,
"s": 7855,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 7879,
"s": 7872,
"text": "Amazon"
},
{
"code": null,
"e": 7884,
"s": 7879,
"text": "Tree"
},
{
"code": null,
"e": 7891,
"s": 7884,
"text": "Amazon"
},
{
"code": null,
"e": 7896,
"s": 7891,
"text": "Tree"
},
{
"code": null,
"e": 7994,
"s": 7896,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8026,
"s": 7994,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 8062,
"s": 8026,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 8103,
"s": 8062,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 8167,
"s": 8103,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 8217,
"s": 8167,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 8265,
"s": 8217,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 8291,
"s": 8265,
"text": "Diameter of a Binary Tree"
},
{
"code": null,
"e": 8305,
"s": 8291,
"text": "Decision Tree"
},
{
"code": null,
"e": 8363,
"s": 8305,
"text": "Construct Tree from given Inorder and Preorder traversals"
}
] |
Remove all occurrences of a character in a string | Recursive approach
|
31 May, 2022
Given string str, the task is to write a recursive program to remove all the occurrences of a character X in the string.
Examples:
Input: str = “geeksforgeeks”, c = ‘e’ Output: gksforgksInput: str = “geeksforgeeks”, c = ‘g’ Output: eeksforeeks
Iterative Approach: The iterative approach to this problem can be found in this post.Recursive Approach: Below are the steps:
Get the string str and character X for which character X is to be removed.Recursively iterate for all the character in the string: Base Case: If the length of the string str called recursively is 0 then return the empty string from the function.
Get the string str and character X for which character X is to be removed.
Recursively iterate for all the character in the string: Base Case: If the length of the string str called recursively is 0 then return the empty string from the function.
Base Case: If the length of the string str called recursively is 0 then return the empty string from the function.
if(str.length()==0) {
return "";
}
Recursive Call: If the base case is not met, then check for the character at 0th index if it is X then recursively iterate for the substring removing the first character.
if (str[0] == X) {
return recursive_function(str.substr(1), X);
}
Return Statement: At each recursive call(except the base case and the above condition), return the recursive function for the next iteration including the character at 0th index.
return str[0] + recursive_function(str.substr(1), X)
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 remove all occurrences// of a character in the stringstring removeCharRecursive(string str, char X){ // Base Case if (str.length() == 0) { return ""; } // Check the first character // of the given string if (str[0] == X) { // Pass the rest of the string // to recursion Function call return removeCharRecursive(str.substr(1), X); } // Add the first character of str // and string from recursion return str[0] + removeCharRecursive(str.substr(1), X);} // Driver Codeint main(){ // Given String string str = "geeksforgeeks"; // Given character char X = 'e'; // Function Call str = removeCharRecursive(str, X); cout << str; return 0;}
// Java program for the above approachclass GFG{ // Function to remove all occurrences// of a character in the stringstatic String removeCharRecursive(String str, char X){ // Base Case if (str.length() == 0) { return ""; } // Check the first character // of the given string if (str.charAt(0) == X) { // Pass the rest of the string // to recursion Function call return removeCharRecursive( str.substring(1), X); } // Add the first character of str // and string from recursion return str.charAt(0) + removeCharRecursive( str.substring(1), X);} // Driver Codepublic static void main(String[] args){ // Given String String str = "geeksforgeeks"; // Given character char X = 'e'; // Function call str = removeCharRecursive(str, X); System.out.println(str);}} // This code is contributed by jrishabh99
# Python3 program for the above approach # Function to remove all occurrences# of a character in the stringdef removeCharRecursive(str, X): # Base Case if (len(str) == 0): return "" # Check the first character # of the given string if (str[0] == X): # Pass the rest of the string # to recursion Function call return removeCharRecursive(str[1:], X) # Add the first character of str # and string from recursion return str[0] + removeCharRecursive(str[1:], X) # Driver Code # Given Stringstr = "geeksforgeeks" # Given characterX = 'e' # Function callstr = removeCharRecursive(str, X) print(str) # This code is contributed by sanjoy_62
// C# program for the above approachusing System; class GFG{ // Function to remove all occurrences// of a character in the stringstatic String removeCharRecursive(String str, char X){ // Base Case if (str.Length == 0) { return ""; } // Check the first character // of the given string if (str[0] == X) { // Pass the rest of the string // to recursion Function call return removeCharRecursive( str.Substring(1), X); } // Add the first character of str // and string from recursion return str[0] + removeCharRecursive( str.Substring(1), X);} // Driver Codepublic static void Main(String[] args){ // Given String String str = "geeksforgeeks"; // Given character char X = 'e'; // Function call str = removeCharRecursive(str, X); Console.WriteLine(str);}} // This code is contributed by Amit Katiyar
<script> // javascript program for the above approach // Function to remove all occurrences// of a character in the stringfunction removeCharRecursive(str,X){ // Base Case if (str.length == 0) { return ""; } // Check the first character // of the given string if (str.charAt(0) == X) { // Pass the rest of the string // to recursion Function call return removeCharRecursive( str.substring(1), X); } // Add the first character of str // and string from recursion return str.charAt(0) + removeCharRecursive( str.substring(1), X);} // Driver Code//Given Stringvar str = "geeksforgeeks"; // Given charactervar X = 'e'; // Function callstr = removeCharRecursive(str, X); document.write(str); // This code is contributed by 29AjayKumar</script>
gksforgks
Time Complexity: O(N), as we are using a recursive calls to traverse N times, where N is the length of the string.
Auxiliary Space: O(1), as we are not using any extra space.
jrishabh99
amit143katiyar
sanjoy_62
29AjayKumar
rohitkumarsinghcna
Competitive Programming
Recursion
Strings
Strings
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 175,
"s": 54,
"text": "Given string str, the task is to write a recursive program to remove all the occurrences of a character X in the string."
},
{
"code": null,
"e": 185,
"s": 175,
"text": "Examples:"
},
{
"code": null,
"e": 300,
"s": 185,
"text": "Input: str = “geeksforgeeks”, c = ‘e’ Output: gksforgksInput: str = “geeksforgeeks”, c = ‘g’ Output: eeksforeeks "
},
{
"code": null,
"e": 428,
"s": 300,
"text": "Iterative Approach: The iterative approach to this problem can be found in this post.Recursive Approach: Below are the steps: "
},
{
"code": null,
"e": 676,
"s": 428,
"text": "Get the string str and character X for which character X is to be removed.Recursively iterate for all the character in the string: Base Case: If the length of the string str called recursively is 0 then return the empty string from the function. "
},
{
"code": null,
"e": 751,
"s": 676,
"text": "Get the string str and character X for which character X is to be removed."
},
{
"code": null,
"e": 925,
"s": 751,
"text": "Recursively iterate for all the character in the string: Base Case: If the length of the string str called recursively is 0 then return the empty string from the function. "
},
{
"code": null,
"e": 1042,
"s": 925,
"text": "Base Case: If the length of the string str called recursively is 0 then return the empty string from the function. "
},
{
"code": null,
"e": 1080,
"s": 1042,
"text": "if(str.length()==0) {\n return \"\";\n}"
},
{
"code": null,
"e": 1251,
"s": 1080,
"text": "Recursive Call: If the base case is not met, then check for the character at 0th index if it is X then recursively iterate for the substring removing the first character."
},
{
"code": null,
"e": 1325,
"s": 1251,
"text": "if (str[0] == X) {\n return recursive_function(str.substr(1), X);\n}"
},
{
"code": null,
"e": 1506,
"s": 1325,
"text": "Return Statement: At each recursive call(except the base case and the above condition), return the recursive function for the next iteration including the character at 0th index. "
},
{
"code": null,
"e": 1559,
"s": 1506,
"text": "return str[0] + recursive_function(str.substr(1), X)"
},
{
"code": null,
"e": 1611,
"s": 1559,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1615,
"s": 1611,
"text": "C++"
},
{
"code": null,
"e": 1620,
"s": 1615,
"text": "Java"
},
{
"code": null,
"e": 1628,
"s": 1620,
"text": "Python3"
},
{
"code": null,
"e": 1631,
"s": 1628,
"text": "C#"
},
{
"code": null,
"e": 1642,
"s": 1631,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to remove all occurrences// of a character in the stringstring removeCharRecursive(string str, char X){ // Base Case if (str.length() == 0) { return \"\"; } // Check the first character // of the given string if (str[0] == X) { // Pass the rest of the string // to recursion Function call return removeCharRecursive(str.substr(1), X); } // Add the first character of str // and string from recursion return str[0] + removeCharRecursive(str.substr(1), X);} // Driver Codeint main(){ // Given String string str = \"geeksforgeeks\"; // Given character char X = 'e'; // Function Call str = removeCharRecursive(str, X); cout << str; return 0;}",
"e": 2494,
"s": 1642,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to remove all occurrences// of a character in the stringstatic String removeCharRecursive(String str, char X){ // Base Case if (str.length() == 0) { return \"\"; } // Check the first character // of the given string if (str.charAt(0) == X) { // Pass the rest of the string // to recursion Function call return removeCharRecursive( str.substring(1), X); } // Add the first character of str // and string from recursion return str.charAt(0) + removeCharRecursive( str.substring(1), X);} // Driver Codepublic static void main(String[] args){ // Given String String str = \"geeksforgeeks\"; // Given character char X = 'e'; // Function call str = removeCharRecursive(str, X); System.out.println(str);}} // This code is contributed by jrishabh99",
"e": 3468,
"s": 2494,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to remove all occurrences# of a character in the stringdef removeCharRecursive(str, X): # Base Case if (len(str) == 0): return \"\" # Check the first character # of the given string if (str[0] == X): # Pass the rest of the string # to recursion Function call return removeCharRecursive(str[1:], X) # Add the first character of str # and string from recursion return str[0] + removeCharRecursive(str[1:], X) # Driver Code # Given Stringstr = \"geeksforgeeks\" # Given characterX = 'e' # Function callstr = removeCharRecursive(str, X) print(str) # This code is contributed by sanjoy_62",
"e": 4168,
"s": 3468,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to remove all occurrences// of a character in the stringstatic String removeCharRecursive(String str, char X){ // Base Case if (str.Length == 0) { return \"\"; } // Check the first character // of the given string if (str[0] == X) { // Pass the rest of the string // to recursion Function call return removeCharRecursive( str.Substring(1), X); } // Add the first character of str // and string from recursion return str[0] + removeCharRecursive( str.Substring(1), X);} // Driver Codepublic static void Main(String[] args){ // Given String String str = \"geeksforgeeks\"; // Given character char X = 'e'; // Function call str = removeCharRecursive(str, X); Console.WriteLine(str);}} // This code is contributed by Amit Katiyar",
"e": 5135,
"s": 4168,
"text": null
},
{
"code": "<script> // javascript program for the above approach // Function to remove all occurrences// of a character in the stringfunction removeCharRecursive(str,X){ // Base Case if (str.length == 0) { return \"\"; } // Check the first character // of the given string if (str.charAt(0) == X) { // Pass the rest of the string // to recursion Function call return removeCharRecursive( str.substring(1), X); } // Add the first character of str // and string from recursion return str.charAt(0) + removeCharRecursive( str.substring(1), X);} // Driver Code//Given Stringvar str = \"geeksforgeeks\"; // Given charactervar X = 'e'; // Function callstr = removeCharRecursive(str, X); document.write(str); // This code is contributed by 29AjayKumar</script>",
"e": 5985,
"s": 5135,
"text": null
},
{
"code": null,
"e": 5995,
"s": 5985,
"text": "gksforgks"
},
{
"code": null,
"e": 6112,
"s": 5997,
"text": "Time Complexity: O(N), as we are using a recursive calls to traverse N times, where N is the length of the string."
},
{
"code": null,
"e": 6173,
"s": 6112,
"text": "Auxiliary Space: O(1), as we are not using any extra space. "
},
{
"code": null,
"e": 6184,
"s": 6173,
"text": "jrishabh99"
},
{
"code": null,
"e": 6199,
"s": 6184,
"text": "amit143katiyar"
},
{
"code": null,
"e": 6209,
"s": 6199,
"text": "sanjoy_62"
},
{
"code": null,
"e": 6221,
"s": 6209,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6240,
"s": 6221,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 6264,
"s": 6240,
"text": "Competitive Programming"
},
{
"code": null,
"e": 6274,
"s": 6264,
"text": "Recursion"
},
{
"code": null,
"e": 6282,
"s": 6274,
"text": "Strings"
},
{
"code": null,
"e": 6290,
"s": 6282,
"text": "Strings"
},
{
"code": null,
"e": 6300,
"s": 6290,
"text": "Recursion"
}
] |
Download web page using Java
|
20 Jan, 2018
Java Program to read and download webpage
Steps:1. Create a URL object and pass url as string to download the webpage.URL example = new URL(pass url of webpage you want to download)2. Create Buffered Reader object and pass openStream(). Method of URL in Input Stream object.3. Create a string object to read each line one by one from stream.4. Write each line in html file where webpage will be downloaded.5. Close all objects.6. Catch exceptions if url failed to download.
Program:
package normal;// Java program to read and download// webpage in html fileimport java.io.*;import java.net.URL;import java.net.MalformedURLException; public class download { public static void DownloadWebPage(String webpage) { try { // Create URL object URL url = new URL(webpage); BufferedReader readr = new BufferedReader(new InputStreamReader(url.openStream())); // Enter filename in which you want to download BufferedWriter writer = new BufferedWriter(new FileWriter("Download.html")); // read each line from stream till end String line; while ((line = readr.readLine()) != null) { writer.write(line); } readr.close(); writer.close(); System.out.println("Successfully Downloaded."); } // Exceptions catch (MalformedURLException mue) { System.out.println("Malformed URL Exception raised"); } catch (IOException ie) { System.out.println("IOException raised"); } } public static void main(String args[]) throws IOException { String url = "https://www.geeksforgeeks.org/"; DownloadWebPage(url); }}
Output:
Successfully Downloaded.
Java-Networking
Java
Web Technologies
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Jan, 2018"
},
{
"code": null,
"e": 94,
"s": 52,
"text": "Java Program to read and download webpage"
},
{
"code": null,
"e": 526,
"s": 94,
"text": "Steps:1. Create a URL object and pass url as string to download the webpage.URL example = new URL(pass url of webpage you want to download)2. Create Buffered Reader object and pass openStream(). Method of URL in Input Stream object.3. Create a string object to read each line one by one from stream.4. Write each line in html file where webpage will be downloaded.5. Close all objects.6. Catch exceptions if url failed to download."
},
{
"code": null,
"e": 535,
"s": 526,
"text": "Program:"
},
{
"code": "package normal;// Java program to read and download// webpage in html fileimport java.io.*;import java.net.URL;import java.net.MalformedURLException; public class download { public static void DownloadWebPage(String webpage) { try { // Create URL object URL url = new URL(webpage); BufferedReader readr = new BufferedReader(new InputStreamReader(url.openStream())); // Enter filename in which you want to download BufferedWriter writer = new BufferedWriter(new FileWriter(\"Download.html\")); // read each line from stream till end String line; while ((line = readr.readLine()) != null) { writer.write(line); } readr.close(); writer.close(); System.out.println(\"Successfully Downloaded.\"); } // Exceptions catch (MalformedURLException mue) { System.out.println(\"Malformed URL Exception raised\"); } catch (IOException ie) { System.out.println(\"IOException raised\"); } } public static void main(String args[]) throws IOException { String url = \"https://www.geeksforgeeks.org/\"; DownloadWebPage(url); }}",
"e": 1844,
"s": 535,
"text": null
},
{
"code": null,
"e": 1852,
"s": 1844,
"text": "Output:"
},
{
"code": null,
"e": 1877,
"s": 1852,
"text": "Successfully Downloaded."
},
{
"code": null,
"e": 1893,
"s": 1877,
"text": "Java-Networking"
},
{
"code": null,
"e": 1898,
"s": 1893,
"text": "Java"
},
{
"code": null,
"e": 1915,
"s": 1898,
"text": "Web Technologies"
},
{
"code": null,
"e": 1920,
"s": 1915,
"text": "Java"
}
] |
Sum of product of x and y such that floor(n/x) = y
|
11 May, 2021
Given a positive integer n. The task is to find the sum of product of x and y such that ⌊n/x⌋ = y (Integer Division).
Examples:
Input : n = 5
Output : 21
Following are the possible pairs of (x, y):
(1, 5), (2, 2), (3, 1), (4, 1), (5, 1).
So, 1*5 + 2*2 + 3*1 + 4*1 + 5*1
= 5 + 4 + 3 + 4 + 5
= 21.
Input : n = 10
Output : 87
Method 1 (Brute Force): Iterate x from 1 to n to find y. Then add x*y to the answer over each iteration.
Below is the implementation of this approach :
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of product of x and y// such that n/x = y (Integer Division)#include<bits/stdc++.h>using namespace std; // Return the sum of product x*y.int sumofproduct(int n){ int ans = 0; // Iterating x from 1 to n for (int x = 1; x <= n; x++) { // Finding y = n/x. int y = n/x; // Adding product of x and y to answer. ans += (y * x); } return ans;} // Driven Programint main(){ int n = 10; cout << sumofproduct(n) << endl; return 0;}
// Java program to find sum of// product of x and y such that// n/x = y (Integer Division)import java.io.*; class GFG { // Return the sum of product x*y.static int sumofproduct(int n){ int ans = 0; // Iterating x from 1 to n for (int x = 1; x <= n; x++) { // Finding y = n/x. int y = n / x; // Adding product of x and // y to answer. ans += (y * x); } return ans;} // Driver Code static public void main(String[] args) { int n = 10; System.out.println(sumofproduct(n)); }} // This code is contributed by vt_m.
# Python3 program to find sum of# product of x and y such that# n/x = y (Integer Division) # Return the sum of product x*ydef sumofproduct(n): ans = 0 # Iterating x from 1 to n for x in range(1, n + 1): # Finding y = n/x. y = int(n / x) # Adding product of x and y to answer. ans += (y * x) return ans # Driven Programn = 10print (sumofproduct(n)) #This code is Shreyanshi Arun
// C# program to find sum of// product of x and y such that// n/x = y (Integer Division)using System; class GFG { // Return the sum of product x*y.static int sumofproduct(int n){ int ans = 0; // Iterating x from 1 to n for (int x = 1; x <= n; x++) { // Finding y = n/x. int y = n / x; // Adding product of x and // y to answer. ans += (y * x); } return ans;} // Driver Code static public void Main(String[] args) { int n = 10; Console.WriteLine(sumofproduct(n)); }} // This code is contributed by vt_m.
<?php// PHP program to find sum of product// of x and y such that n/x = y// (Integer Division) // Return the sum of product x*y.function sumofproduct($n){ $ans = 0; // Iterating x from 1 to n for($x = 1; $x <= $n; $x++) { // Finding y = n/x. $y = (int)($n / $x); // Adding product of x // and y to answer. $ans += ($y * $x); } return $ans;} // Driver Code$n = 10;echo sumofproduct($n); // This code is contributed by mits?>
<script> // Javascript program to find sum of// product of x and y such that// n/x = y (Integer Division) // Return the sum of product x*y.function sumofproduct(n){ var ans = 0; // Iterating x from 1 to n for(x = 1; x <= n; x++) { // Finding y = n/x. var y = parseInt(n / x); // Adding product of x and // y to answer. ans += (y * x); } return ans;} // Driver Codevar n = 10;document.write(sumofproduct(n)); // This code is contributed by Princi Singh </script>
Output :
87
Time Complexity : O(n)Method 2 (Efficient Approach): Let’s solve for n = 10, so x = 1, y = 10 x = 2, y = 5 x = 3, y = 3 x = 4, y = 2 x = 5, y = 2 x = 6, y = 1 x = 7, y = 1 x = 8, y = 1 x = 9, y = 1 x = 10, y = 1So, our answer would be 1*10 + 2*5 + 3*3 + 4*2 + 5*2 + 6*1 + 7*1 + 8*1 + 9*1 + 10*1.Now, observe some value of y is repeating. Also, observe that they are repeating for some range of consecutive value of x like y = 1 is repeating for x = 6 to 10.
So, instead of finding the value of y for all the value of x (1 to n) as done in method 1, try to find the lower and higher value of x for which the value of possible value of y like for y = 1 try to find lower value of x = 6 and higher value of x = 10. Now, observe lower value will be (n/(y+1)) + 1 and higher value will be (n/y). Find the sum of range of x and multiply with y and add to the answer.How to find the possible value of y?
Observe, y has all values from 1 to sqrt(n) when y is smaller than or equal to x. So for y = 1 to sqrt(n), find the lower and higher limits of x for each y. For n = 10, y = 1, lo = 6 and hi = 10, ans += (6 + 7 + 8 + 9 + 10)*1 y = 2, lo = 4 and hi = 5, ans += (4 + 5)*2 y = 3, lo = 3 and hi = 3, ans += (3)*3
For other values to be added (for y = 10 and 5 in n = 10), observe they can be found in above steps, for each y, add y * (n/y) in the answer. For n = 10, y = 1, ans += 1 * (10/1) y = 2, ans += 2 * (10/2).
Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of product of x and y// such that n/x = y (Integer Division)#include<bits/stdc++.h>using namespace std; // Return the sum of natural number in a range.int sumOfRange(int a, int b){ // n*(n+1)/2. int i = (a * (a+1)) >> 1; int j = (b * (b+1)) >> 1; return (i - j);} // Return the sum of product x*y.int sumofproduct(int n){ int sum = 0; // Iterating i from 1 to sqrt(n) int root = sqrt(n); for (int i=1; i<=root; i++) { // Finding the upper limit. int up = n/i; // Finding the lower limit. int low = max(n/(i+1), root); sum += (i * sumOfRange(up, low)); sum += (i * (n/i)); } return sum;} // Driven Programint main(){ int n = 10; cout << sumofproduct(n) << endl; return 0;}
// Java program to find sum of// product of x and y such that// n / x = y (Integer Division)import java.io.*; class GFG { // Return the sum of natural number in a range.static int sumOfRange(int a, int b){ // n * (n + 1) / 2. int i = (a * (a + 1)) >> 1; int j = (b * (b + 1)) >> 1; return (i - j);} // Return the sum of product x*y.static int sumofproduct(int n){ int sum = 0; // Iterating i from 1 to sqrt(n) int root = (int)Math.sqrt(n); for (int i = 1; i <= root; i++) { // Finding the upper limit. int up = n / i; // Finding the lower limit. int low = Math.max(n / (i + 1), root); sum += (i * sumOfRange(up, low)); sum += (i * (n / i)); } return sum;} // Driver Code static public void main(String[] args) { int n = 10; System.out.println(sumofproduct(n)); }} // This code is contributed by vt_m.
# Python3 program to find sum# of product of x and y such# that n/x = y (Integer Division)import math # Return the sum of natural# number in a range.def sumOfRange(a, b): # n*(n+1)/2. i = (a * (a + 1)) >> 1; j = (b * (b + 1)) >> 1; return (i - j); # Return the sum of product x*y.def sumofproduct(n): sum = 0; # Iterating i from 1 to sqrt(n) root = int(math.sqrt(n)); for i in range(1, root + 1): # Finding the upper limit. up = int(n / i); # Finding the lower limit. low = max(int(n / (i + 1)), root); sum += (i * sumOfRange(up, low)); sum += (i * int(n / i)); return sum; # Driven Coden = 10;print(sumofproduct(n)); # This code is contributed by mits
// C# program to find sum of// product of x and y such that// n / x = y (Integer Division)using System; class GFG { // Return the sum of natural number in a range.static int sumOfRange(int a, int b){ // n * (n + 1) / 2. int i = (a * (a + 1)) >> 1; int j = (b * (b + 1)) >> 1; return (i - j);} // Return the sum of product x*y.static int sumofproduct(int n){ int sum = 0; // Iterating i from 1 to sqrt(n) int root = (int)Math.Sqrt(n); for (int i = 1; i <= root; i++) { // Finding the upper limit. int up = n / i; // Finding the lower limit. int low = Math.Max(n / (i + 1), root); sum += (i * sumOfRange(up, low)); sum += (i * (n / i)); } return sum;} // Driver Code static public void Main(String[] args) { int n = 10; Console.WriteLine(sumofproduct(n)); }} // This code is contributed by vt_m.
<?php// PHP program to find sum of// product of x and y such// that n/x = y (Integer Division) // Return the sum of natural// number in a range.function sumOfRange($a, $b){ // n*(n+1)/2. $i = ($a * ($a + 1)) >> 1; $j = ($b * ($b + 1)) >> 1; return ($i - $j);} // Return the sum of product x*y.function sumofproduct($n){ $sum = 0; // Iterating i from 1 to sqrt(n) $root = sqrt($n); for ($i = 1; $i <= $root; $i++) { // Finding the upper limit. $up = (int)($n / $i); // Finding the lower limit. $low = max((int)($n / ($i + 1)), $root); $sum += ($i * sumOfRange($up, $low)); $sum += ($i * (int)($n / $i)); } return $sum;} // Driven Code$n = 10;echo sumofproduct($n) . "\n"; // This code is contributed// by Akanksha Rai(Abby_akku)?>
<script> // Javascript program to implement// the above approach // Return the sum of natural number in a range.function sumOfRange(a, b){ // n * (n + 1) / 2. let i = (a * (a + 1)) >> 1; let j = (b * (b + 1)) >> 1; return (i - j);} // Return the sum of product x*y.function sumofproduct(n){ let sum = 0; // Iterating i from 1 to sqrt(n) let root = Math.floor(Math.sqrt(n)); for (let i = 1; i <= root; i++) { // Finding the upper limit. let up = Math.floor(n / i); // Finding the lower limit. let low = Math.max(Math.floor(n / (i + 1)), root); sum += (i * sumOfRange(up, low)); sum += (i * Math.floor(n / i)); } return sum;} // Driver Code let n = 10; document.write(sumofproduct(n)); </script>
Output:
87
Time Complexity: O((√n)Source: https://www.quora.com/What-is-the-fastest-way-to-solve-the-problem-that-states-given-a-number-N-find-the-sum-of-all-products-x*y-such-that-N-x-y-integer-division-Here-N-would-be-N-10This article is contributed by Anuj Chauhan(APC). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
Mithun Kumar
Akanksha_Rai
princi singh
chinmoy1997pal
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": "\n11 May, 2021"
},
{
"code": null,
"e": 172,
"s": 54,
"text": "Given a positive integer n. The task is to find the sum of product of x and y such that ⌊n/x⌋ = y (Integer Division)."
},
{
"code": null,
"e": 183,
"s": 172,
"text": "Examples: "
},
{
"code": null,
"e": 387,
"s": 183,
"text": "Input : n = 5\nOutput : 21\nFollowing are the possible pairs of (x, y):\n(1, 5), (2, 2), (3, 1), (4, 1), (5, 1).\nSo, 1*5 + 2*2 + 3*1 + 4*1 + 5*1 \n = 5 + 4 + 3 + 4 + 5 \n = 21.\n\nInput : n = 10\nOutput : 87"
},
{
"code": null,
"e": 492,
"s": 387,
"text": "Method 1 (Brute Force): Iterate x from 1 to n to find y. Then add x*y to the answer over each iteration."
},
{
"code": null,
"e": 541,
"s": 492,
"text": "Below is the implementation of this approach : "
},
{
"code": null,
"e": 545,
"s": 541,
"text": "C++"
},
{
"code": null,
"e": 550,
"s": 545,
"text": "Java"
},
{
"code": null,
"e": 558,
"s": 550,
"text": "Python3"
},
{
"code": null,
"e": 561,
"s": 558,
"text": "C#"
},
{
"code": null,
"e": 565,
"s": 561,
"text": "PHP"
},
{
"code": null,
"e": 576,
"s": 565,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of product of x and y// such that n/x = y (Integer Division)#include<bits/stdc++.h>using namespace std; // Return the sum of product x*y.int sumofproduct(int n){ int ans = 0; // Iterating x from 1 to n for (int x = 1; x <= n; x++) { // Finding y = n/x. int y = n/x; // Adding product of x and y to answer. ans += (y * x); } return ans;} // Driven Programint main(){ int n = 10; cout << sumofproduct(n) << endl; return 0;}",
"e": 1083,
"s": 576,
"text": null
},
{
"code": "// Java program to find sum of// product of x and y such that// n/x = y (Integer Division)import java.io.*; class GFG { // Return the sum of product x*y.static int sumofproduct(int n){ int ans = 0; // Iterating x from 1 to n for (int x = 1; x <= n; x++) { // Finding y = n/x. int y = n / x; // Adding product of x and // y to answer. ans += (y * x); } return ans;} // Driver Code static public void main(String[] args) { int n = 10; System.out.println(sumofproduct(n)); }} // This code is contributed by vt_m.",
"e": 1680,
"s": 1083,
"text": null
},
{
"code": "# Python3 program to find sum of# product of x and y such that# n/x = y (Integer Division) # Return the sum of product x*ydef sumofproduct(n): ans = 0 # Iterating x from 1 to n for x in range(1, n + 1): # Finding y = n/x. y = int(n / x) # Adding product of x and y to answer. ans += (y * x) return ans # Driven Programn = 10print (sumofproduct(n)) #This code is Shreyanshi Arun",
"e": 2110,
"s": 1680,
"text": null
},
{
"code": "// C# program to find sum of// product of x and y such that// n/x = y (Integer Division)using System; class GFG { // Return the sum of product x*y.static int sumofproduct(int n){ int ans = 0; // Iterating x from 1 to n for (int x = 1; x <= n; x++) { // Finding y = n/x. int y = n / x; // Adding product of x and // y to answer. ans += (y * x); } return ans;} // Driver Code static public void Main(String[] args) { int n = 10; Console.WriteLine(sumofproduct(n)); }} // This code is contributed by vt_m.",
"e": 2700,
"s": 2110,
"text": null
},
{
"code": "<?php// PHP program to find sum of product// of x and y such that n/x = y// (Integer Division) // Return the sum of product x*y.function sumofproduct($n){ $ans = 0; // Iterating x from 1 to n for($x = 1; $x <= $n; $x++) { // Finding y = n/x. $y = (int)($n / $x); // Adding product of x // and y to answer. $ans += ($y * $x); } return $ans;} // Driver Code$n = 10;echo sumofproduct($n); // This code is contributed by mits?>",
"e": 3180,
"s": 2700,
"text": null
},
{
"code": "<script> // Javascript program to find sum of// product of x and y such that// n/x = y (Integer Division) // Return the sum of product x*y.function sumofproduct(n){ var ans = 0; // Iterating x from 1 to n for(x = 1; x <= n; x++) { // Finding y = n/x. var y = parseInt(n / x); // Adding product of x and // y to answer. ans += (y * x); } return ans;} // Driver Codevar n = 10;document.write(sumofproduct(n)); // This code is contributed by Princi Singh </script>",
"e": 3709,
"s": 3180,
"text": null
},
{
"code": null,
"e": 3718,
"s": 3709,
"text": "Output :"
},
{
"code": null,
"e": 3721,
"s": 3718,
"text": "87"
},
{
"code": null,
"e": 4179,
"s": 3721,
"text": "Time Complexity : O(n)Method 2 (Efficient Approach): Let’s solve for n = 10, so x = 1, y = 10 x = 2, y = 5 x = 3, y = 3 x = 4, y = 2 x = 5, y = 2 x = 6, y = 1 x = 7, y = 1 x = 8, y = 1 x = 9, y = 1 x = 10, y = 1So, our answer would be 1*10 + 2*5 + 3*3 + 4*2 + 5*2 + 6*1 + 7*1 + 8*1 + 9*1 + 10*1.Now, observe some value of y is repeating. Also, observe that they are repeating for some range of consecutive value of x like y = 1 is repeating for x = 6 to 10."
},
{
"code": null,
"e": 4619,
"s": 4179,
"text": "So, instead of finding the value of y for all the value of x (1 to n) as done in method 1, try to find the lower and higher value of x for which the value of possible value of y like for y = 1 try to find lower value of x = 6 and higher value of x = 10. Now, observe lower value will be (n/(y+1)) + 1 and higher value will be (n/y). Find the sum of range of x and multiply with y and add to the answer.How to find the possible value of y? "
},
{
"code": null,
"e": 4927,
"s": 4619,
"text": "Observe, y has all values from 1 to sqrt(n) when y is smaller than or equal to x. So for y = 1 to sqrt(n), find the lower and higher limits of x for each y. For n = 10, y = 1, lo = 6 and hi = 10, ans += (6 + 7 + 8 + 9 + 10)*1 y = 2, lo = 4 and hi = 5, ans += (4 + 5)*2 y = 3, lo = 3 and hi = 3, ans += (3)*3"
},
{
"code": null,
"e": 5132,
"s": 4927,
"text": "For other values to be added (for y = 10 and 5 in n = 10), observe they can be found in above steps, for each y, add y * (n/y) in the answer. For n = 10, y = 1, ans += 1 * (10/1) y = 2, ans += 2 * (10/2)."
},
{
"code": null,
"e": 5180,
"s": 5132,
"text": "Below is the implementation of this approach: "
},
{
"code": null,
"e": 5184,
"s": 5180,
"text": "C++"
},
{
"code": null,
"e": 5189,
"s": 5184,
"text": "Java"
},
{
"code": null,
"e": 5197,
"s": 5189,
"text": "Python3"
},
{
"code": null,
"e": 5200,
"s": 5197,
"text": "C#"
},
{
"code": null,
"e": 5204,
"s": 5200,
"text": "PHP"
},
{
"code": null,
"e": 5215,
"s": 5204,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of product of x and y// such that n/x = y (Integer Division)#include<bits/stdc++.h>using namespace std; // Return the sum of natural number in a range.int sumOfRange(int a, int b){ // n*(n+1)/2. int i = (a * (a+1)) >> 1; int j = (b * (b+1)) >> 1; return (i - j);} // Return the sum of product x*y.int sumofproduct(int n){ int sum = 0; // Iterating i from 1 to sqrt(n) int root = sqrt(n); for (int i=1; i<=root; i++) { // Finding the upper limit. int up = n/i; // Finding the lower limit. int low = max(n/(i+1), root); sum += (i * sumOfRange(up, low)); sum += (i * (n/i)); } return sum;} // Driven Programint main(){ int n = 10; cout << sumofproduct(n) << endl; return 0;}",
"e": 6002,
"s": 5215,
"text": null
},
{
"code": "// Java program to find sum of// product of x and y such that// n / x = y (Integer Division)import java.io.*; class GFG { // Return the sum of natural number in a range.static int sumOfRange(int a, int b){ // n * (n + 1) / 2. int i = (a * (a + 1)) >> 1; int j = (b * (b + 1)) >> 1; return (i - j);} // Return the sum of product x*y.static int sumofproduct(int n){ int sum = 0; // Iterating i from 1 to sqrt(n) int root = (int)Math.sqrt(n); for (int i = 1; i <= root; i++) { // Finding the upper limit. int up = n / i; // Finding the lower limit. int low = Math.max(n / (i + 1), root); sum += (i * sumOfRange(up, low)); sum += (i * (n / i)); } return sum;} // Driver Code static public void main(String[] args) { int n = 10; System.out.println(sumofproduct(n)); }} // This code is contributed by vt_m.",
"e": 6913,
"s": 6002,
"text": null
},
{
"code": "# Python3 program to find sum# of product of x and y such# that n/x = y (Integer Division)import math # Return the sum of natural# number in a range.def sumOfRange(a, b): # n*(n+1)/2. i = (a * (a + 1)) >> 1; j = (b * (b + 1)) >> 1; return (i - j); # Return the sum of product x*y.def sumofproduct(n): sum = 0; # Iterating i from 1 to sqrt(n) root = int(math.sqrt(n)); for i in range(1, root + 1): # Finding the upper limit. up = int(n / i); # Finding the lower limit. low = max(int(n / (i + 1)), root); sum += (i * sumOfRange(up, low)); sum += (i * int(n / i)); return sum; # Driven Coden = 10;print(sumofproduct(n)); # This code is contributed by mits",
"e": 7643,
"s": 6913,
"text": null
},
{
"code": "// C# program to find sum of// product of x and y such that// n / x = y (Integer Division)using System; class GFG { // Return the sum of natural number in a range.static int sumOfRange(int a, int b){ // n * (n + 1) / 2. int i = (a * (a + 1)) >> 1; int j = (b * (b + 1)) >> 1; return (i - j);} // Return the sum of product x*y.static int sumofproduct(int n){ int sum = 0; // Iterating i from 1 to sqrt(n) int root = (int)Math.Sqrt(n); for (int i = 1; i <= root; i++) { // Finding the upper limit. int up = n / i; // Finding the lower limit. int low = Math.Max(n / (i + 1), root); sum += (i * sumOfRange(up, low)); sum += (i * (n / i)); } return sum;} // Driver Code static public void Main(String[] args) { int n = 10; Console.WriteLine(sumofproduct(n)); }} // This code is contributed by vt_m.",
"e": 8547,
"s": 7643,
"text": null
},
{
"code": "<?php// PHP program to find sum of// product of x and y such// that n/x = y (Integer Division) // Return the sum of natural// number in a range.function sumOfRange($a, $b){ // n*(n+1)/2. $i = ($a * ($a + 1)) >> 1; $j = ($b * ($b + 1)) >> 1; return ($i - $j);} // Return the sum of product x*y.function sumofproduct($n){ $sum = 0; // Iterating i from 1 to sqrt(n) $root = sqrt($n); for ($i = 1; $i <= $root; $i++) { // Finding the upper limit. $up = (int)($n / $i); // Finding the lower limit. $low = max((int)($n / ($i + 1)), $root); $sum += ($i * sumOfRange($up, $low)); $sum += ($i * (int)($n / $i)); } return $sum;} // Driven Code$n = 10;echo sumofproduct($n) . \"\\n\"; // This code is contributed// by Akanksha Rai(Abby_akku)?>",
"e": 9356,
"s": 8547,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Return the sum of natural number in a range.function sumOfRange(a, b){ // n * (n + 1) / 2. let i = (a * (a + 1)) >> 1; let j = (b * (b + 1)) >> 1; return (i - j);} // Return the sum of product x*y.function sumofproduct(n){ let sum = 0; // Iterating i from 1 to sqrt(n) let root = Math.floor(Math.sqrt(n)); for (let i = 1; i <= root; i++) { // Finding the upper limit. let up = Math.floor(n / i); // Finding the lower limit. let low = Math.max(Math.floor(n / (i + 1)), root); sum += (i * sumOfRange(up, low)); sum += (i * Math.floor(n / i)); } return sum;} // Driver Code let n = 10; document.write(sumofproduct(n)); </script>",
"e": 10161,
"s": 9356,
"text": null
},
{
"code": null,
"e": 10170,
"s": 10161,
"text": "Output: "
},
{
"code": null,
"e": 10173,
"s": 10170,
"text": "87"
},
{
"code": null,
"e": 10812,
"s": 10173,
"text": "Time Complexity: O((√n)Source: https://www.quora.com/What-is-the-fastest-way-to-solve-the-problem-that-states-given-a-number-N-find-the-sum-of-all-products-x*y-such-that-N-x-y-integer-division-Here-N-would-be-N-10This article is contributed by Anuj Chauhan(APC). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 10817,
"s": 10812,
"text": "vt_m"
},
{
"code": null,
"e": 10830,
"s": 10817,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 10843,
"s": 10830,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 10856,
"s": 10843,
"text": "princi singh"
},
{
"code": null,
"e": 10871,
"s": 10856,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 10884,
"s": 10871,
"text": "Mathematical"
},
{
"code": null,
"e": 10897,
"s": 10884,
"text": "Mathematical"
}
] |
MySQL query to avoid displaying duplicates values?
|
For this, you can use GROUP BY and use COUNT to get only non-duplicate values. Following is the syntax −
select yourColumnName from yourTableName group by yourColumnName having count(*)=1;
Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Subject varchar(100)
-> );
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Subject) values('MySQL');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Subject) values('Java');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Subject) values('C');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Subject) values('C++');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Subject) values('Java');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Subject) values('C');
Query OK, 1 row affected (0.23 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+----+---------+
| Id | Subject |
+----+---------+
| 1 | MySQL |
| 2 | MongoDB |
| 3 | Java |
| 4 | MongoDB |
| 5 | C |
| 6 | C++ |
| 7 | Java |
| 8 | C |
+----+---------+
8 rows in set (0.00 sec)
Here is the query to avoid displaying duplicates −
mysql> select Subject from DemoTable group by Subject having count(*)=1;
+---------+
| Subject |
+---------+
| MySQL |
| C++ |
+---------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1292,
"s": 1187,
"text": "For this, you can use GROUP BY and use COUNT to get only non-duplicate values. Following is the syntax −"
},
{
"code": null,
"e": 1376,
"s": 1292,
"text": "select yourColumnName from yourTableName group by yourColumnName having count(*)=1;"
},
{
"code": null,
"e": 1406,
"s": 1376,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1567,
"s": 1406,
"text": "mysql> create table DemoTable\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Subject varchar(100)\n -> );\nQuery OK, 0 rows affected (0.70 sec)"
},
{
"code": null,
"e": 1623,
"s": 1567,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2350,
"s": 1623,
"text": "mysql> insert into DemoTable(Subject) values('MySQL');\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into DemoTable(Subject) values('MongoDB');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable(Subject) values('Java');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DemoTable(Subject) values('MongoDB');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DemoTable(Subject) values('C');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DemoTable(Subject) values('C++');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DemoTable(Subject) values('Java');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable(Subject) values('C');\nQuery OK, 1 row affected (0.23 sec)"
},
{
"code": null,
"e": 2410,
"s": 2350,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2441,
"s": 2410,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2670,
"s": 2441,
"text": "+----+---------+\n| Id | Subject |\n+----+---------+\n| 1 | MySQL |\n| 2 | MongoDB |\n| 3 | Java |\n| 4 | MongoDB |\n| 5 | C |\n| 6 | C++ |\n| 7 | Java |\n| 8 | C |\n+----+---------+\n8 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2721,
"s": 2670,
"text": "Here is the query to avoid displaying duplicates −"
},
{
"code": null,
"e": 2794,
"s": 2721,
"text": "mysql> select Subject from DemoTable group by Subject having count(*)=1;"
},
{
"code": null,
"e": 2891,
"s": 2794,
"text": "+---------+\n| Subject |\n+---------+\n| MySQL |\n| C++ |\n+---------+\n2 rows in set (0.00 sec)"
}
] |
Python | Convert list of tuples to list of list
|
27 Mar, 2019
This is a quite simple problem but can have a good amount of application due to certain constraints of python language. Because tuples are immutable, they are not easy to process whereas lists are always a better option while processing. Let’s discuss certain ways in which we can convert a list of tuples to list of list.
Method #1 : Using list comprehensionThis can easily be achieved using the list comprehension. We just iterate through each list converting the tuples to the list.
# Python3 code to demonstrate# convert list of tuples to list of list# using list comprehension # initializing list test_list = [(1, 2), (3, 4), (5, 6)] # printing original list print("The original list of tuples : " + str(test_list)) # using list comprehension# convert list of tuples to list of listres = [list(ele) for ele in test_list] # print resultprint("The converted list of list : " + str(res))
The original list of tuples : [(1, 2), (3, 4), (5, 6)]
The converted list of list : [[1, 2], [3, 4], [5, 6]]
Method #2 : Using map() + listWe can use the combination of map function and list operator to perform this particular task. The map function binds each tuple and converts it into list.
# Python3 code to demonstrate# convert list of tuples to list of list# using map() + list # initializing list test_list = [(1, 2), (3, 4), (5, 6)] # printing original list print("The original list of tuples : " + str(test_list)) # using map() + list# convert list of tuples to list of listres = list(map(list, test_list)) # print resultprint("The converted list of list : " + str(res))
The original list of tuples : [(1, 2), (3, 4), (5, 6)]
The converted list of list : [[1, 2], [3, 4], [5, 6]]
Python list-programs
python-list
python-tuple
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 351,
"s": 28,
"text": "This is a quite simple problem but can have a good amount of application due to certain constraints of python language. Because tuples are immutable, they are not easy to process whereas lists are always a better option while processing. Let’s discuss certain ways in which we can convert a list of tuples to list of list."
},
{
"code": null,
"e": 514,
"s": 351,
"text": "Method #1 : Using list comprehensionThis can easily be achieved using the list comprehension. We just iterate through each list converting the tuples to the list."
},
{
"code": "# Python3 code to demonstrate# convert list of tuples to list of list# using list comprehension # initializing list test_list = [(1, 2), (3, 4), (5, 6)] # printing original list print(\"The original list of tuples : \" + str(test_list)) # using list comprehension# convert list of tuples to list of listres = [list(ele) for ele in test_list] # print resultprint(\"The converted list of list : \" + str(res))",
"e": 922,
"s": 514,
"text": null
},
{
"code": null,
"e": 1032,
"s": 922,
"text": "The original list of tuples : [(1, 2), (3, 4), (5, 6)]\nThe converted list of list : [[1, 2], [3, 4], [5, 6]]\n"
},
{
"code": null,
"e": 1219,
"s": 1034,
"text": "Method #2 : Using map() + listWe can use the combination of map function and list operator to perform this particular task. The map function binds each tuple and converts it into list."
},
{
"code": "# Python3 code to demonstrate# convert list of tuples to list of list# using map() + list # initializing list test_list = [(1, 2), (3, 4), (5, 6)] # printing original list print(\"The original list of tuples : \" + str(test_list)) # using map() + list# convert list of tuples to list of listres = list(map(list, test_list)) # print resultprint(\"The converted list of list : \" + str(res))",
"e": 1609,
"s": 1219,
"text": null
},
{
"code": null,
"e": 1719,
"s": 1609,
"text": "The original list of tuples : [(1, 2), (3, 4), (5, 6)]\nThe converted list of list : [[1, 2], [3, 4], [5, 6]]\n"
},
{
"code": null,
"e": 1740,
"s": 1719,
"text": "Python list-programs"
},
{
"code": null,
"e": 1752,
"s": 1740,
"text": "python-list"
},
{
"code": null,
"e": 1765,
"s": 1752,
"text": "python-tuple"
},
{
"code": null,
"e": 1772,
"s": 1765,
"text": "Python"
},
{
"code": null,
"e": 1788,
"s": 1772,
"text": "Python Programs"
},
{
"code": null,
"e": 1800,
"s": 1788,
"text": "python-list"
}
] |
Tkinter | Adding style to the input text using ttk.Entry widget
|
29 Nov, 2021
Tkinter is a GUI (Graphical User Interface) module which is widely used to create GUI applications. It comes along with the Python itself.
Entry widgets are used to get the entry from the user. It can be created as follows-
entry = ttk.Entry(master, option = value, ...)
Code #1: Creating Entry widget and taking input from user (taking only String data).
# importing tkinterfrom tkinter import * from tkinter import ttkfrom tkinter.messagebox import askyesno # creating rootroot = Tk() # specifying geometryroot.geometry('200x100') # This is used to take input from user# and show it in Entry Widget.# Whatever data that we get from keyboard# will be treated as string.input_text = StringVar() entry1 = ttk.Entry(root, textvariable = input_text, justify = CENTER) # focus_force is used to take focus# as soon as application startsentry1.focus_force()entry1.pack(side = TOP, ipadx = 30, ipady = 6) save = ttk.Button(root, text = 'Save', command = lambda : askyesno( 'Confirm', 'Do you want to save?'))save.pack(side = TOP, pady = 10) root.mainloop()
Output:
In above output, as soon as you run the code a Tkinter window will appear and Entry widget is already focussed that means we don’t have to give focus to the Entry area.When we press Button a confirmation message will appear, saying whether you want to save the text or not (it will not save the text, it is only used to show the functioning of Button). Code #2: Adding Style to the entered text in Entry widget.
# importing tkinterfrom tkinter import * from tkinter import ttkfrom tkinter.messagebox import askyesno # creating rootroot = Tk()root.geometry('200x100') input_text = StringVar() # This class is used to add styling# to any widget which are availablestyle = ttk.Style()style.configure('TEntry', foreground = 'green') entry1 = ttk.Entry(root, textvariable = input_text, justify = CENTER, font = ('courier', 15, 'bold')) entry1.focus_force()entry1.pack(side = TOP, ipadx = 30, ipady = 10) save = ttk.Button(root, text = 'Save', command = lambda : askyesno( 'Confirm', 'Do you want to save?'))save.pack(side = TOP, pady = 10) root.mainloop()
Output:In the above output, you may notice that the color of the font is changed, font family is changed, size of the text is bigger than normal as well as text is written in bold. This is because we are adding style to the input text.
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "Tkinter is a GUI (Graphical User Interface) module which is widely used to create GUI applications. It comes along with the Python itself."
},
{
"code": null,
"e": 252,
"s": 167,
"text": "Entry widgets are used to get the entry from the user. It can be created as follows-"
},
{
"code": null,
"e": 301,
"s": 252,
"text": " entry = ttk.Entry(master, option = value, ...) "
},
{
"code": null,
"e": 386,
"s": 301,
"text": "Code #1: Creating Entry widget and taking input from user (taking only String data)."
},
{
"code": "# importing tkinterfrom tkinter import * from tkinter import ttkfrom tkinter.messagebox import askyesno # creating rootroot = Tk() # specifying geometryroot.geometry('200x100') # This is used to take input from user# and show it in Entry Widget.# Whatever data that we get from keyboard# will be treated as string.input_text = StringVar() entry1 = ttk.Entry(root, textvariable = input_text, justify = CENTER) # focus_force is used to take focus# as soon as application startsentry1.focus_force()entry1.pack(side = TOP, ipadx = 30, ipady = 6) save = ttk.Button(root, text = 'Save', command = lambda : askyesno( 'Confirm', 'Do you want to save?'))save.pack(side = TOP, pady = 10) root.mainloop()",
"e": 1118,
"s": 386,
"text": null
},
{
"code": null,
"e": 1126,
"s": 1118,
"text": "Output:"
},
{
"code": null,
"e": 1538,
"s": 1126,
"text": "In above output, as soon as you run the code a Tkinter window will appear and Entry widget is already focussed that means we don’t have to give focus to the Entry area.When we press Button a confirmation message will appear, saying whether you want to save the text or not (it will not save the text, it is only used to show the functioning of Button). Code #2: Adding Style to the entered text in Entry widget."
},
{
"code": "# importing tkinterfrom tkinter import * from tkinter import ttkfrom tkinter.messagebox import askyesno # creating rootroot = Tk()root.geometry('200x100') input_text = StringVar() # This class is used to add styling# to any widget which are availablestyle = ttk.Style()style.configure('TEntry', foreground = 'green') entry1 = ttk.Entry(root, textvariable = input_text, justify = CENTER, font = ('courier', 15, 'bold')) entry1.focus_force()entry1.pack(side = TOP, ipadx = 30, ipady = 10) save = ttk.Button(root, text = 'Save', command = lambda : askyesno( 'Confirm', 'Do you want to save?'))save.pack(side = TOP, pady = 10) root.mainloop()",
"e": 2253,
"s": 1538,
"text": null
},
{
"code": null,
"e": 2489,
"s": 2253,
"text": "Output:In the above output, you may notice that the color of the font is changed, font family is changed, size of the text is bigger than normal as well as text is written in bold. This is because we are adding style to the input text."
},
{
"code": null,
"e": 2500,
"s": 2489,
"text": "Python-gui"
},
{
"code": null,
"e": 2515,
"s": 2500,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2522,
"s": 2515,
"text": "Python"
}
] |
How to Install Hadoop in Linux?
|
12 Jun, 2020
Hadoop is a framework written in Java for running applications on a large cluster of community hardware. It is similar to the Google file system. In order to install Hadoop, we need java first so first, we install java in our Ubuntu.
Step 1: Open your terminal and first check whether your system is equipped with Java or not with command
java -version
Step 2: Now it is time to update your system. Below are the 2 commands to update your system.
sudo apt-get update
sudo apt-get install update
Step 3: Now we will install the default JDK for java using the following command:
sudo apt-get install default-jdk
It will ask you for Y/N press Y.
Step 4: Now check whether Java is installed or not using the command
java -version
Step 5: Once it installs we require a dedicated user for the same. It is not necessary but it is a good thing to make a dedicated user for the Hadoop installation. You can use the following command:
sudo addgroup hadoop
sudo adduser --ingroup hadoop hadoopusr
Step 6: Now after running the above 2 commands, you have successfully created a dedicated user with name hadoopusr. Now it will ask for a new UNIX password so choose password according to your convenience(make sure sometimes it doesn’t show the character or number you type so please remember whatever you type). Then it will ask you for information like Full Name etc. Keep pressing enter for default then press Y for correct information.
Step 7: Now use the following command:
sudo adduser hadoopusr sudo
With this command, you add your ‘hadoopusr’ to the ‘sudo’ group so that we can also make it a superuser.
Step 8: Now we also need to install ssh key’s that is secured shell.
sudo apt-get install openssh-server
Step 9: Now it’s time for us to switch to new user that is hadoopusr and also enter the password you use above command for switching user:
su - hadoopusr
Step 10: Now it’s time to generate ssh key because Hadoop requires ssh access to manage it’s node, remote or local machine so for our single node of the setup of Hadoop we configure such that we have access to the localhost.
ssh-keygen -t rsa -P ""
After this command simple press enter.
Step 11: Now we use the below command because we need to add the public key of the computer to the authorized key file of the compute that you want to access with ssh keys so we fired these command.
cat $HOME/ .ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
Step 12: Now check for the local host i.e. ssh localhost with below command and press yes to continue and enter your password if it ask then type exit.
ssh localhost
Now you have completed the basic requirement for Hadoop installation.
Step 13: Now download the package that you will going to install . download it from Hadoop-2.9.0 by clicking to the file shown in below image.
Step 14: Once you have download hadoop-2.9.0.tar.gz then place this tar file to your preferred location then extract it with below commands. In my case I moved it to the /Documents folder.
Now we extract this file with below command and enter your hadoopusr password. If you don’t know the password don’t worry you can simply switch your user and change password according to yourself.
command : sudo tar xvzf hadoop-2.9.0.tar.gz
Step 15: Now we need to move this extracted folder to the hadoopusr user so for that type below command(make sure name of your extracted folder is hadoop):
sudo mv hadoop /usr/local/hadoop
Step 16: Now we need to change the ownership so for that command is:
sudo chown -R hadoopusr /usr/local
Step 17: This is the most important Step i.e. now we are going to configure some files this is really very important.
First we configure our ./bashrc file so that to open that file type the below command:
sudo gedit ~/.bashrc
Then a ./bashrc file is open then copy the below command inside this file (change java version according to your PC java version like it might be java-8-openjdk-amd64 ).
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
export HADOOP_HOME=/usr/local/hadoop
export PATH=$PATH:$HADOOP_HOME/bin
export PATH=$PATH:$HADOOP_HOME/sbin
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME
export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export HADOOP_OPTS="-Djava.library.path=$HADOOP_HOME/lib"
Then check whether you have configured it correctly or not.
source ~/.bashrc
Step 18: Before configuring more file first we ensure which version of java we have installed for that go to the location /usr/lib/jvm and after going to this location type ls command to list down the file inside it now see the java version, In my case it is java-11-openjdk-amd64.
Step 19: Now we will configure hadoop-env.sh. For that open the file using below command.
sudo gedit /usr/local/hadoop/etc/hadoop/hadoop-env.sh
Once the file opened, copy the below export command inside it and make sure to comment the already existing export command with JAVA_HOME:
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
Don’t forget to save.
Step 20: Now we will configure the core-site.xml. For that open that file using below command:
sudo gedit /usr/local/hadoop/etc/hadoop/core-site.xml
once the file opens copy the below text inside the configuration tag
<!-- <property><name>fs.default.name</name><value>hdfs://localhost:9000</value></property> -->
See the below image for better understanding:
Step 21: Now we will configure the hdfs-site.xml for that open that file using below command.
sudo gedit /usr/local/hadoop/etc/hadoop/hdfs-site.xml
Once the file opens copy the below text inside the configuration tag
<!-- <property><name>dfs.replication</name><value>1</value></property><property><name>dfs.namenode.name.dir</name><value>file:/usr/local/hadoop_tmp/hdfs/namenode</value></property><property><name>dfs.datanode.data.dir</name><value>file:/usr/local/hadoop_tmp/hdfs/datanode</value></property> -->
See the below image for better understanding:
Step 22: Now we will configure the yarn-site.xml which is responsible for the execution of file in the Hadoop environment. For that open that file using below command:
sudo gedit /usr/local/hadoop/etc/hadoop/yarn-site.xml
once the file opens copy the below text inside the configuration tag
<!-- <property><name>yarn.nodemanager.aux-services</name><value>mapreduce_shuffle</value></property><property><name>yarn.nodemanager.aux-services.mapreduce.shuffle.class</name><value>org.apache.hadoop.mapred.ShuffleHandler</value></property> -->
See the below image for better understanding:
Step 23: Now the last file to configure is mapred-site.xml. For that we have mapred-site.xml.template so we need to locate that file then copy this file to that location and then rename it.
So to locate the file we need to go to the location /usr/local/hadoop/etc/hadoop/ so to copy this file and also rename the file the single, use the following command
sudo cp /usr/local/hadoop/etc/hadoop/mapred-site.xml.template /usr/local/hadoop/etc/hadoop/mapred-site.xml
once the file gets copied or renamed now open that file using the following command:
sudo gedit /usr/local/hadoop/etc/hadoop/mapred-site.xml
And then place the below content inside its configuration tag.
<!-- <property><name>mapreduce.framework.name</name><value>yarn</value></property> -->
See the below image for better understanding:
Step 24: Now we have successfully configured all the files. So now it is time to check our installation. As we know that in Hadoop architecture we have name node and other blocks so we need to make one directory i.e. hadoop_space. Inside this directory we make another directory i.e. hdfs and namenode and datanode. The command to make directory is given below:
sudo mkdir -p /usr/local/hadoop_space
sudo mkdir -p /usr/local/hadoop_space/hdfs/namenode
sudo mkdir -p /usr/local/hadoop_space/hdfs/datanode
Now we need to give permission for that commands are below:
sudo chown -R hadoopusr /usr/local/hadoop_space
1. First, we need to format the namenode then you need to run the below command for first time when you starting the cluster if you use it again then all your metadata will get erase.
hdfs namenode -format
2. Now we need to start the DFS i.e. Distributed File System.
start-dfs.sh
3. now the last thing you need to start is yarn
start-yarn.sh
4. Now use the following command:
jps
Now you will be able to see the SecondaryNameNode, NodeManager, ResourceManager, NameNode, jpd, and DataNode which means you will have successfully installed Hadoop.
5. You have successfully installed hadoop on your system. Now to check all you cluster information you can use localhost:50070 in your browser. The Interface will look like as:
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Hadoop and Spark
Hadoop Streaming Using Python - Word Count Problem
Architecture of HBase
Hadoop - Different Modes of Operation
What is Big Data?
Architecture and Working of Hive
How to Create Table in Hive?
Applications of Big Data
Introduction to Apache Pig
What is Schema On Read and Schema On Write in Hadoop?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 286,
"s": 52,
"text": "Hadoop is a framework written in Java for running applications on a large cluster of community hardware. It is similar to the Google file system. In order to install Hadoop, we need java first so first, we install java in our Ubuntu."
},
{
"code": null,
"e": 391,
"s": 286,
"text": "Step 1: Open your terminal and first check whether your system is equipped with Java or not with command"
},
{
"code": null,
"e": 405,
"s": 391,
"text": "java -version"
},
{
"code": null,
"e": 499,
"s": 405,
"text": "Step 2: Now it is time to update your system. Below are the 2 commands to update your system."
},
{
"code": null,
"e": 519,
"s": 499,
"text": "sudo apt-get update"
},
{
"code": null,
"e": 547,
"s": 519,
"text": "sudo apt-get install update"
},
{
"code": null,
"e": 629,
"s": 547,
"text": "Step 3: Now we will install the default JDK for java using the following command:"
},
{
"code": null,
"e": 662,
"s": 629,
"text": "sudo apt-get install default-jdk"
},
{
"code": null,
"e": 695,
"s": 662,
"text": "It will ask you for Y/N press Y."
},
{
"code": null,
"e": 764,
"s": 695,
"text": "Step 4: Now check whether Java is installed or not using the command"
},
{
"code": null,
"e": 778,
"s": 764,
"text": "java -version"
},
{
"code": null,
"e": 977,
"s": 778,
"text": "Step 5: Once it installs we require a dedicated user for the same. It is not necessary but it is a good thing to make a dedicated user for the Hadoop installation. You can use the following command:"
},
{
"code": null,
"e": 998,
"s": 977,
"text": "sudo addgroup hadoop"
},
{
"code": null,
"e": 1038,
"s": 998,
"text": "sudo adduser --ingroup hadoop hadoopusr"
},
{
"code": null,
"e": 1478,
"s": 1038,
"text": "Step 6: Now after running the above 2 commands, you have successfully created a dedicated user with name hadoopusr. Now it will ask for a new UNIX password so choose password according to your convenience(make sure sometimes it doesn’t show the character or number you type so please remember whatever you type). Then it will ask you for information like Full Name etc. Keep pressing enter for default then press Y for correct information."
},
{
"code": null,
"e": 1517,
"s": 1478,
"text": "Step 7: Now use the following command:"
},
{
"code": null,
"e": 1545,
"s": 1517,
"text": "sudo adduser hadoopusr sudo"
},
{
"code": null,
"e": 1650,
"s": 1545,
"text": "With this command, you add your ‘hadoopusr’ to the ‘sudo’ group so that we can also make it a superuser."
},
{
"code": null,
"e": 1719,
"s": 1650,
"text": "Step 8: Now we also need to install ssh key’s that is secured shell."
},
{
"code": null,
"e": 1755,
"s": 1719,
"text": "sudo apt-get install openssh-server"
},
{
"code": null,
"e": 1894,
"s": 1755,
"text": "Step 9: Now it’s time for us to switch to new user that is hadoopusr and also enter the password you use above command for switching user:"
},
{
"code": null,
"e": 1909,
"s": 1894,
"text": "su - hadoopusr"
},
{
"code": null,
"e": 2134,
"s": 1909,
"text": "Step 10: Now it’s time to generate ssh key because Hadoop requires ssh access to manage it’s node, remote or local machine so for our single node of the setup of Hadoop we configure such that we have access to the localhost."
},
{
"code": null,
"e": 2158,
"s": 2134,
"text": "ssh-keygen -t rsa -P \"\""
},
{
"code": null,
"e": 2197,
"s": 2158,
"text": "After this command simple press enter."
},
{
"code": null,
"e": 2396,
"s": 2197,
"text": "Step 11: Now we use the below command because we need to add the public key of the computer to the authorized key file of the compute that you want to access with ssh keys so we fired these command."
},
{
"code": null,
"e": 2453,
"s": 2396,
"text": "cat $HOME/ .ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys"
},
{
"code": null,
"e": 2605,
"s": 2453,
"text": "Step 12: Now check for the local host i.e. ssh localhost with below command and press yes to continue and enter your password if it ask then type exit."
},
{
"code": null,
"e": 2619,
"s": 2605,
"text": "ssh localhost"
},
{
"code": null,
"e": 2689,
"s": 2619,
"text": "Now you have completed the basic requirement for Hadoop installation."
},
{
"code": null,
"e": 2832,
"s": 2689,
"text": "Step 13: Now download the package that you will going to install . download it from Hadoop-2.9.0 by clicking to the file shown in below image."
},
{
"code": null,
"e": 3021,
"s": 2832,
"text": "Step 14: Once you have download hadoop-2.9.0.tar.gz then place this tar file to your preferred location then extract it with below commands. In my case I moved it to the /Documents folder."
},
{
"code": null,
"e": 3218,
"s": 3021,
"text": "Now we extract this file with below command and enter your hadoopusr password. If you don’t know the password don’t worry you can simply switch your user and change password according to yourself."
},
{
"code": null,
"e": 3262,
"s": 3218,
"text": "command : sudo tar xvzf hadoop-2.9.0.tar.gz"
},
{
"code": null,
"e": 3418,
"s": 3262,
"text": "Step 15: Now we need to move this extracted folder to the hadoopusr user so for that type below command(make sure name of your extracted folder is hadoop):"
},
{
"code": null,
"e": 3451,
"s": 3418,
"text": "sudo mv hadoop /usr/local/hadoop"
},
{
"code": null,
"e": 3520,
"s": 3451,
"text": "Step 16: Now we need to change the ownership so for that command is:"
},
{
"code": null,
"e": 3555,
"s": 3520,
"text": "sudo chown -R hadoopusr /usr/local"
},
{
"code": null,
"e": 3673,
"s": 3555,
"text": "Step 17: This is the most important Step i.e. now we are going to configure some files this is really very important."
},
{
"code": null,
"e": 3760,
"s": 3673,
"text": "First we configure our ./bashrc file so that to open that file type the below command:"
},
{
"code": null,
"e": 3781,
"s": 3760,
"text": "sudo gedit ~/.bashrc"
},
{
"code": null,
"e": 3951,
"s": 3781,
"text": "Then a ./bashrc file is open then copy the below command inside this file (change java version according to your PC java version like it might be java-8-openjdk-amd64 )."
},
{
"code": null,
"e": 4386,
"s": 3951,
"text": " \nexport JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64\nexport HADOOP_HOME=/usr/local/hadoop\nexport PATH=$PATH:$HADOOP_HOME/bin\nexport PATH=$PATH:$HADOOP_HOME/sbin\nexport HADOOP_MAPRED_HOME=$HADOOP_HOME\nexport HADOOP_COMMON_HOME=$HADOOP_HOME\nexport HADOOP_HDFS_HOME=$HADOOP_HOME\nexport YARN_HOME=$HADOOP_HOME\nexport HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native\nexport HADOOP_OPTS=\"-Djava.library.path=$HADOOP_HOME/lib\"\n"
},
{
"code": null,
"e": 4446,
"s": 4386,
"text": "Then check whether you have configured it correctly or not."
},
{
"code": null,
"e": 4463,
"s": 4446,
"text": "source ~/.bashrc"
},
{
"code": null,
"e": 4745,
"s": 4463,
"text": "Step 18: Before configuring more file first we ensure which version of java we have installed for that go to the location /usr/lib/jvm and after going to this location type ls command to list down the file inside it now see the java version, In my case it is java-11-openjdk-amd64."
},
{
"code": null,
"e": 4835,
"s": 4745,
"text": "Step 19: Now we will configure hadoop-env.sh. For that open the file using below command."
},
{
"code": null,
"e": 4889,
"s": 4835,
"text": "sudo gedit /usr/local/hadoop/etc/hadoop/hadoop-env.sh"
},
{
"code": null,
"e": 5028,
"s": 4889,
"text": "Once the file opened, copy the below export command inside it and make sure to comment the already existing export command with JAVA_HOME:"
},
{
"code": null,
"e": 5080,
"s": 5028,
"text": "export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64"
},
{
"code": null,
"e": 5102,
"s": 5080,
"text": "Don’t forget to save."
},
{
"code": null,
"e": 5197,
"s": 5102,
"text": "Step 20: Now we will configure the core-site.xml. For that open that file using below command:"
},
{
"code": null,
"e": 5251,
"s": 5197,
"text": "sudo gedit /usr/local/hadoop/etc/hadoop/core-site.xml"
},
{
"code": null,
"e": 5320,
"s": 5251,
"text": "once the file opens copy the below text inside the configuration tag"
},
{
"code": "<!-- <property><name>fs.default.name</name><value>hdfs://localhost:9000</value></property> -->",
"e": 5415,
"s": 5320,
"text": null
},
{
"code": null,
"e": 5461,
"s": 5415,
"text": "See the below image for better understanding:"
},
{
"code": null,
"e": 5555,
"s": 5461,
"text": "Step 21: Now we will configure the hdfs-site.xml for that open that file using below command."
},
{
"code": null,
"e": 5609,
"s": 5555,
"text": "sudo gedit /usr/local/hadoop/etc/hadoop/hdfs-site.xml"
},
{
"code": null,
"e": 5678,
"s": 5609,
"text": "Once the file opens copy the below text inside the configuration tag"
},
{
"code": "<!-- <property><name>dfs.replication</name><value>1</value></property><property><name>dfs.namenode.name.dir</name><value>file:/usr/local/hadoop_tmp/hdfs/namenode</value></property><property><name>dfs.datanode.data.dir</name><value>file:/usr/local/hadoop_tmp/hdfs/datanode</value></property> -->",
"e": 5973,
"s": 5678,
"text": null
},
{
"code": null,
"e": 6019,
"s": 5973,
"text": "See the below image for better understanding:"
},
{
"code": null,
"e": 6187,
"s": 6019,
"text": "Step 22: Now we will configure the yarn-site.xml which is responsible for the execution of file in the Hadoop environment. For that open that file using below command:"
},
{
"code": null,
"e": 6241,
"s": 6187,
"text": "sudo gedit /usr/local/hadoop/etc/hadoop/yarn-site.xml"
},
{
"code": null,
"e": 6310,
"s": 6241,
"text": "once the file opens copy the below text inside the configuration tag"
},
{
"code": "<!-- <property><name>yarn.nodemanager.aux-services</name><value>mapreduce_shuffle</value></property><property><name>yarn.nodemanager.aux-services.mapreduce.shuffle.class</name><value>org.apache.hadoop.mapred.ShuffleHandler</value></property> -->",
"e": 6556,
"s": 6310,
"text": null
},
{
"code": null,
"e": 6602,
"s": 6556,
"text": "See the below image for better understanding:"
},
{
"code": null,
"e": 6792,
"s": 6602,
"text": "Step 23: Now the last file to configure is mapred-site.xml. For that we have mapred-site.xml.template so we need to locate that file then copy this file to that location and then rename it."
},
{
"code": null,
"e": 6958,
"s": 6792,
"text": "So to locate the file we need to go to the location /usr/local/hadoop/etc/hadoop/ so to copy this file and also rename the file the single, use the following command"
},
{
"code": null,
"e": 7065,
"s": 6958,
"text": "sudo cp /usr/local/hadoop/etc/hadoop/mapred-site.xml.template /usr/local/hadoop/etc/hadoop/mapred-site.xml"
},
{
"code": null,
"e": 7150,
"s": 7065,
"text": "once the file gets copied or renamed now open that file using the following command:"
},
{
"code": null,
"e": 7206,
"s": 7150,
"text": "sudo gedit /usr/local/hadoop/etc/hadoop/mapred-site.xml"
},
{
"code": null,
"e": 7269,
"s": 7206,
"text": "And then place the below content inside its configuration tag."
},
{
"code": "<!-- <property><name>mapreduce.framework.name</name><value>yarn</value></property> -->",
"e": 7356,
"s": 7269,
"text": null
},
{
"code": null,
"e": 7402,
"s": 7356,
"text": "See the below image for better understanding:"
},
{
"code": null,
"e": 7764,
"s": 7402,
"text": "Step 24: Now we have successfully configured all the files. So now it is time to check our installation. As we know that in Hadoop architecture we have name node and other blocks so we need to make one directory i.e. hadoop_space. Inside this directory we make another directory i.e. hdfs and namenode and datanode. The command to make directory is given below:"
},
{
"code": null,
"e": 7909,
"s": 7764,
"text": " \nsudo mkdir -p /usr/local/hadoop_space\nsudo mkdir -p /usr/local/hadoop_space/hdfs/namenode\nsudo mkdir -p /usr/local/hadoop_space/hdfs/datanode\n"
},
{
"code": null,
"e": 7969,
"s": 7909,
"text": "Now we need to give permission for that commands are below:"
},
{
"code": null,
"e": 8017,
"s": 7969,
"text": "sudo chown -R hadoopusr /usr/local/hadoop_space"
},
{
"code": null,
"e": 8201,
"s": 8017,
"text": "1. First, we need to format the namenode then you need to run the below command for first time when you starting the cluster if you use it again then all your metadata will get erase."
},
{
"code": null,
"e": 8223,
"s": 8201,
"text": "hdfs namenode -format"
},
{
"code": null,
"e": 8285,
"s": 8223,
"text": "2. Now we need to start the DFS i.e. Distributed File System."
},
{
"code": null,
"e": 8298,
"s": 8285,
"text": "start-dfs.sh"
},
{
"code": null,
"e": 8346,
"s": 8298,
"text": "3. now the last thing you need to start is yarn"
},
{
"code": null,
"e": 8360,
"s": 8346,
"text": "start-yarn.sh"
},
{
"code": null,
"e": 8394,
"s": 8360,
"text": "4. Now use the following command:"
},
{
"code": null,
"e": 8398,
"s": 8394,
"text": "jps"
},
{
"code": null,
"e": 8564,
"s": 8398,
"text": "Now you will be able to see the SecondaryNameNode, NodeManager, ResourceManager, NameNode, jpd, and DataNode which means you will have successfully installed Hadoop."
},
{
"code": null,
"e": 8741,
"s": 8564,
"text": "5. You have successfully installed hadoop on your system. Now to check all you cluster information you can use localhost:50070 in your browser. The Interface will look like as:"
},
{
"code": null,
"e": 8748,
"s": 8741,
"text": "Hadoop"
},
{
"code": null,
"e": 8755,
"s": 8748,
"text": "Hadoop"
},
{
"code": null,
"e": 8853,
"s": 8755,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8889,
"s": 8853,
"text": "Difference Between Hadoop and Spark"
},
{
"code": null,
"e": 8940,
"s": 8889,
"text": "Hadoop Streaming Using Python - Word Count Problem"
},
{
"code": null,
"e": 8962,
"s": 8940,
"text": "Architecture of HBase"
},
{
"code": null,
"e": 9000,
"s": 8962,
"text": "Hadoop - Different Modes of Operation"
},
{
"code": null,
"e": 9018,
"s": 9000,
"text": "What is Big Data?"
},
{
"code": null,
"e": 9051,
"s": 9018,
"text": "Architecture and Working of Hive"
},
{
"code": null,
"e": 9080,
"s": 9051,
"text": "How to Create Table in Hive?"
},
{
"code": null,
"e": 9105,
"s": 9080,
"text": "Applications of Big Data"
},
{
"code": null,
"e": 9132,
"s": 9105,
"text": "Introduction to Apache Pig"
}
] |
WebRTC - RTCPeerConnection APIs
|
The RTCPeerConnection API is the core of the peer-to-peer connection between each of the browsers. To create the RTCPeerConnection objects simply write
var pc = RTCPeerConnection(config);
where the config argument contains at least on key, iceServers. It is an array of URL objects containing information about STUN and TURN servers, used during the finding of the ICE candidates. You can find a list of available public STUN servers at code.google.com
Depending upon whether you are the caller or the callee the RTCPeerConnection object is used in a slightly different way on each side of the connection.
Here is an example of the user's flow −
Register the onicecandidate handler. It sends any ICE candidates to the other peer, as they are received.
Register the onicecandidate handler. It sends any ICE candidates to the other peer, as they are received.
Register the onaddstream handler. It handles the displaying of the video stream once it is received from the remote peer.
Register the onaddstream handler. It handles the displaying of the video stream once it is received from the remote peer.
Register the message handler. Your signaling server should also have a handler for messages received from the other peer. If the message contains the RTCSessionDescription object, it should be added to the RTCPeerConnection object using the setRemoteDescription() method. If the message contains the RTCIceCandidate object, it should be added to the RTCPeerConnection object using the addIceCandidate() method.
Register the message handler. Your signaling server should also have a handler for messages received from the other peer. If the message contains the RTCSessionDescription object, it should be added to the RTCPeerConnection object using the setRemoteDescription() method. If the message contains the RTCIceCandidate object, it should be added to the RTCPeerConnection object using the addIceCandidate() method.
Utilize getUserMedia() to set up your local media stream and add it to the RTCPeerConnection object using the addStream() method.
Utilize getUserMedia() to set up your local media stream and add it to the RTCPeerConnection object using the addStream() method.
Start offer/answer negotiation process. This is the only step where the caller's flow is different from the callee's one. The caller starts negotiation using the createOffer() method and registers a callback that receives the RTCSessionDescription object. Then this callback should add this RTCSessionDescription object to your RTCPeerConnection object using setLocalDescription(). And finally, the caller should send this RTCSessionDescription to the remote peer using the signaling server. The callee, on the other, registers the same callback, but in the createAnswer() method. Notice that the callee flow is initiated only after the offer is received from the caller.
Start offer/answer negotiation process. This is the only step where the caller's flow is different from the callee's one. The caller starts negotiation using the createOffer() method and registers a callback that receives the RTCSessionDescription object. Then this callback should add this RTCSessionDescription object to your RTCPeerConnection object using setLocalDescription(). And finally, the caller should send this RTCSessionDescription to the remote peer using the signaling server. The callee, on the other, registers the same callback, but in the createAnswer() method. Notice that the callee flow is initiated only after the offer is received from the caller.
RTCPeerConnection.iceConnectionState (read only) − Returns an RTCIceConnectionState enum that describes the state of the connection. An iceconnectionstatechange event is fired when this value changes. The possible values −
new − the ICE agent is waiting for remote candidates or gathering addresses
checking − the ICE agent has remote candidates, but it has not found a connection yet
connected − the ICE agent has found a usable connection, but is still checking more remote candidate for better connection.
completed − the ICE agent has found a usable connection and stopped testing remote candidates.
failed − the ICE agent has checked all the remote candidates but didn't find a match for at least one component.
disconnected − at least one component is no longer alive.
closed − the ICE agent is closed.
RTCPeerConnection.iceConnectionState (read only) − Returns an RTCIceConnectionState enum that describes the state of the connection. An iceconnectionstatechange event is fired when this value changes. The possible values −
new − the ICE agent is waiting for remote candidates or gathering addresses
new − the ICE agent is waiting for remote candidates or gathering addresses
checking − the ICE agent has remote candidates, but it has not found a connection yet
checking − the ICE agent has remote candidates, but it has not found a connection yet
connected − the ICE agent has found a usable connection, but is still checking more remote candidate for better connection.
connected − the ICE agent has found a usable connection, but is still checking more remote candidate for better connection.
completed − the ICE agent has found a usable connection and stopped testing remote candidates.
completed − the ICE agent has found a usable connection and stopped testing remote candidates.
failed − the ICE agent has checked all the remote candidates but didn't find a match for at least one component.
failed − the ICE agent has checked all the remote candidates but didn't find a match for at least one component.
disconnected − at least one component is no longer alive.
disconnected − at least one component is no longer alive.
closed − the ICE agent is closed.
closed − the ICE agent is closed.
RTCPeerConnection.iceGatheringState (read only) − Returns a RTCIceGatheringState enum that describes the ICE gathering state for the connection −
new − the object was just created.
gathering − the ICE agent is in the process of gathering candidates
complete the ICE agent has completed gathering.
RTCPeerConnection.iceGatheringState (read only) − Returns a RTCIceGatheringState enum that describes the ICE gathering state for the connection −
new − the object was just created.
new − the object was just created.
gathering − the ICE agent is in the process of gathering candidates
gathering − the ICE agent is in the process of gathering candidates
complete the ICE agent has completed gathering.
complete the ICE agent has completed gathering.
RTCPeerConnection.localDescription (read only) − Returns an RTCSessionDescription describing the local session. It can be null if it has not yet been set.
RTCPeerConnection.localDescription (read only) − Returns an RTCSessionDescription describing the local session. It can be null if it has not yet been set.
RTCPeerConnection.peerIdentity (read only) − Returns an RTCIdentityAssertion. It consists of an idp(domain name) and a name representing the identity of the remote peer.
RTCPeerConnection.peerIdentity (read only) − Returns an RTCIdentityAssertion. It consists of an idp(domain name) and a name representing the identity of the remote peer.
RTCPeerConnection.remoteDescription (read only) − Return an RTCSessionDescription describing the remote session. It can be null if it has not yet been set.
RTCPeerConnection.remoteDescription (read only) − Return an RTCSessionDescription describing the remote session. It can be null if it has not yet been set.
RTCPeerConnection.signalingState (read only) − Returns an RTCSignalingState enum that describes the signaling state of the local connection. This state describes the SDP offer. A signalingstatechange event is fired when this value changes. The possible values −
stable − The initial state. There is no SDP offer/answer exchange in progress.
have-local-offer − the local side of the connection has locally applied a SDP offer.
have-remote-offer − the remote side of the connection has locally applied a SDP offer.
have-local-pranswer − a remote SDP offer has been applied, and a SDP pranswer applied locally.
have-remote-pranswer − a local SDP has been applied, and a SDP pranswer applied remotely.
closed − the connection is closed.
RTCPeerConnection.signalingState (read only) − Returns an RTCSignalingState enum that describes the signaling state of the local connection. This state describes the SDP offer. A signalingstatechange event is fired when this value changes. The possible values −
stable − The initial state. There is no SDP offer/answer exchange in progress.
stable − The initial state. There is no SDP offer/answer exchange in progress.
have-local-offer − the local side of the connection has locally applied a SDP offer.
have-local-offer − the local side of the connection has locally applied a SDP offer.
have-remote-offer − the remote side of the connection has locally applied a SDP offer.
have-remote-offer − the remote side of the connection has locally applied a SDP offer.
have-local-pranswer − a remote SDP offer has been applied, and a SDP pranswer applied locally.
have-local-pranswer − a remote SDP offer has been applied, and a SDP pranswer applied locally.
have-remote-pranswer − a local SDP has been applied, and a SDP pranswer applied remotely.
have-remote-pranswer − a local SDP has been applied, and a SDP pranswer applied remotely.
closed − the connection is closed.
closed − the connection is closed.
RTCPeerConnection.onaddstream
This handler is called when the addstream event is fired. This event is sent when a MediaStream is added to this connection by the remote peer.
RTCPeerConnection.ondatachannel
This handler is called when the datachannel event is fired. This event is sent when a RTCDataChannel is added to this connection.
RTCPeerConnection.onicecandidate
This handler is called when the icecandidate event is fired. This event is sent when a RTCIceCandidate object is added to the script.
RTCPeerConnection.oniceconnectionstatechange
This handler is called when the iceconnectionstatechange event is fired. This event is sent when the value of iceConnectionState changes.
RTCPeerConnection.onidentityresult
This handler is called when the identityresult event is fired. This event is sent when an identity assertion is generated during the creating of an offer or an answer of via getIdentityAssertion().
RTCPeerConnection.onidpassertionerror
This handler is called when the idpassertionerror event is fired. This event is sent when the IdP (Identitry Provider) finds an error while generating an identity assertion.
RTCPeerConnection.onidpvalidation
This handler is called when the idpvalidationerror event is fired. This event is sent when the IdP (Identitry Provider) finds an error while validating an identity assertion.
RTCPeerConnection.onnegotiationneeded
This handler is called when the negotiationneeded event is fired. This event is sent by the browser to inform the negotiation will be required at some point in the future.
RTCPeerConnection.onpeeridentity
This handler is called when the peeridentity event is fired. This event is sent when a peer identity has been set and verified on this connection.
RTCPeerConnection.onremovestream
This handler is called when the signalingstatechange event is fired. This event is sent when the value of signalingState changes.
RTCPeerConnection.onsignalingstatechange
This handler is called when the removestream event is fired. This event is sent when a MediaStream is removed from this connection.
RTCPeerConnection()
Returns a new RTCPeerConnection object.
RTCPeerConnection.createOffer()
Creates an offer(request) to find a remote peer. The two first parameters of this method are success and error callbacks. The optional third parameter are options, like enabling audio or video streams.
RTCPeerConnection.createAnswer()
Creates an answer to the offer received by the remote peer during the offer/answer negotiation process. The two first parameters of this method are success and error callbacks. The optional third parameter are options for the answer to be created.
RTCPeerConnection.setLocalDescription()
Changes the local connection description. The description defines the properties of the connection. The connection must be able to support both old and new descriptions. The method takes three parameters, RTCSessionDescription object, callback if the change of description succeeds, callback if the change of description fails.
RTCPeerConnection.setRemoteDescription()
Changes the remote connection description. The description defines the properties of the connection. The connection must be able to support both old and new descriptions. The method takes three parameters, RTCSessionDescription object, callback if the change of description succeeds, callback if the change of description fails.
RTCPeerConnection.updateIce()
Updates the ICE agent process of pinging remote candidates and gathering local candidates.
RTCPeerConnection.addIceCandidate()
Provides a remote candidate to the ICE agent.
RTCPeerConnection.getConfiguration()
Returns a RTCConfiguration object. It represents the configuration of the RTCPeerConnection object.
RTCPeerConnection.getLocalStreams()
Returns an array of local MediaStream connection.
RTCPeerConnection.getRemoteStreams()
Returns an array of remote MediaStream connection.
RTCPeerConnection.getStreamById()
Returns local or remote MediaStream by the given ID.
RTCPeerConnection.addStream()
Adds a MediaStream as a local source of video or audio.
RTCPeerConnection.removeStream()
Removes a MediaStream as a local source of video or audio.
RTCPeerConnection.close()
Closes a connection.
RTCPeerConnection.createDataChannel()
Creates a new RTCDataChannel.
RTCPeerConnection.createDTMFSender()
Creates a new RTCDTMFSender, associated to a specific MediaStreamTrack. Allows to send DTMF (Dual-tone multifrequency) phone signaling over the connection.
RTCPeerConnection.getStats()
Creates a new RTCStatsReport that contains statistics concerning the connection.
RTCPeerConnection.setIdentityProvider()
Sets the IdP. Takes three parameters − the name, the protocol used to communicate and an optional username.
RTCPeerConnection.getIdentityAssertion()
Gathers an identity assertion. It is not expected to deal with this method in the application. So you may call it explicitly only to anticipate the need.
Now let's create an example application. Firstly, run the signaling server we created in the “signaling server” tutorial via “node server”.
There will be two text inputs on the page, one for a login and one for a username we want to connect to. Create an index.html file and add the following code −
<html lang = "en">
<head>
<meta charset = "utf-8" />
</head>
<body>
<div>
<input type = "text" id = "loginInput" />
<button id = "loginBtn">Login</button>
</div>
<div>
<input type = "text" id = "otherUsernameInput" />
<button id = "connectToOtherUsernameBtn">Establish connection</button>
</div>
<script src = "client2.js"></script>
</body>
</html>
You can see that we've added the text input for a login, the login button, the text input for the other peer username, and the connect-to-him button. Now create a client.js file and add the following code −
var connection = new WebSocket('ws://localhost:9090');
var name = "";
var loginInput = document.querySelector('#loginInput');
var loginBtn = document.querySelector('#loginBtn');
var otherUsernameInput = document.querySelector('#otherUsernameInput');
var connectToOtherUsernameBtn = document.querySelector('#connectToOtherUsernameBtn');
var connectedUser, myConnection;
//when a user clicks the login button
loginBtn.addEventListener("click", function(event){
name = loginInput.value;
if(name.length > 0){
send({
type: "login",
name: name
});
}
});
//handle messages from the server
connection.onmessage = function (message) {
console.log("Got message", message.data);
var data = JSON.parse(message.data);
switch(data.type) {
case "login":
onLogin(data.success);
break;
case "offer":
onOffer(data.offer, data.name);
break;
case "answer":
onAnswer(data.answer);
break;
case "candidate":
onCandidate(data.candidate);
break;
default:
break;
}
};
//when a user logs in
function onLogin(success) {
if (success === false) {
alert("oops...try a different username");
} else {
//creating our RTCPeerConnection object
var configuration = {
"iceServers": [{ "url": "stun:stun.1.google.com:19302" }]
};
myConnection = new webkitRTCPeerConnection(configuration);
console.log("RTCPeerConnection object was created");
console.log(myConnection);
//setup ice handling
//when the browser finds an ice candidate we send it to another peer
myConnection.onicecandidate = function (event) {
if (event.candidate) {
send({
type: "candidate",
candidate: event.candidate
});
}
};
}
};
connection.onopen = function () {
console.log("Connected");
};
connection.onerror = function (err) {
console.log("Got error", err);
};
// Alias for sending messages in JSON format
function send(message) {
if (connectedUser) {
message.name = connectedUser;
}
connection.send(JSON.stringify(message));
};
You can see that we establish a socket connection to our signaling server. When a user clicks on the login button the application sends his username to the server. If login is successful the application creates the RTCPeerConnection object and setup onicecandidate handler which sends all found icecandidates to the other peer. Now open the page and try to login. You should see the following console output −
The next step is to create an offer to the other peer. Add the following code to your client.js file −
//setup a peer connection with another user
connectToOtherUsernameBtn.addEventListener("click", function () {
var otherUsername = otherUsernameInput.value;
connectedUser = otherUsername;
if (otherUsername.length > 0) {
//make an offer
myConnection.createOffer(function (offer) {
console.log();
send({
type: "offer",
offer: offer
});
myConnection.setLocalDescription(offer);
}, function (error) {
alert("An error has occurred.");
});
}
});
//when somebody wants to call us
function onOffer(offer, name) {
connectedUser = name;
myConnection.setRemoteDescription(new RTCSessionDescription(offer));
myConnection.createAnswer(function (answer) {
myConnection.setLocalDescription(answer);
send({
type: "answer",
answer: answer
});
}, function (error) {
alert("oops...error");
});
}
//when another user answers to our offer
function onAnswer(answer) {
myConnection.setRemoteDescription(new RTCSessionDescription(answer));
}
//when we got ice candidate from another user
function onCandidate(candidate) {
myConnection.addIceCandidate(new RTCIceCandidate(candidate));
}
You can see that when a user clicks the “Establish connection” button the application makes an SDP offer to the other peer. We also set onAnswer and onCandidate handlers. Reload your page, open it in two tabs, login with two users and try to establish a connection between them. You should see the following console output −
Now the peer-to-peer connection is established. In the next tutorials, we will add video and audio streams as well as text chat support.
|
[
{
"code": null,
"e": 2173,
"s": 2021,
"text": "The RTCPeerConnection API is the core of the peer-to-peer connection between each of the browsers. To create the RTCPeerConnection objects simply write"
},
{
"code": null,
"e": 2210,
"s": 2173,
"text": "var pc = RTCPeerConnection(config);\n"
},
{
"code": null,
"e": 2475,
"s": 2210,
"text": "where the config argument contains at least on key, iceServers. It is an array of URL objects containing information about STUN and TURN servers, used during the finding of the ICE candidates. You can find a list of available public STUN servers at code.google.com"
},
{
"code": null,
"e": 2628,
"s": 2475,
"text": "Depending upon whether you are the caller or the callee the RTCPeerConnection object is used in a slightly different way on each side of the connection."
},
{
"code": null,
"e": 2668,
"s": 2628,
"text": "Here is an example of the user's flow −"
},
{
"code": null,
"e": 2774,
"s": 2668,
"text": "Register the onicecandidate handler. It sends any ICE candidates to the other peer, as they are received."
},
{
"code": null,
"e": 2880,
"s": 2774,
"text": "Register the onicecandidate handler. It sends any ICE candidates to the other peer, as they are received."
},
{
"code": null,
"e": 3002,
"s": 2880,
"text": "Register the onaddstream handler. It handles the displaying of the video stream once it is received from the remote peer."
},
{
"code": null,
"e": 3124,
"s": 3002,
"text": "Register the onaddstream handler. It handles the displaying of the video stream once it is received from the remote peer."
},
{
"code": null,
"e": 3535,
"s": 3124,
"text": "Register the message handler. Your signaling server should also have a handler for messages received from the other peer. If the message contains the RTCSessionDescription object, it should be added to the RTCPeerConnection object using the setRemoteDescription() method. If the message contains the RTCIceCandidate object, it should be added to the RTCPeerConnection object using the addIceCandidate() method."
},
{
"code": null,
"e": 3946,
"s": 3535,
"text": "Register the message handler. Your signaling server should also have a handler for messages received from the other peer. If the message contains the RTCSessionDescription object, it should be added to the RTCPeerConnection object using the setRemoteDescription() method. If the message contains the RTCIceCandidate object, it should be added to the RTCPeerConnection object using the addIceCandidate() method."
},
{
"code": null,
"e": 4076,
"s": 3946,
"text": "Utilize getUserMedia() to set up your local media stream and add it to the RTCPeerConnection object using the addStream() method."
},
{
"code": null,
"e": 4206,
"s": 4076,
"text": "Utilize getUserMedia() to set up your local media stream and add it to the RTCPeerConnection object using the addStream() method."
},
{
"code": null,
"e": 4878,
"s": 4206,
"text": "Start offer/answer negotiation process. This is the only step where the caller's flow is different from the callee's one. The caller starts negotiation using the createOffer() method and registers a callback that receives the RTCSessionDescription object. Then this callback should add this RTCSessionDescription object to your RTCPeerConnection object using setLocalDescription(). And finally, the caller should send this RTCSessionDescription to the remote peer using the signaling server. The callee, on the other, registers the same callback, but in the createAnswer() method. Notice that the callee flow is initiated only after the offer is received from the caller."
},
{
"code": null,
"e": 5550,
"s": 4878,
"text": "Start offer/answer negotiation process. This is the only step where the caller's flow is different from the callee's one. The caller starts negotiation using the createOffer() method and registers a callback that receives the RTCSessionDescription object. Then this callback should add this RTCSessionDescription object to your RTCPeerConnection object using setLocalDescription(). And finally, the caller should send this RTCSessionDescription to the remote peer using the signaling server. The callee, on the other, registers the same callback, but in the createAnswer() method. Notice that the callee flow is initiated only after the offer is received from the caller."
},
{
"code": null,
"e": 6362,
"s": 5550,
"text": "RTCPeerConnection.iceConnectionState (read only) − Returns an RTCIceConnectionState enum that describes the state of the connection. An iceconnectionstatechange event is fired when this value changes. The possible values −\n\nnew − the ICE agent is waiting for remote candidates or gathering addresses\nchecking − the ICE agent has remote candidates, but it has not found a connection yet\nconnected − the ICE agent has found a usable connection, but is still checking more remote candidate for better connection.\ncompleted − the ICE agent has found a usable connection and stopped testing remote candidates.\nfailed − the ICE agent has checked all the remote candidates but didn't find a match for at least one component.\ndisconnected − at least one component is no longer alive.\nclosed − the ICE agent is closed.\n\n"
},
{
"code": null,
"e": 6585,
"s": 6362,
"text": "RTCPeerConnection.iceConnectionState (read only) − Returns an RTCIceConnectionState enum that describes the state of the connection. An iceconnectionstatechange event is fired when this value changes. The possible values −"
},
{
"code": null,
"e": 6661,
"s": 6585,
"text": "new − the ICE agent is waiting for remote candidates or gathering addresses"
},
{
"code": null,
"e": 6737,
"s": 6661,
"text": "new − the ICE agent is waiting for remote candidates or gathering addresses"
},
{
"code": null,
"e": 6823,
"s": 6737,
"text": "checking − the ICE agent has remote candidates, but it has not found a connection yet"
},
{
"code": null,
"e": 6909,
"s": 6823,
"text": "checking − the ICE agent has remote candidates, but it has not found a connection yet"
},
{
"code": null,
"e": 7033,
"s": 6909,
"text": "connected − the ICE agent has found a usable connection, but is still checking more remote candidate for better connection."
},
{
"code": null,
"e": 7157,
"s": 7033,
"text": "connected − the ICE agent has found a usable connection, but is still checking more remote candidate for better connection."
},
{
"code": null,
"e": 7252,
"s": 7157,
"text": "completed − the ICE agent has found a usable connection and stopped testing remote candidates."
},
{
"code": null,
"e": 7347,
"s": 7252,
"text": "completed − the ICE agent has found a usable connection and stopped testing remote candidates."
},
{
"code": null,
"e": 7460,
"s": 7347,
"text": "failed − the ICE agent has checked all the remote candidates but didn't find a match for at least one component."
},
{
"code": null,
"e": 7573,
"s": 7460,
"text": "failed − the ICE agent has checked all the remote candidates but didn't find a match for at least one component."
},
{
"code": null,
"e": 7631,
"s": 7573,
"text": "disconnected − at least one component is no longer alive."
},
{
"code": null,
"e": 7689,
"s": 7631,
"text": "disconnected − at least one component is no longer alive."
},
{
"code": null,
"e": 7723,
"s": 7689,
"text": "closed − the ICE agent is closed."
},
{
"code": null,
"e": 7757,
"s": 7723,
"text": "closed − the ICE agent is closed."
},
{
"code": null,
"e": 8057,
"s": 7757,
"text": "RTCPeerConnection.iceGatheringState (read only) − Returns a RTCIceGatheringState enum that describes the ICE gathering state for the connection −\n\nnew − the object was just created.\ngathering − the ICE agent is in the process of gathering candidates\ncomplete the ICE agent has completed gathering.\n\n"
},
{
"code": null,
"e": 8203,
"s": 8057,
"text": "RTCPeerConnection.iceGatheringState (read only) − Returns a RTCIceGatheringState enum that describes the ICE gathering state for the connection −"
},
{
"code": null,
"e": 8238,
"s": 8203,
"text": "new − the object was just created."
},
{
"code": null,
"e": 8273,
"s": 8238,
"text": "new − the object was just created."
},
{
"code": null,
"e": 8341,
"s": 8273,
"text": "gathering − the ICE agent is in the process of gathering candidates"
},
{
"code": null,
"e": 8409,
"s": 8341,
"text": "gathering − the ICE agent is in the process of gathering candidates"
},
{
"code": null,
"e": 8457,
"s": 8409,
"text": "complete the ICE agent has completed gathering."
},
{
"code": null,
"e": 8505,
"s": 8457,
"text": "complete the ICE agent has completed gathering."
},
{
"code": null,
"e": 8660,
"s": 8505,
"text": "RTCPeerConnection.localDescription (read only) − Returns an RTCSessionDescription describing the local session. It can be null if it has not yet been set."
},
{
"code": null,
"e": 8815,
"s": 8660,
"text": "RTCPeerConnection.localDescription (read only) − Returns an RTCSessionDescription describing the local session. It can be null if it has not yet been set."
},
{
"code": null,
"e": 8985,
"s": 8815,
"text": "RTCPeerConnection.peerIdentity (read only) − Returns an RTCIdentityAssertion. It consists of an idp(domain name) and a name representing the identity of the remote peer."
},
{
"code": null,
"e": 9155,
"s": 8985,
"text": "RTCPeerConnection.peerIdentity (read only) − Returns an RTCIdentityAssertion. It consists of an idp(domain name) and a name representing the identity of the remote peer."
},
{
"code": null,
"e": 9311,
"s": 9155,
"text": "RTCPeerConnection.remoteDescription (read only) − Return an RTCSessionDescription describing the remote session. It can be null if it has not yet been set."
},
{
"code": null,
"e": 9467,
"s": 9311,
"text": "RTCPeerConnection.remoteDescription (read only) − Return an RTCSessionDescription describing the remote session. It can be null if it has not yet been set."
},
{
"code": null,
"e": 10203,
"s": 9467,
"text": "RTCPeerConnection.signalingState (read only) − Returns an RTCSignalingState enum that describes the signaling state of the local connection. This state describes the SDP offer. A signalingstatechange event is fired when this value changes. The possible values −\n\nstable − The initial state. There is no SDP offer/answer exchange in progress.\nhave-local-offer − the local side of the connection has locally applied a SDP offer.\nhave-remote-offer − the remote side of the connection has locally applied a SDP offer.\nhave-local-pranswer − a remote SDP offer has been applied, and a SDP pranswer applied locally.\nhave-remote-pranswer − a local SDP has been applied, and a SDP pranswer applied remotely.\nclosed − the connection is closed.\n\n"
},
{
"code": null,
"e": 10465,
"s": 10203,
"text": "RTCPeerConnection.signalingState (read only) − Returns an RTCSignalingState enum that describes the signaling state of the local connection. This state describes the SDP offer. A signalingstatechange event is fired when this value changes. The possible values −"
},
{
"code": null,
"e": 10544,
"s": 10465,
"text": "stable − The initial state. There is no SDP offer/answer exchange in progress."
},
{
"code": null,
"e": 10623,
"s": 10544,
"text": "stable − The initial state. There is no SDP offer/answer exchange in progress."
},
{
"code": null,
"e": 10708,
"s": 10623,
"text": "have-local-offer − the local side of the connection has locally applied a SDP offer."
},
{
"code": null,
"e": 10793,
"s": 10708,
"text": "have-local-offer − the local side of the connection has locally applied a SDP offer."
},
{
"code": null,
"e": 10880,
"s": 10793,
"text": "have-remote-offer − the remote side of the connection has locally applied a SDP offer."
},
{
"code": null,
"e": 10967,
"s": 10880,
"text": "have-remote-offer − the remote side of the connection has locally applied a SDP offer."
},
{
"code": null,
"e": 11062,
"s": 10967,
"text": "have-local-pranswer − a remote SDP offer has been applied, and a SDP pranswer applied locally."
},
{
"code": null,
"e": 11157,
"s": 11062,
"text": "have-local-pranswer − a remote SDP offer has been applied, and a SDP pranswer applied locally."
},
{
"code": null,
"e": 11247,
"s": 11157,
"text": "have-remote-pranswer − a local SDP has been applied, and a SDP pranswer applied remotely."
},
{
"code": null,
"e": 11337,
"s": 11247,
"text": "have-remote-pranswer − a local SDP has been applied, and a SDP pranswer applied remotely."
},
{
"code": null,
"e": 11372,
"s": 11337,
"text": "closed − the connection is closed."
},
{
"code": null,
"e": 11407,
"s": 11372,
"text": "closed − the connection is closed."
},
{
"code": null,
"e": 11437,
"s": 11407,
"text": "RTCPeerConnection.onaddstream"
},
{
"code": null,
"e": 11581,
"s": 11437,
"text": "This handler is called when the addstream event is fired. This event is sent when a MediaStream is added to this connection by the remote peer."
},
{
"code": null,
"e": 11613,
"s": 11581,
"text": "RTCPeerConnection.ondatachannel"
},
{
"code": null,
"e": 11743,
"s": 11613,
"text": "This handler is called when the datachannel event is fired. This event is sent when a RTCDataChannel is added to this connection."
},
{
"code": null,
"e": 11776,
"s": 11743,
"text": "RTCPeerConnection.onicecandidate"
},
{
"code": null,
"e": 11910,
"s": 11776,
"text": "This handler is called when the icecandidate event is fired. This event is sent when a RTCIceCandidate object is added to the script."
},
{
"code": null,
"e": 11955,
"s": 11910,
"text": "RTCPeerConnection.oniceconnectionstatechange"
},
{
"code": null,
"e": 12093,
"s": 11955,
"text": "This handler is called when the iceconnectionstatechange event is fired. This event is sent when the value of iceConnectionState changes."
},
{
"code": null,
"e": 12128,
"s": 12093,
"text": "RTCPeerConnection.onidentityresult"
},
{
"code": null,
"e": 12326,
"s": 12128,
"text": "This handler is called when the identityresult event is fired. This event is sent when an identity assertion is generated during the creating of an offer or an answer of via getIdentityAssertion()."
},
{
"code": null,
"e": 12364,
"s": 12326,
"text": "RTCPeerConnection.onidpassertionerror"
},
{
"code": null,
"e": 12538,
"s": 12364,
"text": "This handler is called when the idpassertionerror event is fired. This event is sent when the IdP (Identitry Provider) finds an error while generating an identity assertion."
},
{
"code": null,
"e": 12572,
"s": 12538,
"text": "RTCPeerConnection.onidpvalidation"
},
{
"code": null,
"e": 12747,
"s": 12572,
"text": "This handler is called when the idpvalidationerror event is fired. This event is sent when the IdP (Identitry Provider) finds an error while validating an identity assertion."
},
{
"code": null,
"e": 12785,
"s": 12747,
"text": "RTCPeerConnection.onnegotiationneeded"
},
{
"code": null,
"e": 12957,
"s": 12785,
"text": "This handler is called when the negotiationneeded event is fired. This event is sent by the browser to inform the negotiation will be required at some point in the future."
},
{
"code": null,
"e": 12990,
"s": 12957,
"text": "RTCPeerConnection.onpeeridentity"
},
{
"code": null,
"e": 13137,
"s": 12990,
"text": "This handler is called when the peeridentity event is fired. This event is sent when a peer identity has been set and verified on this connection."
},
{
"code": null,
"e": 13170,
"s": 13137,
"text": "RTCPeerConnection.onremovestream"
},
{
"code": null,
"e": 13300,
"s": 13170,
"text": "This handler is called when the signalingstatechange event is fired. This event is sent when the value of signalingState changes."
},
{
"code": null,
"e": 13341,
"s": 13300,
"text": "RTCPeerConnection.onsignalingstatechange"
},
{
"code": null,
"e": 13473,
"s": 13341,
"text": "This handler is called when the removestream event is fired. This event is sent when a MediaStream is removed from this connection."
},
{
"code": null,
"e": 13493,
"s": 13473,
"text": "RTCPeerConnection()"
},
{
"code": null,
"e": 13533,
"s": 13493,
"text": "Returns a new RTCPeerConnection object."
},
{
"code": null,
"e": 13565,
"s": 13533,
"text": "RTCPeerConnection.createOffer()"
},
{
"code": null,
"e": 13767,
"s": 13565,
"text": "Creates an offer(request) to find a remote peer. The two first parameters of this method are success and error callbacks. The optional third parameter are options, like enabling audio or video streams."
},
{
"code": null,
"e": 13800,
"s": 13767,
"text": "RTCPeerConnection.createAnswer()"
},
{
"code": null,
"e": 14048,
"s": 13800,
"text": "Creates an answer to the offer received by the remote peer during the offer/answer negotiation process. The two first parameters of this method are success and error callbacks. The optional third parameter are options for the answer to be created."
},
{
"code": null,
"e": 14088,
"s": 14048,
"text": "RTCPeerConnection.setLocalDescription()"
},
{
"code": null,
"e": 14416,
"s": 14088,
"text": "Changes the local connection description. The description defines the properties of the connection. The connection must be able to support both old and new descriptions. The method takes three parameters, RTCSessionDescription object, callback if the change of description succeeds, callback if the change of description fails."
},
{
"code": null,
"e": 14457,
"s": 14416,
"text": "RTCPeerConnection.setRemoteDescription()"
},
{
"code": null,
"e": 14786,
"s": 14457,
"text": "Changes the remote connection description. The description defines the properties of the connection. The connection must be able to support both old and new descriptions. The method takes three parameters, RTCSessionDescription object, callback if the change of description succeeds, callback if the change of description fails."
},
{
"code": null,
"e": 14816,
"s": 14786,
"text": "RTCPeerConnection.updateIce()"
},
{
"code": null,
"e": 14907,
"s": 14816,
"text": "Updates the ICE agent process of pinging remote candidates and gathering local candidates."
},
{
"code": null,
"e": 14943,
"s": 14907,
"text": "RTCPeerConnection.addIceCandidate()"
},
{
"code": null,
"e": 14989,
"s": 14943,
"text": "Provides a remote candidate to the ICE agent."
},
{
"code": null,
"e": 15026,
"s": 14989,
"text": "RTCPeerConnection.getConfiguration()"
},
{
"code": null,
"e": 15126,
"s": 15026,
"text": "Returns a RTCConfiguration object. It represents the configuration of the RTCPeerConnection object."
},
{
"code": null,
"e": 15162,
"s": 15126,
"text": "RTCPeerConnection.getLocalStreams()"
},
{
"code": null,
"e": 15212,
"s": 15162,
"text": "Returns an array of local MediaStream connection."
},
{
"code": null,
"e": 15249,
"s": 15212,
"text": "RTCPeerConnection.getRemoteStreams()"
},
{
"code": null,
"e": 15300,
"s": 15249,
"text": "Returns an array of remote MediaStream connection."
},
{
"code": null,
"e": 15334,
"s": 15300,
"text": "RTCPeerConnection.getStreamById()"
},
{
"code": null,
"e": 15387,
"s": 15334,
"text": "Returns local or remote MediaStream by the given ID."
},
{
"code": null,
"e": 15417,
"s": 15387,
"text": "RTCPeerConnection.addStream()"
},
{
"code": null,
"e": 15473,
"s": 15417,
"text": "Adds a MediaStream as a local source of video or audio."
},
{
"code": null,
"e": 15506,
"s": 15473,
"text": "RTCPeerConnection.removeStream()"
},
{
"code": null,
"e": 15565,
"s": 15506,
"text": "Removes a MediaStream as a local source of video or audio."
},
{
"code": null,
"e": 15591,
"s": 15565,
"text": "RTCPeerConnection.close()"
},
{
"code": null,
"e": 15612,
"s": 15591,
"text": "Closes a connection."
},
{
"code": null,
"e": 15650,
"s": 15612,
"text": "RTCPeerConnection.createDataChannel()"
},
{
"code": null,
"e": 15680,
"s": 15650,
"text": "Creates a new RTCDataChannel."
},
{
"code": null,
"e": 15717,
"s": 15680,
"text": "RTCPeerConnection.createDTMFSender()"
},
{
"code": null,
"e": 15873,
"s": 15717,
"text": "Creates a new RTCDTMFSender, associated to a specific MediaStreamTrack. Allows to send DTMF (Dual-tone multifrequency) phone signaling over the connection."
},
{
"code": null,
"e": 15902,
"s": 15873,
"text": "RTCPeerConnection.getStats()"
},
{
"code": null,
"e": 15983,
"s": 15902,
"text": "Creates a new RTCStatsReport that contains statistics concerning the connection."
},
{
"code": null,
"e": 16023,
"s": 15983,
"text": "RTCPeerConnection.setIdentityProvider()"
},
{
"code": null,
"e": 16131,
"s": 16023,
"text": "Sets the IdP. Takes three parameters − the name, the protocol used to communicate and an optional username."
},
{
"code": null,
"e": 16172,
"s": 16131,
"text": "RTCPeerConnection.getIdentityAssertion()"
},
{
"code": null,
"e": 16326,
"s": 16172,
"text": "Gathers an identity assertion. It is not expected to deal with this method in the application. So you may call it explicitly only to anticipate the need."
},
{
"code": null,
"e": 16466,
"s": 16326,
"text": "Now let's create an example application. Firstly, run the signaling server we created in the “signaling server” tutorial via “node server”."
},
{
"code": null,
"e": 16626,
"s": 16466,
"text": "There will be two text inputs on the page, one for a login and one for a username we want to connect to. Create an index.html file and add the following code −"
},
{
"code": null,
"e": 17084,
"s": 16626,
"text": "<html lang = \"en\"> \n <head> \n <meta charset = \"utf-8\" /> \n </head>\n\t\n <body> \n\t\n <div> \n <input type = \"text\" id = \"loginInput\" /> \n <button id = \"loginBtn\">Login</button> \n </div> \n\t\n <div> \n <input type = \"text\" id = \"otherUsernameInput\" />\n <button id = \"connectToOtherUsernameBtn\">Establish connection</button> \n </div> \n\t\t\n <script src = \"client2.js\"></script>\n\t\t\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 17291,
"s": 17084,
"text": "You can see that we've added the text input for a login, the login button, the text input for the other peer username, and the connect-to-him button. Now create a client.js file and add the following code −"
},
{
"code": null,
"e": 19600,
"s": 17291,
"text": "var connection = new WebSocket('ws://localhost:9090'); \nvar name = \"\"; \n \nvar loginInput = document.querySelector('#loginInput'); \nvar loginBtn = document.querySelector('#loginBtn'); \nvar otherUsernameInput = document.querySelector('#otherUsernameInput'); \nvar connectToOtherUsernameBtn = document.querySelector('#connectToOtherUsernameBtn'); \nvar connectedUser, myConnection;\n \n//when a user clicks the login button \nloginBtn.addEventListener(\"click\", function(event){ \n name = loginInput.value; \n\t\n if(name.length > 0){ \n send({ \n type: \"login\", \n name: name \n }); \n } \n\t\n});\n \n//handle messages from the server \nconnection.onmessage = function (message) { \n console.log(\"Got message\", message.data);\n var data = JSON.parse(message.data); \n\t\n switch(data.type) { \n case \"login\": \n onLogin(data.success); \n break; \n case \"offer\": \n onOffer(data.offer, data.name); \n break; \n case \"answer\": \n onAnswer(data.answer); \n break; \n case \"candidate\": \n onCandidate(data.candidate); \n break; \n default: \n break; \n } \n};\n \n//when a user logs in \nfunction onLogin(success) { \n\n if (success === false) { \n alert(\"oops...try a different username\"); \n } else { \n //creating our RTCPeerConnection object \n\t\t\n var configuration = { \n \"iceServers\": [{ \"url\": \"stun:stun.1.google.com:19302\" }] \n }; \n\t\t\n myConnection = new webkitRTCPeerConnection(configuration); \n console.log(\"RTCPeerConnection object was created\"); \n console.log(myConnection); \n \n //setup ice handling\n //when the browser finds an ice candidate we send it to another peer \n myConnection.onicecandidate = function (event) { \n\t\t\n if (event.candidate) { \n send({ \n type: \"candidate\", \n candidate: event.candidate \n }); \n } \n }; \n } \n};\n \nconnection.onopen = function () { \n console.log(\"Connected\"); \n};\n \nconnection.onerror = function (err) { \n console.log(\"Got error\", err); \n};\n \n// Alias for sending messages in JSON format \nfunction send(message) { \n\n if (connectedUser) { \n message.name = connectedUser; \n } \n\t\n connection.send(JSON.stringify(message)); \n};"
},
{
"code": null,
"e": 20010,
"s": 19600,
"text": "You can see that we establish a socket connection to our signaling server. When a user clicks on the login button the application sends his username to the server. If login is successful the application creates the RTCPeerConnection object and setup onicecandidate handler which sends all found icecandidates to the other peer. Now open the page and try to login. You should see the following console output −"
},
{
"code": null,
"e": 20113,
"s": 20010,
"text": "The next step is to create an offer to the other peer. Add the following code to your client.js file −"
},
{
"code": null,
"e": 21402,
"s": 20113,
"text": "//setup a peer connection with another user \nconnectToOtherUsernameBtn.addEventListener(\"click\", function () { \n \n var otherUsername = otherUsernameInput.value; \n connectedUser = otherUsername;\n\t\n if (otherUsername.length > 0) { \n //make an offer \n myConnection.createOffer(function (offer) { \n console.log(); \n send({ \n type: \"offer\", \n offer: offer \n });\n\t\t\t\n myConnection.setLocalDescription(offer); \n }, function (error) { \n alert(\"An error has occurred.\"); \n }); \n } \n}); \n \n//when somebody wants to call us \nfunction onOffer(offer, name) { \n connectedUser = name; \n myConnection.setRemoteDescription(new RTCSessionDescription(offer)); \n\t\n myConnection.createAnswer(function (answer) { \n myConnection.setLocalDescription(answer); \n\t\t\n send({ \n type: \"answer\", \n answer: answer \n }); \n\t\t\n }, function (error) { \n alert(\"oops...error\"); \n }); \n}\n \n//when another user answers to our offer \nfunction onAnswer(answer) { \n myConnection.setRemoteDescription(new RTCSessionDescription(answer)); \n} \n \n//when we got ice candidate from another user \nfunction onCandidate(candidate) { \n myConnection.addIceCandidate(new RTCIceCandidate(candidate)); \n}\t"
},
{
"code": null,
"e": 21727,
"s": 21402,
"text": "You can see that when a user clicks the “Establish connection” button the application makes an SDP offer to the other peer. We also set onAnswer and onCandidate handlers. Reload your page, open it in two tabs, login with two users and try to establish a connection between them. You should see the following console output −"
}
] |
How to remove CSS property using JavaScript?
|
14 May, 2019
Method 1: Using CSS removeProperty: The CSSStyleDeclaration.removeProperty() method is used to remove a property from a style of an element. The style of the element is selected by going through the styleSheets array and selecting the cssRule. The removeProperty method can then be specified with the property to be removed.
Syntax:
element.removeProperty('property')
Example-1:
<!DOCTYPE html><html> <head> <title> How to remove CSS property using JavaScript? </title> <style> .elem { color: green; font-size: 3rem; text-decoration: underline; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to remove CSS property using JavaScript? </b> <div class="elem">Hello World!</div> <p> Click on the button below to remove the text decoration of the element </p> <button onclick="removeProperty()"> Remove text-decoration property </button> <script> function removeProperty() { element = document.styleSheets[0].cssRules[0].style; element.removeProperty('text-decoration'); } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Using the setProperty method: The CSSStyleDeclaration.setProperty() method can be used to set the required property of the style. The element of which the property has to be removed is selected and this property is applied to its style property. Setting this property to ‘initial’ resets the property to its initial value, removing any effect of the property.
Syntax:
element.style.setProperty('color', 'initial')
Example:
<!DOCTYPE html><html> <head> <title> How to remove CSS property using JavaScript? </title> <style> .elem { color: green; font-size: 3rem; text-decoration: underline; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to remove CSS property using JavaScript? </b> <div class="elem">Hello World!</div> <p> Click on the button below to remove the text color of the element </p> <button onclick="removeProperty()"> Remove color property </button> <script> function removeProperty() { element = document.querySelector('.elem'); element.style.setProperty('color', 'initial'); } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
CSS-Misc
JavaScript-Misc
Picked
CSS
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
How to select all child elements recursively using CSS?
CSS | :not(:last-child):after Selector
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 May, 2019"
},
{
"code": null,
"e": 353,
"s": 28,
"text": "Method 1: Using CSS removeProperty: The CSSStyleDeclaration.removeProperty() method is used to remove a property from a style of an element. The style of the element is selected by going through the styleSheets array and selecting the cssRule. The removeProperty method can then be specified with the property to be removed."
},
{
"code": null,
"e": 361,
"s": 353,
"text": "Syntax:"
},
{
"code": null,
"e": 396,
"s": 361,
"text": "element.removeProperty('property')"
},
{
"code": null,
"e": 407,
"s": 396,
"text": "Example-1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to remove CSS property using JavaScript? </title> <style> .elem { color: green; font-size: 3rem; text-decoration: underline; } </style></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to remove CSS property using JavaScript? </b> <div class=\"elem\">Hello World!</div> <p> Click on the button below to remove the text decoration of the element </p> <button onclick=\"removeProperty()\"> Remove text-decoration property </button> <script> function removeProperty() { element = document.styleSheets[0].cssRules[0].style; element.removeProperty('text-decoration'); } </script></body> </html>",
"e": 1218,
"s": 407,
"text": null
},
{
"code": null,
"e": 1226,
"s": 1218,
"text": "Output:"
},
{
"code": null,
"e": 1254,
"s": 1226,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 1281,
"s": 1254,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1651,
"s": 1281,
"text": "Method 2: Using the setProperty method: The CSSStyleDeclaration.setProperty() method can be used to set the required property of the style. The element of which the property has to be removed is selected and this property is applied to its style property. Setting this property to ‘initial’ resets the property to its initial value, removing any effect of the property."
},
{
"code": null,
"e": 1659,
"s": 1651,
"text": "Syntax:"
},
{
"code": null,
"e": 1705,
"s": 1659,
"text": "element.style.setProperty('color', 'initial')"
},
{
"code": null,
"e": 1714,
"s": 1705,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to remove CSS property using JavaScript? </title> <style> .elem { color: green; font-size: 3rem; text-decoration: underline; } </style></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to remove CSS property using JavaScript? </b> <div class=\"elem\">Hello World!</div> <p> Click on the button below to remove the text color of the element </p> <button onclick=\"removeProperty()\"> Remove color property </button> <script> function removeProperty() { element = document.querySelector('.elem'); element.style.setProperty('color', 'initial'); } </script></body> </html>",
"e": 2490,
"s": 1714,
"text": null
},
{
"code": null,
"e": 2498,
"s": 2490,
"text": "Output:"
},
{
"code": null,
"e": 2526,
"s": 2498,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 2553,
"s": 2526,
"text": "After clicking the button:"
},
{
"code": null,
"e": 2562,
"s": 2553,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2578,
"s": 2562,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2585,
"s": 2578,
"text": "Picked"
},
{
"code": null,
"e": 2589,
"s": 2585,
"text": "CSS"
},
{
"code": null,
"e": 2600,
"s": 2589,
"text": "JavaScript"
},
{
"code": null,
"e": 2617,
"s": 2600,
"text": "Web Technologies"
},
{
"code": null,
"e": 2644,
"s": 2617,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2742,
"s": 2644,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2781,
"s": 2742,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2820,
"s": 2781,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2859,
"s": 2820,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2915,
"s": 2859,
"text": "How to select all child elements recursively using CSS?"
},
{
"code": null,
"e": 2954,
"s": 2915,
"text": "CSS | :not(:last-child):after Selector"
},
{
"code": null,
"e": 3015,
"s": 2954,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3087,
"s": 3015,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3127,
"s": 3087,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3180,
"s": 3127,
"text": "Hide or show elements in HTML using display property"
}
] |
Python | Pandas Series.str.extractall()
|
27 Mar, 2019
Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.extractall() function is used to extract capture groups in the regex pat as columns in a DataFrame. For each subject string in the Series, extract groups from all matches of regular expression pat. When each subject string in the Series has exactly one match, extractall(pat).xs(0, level=’match’) is the same as extract(pat).
Syntax: Series.str.extractall(pat, flags=0)
Parameter :pat : Regular expression pattern with capturing groups.flags : A re module flag, for example re.IGNORECASE.
Returns : DataFrame
Example #1: Use Series.str.extractall() function to extract all groups from the string in the underlying data of the given series object.
# importing pandas as pdimport pandas as pd # importing re for regular expressionsimport re # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich']) # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.str.extractall() function to extract all groups from the strings in the given series object.
# extract all groups having a vowel followed by# any characterresult = sr.str.extractall(pat = '([aeiou].)') # print the resultprint(result)
Output :
As we can see in the output, the Series.str.extractall() function has returned a dataframe containing a column of all the extracted group.
Example #2 : Use Series.str.extractall() function to extract all groups from the string in the underlying data of the given series object.
# importing pandas as pdimport pandas as pd # importing re for regular expressionsimport re # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney']) # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.str.extractall() function to extract all groups from the strings in the given series object.
# extract all groups having any capital letter# followed by 'i' and any other characterresult = sr.str.extractall(pat = '([A-Z]i.)') # print the resultprint(result)
Output :
As we can see in the output, the Series.str.extractall() function has returned a dataframe containing a column of all the extracted group.
Python-pandas
Python-pandas-series-str
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 474,
"s": 28,
"text": "Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.extractall() function is used to extract capture groups in the regex pat as columns in a DataFrame. For each subject string in the Series, extract groups from all matches of regular expression pat. When each subject string in the Series has exactly one match, extractall(pat).xs(0, level=’match’) is the same as extract(pat)."
},
{
"code": null,
"e": 518,
"s": 474,
"text": "Syntax: Series.str.extractall(pat, flags=0)"
},
{
"code": null,
"e": 637,
"s": 518,
"text": "Parameter :pat : Regular expression pattern with capturing groups.flags : A re module flag, for example re.IGNORECASE."
},
{
"code": null,
"e": 657,
"s": 637,
"text": "Returns : DataFrame"
},
{
"code": null,
"e": 795,
"s": 657,
"text": "Example #1: Use Series.str.extractall() function to extract all groups from the string in the underlying data of the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # importing re for regular expressionsimport re # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich']) # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 1115,
"s": 795,
"text": null
},
{
"code": null,
"e": 1124,
"s": 1115,
"text": "Output :"
},
{
"code": null,
"e": 1240,
"s": 1124,
"text": "Now we will use Series.str.extractall() function to extract all groups from the strings in the given series object."
},
{
"code": "# extract all groups having a vowel followed by# any characterresult = sr.str.extractall(pat = '([aeiou].)') # print the resultprint(result)",
"e": 1382,
"s": 1240,
"text": null
},
{
"code": null,
"e": 1391,
"s": 1382,
"text": "Output :"
},
{
"code": null,
"e": 1530,
"s": 1391,
"text": "As we can see in the output, the Series.str.extractall() function has returned a dataframe containing a column of all the extracted group."
},
{
"code": null,
"e": 1669,
"s": 1530,
"text": "Example #2 : Use Series.str.extractall() function to extract all groups from the string in the underlying data of the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # importing re for regular expressionsimport re # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney']) # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 1983,
"s": 1669,
"text": null
},
{
"code": null,
"e": 1992,
"s": 1983,
"text": "Output :"
},
{
"code": null,
"e": 2108,
"s": 1992,
"text": "Now we will use Series.str.extractall() function to extract all groups from the strings in the given series object."
},
{
"code": "# extract all groups having any capital letter# followed by 'i' and any other characterresult = sr.str.extractall(pat = '([A-Z]i.)') # print the resultprint(result)",
"e": 2274,
"s": 2108,
"text": null
},
{
"code": null,
"e": 2283,
"s": 2274,
"text": "Output :"
},
{
"code": null,
"e": 2422,
"s": 2283,
"text": "As we can see in the output, the Series.str.extractall() function has returned a dataframe containing a column of all the extracted group."
},
{
"code": null,
"e": 2436,
"s": 2422,
"text": "Python-pandas"
},
{
"code": null,
"e": 2461,
"s": 2436,
"text": "Python-pandas-series-str"
},
{
"code": null,
"e": 2468,
"s": 2461,
"text": "Python"
},
{
"code": null,
"e": 2566,
"s": 2468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2598,
"s": 2566,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2625,
"s": 2598,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2646,
"s": 2625,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2669,
"s": 2646,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2725,
"s": 2669,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2756,
"s": 2725,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2798,
"s": 2756,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2840,
"s": 2798,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2879,
"s": 2840,
"text": "Python | Get unique values from a list"
}
] |
Create a white space in HTML
|
The HTML <spacer> tag specifies a whitespace. It supports the following additional attributes −
Note − The <spacer> tag is available in Netscape 4 and higher versions only.
You can try to run the following code to create a white space in HTML (visible in Netscape Web Browser only) −
<!DOCTYPE html>
<html>
<head>
<title>HTML spacer Tag</title>
</head>
<body>
Create some space <spacer type = "block" width = "70" /> now.
</body>
</html>
|
[
{
"code": null,
"e": 1283,
"s": 1187,
"text": "The HTML <spacer> tag specifies a whitespace. It supports the following additional attributes −"
},
{
"code": null,
"e": 1360,
"s": 1283,
"text": "Note − The <spacer> tag is available in Netscape 4 and higher versions only."
},
{
"code": null,
"e": 1471,
"s": 1360,
"text": "You can try to run the following code to create a white space in HTML (visible in Netscape Web Browser only) −"
},
{
"code": null,
"e": 1649,
"s": 1471,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML spacer Tag</title>\n </head>\n <body>\n Create some space <spacer type = \"block\" width = \"70\" /> now.\n </body>\n</html>"
}
] |
Ruby | Array class include?() operation
|
08 Jan, 2020
Array#include?() : include?() is a Array class method checks if the argumented object is present in the array or not.
Syntax: Array.include?()
Parameter: obj – element to find
Return: true – if the element is present; otherwise false
Code #1 : Example for include?() method
# Ruby code for include?() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # include?puts "include? : #{a.include?(5)}\n\n" # include?puts "include? : #{b.include?(0)}\n\n" # include?puts "include? : #{c.include?(nil)}\n\n"
Output :
include? : true
include? : false
include? : true
Code #2 : Example for include?() method
# Ruby code for include?() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayb = ["cow", nil, "dog"] # declaring arrayc = ["cat", nil, nil] # include?puts "include? : #{a.include?("cat")}\n\n" # include?puts "include? : #{b.include?("nil")}\n\n" # include?puts "include? : #{c.include?("cat")}\n\n"
Output :
include? : false
include? : false
include? : true
Ruby Array-class
Ruby Collections
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jan, 2020"
},
{
"code": null,
"e": 146,
"s": 28,
"text": "Array#include?() : include?() is a Array class method checks if the argumented object is present in the array or not."
},
{
"code": null,
"e": 171,
"s": 146,
"text": "Syntax: Array.include?()"
},
{
"code": null,
"e": 204,
"s": 171,
"text": "Parameter: obj – element to find"
},
{
"code": null,
"e": 262,
"s": 204,
"text": "Return: true – if the element is present; otherwise false"
},
{
"code": null,
"e": 302,
"s": 262,
"text": "Code #1 : Example for include?() method"
},
{
"code": "# Ruby code for include?() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # include?puts \"include? : #{a.include?(5)}\\n\\n\" # include?puts \"include? : #{b.include?(0)}\\n\\n\" # include?puts \"include? : #{c.include?(nil)}\\n\\n\"",
"e": 624,
"s": 302,
"text": null
},
{
"code": null,
"e": 633,
"s": 624,
"text": "Output :"
},
{
"code": null,
"e": 685,
"s": 633,
"text": "include? : true\n\ninclude? : false\n\ninclude? : true\n"
},
{
"code": null,
"e": 725,
"s": 685,
"text": "Code #2 : Example for include?() method"
},
{
"code": "# Ruby code for include?() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayb = [\"cow\", nil, \"dog\"] # declaring arrayc = [\"cat\", nil, nil] # include?puts \"include? : #{a.include?(\"cat\")}\\n\\n\" # include?puts \"include? : #{b.include?(\"nil\")}\\n\\n\" # include?puts \"include? : #{c.include?(\"cat\")}\\n\\n\"",
"e": 1047,
"s": 725,
"text": null
},
{
"code": null,
"e": 1056,
"s": 1047,
"text": "Output :"
},
{
"code": null,
"e": 1109,
"s": 1056,
"text": "include? : false\n\ninclude? : false\n\ninclude? : true\n"
},
{
"code": null,
"e": 1126,
"s": 1109,
"text": "Ruby Array-class"
},
{
"code": null,
"e": 1143,
"s": 1126,
"text": "Ruby Collections"
},
{
"code": null,
"e": 1148,
"s": 1143,
"text": "Ruby"
},
{
"code": null,
"e": 1246,
"s": 1148,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1292,
"s": 1246,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 1323,
"s": 1292,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 1350,
"s": 1323,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 1374,
"s": 1350,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 1405,
"s": 1374,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 1448,
"s": 1405,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 1470,
"s": 1448,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 1514,
"s": 1470,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 1544,
"s": 1514,
"text": "Ruby | Hash delete() function"
}
] |
Program to print Collatz Sequence
|
22 Jun, 2022
Starting with any positive integer N, Collatz sequence is defined corresponding to n as the numbers formed by the following operations :
If n is even, then n = n / 2.If n is odd, then n = 3*n + 1.Repeat above steps, until it becomes 1.
If n is even, then n = n / 2.
If n is odd, then n = 3*n + 1.
Repeat above steps, until it becomes 1.
Examples :
Input : 3
Output : 3, 10, 5, 16, 8, 4, 2, 1
Input : 6
Output : 6, 3, 10, 5, 16, 8, 4, 2, 1
Below is the implementation :
C++
Java
Python3
C#
PHP
Javascript
// CPP program to print Collatz sequence#include <bits/stdc++.h>using namespace std; void printCollatz(int n){ // We simply follow steps // while we do not reach 1 while (n != 1) { cout << n << " "; // If n is odd if (n & 1) n = 3*n + 1; // If even else n = n/2; } // Print 1 at the end cout << n;} // Driver codeint main(){ printCollatz(6); return 0;}
// Java program to print// Collatz sequenceimport java.io.*; class GFG{ static void printCollatz(int n) { // We simply follow steps // while we do not reach 1 while (n != 1) { System.out.print(n + " "); // If n is odd if ((n & 1) == 1) n = 3 * n + 1; // If even else n = n / 2; } // Print 1 at the end System.out.print(n); } // Driver code public static void main (String[] args) { printCollatz(6); }} // This code is contributed// by akt_mit
# Python 3 program to print# Collatz sequence def printCollatz(n): # We simply follow steps # while we do not reach 1 while n != 1: print(n, end = ' ') # If n is odd if n & 1: n = 3 * n + 1 # If even else: n = n // 2 # Print 1 at the end print(n) # Driver codeprintCollatz(6) # This code is contributed# by vaibhav29498
// C# program to print Collatz sequenceusing System; class GFG { static void printCollatz(int n) { // We simply follow steps // while we do not reach 1 while (n != 1) { Console.Write (n + " "); // If n is odd if ((n & 1) == 1) n = 3 * n + 1; // If even else n = n / 2; } // Print 1 at the end Console.Write (n); } // Driver code static void Main() { printCollatz(6); }} // This code is contributed by// Manish Shaw (manishshaw1)
<?php// PHP program to print Collatz sequence function printCollatz($n){ // We simply follow steps // while we do not reach 1 while ($n != 1) { echo $n . " "; // If $n is odd if ($n & 1) $n = 3 * $n + 1; // If even else $n = $n / 2; } // Print 1 at the end echo $n;} // Driver codeprintCollatz(6); // This code is contributed// by ChitraNayal?>
<script> // Javascript program to print Collatz sequence function printCollatz(n) { // We simply follow steps // while we do not reach 1 while (n != 1) { document.write(n + " "); // If n is odd if ((n & 1) != 0) n = 3*n + 1; // If even else n = parseInt(n/2, 10); } // Print 1 at the end document.write(n); } printCollatz(6); </script>
Output
6 3 10 5 16 8 4 2 1
Time Complexity: O(log n) since n is halved in while loop
Auxiliary Space: O(1)
manishshaw1
jit_t
vaibhav29498
ukasp
divyeshrabadiya07
kumargaurav97520
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Sieve of Eratosthenes
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
Modulo 10^9+7 (1000000007)
The Knight's tour problem | Backtracking-1
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 190,
"s": 52,
"text": "Starting with any positive integer N, Collatz sequence is defined corresponding to n as the numbers formed by the following operations : "
},
{
"code": null,
"e": 289,
"s": 190,
"text": "If n is even, then n = n / 2.If n is odd, then n = 3*n + 1.Repeat above steps, until it becomes 1."
},
{
"code": null,
"e": 319,
"s": 289,
"text": "If n is even, then n = n / 2."
},
{
"code": null,
"e": 350,
"s": 319,
"text": "If n is odd, then n = 3*n + 1."
},
{
"code": null,
"e": 390,
"s": 350,
"text": "Repeat above steps, until it becomes 1."
},
{
"code": null,
"e": 403,
"s": 390,
"text": "Examples : "
},
{
"code": null,
"e": 502,
"s": 403,
"text": "Input : 3\nOutput : 3, 10, 5, 16, 8, 4, 2, 1 \n\nInput : 6\nOutput : 6, 3, 10, 5, 16, 8, 4, 2, 1"
},
{
"code": null,
"e": 536,
"s": 504,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 540,
"s": 536,
"text": "C++"
},
{
"code": null,
"e": 545,
"s": 540,
"text": "Java"
},
{
"code": null,
"e": 553,
"s": 545,
"text": "Python3"
},
{
"code": null,
"e": 556,
"s": 553,
"text": "C#"
},
{
"code": null,
"e": 560,
"s": 556,
"text": "PHP"
},
{
"code": null,
"e": 571,
"s": 560,
"text": "Javascript"
},
{
"code": "// CPP program to print Collatz sequence#include <bits/stdc++.h>using namespace std; void printCollatz(int n){ // We simply follow steps // while we do not reach 1 while (n != 1) { cout << n << \" \"; // If n is odd if (n & 1) n = 3*n + 1; // If even else n = n/2; } // Print 1 at the end cout << n;} // Driver codeint main(){ printCollatz(6); return 0;}",
"e": 1011,
"s": 571,
"text": null
},
{
"code": "// Java program to print// Collatz sequenceimport java.io.*; class GFG{ static void printCollatz(int n) { // We simply follow steps // while we do not reach 1 while (n != 1) { System.out.print(n + \" \"); // If n is odd if ((n & 1) == 1) n = 3 * n + 1; // If even else n = n / 2; } // Print 1 at the end System.out.print(n); } // Driver code public static void main (String[] args) { printCollatz(6); }} // This code is contributed// by akt_mit",
"e": 1636,
"s": 1011,
"text": null
},
{
"code": "# Python 3 program to print# Collatz sequence def printCollatz(n): # We simply follow steps # while we do not reach 1 while n != 1: print(n, end = ' ') # If n is odd if n & 1: n = 3 * n + 1 # If even else: n = n // 2 # Print 1 at the end print(n) # Driver codeprintCollatz(6) # This code is contributed# by vaibhav29498",
"e": 2036,
"s": 1636,
"text": null
},
{
"code": "// C# program to print Collatz sequenceusing System; class GFG { static void printCollatz(int n) { // We simply follow steps // while we do not reach 1 while (n != 1) { Console.Write (n + \" \"); // If n is odd if ((n & 1) == 1) n = 3 * n + 1; // If even else n = n / 2; } // Print 1 at the end Console.Write (n); } // Driver code static void Main() { printCollatz(6); }} // This code is contributed by// Manish Shaw (manishshaw1)",
"e": 2652,
"s": 2036,
"text": null
},
{
"code": "<?php// PHP program to print Collatz sequence function printCollatz($n){ // We simply follow steps // while we do not reach 1 while ($n != 1) { echo $n . \" \"; // If $n is odd if ($n & 1) $n = 3 * $n + 1; // If even else $n = $n / 2; } // Print 1 at the end echo $n;} // Driver codeprintCollatz(6); // This code is contributed// by ChitraNayal?>",
"e": 3078,
"s": 2652,
"text": null
},
{
"code": "<script> // Javascript program to print Collatz sequence function printCollatz(n) { // We simply follow steps // while we do not reach 1 while (n != 1) { document.write(n + \" \"); // If n is odd if ((n & 1) != 0) n = 3*n + 1; // If even else n = parseInt(n/2, 10); } // Print 1 at the end document.write(n); } printCollatz(6); </script>",
"e": 3574,
"s": 3078,
"text": null
},
{
"code": null,
"e": 3583,
"s": 3574,
"text": "Output "
},
{
"code": null,
"e": 3603,
"s": 3583,
"text": "6 3 10 5 16 8 4 2 1"
},
{
"code": null,
"e": 3663,
"s": 3603,
"text": "Time Complexity: O(log n) since n is halved in while loop "
},
{
"code": null,
"e": 3686,
"s": 3663,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 3698,
"s": 3686,
"text": "manishshaw1"
},
{
"code": null,
"e": 3704,
"s": 3698,
"text": "jit_t"
},
{
"code": null,
"e": 3717,
"s": 3704,
"text": "vaibhav29498"
},
{
"code": null,
"e": 3723,
"s": 3717,
"text": "ukasp"
},
{
"code": null,
"e": 3741,
"s": 3723,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 3758,
"s": 3741,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 3765,
"s": 3758,
"text": "series"
},
{
"code": null,
"e": 3778,
"s": 3765,
"text": "Mathematical"
},
{
"code": null,
"e": 3791,
"s": 3778,
"text": "Mathematical"
},
{
"code": null,
"e": 3798,
"s": 3791,
"text": "series"
},
{
"code": null,
"e": 3896,
"s": 3798,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3920,
"s": 3896,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 3941,
"s": 3920,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 3955,
"s": 3941,
"text": "Prime Numbers"
},
{
"code": null,
"e": 3977,
"s": 3955,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 4019,
"s": 3977,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 4072,
"s": 4019,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 4104,
"s": 4072,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 4141,
"s": 4104,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 4168,
"s": 4141,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
How to Align navbar logo to the left screen using Bootstrap ?
|
01 Jun, 2020
It is very easy in Bootstrap to align items left and right by using the bootstrap classes. By default, it sets to left. If you want to align items center or right then it will be done by yourself. To align the navbar logo to the left of the screen with the Bootstrap method is a quick trick that can save you from writing extra CSS. In this, we simply add another div tag above the div tag having class navbar navbar-expand-lg navbar-light bg-light fixed-top py-lg-0.
Example:
<!DOCTYPE html><html> <head> <title> How to Align navbar logo to the left screen using Bootstrap ? </title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"> </script></head> <body> <!-- NAVBAR STARTING --> <!-- Use navbar class to the navbar logo to the far left of the screen--> <nav class=" navbar navbar-expand-lg navbar-light bg-light fixed-top py-lg-0 "> <a class="navbar-brand" href="#"> <!-- Add logo with size of 90*80 --> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" width="90" height="80" alt=""> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Courses</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </nav></body> </html>
Output:
Bootstrap-4
Bootstrap-Misc
Picked
Bootstrap
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set Bootstrap Timepicker using datetimepicker library ?
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
How to make Bootstrap table with sticky table head?
Tailwind CSS vs Bootstrap
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 522,
"s": 54,
"text": "It is very easy in Bootstrap to align items left and right by using the bootstrap classes. By default, it sets to left. If you want to align items center or right then it will be done by yourself. To align the navbar logo to the left of the screen with the Bootstrap method is a quick trick that can save you from writing extra CSS. In this, we simply add another div tag above the div tag having class navbar navbar-expand-lg navbar-light bg-light fixed-top py-lg-0."
},
{
"code": null,
"e": 531,
"s": 522,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to Align navbar logo to the left screen using Bootstrap ? </title> <link href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh\" crossorigin=\"anonymous\"> <script src=\"https://code.jquery.com/jquery-3.5.1.js\" integrity=\"sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\" integrity=\"sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6\" crossorigin=\"anonymous\"> </script></head> <body> <!-- NAVBAR STARTING --> <!-- Use navbar class to the navbar logo to the far left of the screen--> <nav class=\" navbar navbar-expand-lg navbar-light bg-light fixed-top py-lg-0 \"> <a class=\"navbar-brand\" href=\"#\"> <!-- Add logo with size of 90*80 --> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" width=\"90\" height=\"80\" alt=\"\"> </a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarResponsive\" aria-controls=\"navbarResponsive\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\" id=\"navbarResponsive\"> <ul class=\"navbar-nav ml-auto\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\">Home <span class=\"sr-only\">(current)</span> </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">About</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">Courses</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">Contact</a> </li> </ul> </div> </nav></body> </html>",
"e": 2898,
"s": 531,
"text": null
},
{
"code": null,
"e": 2906,
"s": 2898,
"text": "Output:"
},
{
"code": null,
"e": 2918,
"s": 2906,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 2933,
"s": 2918,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 2940,
"s": 2933,
"text": "Picked"
},
{
"code": null,
"e": 2950,
"s": 2940,
"text": "Bootstrap"
},
{
"code": null,
"e": 2955,
"s": 2950,
"text": "HTML"
},
{
"code": null,
"e": 2972,
"s": 2955,
"text": "Web Technologies"
},
{
"code": null,
"e": 2977,
"s": 2972,
"text": "HTML"
},
{
"code": null,
"e": 3075,
"s": 2977,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3138,
"s": 3075,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 3179,
"s": 3138,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 3212,
"s": 3179,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 3264,
"s": 3212,
"text": "How to make Bootstrap table with sticky table head?"
},
{
"code": null,
"e": 3290,
"s": 3264,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 3338,
"s": 3290,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3400,
"s": 3338,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3450,
"s": 3400,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3474,
"s": 3450,
"text": "REST API (Introduction)"
}
] |
Arden’s Theorem in Theory of Computation
|
02 Mar, 2020
Arden’s theorem state that:“If P and Q are two regular expressions over , and if P does not contain , then the following equation in R given by R = Q + RP has an unique solution i.e., R = QP*.”That means, whenever we get any equation in the form of R = Q + RP, then we can directly replaced by R = QP*. So, here first we will prove that R = QP* is the solution of this equation and then we will also prove that it is the unique solution of this equation.
Let’s start by taking this equation as equation (i)
R = Q + RP ......(i)
Now, replacing R by R = QP*, we get,
R = Q + QP*P
Taking Q as common,
R = Q( + P*P)
R = QP*
(As we know that + R*R = R*). Hence proved.
Thus, R = QP* is the solution of the equation R = Q + RP.
Now, we have to prove that this is the only solution of this equation. Let me take this equation again:
R = Q + RP
Now, replace R by R = Q + RP,
R = Q + (Q + RP)P
= Q + QP + R
Again, replace R by R = Q + RP:-
R = Q + QP + (Q + RP)
= Q + QP + Q + R
= ...
= ...
= Q + QP + Q + .. + Q + R
Now, replace R by R = QP*, we get,
R = Q + QP + Q + .. + Q + QP*
Taking Q as common,
R = Q( + P + + .. + + P*)
= QP* [As + P + + .. + + P* represent
the closure of P]
Hence proved.
Thus, R = QP* is the unique solution of the equation R = Q + RP.
To understand this theorem, we will solve an example:
Example –
q1 = q1.0 +
q2 = q1.1 + q2.0
q3 = q2.1 + q3.0 + q3.1
Now,
q1 = + q1.0
q1 = .0* [By Arden's theorem]
q1 = 0* [R = R]
.'. q2 = 0*1 +q2.0
q2 = 0*10*
[Applying Arden’s theorem]. Hence, the value of q2 is 0*10*.
AllenDeAlpha
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Mar, 2020"
},
{
"code": null,
"e": 507,
"s": 52,
"text": "Arden’s theorem state that:“If P and Q are two regular expressions over , and if P does not contain , then the following equation in R given by R = Q + RP has an unique solution i.e., R = QP*.”That means, whenever we get any equation in the form of R = Q + RP, then we can directly replaced by R = QP*. So, here first we will prove that R = QP* is the solution of this equation and then we will also prove that it is the unique solution of this equation."
},
{
"code": null,
"e": 559,
"s": 507,
"text": "Let’s start by taking this equation as equation (i)"
},
{
"code": null,
"e": 581,
"s": 559,
"text": "R = Q + RP ......(i)"
},
{
"code": null,
"e": 618,
"s": 581,
"text": "Now, replacing R by R = QP*, we get,"
},
{
"code": null,
"e": 632,
"s": 618,
"text": "R = Q + QP*P "
},
{
"code": null,
"e": 652,
"s": 632,
"text": "Taking Q as common,"
},
{
"code": null,
"e": 676,
"s": 652,
"text": "R = Q( + P*P)\nR = QP* "
},
{
"code": null,
"e": 721,
"s": 676,
"text": "(As we know that + R*R = R*). Hence proved."
},
{
"code": null,
"e": 779,
"s": 721,
"text": "Thus, R = QP* is the solution of the equation R = Q + RP."
},
{
"code": null,
"e": 883,
"s": 779,
"text": "Now, we have to prove that this is the only solution of this equation. Let me take this equation again:"
},
{
"code": null,
"e": 894,
"s": 883,
"text": "R = Q + RP"
},
{
"code": null,
"e": 924,
"s": 894,
"text": "Now, replace R by R = Q + RP,"
},
{
"code": null,
"e": 958,
"s": 924,
"text": "R = Q + (Q + RP)P\n = Q + QP + R "
},
{
"code": null,
"e": 991,
"s": 958,
"text": "Again, replace R by R = Q + RP:-"
},
{
"code": null,
"e": 1079,
"s": 991,
"text": "R = Q + QP + (Q + RP) \n = Q + QP + Q + R\n = ...\n = ...\n = Q + QP + Q + .. + Q + R "
},
{
"code": null,
"e": 1114,
"s": 1079,
"text": "Now, replace R by R = QP*, we get,"
},
{
"code": null,
"e": 1145,
"s": 1114,
"text": "R = Q + QP + Q + .. + Q + QP* "
},
{
"code": null,
"e": 1165,
"s": 1145,
"text": "Taking Q as common,"
},
{
"code": null,
"e": 1269,
"s": 1165,
"text": "R = Q( + P + + .. + + P*)\n = QP* [As + P + + .. + + P* represent \n the closure of P] "
},
{
"code": null,
"e": 1283,
"s": 1269,
"text": "Hence proved."
},
{
"code": null,
"e": 1348,
"s": 1283,
"text": "Thus, R = QP* is the unique solution of the equation R = Q + RP."
},
{
"code": null,
"e": 1402,
"s": 1348,
"text": "To understand this theorem, we will solve an example:"
},
{
"code": null,
"e": 1412,
"s": 1402,
"text": "Example –"
},
{
"code": null,
"e": 1468,
"s": 1412,
"text": "q1 = q1.0 + \nq2 = q1.1 + q2.0\nq3 = q2.1 + q3.0 + q3.1 "
},
{
"code": null,
"e": 1473,
"s": 1468,
"text": "Now,"
},
{
"code": null,
"e": 1579,
"s": 1473,
"text": "q1 = + q1.0\nq1 = .0* [By Arden's theorem]\nq1 = 0* [R = R]\n\n.'. q2 = 0*1 +q2.0\n q2 = 0*10* "
},
{
"code": null,
"e": 1640,
"s": 1579,
"text": "[Applying Arden’s theorem]. Hence, the value of q2 is 0*10*."
},
{
"code": null,
"e": 1653,
"s": 1640,
"text": "AllenDeAlpha"
},
{
"code": null,
"e": 1661,
"s": 1653,
"text": "GATE CS"
},
{
"code": null,
"e": 1694,
"s": 1661,
"text": "Theory of Computation & Automata"
}
] |
ranlib command in Linux with Examples
|
17 Apr, 2019
ranlib command in Linux is used to generate index to archive. ranlib generates an index to the contents of an archive and it will be stored in the archive. The index lists each symbol defined by a member of an archive which is simply relocatable object file. You may use nm -s or nm –print-armap to list all of this index. An archive with such an index speeds up the linking to the library and allows routines in the library to call each other without regard to their placement in the archive. The GNU ranlib program is another form of GNU ar; running ranlib is completely equivalent to running ar -s.
Syntax:
ranlib [--plugin name] [-DhHvVt] archive
Example: It will generate index to archive as shown in the below example.
Explanation: As you can see in above example we are archiving three files named main.o, point.o and rectangle.o to fruits.a and then using ranlib command generating an index to the contents of an archive and it will be stored in the archive.
Options:
–help: This option will show usage information for ranlib.ranlib --help
ranlib --help
–version: This option will show the version number of ranlib.ranlib --version
ranlib --version
-D : This option will operate in deterministic mode. The symbol map archive of member’s header will show zero for the UID, GID, and timestamp. When this option is being used, multiple runs will produce identical output files.Example:ranlib -D fruits.aExplanation: As you can see in above example we are archiving three files named main.o, point.o and rectangle.o to fruits.a and then using ranlib command with the option -D we are changing the mode of operation to deterministic and generating an index to the contents of an archive and it will stores it in the archive.
Example:
ranlib -D fruits.a
Explanation: As you can see in above example we are archiving three files named main.o, point.o and rectangle.o to fruits.a and then using ranlib command with the option -D we are changing the mode of operation to deterministic and generating an index to the contents of an archive and it will stores it in the archive.
-t : This option will update the timestamp of the symbol map of an archive.Example :ranlib -t fruits.a
Example :
ranlib -t fruits.a
-U: This option do not operate in deterministic mode. This is exactly the inverse of the -D option. The archive index will get actual UID, GID, timestamp, and file mode values. If binutils was configured without using –enable-deterministic-archives, then this mode is set by default.Example:ranlib -U fruits.a
Example:
ranlib -U fruits.a
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Apr, 2019"
},
{
"code": null,
"e": 630,
"s": 28,
"text": "ranlib command in Linux is used to generate index to archive. ranlib generates an index to the contents of an archive and it will be stored in the archive. The index lists each symbol defined by a member of an archive which is simply relocatable object file. You may use nm -s or nm –print-armap to list all of this index. An archive with such an index speeds up the linking to the library and allows routines in the library to call each other without regard to their placement in the archive. The GNU ranlib program is another form of GNU ar; running ranlib is completely equivalent to running ar -s."
},
{
"code": null,
"e": 638,
"s": 630,
"text": "Syntax:"
},
{
"code": null,
"e": 680,
"s": 638,
"text": "ranlib [--plugin name] [-DhHvVt] archive\n"
},
{
"code": null,
"e": 754,
"s": 680,
"text": "Example: It will generate index to archive as shown in the below example."
},
{
"code": null,
"e": 996,
"s": 754,
"text": "Explanation: As you can see in above example we are archiving three files named main.o, point.o and rectangle.o to fruits.a and then using ranlib command generating an index to the contents of an archive and it will be stored in the archive."
},
{
"code": null,
"e": 1005,
"s": 996,
"text": "Options:"
},
{
"code": null,
"e": 1077,
"s": 1005,
"text": "–help: This option will show usage information for ranlib.ranlib --help"
},
{
"code": null,
"e": 1091,
"s": 1077,
"text": "ranlib --help"
},
{
"code": null,
"e": 1169,
"s": 1091,
"text": "–version: This option will show the version number of ranlib.ranlib --version"
},
{
"code": null,
"e": 1186,
"s": 1169,
"text": "ranlib --version"
},
{
"code": null,
"e": 1757,
"s": 1186,
"text": "-D : This option will operate in deterministic mode. The symbol map archive of member’s header will show zero for the UID, GID, and timestamp. When this option is being used, multiple runs will produce identical output files.Example:ranlib -D fruits.aExplanation: As you can see in above example we are archiving three files named main.o, point.o and rectangle.o to fruits.a and then using ranlib command with the option -D we are changing the mode of operation to deterministic and generating an index to the contents of an archive and it will stores it in the archive."
},
{
"code": null,
"e": 1766,
"s": 1757,
"text": "Example:"
},
{
"code": null,
"e": 1785,
"s": 1766,
"text": "ranlib -D fruits.a"
},
{
"code": null,
"e": 2105,
"s": 1785,
"text": "Explanation: As you can see in above example we are archiving three files named main.o, point.o and rectangle.o to fruits.a and then using ranlib command with the option -D we are changing the mode of operation to deterministic and generating an index to the contents of an archive and it will stores it in the archive."
},
{
"code": null,
"e": 2208,
"s": 2105,
"text": "-t : This option will update the timestamp of the symbol map of an archive.Example :ranlib -t fruits.a"
},
{
"code": null,
"e": 2218,
"s": 2208,
"text": "Example :"
},
{
"code": null,
"e": 2237,
"s": 2218,
"text": "ranlib -t fruits.a"
},
{
"code": null,
"e": 2547,
"s": 2237,
"text": "-U: This option do not operate in deterministic mode. This is exactly the inverse of the -D option. The archive index will get actual UID, GID, timestamp, and file mode values. If binutils was configured without using –enable-deterministic-archives, then this mode is set by default.Example:ranlib -U fruits.a"
},
{
"code": null,
"e": 2556,
"s": 2547,
"text": "Example:"
},
{
"code": null,
"e": 2575,
"s": 2556,
"text": "ranlib -U fruits.a"
},
{
"code": null,
"e": 2589,
"s": 2575,
"text": "linux-command"
},
{
"code": null,
"e": 2609,
"s": 2589,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 2620,
"s": 2609,
"text": "Linux-Unix"
}
] |
Python | Shuffle two lists with same order - GeeksforGeeks
|
22 Feb, 2022
Sometimes, while working with Python list, we can have a problem in which we need to perform shuffle operation in list. This task is easy and there are straightforward functionalities available in Python to perform this. But sometimes, we need to shuffle two lists so that their shuffle orders are consistent. Let’s discuss a way in which this task can be performed.Method : Using zip() + shuffle() + * operator In this method, this task is performed in three steps. Firstly, the lists are zipped together using zip(). Next step is to perform shuffle using inbuilt shuffle() and last step is to unzip the lists to separate lists using * operator.
Python3
# Python3 code to demonstrate working of# Shuffle two lists with same order# Using zip() + * operator + shuffle()import random # initializing liststest_list1 = [6, 4, 8, 9, 10]test_list2 = [1, 2, 3, 4, 5] # printing listsprint(f"The original list 1 : {test_list1}")print(f"The original list 2 : {test_list2}") # Shuffle two lists with same order# Using zip() + * operator + shuffle()temp = list(zip(test_list1, test_list2))random.shuffle(temp)res1, res2 = zip(*temp)# res1 and res2 come out as tuples, and so must be converted to lists.res1, res2 = list(res1), list(res2) # Printing resultprint(f"List 1 after shuffle : {res1}")print(f"List 2 after shuffle : {res2}")
The original list 1 : [6, 4, 8, 9, 10]
The original list 2 : [1, 2, 3, 4, 5]
List 1 after shuffle : [6, 10, 4, 8, 9]
List 2 after shuffle : [1, 5, 2, 3, 4]
snny2b8fx3cw6oudpwqpr7xvo6nb98gq2qblbywl
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 26033,
"s": 26005,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 26682,
"s": 26033,
"text": "Sometimes, while working with Python list, we can have a problem in which we need to perform shuffle operation in list. This task is easy and there are straightforward functionalities available in Python to perform this. But sometimes, we need to shuffle two lists so that their shuffle orders are consistent. Let’s discuss a way in which this task can be performed.Method : Using zip() + shuffle() + * operator In this method, this task is performed in three steps. Firstly, the lists are zipped together using zip(). Next step is to perform shuffle using inbuilt shuffle() and last step is to unzip the lists to separate lists using * operator. "
},
{
"code": null,
"e": 26690,
"s": 26682,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Shuffle two lists with same order# Using zip() + * operator + shuffle()import random # initializing liststest_list1 = [6, 4, 8, 9, 10]test_list2 = [1, 2, 3, 4, 5] # printing listsprint(f\"The original list 1 : {test_list1}\")print(f\"The original list 2 : {test_list2}\") # Shuffle two lists with same order# Using zip() + * operator + shuffle()temp = list(zip(test_list1, test_list2))random.shuffle(temp)res1, res2 = zip(*temp)# res1 and res2 come out as tuples, and so must be converted to lists.res1, res2 = list(res1), list(res2) # Printing resultprint(f\"List 1 after shuffle : {res1}\")print(f\"List 2 after shuffle : {res2}\")",
"e": 27360,
"s": 26690,
"text": null
},
{
"code": null,
"e": 27518,
"s": 27360,
"text": " \nThe original list 1 : [6, 4, 8, 9, 10]\nThe original list 2 : [1, 2, 3, 4, 5]\nList 1 after shuffle : [6, 10, 4, 8, 9]\nList 2 after shuffle : [1, 5, 2, 3, 4]"
},
{
"code": null,
"e": 27561,
"s": 27520,
"text": "snny2b8fx3cw6oudpwqpr7xvo6nb98gq2qblbywl"
},
{
"code": null,
"e": 27582,
"s": 27561,
"text": "Python list-programs"
},
{
"code": null,
"e": 27589,
"s": 27582,
"text": "Python"
},
{
"code": null,
"e": 27605,
"s": 27589,
"text": "Python Programs"
},
{
"code": null,
"e": 27703,
"s": 27605,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27735,
"s": 27703,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27757,
"s": 27735,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27799,
"s": 27757,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27825,
"s": 27799,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27854,
"s": 27825,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27876,
"s": 27854,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27915,
"s": 27876,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27961,
"s": 27915,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27999,
"s": 27961,
"text": "Python | Convert a list to dictionary"
}
] |
Create Heatmap in R Using ggplot2 - GeeksforGeeks
|
29 Jul, 2021
A heatmap depicts the relationship between two attributes of a dataframe as a color-coded tile. A heatmap produces a grid with multiple attributes of the dataframe, representing the relationship between the two attributes taken at a time.
Dataset used: bestsellers
Let us first create a correlation matrix to understand the relation between different attributes, for this cor() function is used.
Syntax: cor(dataframe)
Note: This function fails when the dataframe consists of values apart from numeric values, so we will also use the sapply() method.
Example:
R
df <- read.csv("bestsellers.csv") cor(df[sapply(df, is.numeric)])
Output:
Now that we have a correlation matrix, we have to melt it in a form that a heatmap can be created. For this melt() function of reshape2 library is used.
Melting in R programming is done to organize the data. It is performed using melt() function which takes dataset and column values that have to be kept constant. Using melt(), dataframe is converted into a long format and stretches the data frame.
Syntax: melt(data, na.rm = FALSE, value.name = “value”)
Parameters:
data: represents dataset that has to be reshaped
na.rm: if TRUE, removes NA values from dataset
value.name: represents name of variable used to store values
Example:
R
library(ggplot2)library(reshape2) df <- read.csv("bestsellers.csv") data <- cor(df[sapply(df,is.numeric)]) data1 <- melt(data) head(data1)
Output:
To create a heatmap with the melted data so produced, we use geom_tile() function of the ggplot2 library. It is essentially used to create heatmaps.
Syntax: geom_tile(x,y,fill)
Parameter:
x: position on x-axis
y: position on y-axis
fill: numeric values that will be translated to colors
To this function, Var1 and Var2 of the melted dataframe are passed to x and y respectively. These represent the relation between attributes taken two at a time. To fill parameters provide, since that will be used to color-code the tiles based on some numeric value.
Example:
R
library(ggplot2)library(reshape2) df <- read.csv("bestsellers.csv") data <- cor(df[sapply(df,is.numeric)]) data1 <- melt(data) ggplot(data1, aes(x = Var1, y = Var2, fill = value))+geom_tile()
Output:
scale_fill_gradient(): adds extreme colors to the plot.
Syntax:
scale_fill_gradient(high, low)
Parameter:
low: color to highlight smaller values
high: color to highlight bigger values
R
library(ggplot2)library(reshape2) df<-read.csv("bestsellers.csv") data<-cor(df[sapply(df,is.numeric)]) data1<-melt(data) ggplot(data1,aes(x = Var1, y = Var2, fill = value))+geom_tile()+scale_fill_gradient(high = "green", low = "white")
Output:
scale_fill_distiller(): It used to customize according to ColorBrewer palette.
Syntax: scale_fill_distiller(palette)
R
library(ggplot2)library(reshape2) df<-read.csv("bestsellers.csv") data<-cor(df[sapply(df, is.numeric)]) data1<-melt(data) ggplot(data1,aes(x = Var1, y = Var2,fill = value))+geom_tile() + scale_fill_distiller(palette = "Spectral")
Output:
scale_fill_viridis(): to use viridis. In this function, discrete is set to FALSE.
Syntax: scale_fill_viridis(discrete)
R
library(ggplot2)library(reshape2)library(viridis) df<-read.csv("bestsellers.csv") data<-cor(df[sapply(df,is.numeric)]) data1<-melt(data) ggplot(data1, aes(x = Var1, y = Var2, fill = value))+geom_tile() + scale_fill_viridis(discrete = FALSE)
Output:
A heatmap can be reordered by reordering its y-elements. This can be done by reorder().
Syntax: reorder(y_value,value)
Where, Value is the element to reorder by.
R
library(ggplot2)library(reshape2) df<-read.csv("bestsellers.csv") data<-cor(df[sapply(df,is.numeric)]) data1<-melt(data) ggplot(data1,aes(x = Var1, y = reorder(Var2, value), fill = value)) + geom_tile()
Output:
The title can be added to a heatmap to make it descriptive. It can be done by using ggtitle().
Syntax: ggtitle(“title”)
R
library(ggplot2)library(reshape2) df<-read.csv("bestsellers.csv") data<-cor(df[sapply(df,is.numeric)]) data1<-melt(data) ggplot(data1, aes(x = Var1, y = Var2, fill = value))+geom_tile()+ggtitle("Bestsellers")
Output:
Labels of the heatmap can also be removed to show only the corresponding values it is representing. If we remove labels, keeping ticks doesn’t make sense. We can use attributes of theme() function axis.ticks and axis.text and set them to element_blank().
Syntax: theme(axis.ticks = element_blank(), axis.text = element_blank())
R
library(ggplot2)library(reshape2) df<-read.csv("bestsellers.csv") data<-cor(df[sapply(df,is.numeric)]) data1<-melt(data) ggplot(data1,aes(x=Var1,y=Var2,fill=value))+geom_tile()+ theme(axis.ticks = element_blank(), axis.text = element_blank())
Output:
simranarora5sos
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
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Logistic Regression in R Programming
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
How to change the order of bars in bar chart in R ?
R - if statement
Replace Specific Characters in String in R
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 25481,
"s": 25242,
"text": "A heatmap depicts the relationship between two attributes of a dataframe as a color-coded tile. A heatmap produces a grid with multiple attributes of the dataframe, representing the relationship between the two attributes taken at a time."
},
{
"code": null,
"e": 25507,
"s": 25481,
"text": "Dataset used: bestsellers"
},
{
"code": null,
"e": 25638,
"s": 25507,
"text": "Let us first create a correlation matrix to understand the relation between different attributes, for this cor() function is used."
},
{
"code": null,
"e": 25661,
"s": 25638,
"text": "Syntax: cor(dataframe)"
},
{
"code": null,
"e": 25793,
"s": 25661,
"text": "Note: This function fails when the dataframe consists of values apart from numeric values, so we will also use the sapply() method."
},
{
"code": null,
"e": 25802,
"s": 25793,
"text": "Example:"
},
{
"code": null,
"e": 25804,
"s": 25802,
"text": "R"
},
{
"code": "df <- read.csv(\"bestsellers.csv\") cor(df[sapply(df, is.numeric)])",
"e": 25870,
"s": 25804,
"text": null
},
{
"code": null,
"e": 25878,
"s": 25870,
"text": "Output:"
},
{
"code": null,
"e": 26031,
"s": 25878,
"text": "Now that we have a correlation matrix, we have to melt it in a form that a heatmap can be created. For this melt() function of reshape2 library is used."
},
{
"code": null,
"e": 26279,
"s": 26031,
"text": "Melting in R programming is done to organize the data. It is performed using melt() function which takes dataset and column values that have to be kept constant. Using melt(), dataframe is converted into a long format and stretches the data frame."
},
{
"code": null,
"e": 26335,
"s": 26279,
"text": "Syntax: melt(data, na.rm = FALSE, value.name = “value”)"
},
{
"code": null,
"e": 26347,
"s": 26335,
"text": "Parameters:"
},
{
"code": null,
"e": 26396,
"s": 26347,
"text": "data: represents dataset that has to be reshaped"
},
{
"code": null,
"e": 26443,
"s": 26396,
"text": "na.rm: if TRUE, removes NA values from dataset"
},
{
"code": null,
"e": 26504,
"s": 26443,
"text": "value.name: represents name of variable used to store values"
},
{
"code": null,
"e": 26513,
"s": 26504,
"text": "Example:"
},
{
"code": null,
"e": 26515,
"s": 26513,
"text": "R"
},
{
"code": "library(ggplot2)library(reshape2) df <- read.csv(\"bestsellers.csv\") data <- cor(df[sapply(df,is.numeric)]) data1 <- melt(data) head(data1)",
"e": 26654,
"s": 26515,
"text": null
},
{
"code": null,
"e": 26663,
"s": 26654,
"text": " Output:"
},
{
"code": null,
"e": 26814,
"s": 26665,
"text": "To create a heatmap with the melted data so produced, we use geom_tile() function of the ggplot2 library. It is essentially used to create heatmaps."
},
{
"code": null,
"e": 26842,
"s": 26814,
"text": "Syntax: geom_tile(x,y,fill)"
},
{
"code": null,
"e": 26853,
"s": 26842,
"text": "Parameter:"
},
{
"code": null,
"e": 26875,
"s": 26853,
"text": "x: position on x-axis"
},
{
"code": null,
"e": 26897,
"s": 26875,
"text": "y: position on y-axis"
},
{
"code": null,
"e": 26952,
"s": 26897,
"text": "fill: numeric values that will be translated to colors"
},
{
"code": null,
"e": 27218,
"s": 26952,
"text": "To this function, Var1 and Var2 of the melted dataframe are passed to x and y respectively. These represent the relation between attributes taken two at a time. To fill parameters provide, since that will be used to color-code the tiles based on some numeric value."
},
{
"code": null,
"e": 27227,
"s": 27218,
"text": "Example:"
},
{
"code": null,
"e": 27229,
"s": 27227,
"text": "R"
},
{
"code": "library(ggplot2)library(reshape2) df <- read.csv(\"bestsellers.csv\") data <- cor(df[sapply(df,is.numeric)]) data1 <- melt(data) ggplot(data1, aes(x = Var1, y = Var2, fill = value))+geom_tile()",
"e": 27455,
"s": 27229,
"text": null
},
{
"code": null,
"e": 27465,
"s": 27455,
"text": " Output: "
},
{
"code": null,
"e": 27521,
"s": 27465,
"text": "scale_fill_gradient(): adds extreme colors to the plot."
},
{
"code": null,
"e": 27529,
"s": 27521,
"text": "Syntax:"
},
{
"code": null,
"e": 27560,
"s": 27529,
"text": "scale_fill_gradient(high, low)"
},
{
"code": null,
"e": 27571,
"s": 27560,
"text": "Parameter:"
},
{
"code": null,
"e": 27610,
"s": 27571,
"text": "low: color to highlight smaller values"
},
{
"code": null,
"e": 27649,
"s": 27610,
"text": "high: color to highlight bigger values"
},
{
"code": null,
"e": 27651,
"s": 27649,
"text": "R"
},
{
"code": "library(ggplot2)library(reshape2) df<-read.csv(\"bestsellers.csv\") data<-cor(df[sapply(df,is.numeric)]) data1<-melt(data) ggplot(data1,aes(x = Var1, y = Var2, fill = value))+geom_tile()+scale_fill_gradient(high = \"green\", low = \"white\")",
"e": 27887,
"s": 27651,
"text": null
},
{
"code": null,
"e": 27896,
"s": 27887,
"text": " Output:"
},
{
"code": null,
"e": 27975,
"s": 27896,
"text": "scale_fill_distiller(): It used to customize according to ColorBrewer palette."
},
{
"code": null,
"e": 28013,
"s": 27975,
"text": "Syntax: scale_fill_distiller(palette)"
},
{
"code": null,
"e": 28015,
"s": 28013,
"text": "R"
},
{
"code": "library(ggplot2)library(reshape2) df<-read.csv(\"bestsellers.csv\") data<-cor(df[sapply(df, is.numeric)]) data1<-melt(data) ggplot(data1,aes(x = Var1, y = Var2,fill = value))+geom_tile() + scale_fill_distiller(palette = \"Spectral\")",
"e": 28245,
"s": 28015,
"text": null
},
{
"code": null,
"e": 28254,
"s": 28245,
"text": " Output:"
},
{
"code": null,
"e": 28336,
"s": 28254,
"text": "scale_fill_viridis(): to use viridis. In this function, discrete is set to FALSE."
},
{
"code": null,
"e": 28373,
"s": 28336,
"text": "Syntax: scale_fill_viridis(discrete)"
},
{
"code": null,
"e": 28375,
"s": 28373,
"text": "R"
},
{
"code": "library(ggplot2)library(reshape2)library(viridis) df<-read.csv(\"bestsellers.csv\") data<-cor(df[sapply(df,is.numeric)]) data1<-melt(data) ggplot(data1, aes(x = Var1, y = Var2, fill = value))+geom_tile() + scale_fill_viridis(discrete = FALSE)",
"e": 28616,
"s": 28375,
"text": null
},
{
"code": null,
"e": 28624,
"s": 28616,
"text": "Output:"
},
{
"code": null,
"e": 28712,
"s": 28624,
"text": "A heatmap can be reordered by reordering its y-elements. This can be done by reorder()."
},
{
"code": null,
"e": 28743,
"s": 28712,
"text": "Syntax: reorder(y_value,value)"
},
{
"code": null,
"e": 28786,
"s": 28743,
"text": "Where, Value is the element to reorder by."
},
{
"code": null,
"e": 28788,
"s": 28786,
"text": "R"
},
{
"code": "library(ggplot2)library(reshape2) df<-read.csv(\"bestsellers.csv\") data<-cor(df[sapply(df,is.numeric)]) data1<-melt(data) ggplot(data1,aes(x = Var1, y = reorder(Var2, value), fill = value)) + geom_tile()",
"e": 29007,
"s": 28788,
"text": null
},
{
"code": null,
"e": 29015,
"s": 29007,
"text": "Output:"
},
{
"code": null,
"e": 29110,
"s": 29015,
"text": "The title can be added to a heatmap to make it descriptive. It can be done by using ggtitle()."
},
{
"code": null,
"e": 29135,
"s": 29110,
"text": "Syntax: ggtitle(“title”)"
},
{
"code": null,
"e": 29137,
"s": 29135,
"text": "R"
},
{
"code": "library(ggplot2)library(reshape2) df<-read.csv(\"bestsellers.csv\") data<-cor(df[sapply(df,is.numeric)]) data1<-melt(data) ggplot(data1, aes(x = Var1, y = Var2, fill = value))+geom_tile()+ggtitle(\"Bestsellers\")",
"e": 29346,
"s": 29137,
"text": null
},
{
"code": null,
"e": 29354,
"s": 29346,
"text": "Output:"
},
{
"code": null,
"e": 29610,
"s": 29354,
"text": "Labels of the heatmap can also be removed to show only the corresponding values it is representing. If we remove labels, keeping ticks doesn’t make sense. We can use attributes of theme() function axis.ticks and axis.text and set them to element_blank(). "
},
{
"code": null,
"e": 29683,
"s": 29610,
"text": "Syntax: theme(axis.ticks = element_blank(), axis.text = element_blank())"
},
{
"code": null,
"e": 29685,
"s": 29683,
"text": "R"
},
{
"code": "library(ggplot2)library(reshape2) df<-read.csv(\"bestsellers.csv\") data<-cor(df[sapply(df,is.numeric)]) data1<-melt(data) ggplot(data1,aes(x=Var1,y=Var2,fill=value))+geom_tile()+ theme(axis.ticks = element_blank(), axis.text = element_blank())",
"e": 29936,
"s": 29685,
"text": null
},
{
"code": null,
"e": 29944,
"s": 29936,
"text": "Output:"
},
{
"code": null,
"e": 29960,
"s": 29944,
"text": "simranarora5sos"
},
{
"code": null,
"e": 29967,
"s": 29960,
"text": "Picked"
},
{
"code": null,
"e": 29976,
"s": 29967,
"text": "R-ggplot"
},
{
"code": null,
"e": 29987,
"s": 29976,
"text": "R Language"
},
{
"code": null,
"e": 30085,
"s": 29987,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30094,
"s": 30085,
"text": "Comments"
},
{
"code": null,
"e": 30107,
"s": 30094,
"text": "Old Comments"
},
{
"code": null,
"e": 30159,
"s": 30107,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30197,
"s": 30159,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30232,
"s": 30197,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30290,
"s": 30232,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30327,
"s": 30290,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 30364,
"s": 30327,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 30413,
"s": 30364,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30465,
"s": 30413,
"text": "How to change the order of bars in bar chart in R ?"
},
{
"code": null,
"e": 30482,
"s": 30465,
"text": "R - if statement"
}
] |
Python Parser for command line options
|
Very often we need to pass arguments to Python script when executing from command line. However, the script raises exception when parameters needed are not provided in equal number or type or order. That’s where the need to properly parse the command line argument occurs.
The argparse module provides tools for writing very easy to use command line interfaces. It handles how to parse the arguments collected in sys.argv list, automatically generate help and issues error message when invalid options are given.
First step to desing the command line interface is to set up parser object. This is done by ArgumentParser() function in argparse module. The function can be given an explanatory string as description parameter.
To start with our script will be executed from command line without any arguments. Still use parse_args() method of parser object, which does nothing because there aren’t any arguments given.
import argparse
parser = argparse.ArgumentParser(description="sample argument parser")
args=parser.parse_args()
When above script is run
C:\python36>python argparser1.py
C:\python36>python argparser1.py --help
usage: argparser1.py [-h]
sample argument parser
optional arguments:
-h, --help show this help message and exit
The second command line usage gives –help option which produces a help message as shown. The –help parameter is available by default.
Now let us define an argument which is mandatory for the script to run and if not given script should throw error. Here we define argument ‘user’ by add_argument() method.
import argparse
parser=argparse.ArgumentParser(description="sample argument parser")
parser.add_argument("user")
args = parser.parse_args()
if args.user=="Admin":
print ("Hello Admin")
else:
print ("Hello Guest")
This script’s help now shows one positional argument in the form of ‘user’. The program checks if it’s value is ‘Admin’ or not and prints corresponding message.
C:\python36>python argparser1.py --help
usage: argparser1.py [-h] user
sample argument parser
positional arguments:
user
optional arguments:
-h, --help show this help message and exit
C:\python36>python argparser1.py Admin
Hello Admin
C:\python36>python argparser1.py temp
Hello Guest
We can assign default value to an argument in add_argument() method.
import argparse
parser=argparse.ArgumentParser(description="sample argument parser")
parser.add_argument("user", nargs='?',default="Admin")
args=parser.parse_args()
if args.user=="Admin":
print ("Hello Admin")
else:
print ("Hello Guest")
Here nargs is the number of command-line arguments that should be consumed. '?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced.
C:\python36>python argparser1.py
Hello Admin
C:\python36>python argparser1.py Admin
Hello Admin
C:\python36>python argparser1.py test
Hello Guest
By default, all arguments are treated as strings. To explicitly mention type of argument, use type parameter in the add_argument() method. All Python data types are valid values of type.
import argparse
parser=argparse.ArgumentParser(description="add numbers")
parser.add_argument("first", type=int)
parser.add_argument("second", type=int)
args = parser.parse_args()
x = args.first
y = args.second
z = x+y
print ('addition of {} and {} = {}'.format(x,y,z))
C:\python36>python argparser2.py 2 3
addition of 2 and 3 = 5
In above examples, the arguments are mandatory. To add optional argument, prefix its name by double dash --. In following case surname argument is optional because it is prefixed by double dash (--surname)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument("--surname")
args = parser.parse_args()
print ("My name is ", args.name, end=' ')
if args.surname:
print (args.surname)
A one letter name of argument prefixed by single dash acts as a short name option.
C:\python36>python argparser3.py Malhar
My name is Malhar
C:\python36>python argparser3.py Malhar --surname Lathkar
My name is Malhar Lathkar
parser.add_argument("-s","--surname")
If it is desired that an argument should value only from a defined list, it is defined as choices parameter.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("sub", choices=['Physics', 'Maths', 'Biology'])
args=parser.parse_args()
print ("My subject is ", args.sub)
Note that if value of parameter is not from the list, invalid choice error is displayed.
C:\python36>python argparser4.py Physics
My subject is Physics
C:\python36>python argparser4.py English
usage: argparser4.py [-h] {Physics,Maths,Biology}
argparser4.py: error: argument sub: invalid choice: 'English' (choose from 'Physics', 'Maths', 'Biology')
|
[
{
"code": null,
"e": 1335,
"s": 1062,
"text": "Very often we need to pass arguments to Python script when executing from command line. However, the script raises exception when parameters needed are not provided in equal number or type or order. That’s where the need to properly parse the command line argument occurs."
},
{
"code": null,
"e": 1575,
"s": 1335,
"text": "The argparse module provides tools for writing very easy to use command line interfaces. It handles how to parse the arguments collected in sys.argv list, automatically generate help and issues error message when invalid options are given."
},
{
"code": null,
"e": 1787,
"s": 1575,
"text": "First step to desing the command line interface is to set up parser object. This is done by ArgumentParser() function in argparse module. The function can be given an explanatory string as description parameter."
},
{
"code": null,
"e": 1979,
"s": 1787,
"text": "To start with our script will be executed from command line without any arguments. Still use parse_args() method of parser object, which does nothing because there aren’t any arguments given."
},
{
"code": null,
"e": 2091,
"s": 1979,
"text": "import argparse\nparser = argparse.ArgumentParser(description=\"sample argument parser\")\nargs=parser.parse_args()"
},
{
"code": null,
"e": 2116,
"s": 2091,
"text": "When above script is run"
},
{
"code": null,
"e": 2301,
"s": 2116,
"text": "C:\\python36>python argparser1.py\nC:\\python36>python argparser1.py --help\nusage: argparser1.py [-h]\nsample argument parser\noptional arguments:\n-h, --help show this help message and exit"
},
{
"code": null,
"e": 2435,
"s": 2301,
"text": "The second command line usage gives –help option which produces a help message as shown. The –help parameter is available by default."
},
{
"code": null,
"e": 2607,
"s": 2435,
"text": "Now let us define an argument which is mandatory for the script to run and if not given script should throw error. Here we define argument ‘user’ by add_argument() method."
},
{
"code": null,
"e": 2820,
"s": 2607,
"text": "import argparse\nparser=argparse.ArgumentParser(description=\"sample argument parser\")\nparser.add_argument(\"user\")\nargs = parser.parse_args()\nif args.user==\"Admin\":\nprint (\"Hello Admin\")\nelse:\nprint (\"Hello Guest\")"
},
{
"code": null,
"e": 2981,
"s": 2820,
"text": "This script’s help now shows one positional argument in the form of ‘user’. The program checks if it’s value is ‘Admin’ or not and prints corresponding message."
},
{
"code": null,
"e": 3266,
"s": 2981,
"text": "C:\\python36>python argparser1.py --help\nusage: argparser1.py [-h] user\nsample argument parser\npositional arguments:\nuser\noptional arguments:\n-h, --help show this help message and exit\nC:\\python36>python argparser1.py Admin\nHello Admin\nC:\\python36>python argparser1.py temp\nHello Guest"
},
{
"code": null,
"e": 3335,
"s": 3266,
"text": "We can assign default value to an argument in add_argument() method."
},
{
"code": null,
"e": 3573,
"s": 3335,
"text": "import argparse\nparser=argparse.ArgumentParser(description=\"sample argument parser\")\nparser.add_argument(\"user\", nargs='?',default=\"Admin\")\nargs=parser.parse_args()\nif args.user==\"Admin\":\nprint (\"Hello Admin\")\nelse:\nprint (\"Hello Guest\")"
},
{
"code": null,
"e": 3831,
"s": 3573,
"text": "Here nargs is the number of command-line arguments that should be consumed. '?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced."
},
{
"code": null,
"e": 3977,
"s": 3831,
"text": "C:\\python36>python argparser1.py\nHello Admin\nC:\\python36>python argparser1.py Admin\nHello Admin\nC:\\python36>python argparser1.py test\nHello Guest"
},
{
"code": null,
"e": 4164,
"s": 3977,
"text": "By default, all arguments are treated as strings. To explicitly mention type of argument, use type parameter in the add_argument() method. All Python data types are valid values of type."
},
{
"code": null,
"e": 4495,
"s": 4164,
"text": "import argparse\nparser=argparse.ArgumentParser(description=\"add numbers\")\nparser.add_argument(\"first\", type=int)\nparser.add_argument(\"second\", type=int)\nargs = parser.parse_args()\nx = args.first\ny = args.second\nz = x+y\nprint ('addition of {} and {} = {}'.format(x,y,z))\nC:\\python36>python argparser2.py 2 3\naddition of 2 and 3 = 5"
},
{
"code": null,
"e": 4701,
"s": 4495,
"text": "In above examples, the arguments are mandatory. To add optional argument, prefix its name by double dash --. In following case surname argument is optional because it is prefixed by double dash (--surname)"
},
{
"code": null,
"e": 4920,
"s": 4701,
"text": "import argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"name\")\nparser.add_argument(\"--surname\")\nargs = parser.parse_args()\nprint (\"My name is \", args.name, end=' ')\nif args.surname:\nprint (args.surname)"
},
{
"code": null,
"e": 5003,
"s": 4920,
"text": "A one letter name of argument prefixed by single dash acts as a short name option."
},
{
"code": null,
"e": 5183,
"s": 5003,
"text": "C:\\python36>python argparser3.py Malhar\nMy name is Malhar\nC:\\python36>python argparser3.py Malhar --surname Lathkar\nMy name is Malhar Lathkar\nparser.add_argument(\"-s\",\"--surname\")"
},
{
"code": null,
"e": 5292,
"s": 5183,
"text": "If it is desired that an argument should value only from a defined list, it is defined as choices parameter."
},
{
"code": null,
"e": 5471,
"s": 5292,
"text": "import argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"sub\", choices=['Physics', 'Maths', 'Biology'])\nargs=parser.parse_args()\nprint (\"My subject is \", args.sub)"
},
{
"code": null,
"e": 5560,
"s": 5471,
"text": "Note that if value of parameter is not from the list, invalid choice error is displayed."
},
{
"code": null,
"e": 5820,
"s": 5560,
"text": "C:\\python36>python argparser4.py Physics\nMy subject is Physics\nC:\\python36>python argparser4.py English\nusage: argparser4.py [-h] {Physics,Maths,Biology}\nargparser4.py: error: argument sub: invalid choice: 'English' (choose from 'Physics', 'Maths', 'Biology')"
}
] |
Java Regular Expression that doesn't contain a certain String.
|
import java.util.regex.*;
class PatternMatch{
public static void main(String args[]) {
String content = "I am a student";
String string = ".*boy.*";
boolean isMatch = Pattern.matches(string,content);
System.out.println("The line contains 'boy'?"+ isMatch);
}
}
the line contains 'boy'?false
It is used to check if the whole text matches a pattern. Its output is boolean. It returns true if match is found otherwise false.This is one of simplest and easiest way of searching a String in a text using Regex .There is a another method compile() , if you want to do a CASE INSENSITIVE search or want to do search multiple occurrences it can be used.
For above example it will be then −
String content = "I am a student";
String string = ".*BoY.";
Pattern pattern = Pattern.compile(string, Pattern.CASE_INSENSITIVE);
|
[
{
"code": null,
"e": 1353,
"s": 1062,
"text": "import java.util.regex.*;\nclass PatternMatch{\n public static void main(String args[]) {\n String content = \"I am a student\";\n String string = \".*boy.*\";\n boolean isMatch = Pattern.matches(string,content);\n System.out.println(\"The line contains 'boy'?\"+ isMatch);\n }\n}"
},
{
"code": null,
"e": 1383,
"s": 1353,
"text": "the line contains 'boy'?false"
},
{
"code": null,
"e": 1738,
"s": 1383,
"text": "It is used to check if the whole text matches a pattern. Its output is boolean. It returns true if match is found otherwise false.This is one of simplest and easiest way of searching a String in a text using Regex .There is a another method compile() , if you want to do a CASE INSENSITIVE search or want to do search multiple occurrences it can be used."
},
{
"code": null,
"e": 1774,
"s": 1738,
"text": "For above example it will be then −"
},
{
"code": null,
"e": 1904,
"s": 1774,
"text": "String content = \"I am a student\";\nString string = \".*BoY.\";\nPattern pattern = Pattern.compile(string, Pattern.CASE_INSENSITIVE);"
}
] |
How to add background Image to JFrame in Java
|
To add background image to JFrame, use the getImage() method of the Image class −
Image img = Toolkit.getDefaultToolkit().getImage("E:\\rahul.jpg");
Now, draw the image −
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}
The following is an example to add Background Image to JFrame −
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.IOException;
import javax.swing.JPanel;
public class SwingDemo extends javax.swing.JFrame {
Image img = Toolkit.getDefaultToolkit().getImage("E:\\rahul.jpg");
public SwingDemo() throws IOException {
this.setContentPane(new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}
});
pack();
setVisible(true);
}
public static void main(String[] args) throws Exception {
new SwingDemo();
}
}
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "To add background image to JFrame, use the getImage() method of the Image class −"
},
{
"code": null,
"e": 1211,
"s": 1144,
"text": "Image img = Toolkit.getDefaultToolkit().getImage(\"E:\\\\rahul.jpg\");"
},
{
"code": null,
"e": 1233,
"s": 1211,
"text": "Now, draw the image −"
},
{
"code": null,
"e": 1337,
"s": 1233,
"text": "public void paintComponent(Graphics g) {\n super.paintComponent(g);\n g.drawImage(img, 0, 0, null);\n}"
},
{
"code": null,
"e": 1401,
"s": 1337,
"text": "The following is an example to add Background Image to JFrame −"
},
{
"code": null,
"e": 2039,
"s": 1401,
"text": "import java.awt.Graphics;\nimport java.awt.Image;\nimport java.awt.Toolkit;\nimport java.io.IOException;\nimport javax.swing.JPanel;\npublic class SwingDemo extends javax.swing.JFrame {\n Image img = Toolkit.getDefaultToolkit().getImage(\"E:\\\\rahul.jpg\");\n public SwingDemo() throws IOException {\n this.setContentPane(new JPanel() {\n @Override\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n g.drawImage(img, 0, 0, null);\n }\n });\n pack();\n setVisible(true);\n }\n public static void main(String[] args) throws Exception {\n new SwingDemo();\n }\n}"
}
] |
List of Keywords in Python Programming
|
The keyword module in Python's standard library allows a Python program to determine if a string is a keyword.
keyword.iskeyword(s): This function returns true if s is a Python keyword.
keyword.kwlist: This attribute returns Sequence containing all the keywords defined for the interpreter. If any keywords are to be appearing in future versions, these will be included as well.
>>> import keyword
>>> kwlist = keyword.kwlist
>>> kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
>>> kw = input('enter a keyword..')
enter a keyword..catch
>>> kw in kwlist
False
>>> kw = input('enter a keyword..')
enter a keyword..import
>>> kw in kwlist
True
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "The keyword module in Python's standard library allows a Python program to determine if a string is a keyword."
},
{
"code": null,
"e": 1248,
"s": 1173,
"text": "keyword.iskeyword(s): This function returns true if s is a Python keyword."
},
{
"code": null,
"e": 1441,
"s": 1248,
"text": "keyword.kwlist: This attribute returns Sequence containing all the keywords defined for the interpreter. If any keywords are to be appearing in future versions, these will be included as well."
},
{
"code": null,
"e": 1959,
"s": 1441,
"text": ">>> import keyword\n>>> kwlist = keyword.kwlist\n>>> kwlist\n['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',\n'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',\n'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',\n'while', 'with', 'yield']\n>>> kw = input('enter a keyword..')\nenter a keyword..catch\n>>> kw in kwlist\nFalse\n>>> kw = input('enter a keyword..')\nenter a keyword..import\n>>> kw in kwlist\nTrue"
}
] |
Java Program to compare two sets
|
Let’s say the following is our 1st Set:
String arr[] = { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
Set<String> set1 = new HashSet<String>(Arrays.asList(arr));
Let’s say the following is our 2nd Set:
arr = new String[] { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
Set<String> set2 = new HashSet<String>(Arrays.asList(arr));
Now let us compare the two sets. TRUE return value means both the sets are equals, whereas FALSE is
returned:
set1.equals(set2)
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
public static void main(String[] a) {
String arr[] = { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
Set<String> set1 = new HashSet<String>(Arrays.asList(arr));
arr = new String[] { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
Set<String> set2 = new HashSet<String>(Arrays.asList(arr));
System.out.println("Both the sets are equal? = "+set1.equals(set2));
}
}
Both the sets are equal? = true
|
[
{
"code": null,
"e": 1102,
"s": 1062,
"text": "Let’s say the following is our 1st Set:"
},
{
"code": null,
"e": 1231,
"s": 1102,
"text": "String arr[] = { \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\" };\nSet<String> set1 = new HashSet<String>(Arrays.asList(arr));"
},
{
"code": null,
"e": 1271,
"s": 1231,
"text": "Let’s say the following is our 2nd Set:"
},
{
"code": null,
"e": 1404,
"s": 1271,
"text": "arr = new String[] { \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\" };\nSet<String> set2 = new HashSet<String>(Arrays.asList(arr));"
},
{
"code": null,
"e": 1514,
"s": 1404,
"text": "Now let us compare the two sets. TRUE return value means both the sets are equals, whereas FALSE is\nreturned:"
},
{
"code": null,
"e": 1532,
"s": 1514,
"text": "set1.equals(set2)"
},
{
"code": null,
"e": 2034,
"s": 1532,
"text": "import java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Set;\npublic class Demo {\n public static void main(String[] a) {\n String arr[] = { \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\" };\n Set<String> set1 = new HashSet<String>(Arrays.asList(arr));\n arr = new String[] { \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\" };\n Set<String> set2 = new HashSet<String>(Arrays.asList(arr));\n System.out.println(\"Both the sets are equal? = \"+set1.equals(set2));\n }\n}"
},
{
"code": null,
"e": 2066,
"s": 2034,
"text": "Both the sets are equal? = true"
}
] |
Convert the string into palindrome string by changing only one character - GeeksforGeeks
|
09 Apr, 2021
Given a string str. Check if it is possible to convert the string into palindrome string by changing only one character.Examples:
Input : str = "abccaa"
Output : Yes
We can change the second last character
i.e. 'a' to 'b' to make it palindrome string
Input : str = "abbcca"
Output : No
We can not convert the string into palindrome
string by changing only one character.
Approach : The idea is simple, we check character str[i] with str[n-i-1]. If there is a mismatch, we increment count. If count of mismatches exceed 1, we return false. Else we return true.Below is the implementation of above idea :
C++
Java
Python3
C#
PHP
Javascript
// CPP program to Check if it is// possible to convert the string// into palindrome string by changing// only one character.#include<bits/stdc++.h>using namespace std; // Function to check if it is possible// to convert the string into palindromebool checkPalindrome(string str){ int n = str.length(); // Counting number of characters // that should be changed. int count = 0; for (int i = 0; i < n/2; ++i) if (str[i] != str[n - i - 1]) ++count; // If count of changes is less than // or equal to 1 return (count <= 1);} // Driver function.int main(){ string str = "abccaa"; if (checkPalindrome(str)) cout << "Yes" << endl; else cout << "No" << endl; return 0;}
// Java program to Check if it is// possible to convert the string// into palindrome string by changing// only one character.import java.io.*; class GFG { // Function to check if it is possible // to convert the string into palindrome static boolean checkPalindrome(String str){ int n = str.length(); // Counting number of characters // that should be changed. int count = 0; for (int i = 0; i < n/2; ++i) if (str.charAt(i) != str.charAt(n - i - 1)) ++count; // If count of changes is less than // or equal to 1 return (count <= 1); } // Driver Function public static void main(String[] args) { String str = "abccaa"; if (checkPalindrome(str)) System.out.println("Yes"); else System.out.println("No"); } } // This code is contributed by vt_m
# Python program to Check# if it is possible to# convert the string into# palindrome string by# changing only one character. # Function to check if# it is possible to# convert the string# into palindromedef checkPalindrome(str) : n = len(str) # Counting number of # characters that # should be changed. count = 0 for i in range(0, int(n / 2)) : if (str[i] != str[n - i - 1]) : count = count + 1 # If count of changes # is less than # or equal to 1 if(count <= 1) : return True else : return False # Driver Codestr = "abccaa"if (checkPalindrome(str)) : print ("Yes")else : print ("No") # This code is contributed by# Manish Shaw(manishshaw1)
// C# program to Check if it is// possible to convert the string// into palindrome string by changing// only one character.using System; class GFG { // Function to check if it is possible // to convert the string into palindrome static bool checkPalindrome(string str){ int n = str.Length; // Counting number of characters // that should be changed. int count = 0; for (int i = 0; i < n / 2; ++i) if (str[i] != str[n - i - 1]) ++count; // If count of changes is less than // or equal to 1 return (count <= 1); } // Driver Function public static void Main() { string str = "abccaa"; if (checkPalindrome(str)) Console.WriteLine("Yes"); else Console.WriteLine("No"); } } // This code is contributed by vt_m
<?php// PHP program to Check if it is// possible to convert the string// into palindrome string by changing// only one character. // Function to check if it is possible// to convert the string into palindromefunction checkPalindrome($str){ $n = strlen($str); // Counting number of characters // that should be changed. $count = 0; for ($i = 0; $i < $n/2; ++$i) if ($str[$i] != $str[$n - $i - 1]) ++$count; // If count of changes // is less than // or equal to 1 return ($count <= 1);} // Driver Code{ $str = "abccaa"; if (checkPalindrome($str)) echo "Yes" ; else echo "No" ; return 0;} // This code is contributed by nitin mittal.?>
<script> // Javascript program to Check if it is // possible to convert the string // into palindrome string by changing // only one character. // Function to check if it is possible // to convert the string into palindrome function checkPalindrome(str){ let n = str.length; // Counting number of characters // that should be changed. let count = 0; for (let i = 0; i < parseInt(n/2, 10); ++i) if (str[i] != str[n - i - 1]) ++count; // If count of changes is less than // or equal to 1 return (count <= 1); } let str = "abccaa"; if (checkPalindrome(str)) document.write("Yes"); else document.write("No"); // This code is contributed by divyesh072019.</script>
Output:
Yes
YouTubeGeeksforGeeks502K subscribersConvert the string into palindrome string by changing only one character | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:41•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0h7eK2NUKow" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
nitin mittal
manishshaw1
Akanksha_Rai
divyesh072019
palindrome
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Reverse words in a given string
Top 50 String Coding Problems for Interviews
|
[
{
"code": null,
"e": 24862,
"s": 24834,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 24994,
"s": 24862,
"text": "Given a string str. Check if it is possible to convert the string into palindrome string by changing only one character.Examples: "
},
{
"code": null,
"e": 25236,
"s": 24994,
"text": "Input : str = \"abccaa\"\nOutput : Yes\nWe can change the second last character\ni.e. 'a' to 'b' to make it palindrome string\n\nInput : str = \"abbcca\"\nOutput : No\nWe can not convert the string into palindrome\nstring by changing only one character."
},
{
"code": null,
"e": 25472,
"s": 25238,
"text": "Approach : The idea is simple, we check character str[i] with str[n-i-1]. If there is a mismatch, we increment count. If count of mismatches exceed 1, we return false. Else we return true.Below is the implementation of above idea : "
},
{
"code": null,
"e": 25476,
"s": 25472,
"text": "C++"
},
{
"code": null,
"e": 25481,
"s": 25476,
"text": "Java"
},
{
"code": null,
"e": 25489,
"s": 25481,
"text": "Python3"
},
{
"code": null,
"e": 25492,
"s": 25489,
"text": "C#"
},
{
"code": null,
"e": 25496,
"s": 25492,
"text": "PHP"
},
{
"code": null,
"e": 25507,
"s": 25496,
"text": "Javascript"
},
{
"code": "// CPP program to Check if it is// possible to convert the string// into palindrome string by changing// only one character.#include<bits/stdc++.h>using namespace std; // Function to check if it is possible// to convert the string into palindromebool checkPalindrome(string str){ int n = str.length(); // Counting number of characters // that should be changed. int count = 0; for (int i = 0; i < n/2; ++i) if (str[i] != str[n - i - 1]) ++count; // If count of changes is less than // or equal to 1 return (count <= 1);} // Driver function.int main(){ string str = \"abccaa\"; if (checkPalindrome(str)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}",
"e": 26263,
"s": 25507,
"text": null
},
{
"code": "// Java program to Check if it is// possible to convert the string// into palindrome string by changing// only one character.import java.io.*; class GFG { // Function to check if it is possible // to convert the string into palindrome static boolean checkPalindrome(String str){ int n = str.length(); // Counting number of characters // that should be changed. int count = 0; for (int i = 0; i < n/2; ++i) if (str.charAt(i) != str.charAt(n - i - 1)) ++count; // If count of changes is less than // or equal to 1 return (count <= 1); } // Driver Function public static void main(String[] args) { String str = \"abccaa\"; if (checkPalindrome(str)) System.out.println(\"Yes\"); else System.out.println(\"No\"); } } // This code is contributed by vt_m",
"e": 27153,
"s": 26263,
"text": null
},
{
"code": "# Python program to Check# if it is possible to# convert the string into# palindrome string by# changing only one character. # Function to check if# it is possible to# convert the string# into palindromedef checkPalindrome(str) : n = len(str) # Counting number of # characters that # should be changed. count = 0 for i in range(0, int(n / 2)) : if (str[i] != str[n - i - 1]) : count = count + 1 # If count of changes # is less than # or equal to 1 if(count <= 1) : return True else : return False # Driver Codestr = \"abccaa\"if (checkPalindrome(str)) : print (\"Yes\")else : print (\"No\") # This code is contributed by# Manish Shaw(manishshaw1)",
"e": 27884,
"s": 27153,
"text": null
},
{
"code": "// C# program to Check if it is// possible to convert the string// into palindrome string by changing// only one character.using System; class GFG { // Function to check if it is possible // to convert the string into palindrome static bool checkPalindrome(string str){ int n = str.Length; // Counting number of characters // that should be changed. int count = 0; for (int i = 0; i < n / 2; ++i) if (str[i] != str[n - i - 1]) ++count; // If count of changes is less than // or equal to 1 return (count <= 1); } // Driver Function public static void Main() { string str = \"abccaa\"; if (checkPalindrome(str)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); } } // This code is contributed by vt_m",
"e": 28828,
"s": 27884,
"text": null
},
{
"code": "<?php// PHP program to Check if it is// possible to convert the string// into palindrome string by changing// only one character. // Function to check if it is possible// to convert the string into palindromefunction checkPalindrome($str){ $n = strlen($str); // Counting number of characters // that should be changed. $count = 0; for ($i = 0; $i < $n/2; ++$i) if ($str[$i] != $str[$n - $i - 1]) ++$count; // If count of changes // is less than // or equal to 1 return ($count <= 1);} // Driver Code{ $str = \"abccaa\"; if (checkPalindrome($str)) echo \"Yes\" ; else echo \"No\" ; return 0;} // This code is contributed by nitin mittal.?>",
"e": 29556,
"s": 28828,
"text": null
},
{
"code": "<script> // Javascript program to Check if it is // possible to convert the string // into palindrome string by changing // only one character. // Function to check if it is possible // to convert the string into palindrome function checkPalindrome(str){ let n = str.length; // Counting number of characters // that should be changed. let count = 0; for (let i = 0; i < parseInt(n/2, 10); ++i) if (str[i] != str[n - i - 1]) ++count; // If count of changes is less than // or equal to 1 return (count <= 1); } let str = \"abccaa\"; if (checkPalindrome(str)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by divyesh072019.</script>",
"e": 30370,
"s": 29556,
"text": null
},
{
"code": null,
"e": 30380,
"s": 30370,
"text": "Output: "
},
{
"code": null,
"e": 30384,
"s": 30380,
"text": "Yes"
},
{
"code": null,
"e": 31257,
"s": 30386,
"text": "YouTubeGeeksforGeeks502K subscribersConvert the string into palindrome string by changing only one character | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:41•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0h7eK2NUKow\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 31272,
"s": 31259,
"text": "nitin mittal"
},
{
"code": null,
"e": 31284,
"s": 31272,
"text": "manishshaw1"
},
{
"code": null,
"e": 31297,
"s": 31284,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31311,
"s": 31297,
"text": "divyesh072019"
},
{
"code": null,
"e": 31322,
"s": 31311,
"text": "palindrome"
},
{
"code": null,
"e": 31330,
"s": 31322,
"text": "Strings"
},
{
"code": null,
"e": 31338,
"s": 31330,
"text": "Strings"
},
{
"code": null,
"e": 31349,
"s": 31338,
"text": "palindrome"
},
{
"code": null,
"e": 31447,
"s": 31349,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31522,
"s": 31447,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 31579,
"s": 31522,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 31615,
"s": 31579,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 31662,
"s": 31615,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 31698,
"s": 31662,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 31751,
"s": 31698,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 31781,
"s": 31751,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 31833,
"s": 31781,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 31865,
"s": 31833,
"text": "Reverse words in a given string"
}
] |
C# | Index of first occurrence in StringCollection - GeeksforGeeks
|
01 Feb, 2019
StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace.StringCollection.IndexOf(String) method is used to search the specified string which returns the zero-based index of the first occurrence within the StringCollection.
Syntax:
public int IndexOf (string value);
Here, value is the string to locate. The value can be null.
Return Value: The method returns zero-based index of the first occurrence of value in the StringCollection, if found otherwise it returns -1.
Note: This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count.
Below programs illustrate the use of StringCollection.IndexOf(String) method:
Example 1:
// C# code to search string and returns// the zero-based index of the first// occurrence in StringCollectionusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr String[] myArr = new String[] { "A", "B", "C", "C", "D" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr); // To search string "C" and return // the zero-based index of the first // occurrence in StringCollection // Here, "C" exists at index 2 and 3. // But, the method should return 2 Console.WriteLine(myCol.IndexOf("C")); }}
2
Example 2:
// C# code to search string and returns// the zero-based index of the first// occurrence in StringCollectionusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr String[] myArr = new String[] { "2", "3", "4", "5", "6" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr); // To search string "9" and return // the zero-based index of the first // occurrence in StringCollection // Here, "9" does not exist in myCol // Hence, method returns -1 Console.WriteLine(myCol.IndexOf("9")); }}
-1
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringcollection.indexof?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-method
CSharp-Specialized-Namespace
CSharp-Specialized-StringCollection
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | Class and Object
C# | Abstract Classes
C# | Data Types
HashSet in C# with Examples
|
[
{
"code": null,
"e": 24504,
"s": 24476,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24871,
"s": 24504,
"text": "StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace.StringCollection.IndexOf(String) method is used to search the specified string which returns the zero-based index of the first occurrence within the StringCollection."
},
{
"code": null,
"e": 24879,
"s": 24871,
"text": "Syntax:"
},
{
"code": null,
"e": 24915,
"s": 24879,
"text": "public int IndexOf (string value);\n"
},
{
"code": null,
"e": 24975,
"s": 24915,
"text": "Here, value is the string to locate. The value can be null."
},
{
"code": null,
"e": 25117,
"s": 24975,
"text": "Return Value: The method returns zero-based index of the first occurrence of value in the StringCollection, if found otherwise it returns -1."
},
{
"code": null,
"e": 25224,
"s": 25117,
"text": "Note: This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count."
},
{
"code": null,
"e": 25302,
"s": 25224,
"text": "Below programs illustrate the use of StringCollection.IndexOf(String) method:"
},
{
"code": null,
"e": 25313,
"s": 25302,
"text": "Example 1:"
},
{
"code": "// C# code to search string and returns// the zero-based index of the first// occurrence in StringCollectionusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr String[] myArr = new String[] { \"A\", \"B\", \"C\", \"C\", \"D\" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr); // To search string \"C\" and return // the zero-based index of the first // occurrence in StringCollection // Here, \"C\" exists at index 2 and 3. // But, the method should return 2 Console.WriteLine(myCol.IndexOf(\"C\")); }}",
"e": 26181,
"s": 25313,
"text": null
},
{
"code": null,
"e": 26184,
"s": 26181,
"text": "2\n"
},
{
"code": null,
"e": 26195,
"s": 26184,
"text": "Example 2:"
},
{
"code": "// C# code to search string and returns// the zero-based index of the first// occurrence in StringCollectionusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr String[] myArr = new String[] { \"2\", \"3\", \"4\", \"5\", \"6\" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr); // To search string \"9\" and return // the zero-based index of the first // occurrence in StringCollection // Here, \"9\" does not exist in myCol // Hence, method returns -1 Console.WriteLine(myCol.IndexOf(\"9\")); }}",
"e": 27055,
"s": 26195,
"text": null
},
{
"code": null,
"e": 27059,
"s": 27055,
"text": "-1\n"
},
{
"code": null,
"e": 27070,
"s": 27059,
"text": "Reference:"
},
{
"code": null,
"e": 27194,
"s": 27070,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringcollection.indexof?view=netframework-4.7.2"
},
{
"code": null,
"e": 27223,
"s": 27194,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 27237,
"s": 27223,
"text": "CSharp-method"
},
{
"code": null,
"e": 27266,
"s": 27237,
"text": "CSharp-Specialized-Namespace"
},
{
"code": null,
"e": 27302,
"s": 27266,
"text": "CSharp-Specialized-StringCollection"
},
{
"code": null,
"e": 27305,
"s": 27302,
"text": "C#"
},
{
"code": null,
"e": 27403,
"s": 27305,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27421,
"s": 27403,
"text": "Destructors in C#"
},
{
"code": null,
"e": 27467,
"s": 27421,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27482,
"s": 27467,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27500,
"s": 27482,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27523,
"s": 27500,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27554,
"s": 27523,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27576,
"s": 27554,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27598,
"s": 27576,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27614,
"s": 27598,
"text": "C# | Data Types"
}
] |
How to create 2-tuple or pair tuple in C#?
|
29 Nov, 2019
In C#, a 2-tuple is a tuple that contains two elements and it is also known as pair. You can create a 2-tuple using two different ways:
Using Tuple<T1,T2>(T1, T2) Constructor
Using the Create method
You can create 2-tuple using Tuple<T1, T2>(T1, T2) constructor. It initializes a new instance of the Tuple<T1,T2> class. But when you create a tuple using this constructor then you have to specify the type of the element stored in the tuple.
Syntax:
public Tuple (T1 item1, T2 item2);
Parameters:
item1: It is the value of the first tuple component.
item2: It is the value of the second tuple component.
Example:
// C# program to create 2-tuple// using the tuple constructorusing System; public class GFG { // Main method static public void Main() { // Creating tuple with two elements // Using Tuple<P1, P2>(T1, T2) constructor Tuple<string, int> My_Tuple = new Tuple<string, int>("GeeksforGeeks", 10); Console.WriteLine("Element 1: " + My_Tuple.Item1); Console.WriteLine("Element 2: " + My_Tuple.Item2); }}
Element 1: GeeksforGeeks
Element 2: 10
You can also create 2-tuple with the help of Create method. When you use this method then there is no need to specify the type of the elements stored in the tuple.
Syntax:
public static Tuple<T1,T2> Create<T1, T2> (T1 item1, T2 item2);
Type Parameters:
T1: It is the type of the first tuple component.
T2: It is the type of the second tuple component.
Parameters:
item1: It is the value of the first tuple component.
item2: It is the value of the second tuple component.
Return Type: This method returns 2-tuple whose value is item1 and item2.
Example:
// C# program to create 2-tuple// using create methodusing System; public class GFG { // Main method static public void Main() { // Creating tuple with two elements // Using Create method var My_Tuple = Tuple.Create("Geeks", 20); Console.WriteLine("Element 1: " + My_Tuple.Item1); Console.WriteLine("Element 2: " + My_Tuple.Item2); }}
Element 1: Geeks
Element 2: 20
References:
https://docs.microsoft.com/en-us/dotnet/api/system.tuple-2.-ctor?view=netframework-4.8
https://docs.microsoft.com/en-us/dotnet/api/system.tuple.create?view=netframework-4.8#System_Tuple_Create__2___0___1_
CSharp-Tuple
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2019"
},
{
"code": null,
"e": 164,
"s": 28,
"text": "In C#, a 2-tuple is a tuple that contains two elements and it is also known as pair. You can create a 2-tuple using two different ways:"
},
{
"code": null,
"e": 203,
"s": 164,
"text": "Using Tuple<T1,T2>(T1, T2) Constructor"
},
{
"code": null,
"e": 227,
"s": 203,
"text": "Using the Create method"
},
{
"code": null,
"e": 469,
"s": 227,
"text": "You can create 2-tuple using Tuple<T1, T2>(T1, T2) constructor. It initializes a new instance of the Tuple<T1,T2> class. But when you create a tuple using this constructor then you have to specify the type of the element stored in the tuple."
},
{
"code": null,
"e": 477,
"s": 469,
"text": "Syntax:"
},
{
"code": null,
"e": 512,
"s": 477,
"text": "public Tuple (T1 item1, T2 item2);"
},
{
"code": null,
"e": 524,
"s": 512,
"text": "Parameters:"
},
{
"code": null,
"e": 577,
"s": 524,
"text": "item1: It is the value of the first tuple component."
},
{
"code": null,
"e": 631,
"s": 577,
"text": "item2: It is the value of the second tuple component."
},
{
"code": null,
"e": 640,
"s": 631,
"text": "Example:"
},
{
"code": "// C# program to create 2-tuple// using the tuple constructorusing System; public class GFG { // Main method static public void Main() { // Creating tuple with two elements // Using Tuple<P1, P2>(T1, T2) constructor Tuple<string, int> My_Tuple = new Tuple<string, int>(\"GeeksforGeeks\", 10); Console.WriteLine(\"Element 1: \" + My_Tuple.Item1); Console.WriteLine(\"Element 2: \" + My_Tuple.Item2); }}",
"e": 1090,
"s": 640,
"text": null
},
{
"code": null,
"e": 1130,
"s": 1090,
"text": "Element 1: GeeksforGeeks\nElement 2: 10\n"
},
{
"code": null,
"e": 1294,
"s": 1130,
"text": "You can also create 2-tuple with the help of Create method. When you use this method then there is no need to specify the type of the elements stored in the tuple."
},
{
"code": null,
"e": 1302,
"s": 1294,
"text": "Syntax:"
},
{
"code": null,
"e": 1366,
"s": 1302,
"text": "public static Tuple<T1,T2> Create<T1, T2> (T1 item1, T2 item2);"
},
{
"code": null,
"e": 1383,
"s": 1366,
"text": "Type Parameters:"
},
{
"code": null,
"e": 1432,
"s": 1383,
"text": "T1: It is the type of the first tuple component."
},
{
"code": null,
"e": 1482,
"s": 1432,
"text": "T2: It is the type of the second tuple component."
},
{
"code": null,
"e": 1494,
"s": 1482,
"text": "Parameters:"
},
{
"code": null,
"e": 1547,
"s": 1494,
"text": "item1: It is the value of the first tuple component."
},
{
"code": null,
"e": 1601,
"s": 1547,
"text": "item2: It is the value of the second tuple component."
},
{
"code": null,
"e": 1674,
"s": 1601,
"text": "Return Type: This method returns 2-tuple whose value is item1 and item2."
},
{
"code": null,
"e": 1683,
"s": 1674,
"text": "Example:"
},
{
"code": "// C# program to create 2-tuple// using create methodusing System; public class GFG { // Main method static public void Main() { // Creating tuple with two elements // Using Create method var My_Tuple = Tuple.Create(\"Geeks\", 20); Console.WriteLine(\"Element 1: \" + My_Tuple.Item1); Console.WriteLine(\"Element 2: \" + My_Tuple.Item2); }}",
"e": 2072,
"s": 1683,
"text": null
},
{
"code": null,
"e": 2104,
"s": 2072,
"text": "Element 1: Geeks\nElement 2: 20\n"
},
{
"code": null,
"e": 2116,
"s": 2104,
"text": "References:"
},
{
"code": null,
"e": 2203,
"s": 2116,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.tuple-2.-ctor?view=netframework-4.8"
},
{
"code": null,
"e": 2321,
"s": 2203,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.tuple.create?view=netframework-4.8#System_Tuple_Create__2___0___1_"
},
{
"code": null,
"e": 2334,
"s": 2321,
"text": "CSharp-Tuple"
},
{
"code": null,
"e": 2337,
"s": 2334,
"text": "C#"
}
] |
Django – How to add multiple submit button in single form?
|
12 Dec, 2021
Prerequisites:
Python
Pip
Django
When we submit the data using the HTML form, it sends the data to the server at a particular URL which is defined in the action attribute. To perform different actions with a single HTML form, we just need to add multiple submit buttons in the form. For example, If you go through the code of the newsletter app, you will find subscribe and unsubscribe buttons in a single HTML form but both perform different actions.
In this tutorial, we are going to make a newsletter app using Django. We will add subscribe and unsubscribe buttons in a single HTML form. Moreover, We will add or remove the email address of the user from our database according to the user clicks on the subscribe or unsubscribe button.
To create the simple newsletter Django app, follow the below steps.
To start a new Django project, your local computer should be satisfied with the prerequisites are given above. Users can use the below command to start a new project.
django-admin startproject newslatter
Next, Go to the project directory.
cd newslatter
To start a new app inside the newsletter project, run the below command inside the project directory.
django-admin startapp appnewslatter
Now, add “appnewslatter” inside the installed_apps section in settings.py of the newsletter project.
path: newslatter/settings.py
Next, Edit the urls.py inside the newsletter folder and add the below code.
Path: newslatter/urls.py
Filename: urls.py
Python3
from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), #including URLS of appnewslatter app path("", include('appnewslatter.urls')),]
Create a new urls.py file inside the “appnewslatter” folder. Now, your project directory should look like the below image.
Edit the urls.py inside the appnewslatter folder. We are adding the URL for the home page.
Path: appnewslattere/urls.py
Filename: urls.py
Python3
from django.urls import pathfrom . import views urlpatterns = [ # URL to open home page path("", views.home, name='home'),]
Create a “templates” folder inside the appnewslatter folder to store the HTML templates.
path: appnewslatter/templates
Create a news.html file inside the templates folder to add a form for our newslatter app.
Path: appnewslatter/templates/news.html
Add the below code inside the news.html file which includes a single form with 2 submit buttons. Every submits button has a unique name. In the views.py file, We will identify from which button users have sent the post request using the name of the button.
Filename: news.html
HTML
<!DOCTYPE html><html> <head> <title>NewsLatter</title> </head> <body> <!--showing success message--> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}> {{ message }}</li> {% endfor %} </ul> {% endif %} <!--Form with multiple submit buttons--> <form action="" method="POST"> <label for="email">Enter your email:</label> <input type="email" id="email" name="email" /> <br> <br> <button type="submit" name="subscribe">Subscribe</button> <button type="submit" name="unsubscribe">Unsubscribe</button> </form> </body></html>
Now, we need to create a table in the database to store the email of the users. We will edit the models.py file.
path: appnewlatter/models.py
Filename: models.py
Python3
from django.db import models # creating database model to store emailclass newslatteremail(models.Model): userEmail = models.EmailField(max_length=254) def __str__(self): return self.userEmail
Register the created model inside the admin.py file.
Path: appnewslatter/admin.py
Filename: admin.py
Python3
from django.contrib import adminfrom .models import newslatteremail # registering the modeladmin.site.register(newslatteremail)
After registering the model, we need to migrate it. Users need to run the below 2 commands one by one.
python manage.py makemigrations
python manage.py migrate
Now, we will edit the views.py file and add the code to handle requests from subscribe and unsubscribe buttons. Here, we check that from which submit button we get the post request with the help of the name attribute of the button.
Syntax:
if 'name_of_button' in request.POST:
# perform some action
Example:
if 'subscribe' in request.POST:
# add the user email in database
if 'unsubscribe' in request.POST:
# remove the user email from database
Copy/paste the below code inside the views.py file.
Path: appnewslatter/views.py
Filename: views.py
Python3
from django.shortcuts import renderfrom django.contrib import messagesfrom .models import newslatteremail def home(request): # if post request comes from the subscribe button # then saving user email in our database if 'subscribe' in request.POST: email = newslatteremail() email.userEmail = request.POST.get("email") email.save() messages.info( request, 'You have successfully subscribed to our newslatter.') # if post request comes from the unsubscribe button # then deleting the user email from our database if 'unsubscribe' in request.POST: newslatteremail.objects.get( userEmail=request.POST.get("email")).delete() messages.info(request, 'sorry to see you!!!') return render(request, 'news.html')
Finally, we have created a simple newsletter app and learned about how we can add multiple submit buttons in a single HTML form. Let’s run the project and see the output. Users can run the Django app using the below command.
Python manage.py runserver
Output:
kalrap615
sooda367
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 43,
"s": 28,
"text": "Prerequisites:"
},
{
"code": null,
"e": 50,
"s": 43,
"text": "Python"
},
{
"code": null,
"e": 54,
"s": 50,
"text": "Pip"
},
{
"code": null,
"e": 61,
"s": 54,
"text": "Django"
},
{
"code": null,
"e": 481,
"s": 61,
"text": "When we submit the data using the HTML form, it sends the data to the server at a particular URL which is defined in the action attribute. To perform different actions with a single HTML form, we just need to add multiple submit buttons in the form. For example, If you go through the code of the newsletter app, you will find subscribe and unsubscribe buttons in a single HTML form but both perform different actions. "
},
{
"code": null,
"e": 769,
"s": 481,
"text": "In this tutorial, we are going to make a newsletter app using Django. We will add subscribe and unsubscribe buttons in a single HTML form. Moreover, We will add or remove the email address of the user from our database according to the user clicks on the subscribe or unsubscribe button."
},
{
"code": null,
"e": 837,
"s": 769,
"text": "To create the simple newsletter Django app, follow the below steps."
},
{
"code": null,
"e": 1004,
"s": 837,
"text": "To start a new Django project, your local computer should be satisfied with the prerequisites are given above. Users can use the below command to start a new project."
},
{
"code": null,
"e": 1041,
"s": 1004,
"text": "django-admin startproject newslatter"
},
{
"code": null,
"e": 1076,
"s": 1041,
"text": "Next, Go to the project directory."
},
{
"code": null,
"e": 1090,
"s": 1076,
"text": "cd newslatter"
},
{
"code": null,
"e": 1192,
"s": 1090,
"text": "To start a new app inside the newsletter project, run the below command inside the project directory."
},
{
"code": null,
"e": 1228,
"s": 1192,
"text": "django-admin startapp appnewslatter"
},
{
"code": null,
"e": 1329,
"s": 1228,
"text": "Now, add “appnewslatter” inside the installed_apps section in settings.py of the newsletter project."
},
{
"code": null,
"e": 1358,
"s": 1329,
"text": "path: newslatter/settings.py"
},
{
"code": null,
"e": 1435,
"s": 1358,
"text": "Next, Edit the urls.py inside the newsletter folder and add the below code. "
},
{
"code": null,
"e": 1460,
"s": 1435,
"text": "Path: newslatter/urls.py"
},
{
"code": null,
"e": 1478,
"s": 1460,
"text": "Filename: urls.py"
},
{
"code": null,
"e": 1486,
"s": 1478,
"text": "Python3"
},
{
"code": "from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), #including URLS of appnewslatter app path(\"\", include('appnewslatter.urls')),]",
"e": 1696,
"s": 1486,
"text": null
},
{
"code": null,
"e": 1819,
"s": 1696,
"text": "Create a new urls.py file inside the “appnewslatter” folder. Now, your project directory should look like the below image."
},
{
"code": null,
"e": 1910,
"s": 1819,
"text": "Edit the urls.py inside the appnewslatter folder. We are adding the URL for the home page."
},
{
"code": null,
"e": 1939,
"s": 1910,
"text": "Path: appnewslattere/urls.py"
},
{
"code": null,
"e": 1957,
"s": 1939,
"text": "Filename: urls.py"
},
{
"code": null,
"e": 1965,
"s": 1957,
"text": "Python3"
},
{
"code": "from django.urls import pathfrom . import views urlpatterns = [ # URL to open home page path(\"\", views.home, name='home'),]",
"e": 2099,
"s": 1965,
"text": null
},
{
"code": null,
"e": 2188,
"s": 2099,
"text": "Create a “templates” folder inside the appnewslatter folder to store the HTML templates."
},
{
"code": null,
"e": 2218,
"s": 2188,
"text": "path: appnewslatter/templates"
},
{
"code": null,
"e": 2308,
"s": 2218,
"text": "Create a news.html file inside the templates folder to add a form for our newslatter app."
},
{
"code": null,
"e": 2348,
"s": 2308,
"text": "Path: appnewslatter/templates/news.html"
},
{
"code": null,
"e": 2605,
"s": 2348,
"text": "Add the below code inside the news.html file which includes a single form with 2 submit buttons. Every submits button has a unique name. In the views.py file, We will identify from which button users have sent the post request using the name of the button."
},
{
"code": null,
"e": 2625,
"s": 2605,
"text": "Filename: news.html"
},
{
"code": null,
"e": 2630,
"s": 2625,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>NewsLatter</title> </head> <body> <!--showing success message--> {% if messages %} <ul class=\"messages\"> {% for message in messages %} <li{% if message.tags %} class=\"{{ message.tags }}\"{% endif %}> {{ message }}</li> {% endfor %} </ul> {% endif %} <!--Form with multiple submit buttons--> <form action=\"\" method=\"POST\"> <label for=\"email\">Enter your email:</label> <input type=\"email\" id=\"email\" name=\"email\" /> <br> <br> <button type=\"submit\" name=\"subscribe\">Subscribe</button> <button type=\"submit\" name=\"unsubscribe\">Unsubscribe</button> </form> </body></html>",
"e": 3331,
"s": 2630,
"text": null
},
{
"code": null,
"e": 3444,
"s": 3331,
"text": "Now, we need to create a table in the database to store the email of the users. We will edit the models.py file."
},
{
"code": null,
"e": 3473,
"s": 3444,
"text": "path: appnewlatter/models.py"
},
{
"code": null,
"e": 3493,
"s": 3473,
"text": "Filename: models.py"
},
{
"code": null,
"e": 3501,
"s": 3493,
"text": "Python3"
},
{
"code": "from django.db import models # creating database model to store emailclass newslatteremail(models.Model): userEmail = models.EmailField(max_length=254) def __str__(self): return self.userEmail",
"e": 3708,
"s": 3501,
"text": null
},
{
"code": null,
"e": 3761,
"s": 3708,
"text": "Register the created model inside the admin.py file."
},
{
"code": null,
"e": 3790,
"s": 3761,
"text": "Path: appnewslatter/admin.py"
},
{
"code": null,
"e": 3809,
"s": 3790,
"text": "Filename: admin.py"
},
{
"code": null,
"e": 3817,
"s": 3809,
"text": "Python3"
},
{
"code": "from django.contrib import adminfrom .models import newslatteremail # registering the modeladmin.site.register(newslatteremail)",
"e": 3945,
"s": 3817,
"text": null
},
{
"code": null,
"e": 4048,
"s": 3945,
"text": "After registering the model, we need to migrate it. Users need to run the below 2 commands one by one."
},
{
"code": null,
"e": 4105,
"s": 4048,
"text": "python manage.py makemigrations\npython manage.py migrate"
},
{
"code": null,
"e": 4337,
"s": 4105,
"text": "Now, we will edit the views.py file and add the code to handle requests from subscribe and unsubscribe buttons. Here, we check that from which submit button we get the post request with the help of the name attribute of the button."
},
{
"code": null,
"e": 4345,
"s": 4337,
"text": "Syntax:"
},
{
"code": null,
"e": 4407,
"s": 4345,
"text": "if 'name_of_button' in request.POST:\n # perform some action"
},
{
"code": null,
"e": 4416,
"s": 4407,
"text": "Example:"
},
{
"code": null,
"e": 4559,
"s": 4416,
"text": "if 'subscribe' in request.POST:\n # add the user email in database\nif 'unsubscribe' in request.POST:\n # remove the user email from database"
},
{
"code": null,
"e": 4611,
"s": 4559,
"text": "Copy/paste the below code inside the views.py file."
},
{
"code": null,
"e": 4640,
"s": 4611,
"text": "Path: appnewslatter/views.py"
},
{
"code": null,
"e": 4659,
"s": 4640,
"text": "Filename: views.py"
},
{
"code": null,
"e": 4667,
"s": 4659,
"text": "Python3"
},
{
"code": "from django.shortcuts import renderfrom django.contrib import messagesfrom .models import newslatteremail def home(request): # if post request comes from the subscribe button # then saving user email in our database if 'subscribe' in request.POST: email = newslatteremail() email.userEmail = request.POST.get(\"email\") email.save() messages.info( request, 'You have successfully subscribed to our newslatter.') # if post request comes from the unsubscribe button # then deleting the user email from our database if 'unsubscribe' in request.POST: newslatteremail.objects.get( userEmail=request.POST.get(\"email\")).delete() messages.info(request, 'sorry to see you!!!') return render(request, 'news.html')",
"e": 5473,
"s": 4667,
"text": null
},
{
"code": null,
"e": 5698,
"s": 5473,
"text": "Finally, we have created a simple newsletter app and learned about how we can add multiple submit buttons in a single HTML form. Let’s run the project and see the output. Users can run the Django app using the below command."
},
{
"code": null,
"e": 5725,
"s": 5698,
"text": "Python manage.py runserver"
},
{
"code": null,
"e": 5733,
"s": 5725,
"text": "Output:"
},
{
"code": null,
"e": 5743,
"s": 5733,
"text": "kalrap615"
},
{
"code": null,
"e": 5752,
"s": 5743,
"text": "sooda367"
},
{
"code": null,
"e": 5765,
"s": 5752,
"text": "Django-forms"
},
{
"code": null,
"e": 5779,
"s": 5765,
"text": "Python Django"
},
{
"code": null,
"e": 5786,
"s": 5779,
"text": "Python"
}
] |
Docker – Hello World
|
04 Aug, 2021
Have you ever experience that in just one second your entire operating system is ready to use?
Yes, you heard it right Docker gives you the facilities to use a new operating system in one second. Docker is a program that uses your base OS resources and only consumes 20MB – 50MB RAM to launch a new OS. In this article, we’ll show you how to install the docker inside Redhat Linux, how to start docker services, how to pull images from the docker hub, and finally how to launch a new container.
In this article, we will discuss the “Hello World” for Docker.
Basic terminologies like docker container, docker image, dockerfile.Docker installation on Redhat/centos.How to start docker services.How to pull Hello-world image from docker hub.Hello-world.
Basic terminologies like docker container, docker image, dockerfile.
Docker installation on Redhat/centos.
How to start docker services.
How to pull Hello-world image from docker hub.
Hello-world.
Let’s start with the key terminologies that you must know.
Docker container is a separate virtualized environment that is used to test, run and deploy the applications. basically, the docker container is used in application development. If any problem or bug comes then it does not affect our Base OS and it also gives extra security. we can easily create new containers with help of docker images. we can also destroy these containers easily.
Docker images are like snapshots in VMs. Docker images are executable files that are used to create separate containers in Docker. We create lots of containers using single docker images. Docker hub is a centralized location that is maintaining docker images. You can find Docker images of Hello-world, Ubuntu, Centos, etc. We also create our own customize image using the docker commit command and using Dockerfile and publish or push them on the docker hub.
Dockerfile is a scripted text file that is used to customize our container and install desire software inside the docker container. we just write the commands in Dockerfile and using this file we build our own image. Later we use this image in our container as well as we push the image on Dockerhub.
As we discuss earlier Dockerhub has the Hello-world official image so let’s see how to install docker and create containers. First of all, we configure a repo that has docker-ce software using the following command:
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
After the repository add you can check the repo in (/etc/yum.repos.d/) location. Now you can easily download the docker using the yum command:
sudo yum install docker
Just in your case if the above command gives some error then try the below command
sudo yum install docker-ce --nobest
Use the below commands to enable and start docker respectively:
sudo systemctl enable docker
sudo systemctl start docker
Now pull the hello-world image from docker use the below command:
docker pull hello-world
Use the below command to run the hello-world file in docker:
docker run hello-world
After running the above command you see some message that prints hello-world which means your docker is successfully installed in your Centos or Redhat Linux.
Hope you understand my explanation.Thanks for reading.
docker
Docker Container
Picked
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 123,
"s": 28,
"text": "Have you ever experience that in just one second your entire operating system is ready to use?"
},
{
"code": null,
"e": 523,
"s": 123,
"text": "Yes, you heard it right Docker gives you the facilities to use a new operating system in one second. Docker is a program that uses your base OS resources and only consumes 20MB – 50MB RAM to launch a new OS. In this article, we’ll show you how to install the docker inside Redhat Linux, how to start docker services, how to pull images from the docker hub, and finally how to launch a new container."
},
{
"code": null,
"e": 586,
"s": 523,
"text": "In this article, we will discuss the “Hello World” for Docker."
},
{
"code": null,
"e": 779,
"s": 586,
"text": "Basic terminologies like docker container, docker image, dockerfile.Docker installation on Redhat/centos.How to start docker services.How to pull Hello-world image from docker hub.Hello-world."
},
{
"code": null,
"e": 848,
"s": 779,
"text": "Basic terminologies like docker container, docker image, dockerfile."
},
{
"code": null,
"e": 886,
"s": 848,
"text": "Docker installation on Redhat/centos."
},
{
"code": null,
"e": 916,
"s": 886,
"text": "How to start docker services."
},
{
"code": null,
"e": 963,
"s": 916,
"text": "How to pull Hello-world image from docker hub."
},
{
"code": null,
"e": 976,
"s": 963,
"text": "Hello-world."
},
{
"code": null,
"e": 1035,
"s": 976,
"text": "Let’s start with the key terminologies that you must know."
},
{
"code": null,
"e": 1420,
"s": 1035,
"text": "Docker container is a separate virtualized environment that is used to test, run and deploy the applications. basically, the docker container is used in application development. If any problem or bug comes then it does not affect our Base OS and it also gives extra security. we can easily create new containers with help of docker images. we can also destroy these containers easily."
},
{
"code": null,
"e": 1880,
"s": 1420,
"text": "Docker images are like snapshots in VMs. Docker images are executable files that are used to create separate containers in Docker. We create lots of containers using single docker images. Docker hub is a centralized location that is maintaining docker images. You can find Docker images of Hello-world, Ubuntu, Centos, etc. We also create our own customize image using the docker commit command and using Dockerfile and publish or push them on the docker hub."
},
{
"code": null,
"e": 2181,
"s": 1880,
"text": "Dockerfile is a scripted text file that is used to customize our container and install desire software inside the docker container. we just write the commands in Dockerfile and using this file we build our own image. Later we use this image in our container as well as we push the image on Dockerhub."
},
{
"code": null,
"e": 2397,
"s": 2181,
"text": "As we discuss earlier Dockerhub has the Hello-world official image so let’s see how to install docker and create containers. First of all, we configure a repo that has docker-ce software using the following command:"
},
{
"code": null,
"e": 2427,
"s": 2397,
"text": "sudo yum install -y yum-utils"
},
{
"code": null,
"e": 2518,
"s": 2427,
"text": "sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo"
},
{
"code": null,
"e": 2661,
"s": 2518,
"text": "After the repository add you can check the repo in (/etc/yum.repos.d/) location. Now you can easily download the docker using the yum command:"
},
{
"code": null,
"e": 2685,
"s": 2661,
"text": "sudo yum install docker"
},
{
"code": null,
"e": 2768,
"s": 2685,
"text": "Just in your case if the above command gives some error then try the below command"
},
{
"code": null,
"e": 2804,
"s": 2768,
"text": "sudo yum install docker-ce --nobest"
},
{
"code": null,
"e": 2868,
"s": 2804,
"text": "Use the below commands to enable and start docker respectively:"
},
{
"code": null,
"e": 2925,
"s": 2868,
"text": "sudo systemctl enable docker\nsudo systemctl start docker"
},
{
"code": null,
"e": 2991,
"s": 2925,
"text": "Now pull the hello-world image from docker use the below command:"
},
{
"code": null,
"e": 3015,
"s": 2991,
"text": "docker pull hello-world"
},
{
"code": null,
"e": 3076,
"s": 3015,
"text": "Use the below command to run the hello-world file in docker:"
},
{
"code": null,
"e": 3099,
"s": 3076,
"text": "docker run hello-world"
},
{
"code": null,
"e": 3258,
"s": 3099,
"text": "After running the above command you see some message that prints hello-world which means your docker is successfully installed in your Centos or Redhat Linux."
},
{
"code": null,
"e": 3313,
"s": 3258,
"text": "Hope you understand my explanation.Thanks for reading."
},
{
"code": null,
"e": 3320,
"s": 3313,
"text": "docker"
},
{
"code": null,
"e": 3337,
"s": 3320,
"text": "Docker Container"
},
{
"code": null,
"e": 3344,
"s": 3337,
"text": "Picked"
},
{
"code": null,
"e": 3370,
"s": 3344,
"text": "Advanced Computer Subject"
}
] |
Program for weighted mean of natural numbers.
|
04 May, 2022
There are given an array of natural numbers and another array with corresponding weight of the number. Then we have to calculate the weighted mean.
Where x (bar) is called the weighted mean, x[i] is the elements of array, and W[i] is the weight of elements of array x[i].
Examples –
Input :
X[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
W[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
weighted mean
= (W[0] * X[0] + W[1] * X[1] + W[2] * X[2] + . . . +
W[n-1] * X[n-1]) / (W[0] + W[1] + W[2] + . . . + W[n-1])
= (1 * 1 + 2 * 2 + 3 * 3 + . . . + 10 * 10) /
(1 + 2 + 3 + . . . + 10)
= 385 / 55 = 7
Output : 7
Input :
X[] = {3, 4, 5, 6, 7}
W[] = {4, 5, 6, 7, 8}
weighted mean
= (W[0] * X[0] + W[1] * X[1] + W[2] * X[2] + . . . +
W[n-1] * X[n-1]) / (W[0] + W[1] + W[2] + . . . + W[n-1])
= (3 * 4 + 4 * 5 + 5 * 6 + 6 * 7 + 7 * 8) /
(4 + 5 + 6 + 7 + 8)
= 160 / 30 = 5.33333
Output : 5.33333
A simple solution to solve weighed mean.
C++
Java
Python
C#
PHP
Javascript
// Program to find weighted mean of// natural numbers.#include<bits/stdc++.h>using namespace std; // Function to calculate weighted mean.float weightedMean(int X[], int W[], int n){ int sum = 0, numWeight = 0; for (int i = 0; i < n; i++) { numWeight = numWeight + X[i] * W[i]; sum = sum + W[i]; } return (float)numWeight / sum;} // Driver program to test the function.int main(){ // Take num array and corresponding weight // array and initialize it. int X[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int W[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Calculate the size of array. int n = sizeof(X)/sizeof(X[0]); int m = sizeof(W)/sizeof(W[0]); // Check the size of both array is equal or not. if (n == m) cout << weightedMean(X, W, n); else cout << "-1"; return 0;}
// JAVA Program to find weighted mean// of natural numbers. class GFG { // Function to calculate weighted mean. static float weightedMean(int X[], int W[], int n) { int sum = 0, numWeight = 0; for (int i = 0; i < n; i++) { numWeight = numWeight + X[i] * W[i]; sum = sum + W[i]; } return (float)(numWeight) / sum; } // Driver program to test the function. public static void main(String args[]) { // Take num array and corresponding // weight array and initialize it. int X[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int W[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Calculate the size of array. int n = X.length; int m = W.length; // Check the size of both array is // equal or not. if (n == m) System.out.println(weightedMean(X, W, n)); else System.out.println("-1" ); }} /*This code is contributed by Nikita Tiwari.*/
# Python Program to find weighted mean of# natural numbers. # Function to calculate weighted mean.def weightedMean(X,W,n) : sum = 0 numWeight = 0 i = 0 while i < n : numWeight = numWeight + X[i] * W[i] sum = sum + W[i] i = i + 1 return (float)(numWeight / sum) # Driver program to test the function. # Take num array and corresponding weight # array and initialize it.X = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]W = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Calculate the size of array.n = len(X)m = len(W) # Check the size of both array is equal or not.if (n == m) : print weightedMean(X, W, n)else : print "-1" # This code is contributed by Nikita Tiwari.
// C# Program to find weighted mean// of natural numbers.using System; class GFG { // Function to calculate weighted mean. static float weightedMean(int []X, int []W, int n) { int sum = 0, numWeight = 0; for (int i = 0; i < n; i++) { numWeight = numWeight + X[i] * W[i]; sum = sum + W[i]; } return (float)(numWeight) / sum; } // Driver program to test the function. public static void Main() { // Take num array and corresponding // weight array and initialize it. int []X = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int []W = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Calculate the size of array. int n = X.Length; int m = W.Length; // Check the size of both array is // equal or not. if (n == m) Console.WriteLine(weightedMean(X, W, n)); else Console.WriteLine("-1" ); }} // This code is contributed by vt_m.
<?php// Program to find weighted mean of// natural numbers. // Function to calculate// weighted mean.function weightedMean($X, $W, $n){ $sum = 0; $numWeight = 0; for ($i = 0; $i < $n; $i++) { $numWeight = $numWeight + $X[$i] * $W[$i]; $sum = $sum + $W[$i]; } return (float)($numWeight / $sum);} // Driver Code // Take num array and corresponding weight// array and initialize it.$X = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);$W = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Calculate the size of array.$n = sizeof($X);$m = sizeof($W); // Check the size of both// array is equal or not.if ($n == $m) echo(weightedMean($X, $W, $n));else echo("-1"); // This code is contributed by Ajit.?>
<script> // Javascript program to find weighted mean// of natural numbers. // Function to calculate weighted mean.function weightedMean(X, W, n){ let sum = 0, numWeight = 0; for(let i = 0; i < n; i++) { numWeight = numWeight + X[i] * W[i]; sum = sum + W[i]; } return (numWeight) / sum;} // Driver code // Take num array and corresponding// weight array and initialize it.let X = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];let W = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; // Calculate the size of array.let n = X.length;let m = W.length; // Check the size of both array is// equal or not.if (n == m) document.write(weightedMean(X, W, n));else document.write("-1" ); // This code is contributed by susmitakundugoaldanga </script>
Output –
7
Second method – to compute the weighted mean of first n natural numbers. It is the formula to compute the weighted mean of first n natural numbers. In this method, we have given first n natural number and their weight are also be the natural numbers. Then we generate the formula
Weighted Mean
= (W[0] * X[0] + W[1] * X[1] + W[2] * X[2] + . . . +
W[n-1] * X[n-1]) / (W[0] + W[1] + W[2] + . . . + W[n-1])
= (1 * 1 + 2 * 2 + 3 * 3 + . . . + n * n) / (1 + 2 + 3 + . . . + n)
= (n * (n + 1) * (2 * n + 1) / 6) / (n * (n + 1) / 2)
Weighted Mean = (2 * n + 1) / 3
Example: Weighted mean of first 10 natural numbers
n = 10
Weighted mean
= (2 * 10 + 1) / 3 = 21 / 3 = 7
C++
Java
Python3
C#
PHP
Javascript
// Program to find weighted mean of first// n natural numbers using formula.#include<bits/stdc++.h>using namespace std; // Returns weighted mean assuming for numbers// {1, 2, ..n} and weights {1, 2, .. n}int weightedMean(int n){ return (2 * n + 1)/3;} // Driver program to test the function.int main(){ int n = 10; cout << weightedMean(n); return 0;}
// Program to find weighted mean of first// n natural numbers using formula.import java.io.*; public class GFG { // Returns weighted mean assuming for numbers // {1, 2, ..n} and weights {1, 2, .. n} static int weightedMean(int n) { return (2 * n + 1)/3; } // Driver program to test the function. static public void main (String[] args) { int n = 10; System.out.println(weightedMean(n)); }} // This code is contributed by vt_m.
# Program to find weighted mean of first# n natural numbers using formula. # Returns weighted mean assuming for numbers# 1, 2, ..n and weights 1, 2, .. ndef weightedMean(n): return (2 * n + 1) / 3 # Driver program to test the function.n = 10print(int(weightedMean(n)))# This code is contributed by smita
// Program to find weighted mean of first// n natural numbers using formula.using System; public class GFG { // Returns weighted mean assuming for numbers // {1, 2, ..n} and weights {1, 2, .. n} static int weightedMean(int n) { return (2 * n + 1) / 3; } // Driver program to test the function. static public void Main () { int n = 10; Console.WriteLine(weightedMean(n)); }} // This code is contributed by vt_m.
<?php// Program to find weighted mean of first// n natural numbers using formula. // Returns weighted mean// assuming for numbers// {1, 2, ..n} and// weights {1, 2, .. n}function weightedMean($n){ return (2 * $n + 1) / 3;} // Driver Code$n = 10;echo(weightedMean($n)); // This code is contributed by Ajit.?>
<script> // Program to find weighted mean of first // n natural numbers using formula. // Returns weighted mean assuming for numbers // {1, 2, ..n} and weights {1, 2, .. n} function weightedMean(n) { return parseInt((2 * n + 1) / 3, 10); } let n = 10; document.write(weightedMean(n)); </script>
Output –
7
This article is contributed by Dharmendra Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
jit_t
Smitha Dinesh Semwal
susmitakundugoaldanga
rameshtravel07
surinderdawra388
statistical-algorithms
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 May, 2022"
},
{
"code": null,
"e": 202,
"s": 52,
"text": "There are given an array of natural numbers and another array with corresponding weight of the number. Then we have to calculate the weighted mean. "
},
{
"code": null,
"e": 326,
"s": 202,
"text": "Where x (bar) is called the weighted mean, x[i] is the elements of array, and W[i] is the weight of elements of array x[i]."
},
{
"code": null,
"e": 339,
"s": 326,
"text": "Examples – "
},
{
"code": null,
"e": 939,
"s": 339,
"text": "Input : \nX[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\nW[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} \nweighted mean \n= (W[0] * X[0] + W[1] * X[1] + W[2] * X[2] + . . . +\n W[n-1] * X[n-1]) / (W[0] + W[1] + W[2] + . . . + W[n-1])\n= (1 * 1 + 2 * 2 + 3 * 3 + . . . + 10 * 10) /\n (1 + 2 + 3 + . . . + 10)\n= 385 / 55 = 7\nOutput : 7\n\nInput : \nX[] = {3, 4, 5, 6, 7}\nW[] = {4, 5, 6, 7, 8}\nweighted mean \n= (W[0] * X[0] + W[1] * X[1] + W[2] * X[2] + . . . +\n W[n-1] * X[n-1]) / (W[0] + W[1] + W[2] + . . . + W[n-1])\n= (3 * 4 + 4 * 5 + 5 * 6 + 6 * 7 + 7 * 8) / \n (4 + 5 + 6 + 7 + 8)\n= 160 / 30 = 5.33333\nOutput : 5.33333"
},
{
"code": null,
"e": 981,
"s": 939,
"text": "A simple solution to solve weighed mean. "
},
{
"code": null,
"e": 985,
"s": 981,
"text": "C++"
},
{
"code": null,
"e": 990,
"s": 985,
"text": "Java"
},
{
"code": null,
"e": 997,
"s": 990,
"text": "Python"
},
{
"code": null,
"e": 1000,
"s": 997,
"text": "C#"
},
{
"code": null,
"e": 1004,
"s": 1000,
"text": "PHP"
},
{
"code": null,
"e": 1015,
"s": 1004,
"text": "Javascript"
},
{
"code": "// Program to find weighted mean of// natural numbers.#include<bits/stdc++.h>using namespace std; // Function to calculate weighted mean.float weightedMean(int X[], int W[], int n){ int sum = 0, numWeight = 0; for (int i = 0; i < n; i++) { numWeight = numWeight + X[i] * W[i]; sum = sum + W[i]; } return (float)numWeight / sum;} // Driver program to test the function.int main(){ // Take num array and corresponding weight // array and initialize it. int X[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int W[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Calculate the size of array. int n = sizeof(X)/sizeof(X[0]); int m = sizeof(W)/sizeof(W[0]); // Check the size of both array is equal or not. if (n == m) cout << weightedMean(X, W, n); else cout << \"-1\"; return 0;}",
"e": 1851,
"s": 1015,
"text": null
},
{
"code": "// JAVA Program to find weighted mean// of natural numbers. class GFG { // Function to calculate weighted mean. static float weightedMean(int X[], int W[], int n) { int sum = 0, numWeight = 0; for (int i = 0; i < n; i++) { numWeight = numWeight + X[i] * W[i]; sum = sum + W[i]; } return (float)(numWeight) / sum; } // Driver program to test the function. public static void main(String args[]) { // Take num array and corresponding // weight array and initialize it. int X[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int W[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Calculate the size of array. int n = X.length; int m = W.length; // Check the size of both array is // equal or not. if (n == m) System.out.println(weightedMean(X, W, n)); else System.out.println(\"-1\" ); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 2924,
"s": 1851,
"text": null
},
{
"code": "# Python Program to find weighted mean of# natural numbers. # Function to calculate weighted mean.def weightedMean(X,W,n) : sum = 0 numWeight = 0 i = 0 while i < n : numWeight = numWeight + X[i] * W[i] sum = sum + W[i] i = i + 1 return (float)(numWeight / sum) # Driver program to test the function. # Take num array and corresponding weight # array and initialize it.X = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]W = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Calculate the size of array.n = len(X)m = len(W) # Check the size of both array is equal or not.if (n == m) : print weightedMean(X, W, n)else : print \"-1\" # This code is contributed by Nikita Tiwari.",
"e": 3626,
"s": 2924,
"text": null
},
{
"code": "// C# Program to find weighted mean// of natural numbers.using System; class GFG { // Function to calculate weighted mean. static float weightedMean(int []X, int []W, int n) { int sum = 0, numWeight = 0; for (int i = 0; i < n; i++) { numWeight = numWeight + X[i] * W[i]; sum = sum + W[i]; } return (float)(numWeight) / sum; } // Driver program to test the function. public static void Main() { // Take num array and corresponding // weight array and initialize it. int []X = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int []W = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Calculate the size of array. int n = X.Length; int m = W.Length; // Check the size of both array is // equal or not. if (n == m) Console.WriteLine(weightedMean(X, W, n)); else Console.WriteLine(\"-1\" ); }} // This code is contributed by vt_m.",
"e": 4680,
"s": 3626,
"text": null
},
{
"code": "<?php// Program to find weighted mean of// natural numbers. // Function to calculate// weighted mean.function weightedMean($X, $W, $n){ $sum = 0; $numWeight = 0; for ($i = 0; $i < $n; $i++) { $numWeight = $numWeight + $X[$i] * $W[$i]; $sum = $sum + $W[$i]; } return (float)($numWeight / $sum);} // Driver Code // Take num array and corresponding weight// array and initialize it.$X = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);$W = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Calculate the size of array.$n = sizeof($X);$m = sizeof($W); // Check the size of both// array is equal or not.if ($n == $m) echo(weightedMean($X, $W, $n));else echo(\"-1\"); // This code is contributed by Ajit.?>",
"e": 5416,
"s": 4680,
"text": null
},
{
"code": "<script> // Javascript program to find weighted mean// of natural numbers. // Function to calculate weighted mean.function weightedMean(X, W, n){ let sum = 0, numWeight = 0; for(let i = 0; i < n; i++) { numWeight = numWeight + X[i] * W[i]; sum = sum + W[i]; } return (numWeight) / sum;} // Driver code // Take num array and corresponding// weight array and initialize it.let X = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];let W = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; // Calculate the size of array.let n = X.length;let m = W.length; // Check the size of both array is// equal or not.if (n == m) document.write(weightedMean(X, W, n));else document.write(\"-1\" ); // This code is contributed by susmitakundugoaldanga </script>",
"e": 6176,
"s": 5416,
"text": null
},
{
"code": null,
"e": 6187,
"s": 6176,
"text": "Output – "
},
{
"code": null,
"e": 6189,
"s": 6187,
"text": "7"
},
{
"code": null,
"e": 6469,
"s": 6189,
"text": "Second method – to compute the weighted mean of first n natural numbers. It is the formula to compute the weighted mean of first n natural numbers. In this method, we have given first n natural number and their weight are also be the natural numbers. Then we generate the formula"
},
{
"code": null,
"e": 6864,
"s": 6469,
"text": "Weighted Mean \n= (W[0] * X[0] + W[1] * X[1] + W[2] * X[2] + . . . +\n W[n-1] * X[n-1]) / (W[0] + W[1] + W[2] + . . . + W[n-1])\n= (1 * 1 + 2 * 2 + 3 * 3 + . . . + n * n) / (1 + 2 + 3 + . . . + n)\n= (n * (n + 1) * (2 * n + 1) / 6) / (n * (n + 1) / 2)\n\nWeighted Mean = (2 * n + 1) / 3\n \nExample: Weighted mean of first 10 natural numbers \nn = 10\nWeighted mean \n= (2 * 10 + 1) / 3 = 21 / 3 = 7 "
},
{
"code": null,
"e": 6868,
"s": 6864,
"text": "C++"
},
{
"code": null,
"e": 6873,
"s": 6868,
"text": "Java"
},
{
"code": null,
"e": 6881,
"s": 6873,
"text": "Python3"
},
{
"code": null,
"e": 6884,
"s": 6881,
"text": "C#"
},
{
"code": null,
"e": 6888,
"s": 6884,
"text": "PHP"
},
{
"code": null,
"e": 6899,
"s": 6888,
"text": "Javascript"
},
{
"code": "// Program to find weighted mean of first// n natural numbers using formula.#include<bits/stdc++.h>using namespace std; // Returns weighted mean assuming for numbers// {1, 2, ..n} and weights {1, 2, .. n}int weightedMean(int n){ return (2 * n + 1)/3;} // Driver program to test the function.int main(){ int n = 10; cout << weightedMean(n); return 0;}",
"e": 7262,
"s": 6899,
"text": null
},
{
"code": "// Program to find weighted mean of first// n natural numbers using formula.import java.io.*; public class GFG { // Returns weighted mean assuming for numbers // {1, 2, ..n} and weights {1, 2, .. n} static int weightedMean(int n) { return (2 * n + 1)/3; } // Driver program to test the function. static public void main (String[] args) { int n = 10; System.out.println(weightedMean(n)); }} // This code is contributed by vt_m.",
"e": 7762,
"s": 7262,
"text": null
},
{
"code": "# Program to find weighted mean of first# n natural numbers using formula. # Returns weighted mean assuming for numbers# 1, 2, ..n and weights 1, 2, .. ndef weightedMean(n): return (2 * n + 1) / 3 # Driver program to test the function.n = 10print(int(weightedMean(n)))# This code is contributed by smita",
"e": 8070,
"s": 7762,
"text": null
},
{
"code": "// Program to find weighted mean of first// n natural numbers using formula.using System; public class GFG { // Returns weighted mean assuming for numbers // {1, 2, ..n} and weights {1, 2, .. n} static int weightedMean(int n) { return (2 * n + 1) / 3; } // Driver program to test the function. static public void Main () { int n = 10; Console.WriteLine(weightedMean(n)); }} // This code is contributed by vt_m.",
"e": 8549,
"s": 8070,
"text": null
},
{
"code": "<?php// Program to find weighted mean of first// n natural numbers using formula. // Returns weighted mean// assuming for numbers// {1, 2, ..n} and// weights {1, 2, .. n}function weightedMean($n){ return (2 * $n + 1) / 3;} // Driver Code$n = 10;echo(weightedMean($n)); // This code is contributed by Ajit.?>",
"e": 8860,
"s": 8549,
"text": null
},
{
"code": "<script> // Program to find weighted mean of first // n natural numbers using formula. // Returns weighted mean assuming for numbers // {1, 2, ..n} and weights {1, 2, .. n} function weightedMean(n) { return parseInt((2 * n + 1) / 3, 10); } let n = 10; document.write(weightedMean(n)); </script>",
"e": 9219,
"s": 8860,
"text": null
},
{
"code": null,
"e": 9229,
"s": 9219,
"text": "Output – "
},
{
"code": null,
"e": 9231,
"s": 9229,
"text": "7"
},
{
"code": null,
"e": 9661,
"s": 9231,
"text": "This article is contributed by Dharmendra Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 9666,
"s": 9661,
"text": "vt_m"
},
{
"code": null,
"e": 9672,
"s": 9666,
"text": "jit_t"
},
{
"code": null,
"e": 9693,
"s": 9672,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 9715,
"s": 9693,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 9730,
"s": 9715,
"text": "rameshtravel07"
},
{
"code": null,
"e": 9747,
"s": 9730,
"text": "surinderdawra388"
},
{
"code": null,
"e": 9770,
"s": 9747,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 9777,
"s": 9770,
"text": "Arrays"
},
{
"code": null,
"e": 9790,
"s": 9777,
"text": "Mathematical"
},
{
"code": null,
"e": 9797,
"s": 9790,
"text": "Arrays"
},
{
"code": null,
"e": 9810,
"s": 9797,
"text": "Mathematical"
},
{
"code": null,
"e": 9908,
"s": 9810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9976,
"s": 9908,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 10020,
"s": 9976,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 10052,
"s": 10020,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 10100,
"s": 10052,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 10114,
"s": 10100,
"text": "Linear Search"
},
{
"code": null,
"e": 10144,
"s": 10114,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 10187,
"s": 10144,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10247,
"s": 10187,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10262,
"s": 10247,
"text": "C++ Data Types"
}
] |
USB Rubber Ducky – PenetrationTesting
|
22 May, 2020
USB Rubber ducky is an HID device that looks similar to a USB Pen drive. It may be used to inject keystroke into a system, used to hack a system, steal victims essential and credential data can inject payload to the victim’s computers. The main important thing about USB Rubber ducky is that it cannot be detected by any Anti-Virus or Firewall as it acts as an HID device.
HID stands for Human Interface Devices, it includes devices like keyboard, mouse, joystick. which acts as an interface between the computer and human beings. That is why it cannot get detected as the computer thinks its an interface.
USB Rubber ducky is a kind of key injection tool, can be used as malicious or non-malicious keystroke.
It is one of the favorite devices of hackers penetration testers as it is very fast and did not detect by ant PC.
USB Rubber Ducky can also be used for targeting vulnerable systems or programming processes and save times.
USB rubber ducky acts as a keyboard and has keystrokes installed in it
When we connect it to PC the keystrokes run automatically.
It has a high speed of approx. 1000 words per minute. So those works which can be done by keyboard can also be done by USB rubber ducky
When ever it is connected to a System it acts as a keyboard and executes the command which is uploaded on it.
The commands used in this are known as payloads and written in Ducky script. One basic script is written below.
Example: Anyone who wants to steal the data from other computers has just to command the keystrokes into the rubber ducky and has to plug-in the device to the victim’s computer, then the device automatically runs a command and steals the data at a very high speed.
The payload used in this device has its payload script known as Ducky Script, And we can write this script in Notepad.
Ducky Code:
REM Type Hello World into Windows notepad. Target: Windows 95 and beyond
DELAY 500
GUI r
DELAY 50
STRING c:\windows\notepad.exe
ENTER
DELAY 500
STRING Hello World
The microSD card: This is a storage device in which all your payloads are saved, so when you attach a device to the victim’s system it will steal data. The keyboard adapter used microSD card to send the payloads.
microSD-to-USB adapter: This is a simple plastic Dongle which is used to mount the SD card to machine.
mini “keyboard” adapter: This is a silicon chip to insert a micro SD card to it. This is the main part and sends the keystrokes to the computer.
USB Rubber Ducky costs around 45$ but you can make it at a cheap rate at home also. You can buy this Device Online.
Software Testing
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 May, 2020"
},
{
"code": null,
"e": 425,
"s": 52,
"text": "USB Rubber ducky is an HID device that looks similar to a USB Pen drive. It may be used to inject keystroke into a system, used to hack a system, steal victims essential and credential data can inject payload to the victim’s computers. The main important thing about USB Rubber ducky is that it cannot be detected by any Anti-Virus or Firewall as it acts as an HID device."
},
{
"code": null,
"e": 659,
"s": 425,
"text": "HID stands for Human Interface Devices, it includes devices like keyboard, mouse, joystick. which acts as an interface between the computer and human beings. That is why it cannot get detected as the computer thinks its an interface."
},
{
"code": null,
"e": 762,
"s": 659,
"text": "USB Rubber ducky is a kind of key injection tool, can be used as malicious or non-malicious keystroke."
},
{
"code": null,
"e": 876,
"s": 762,
"text": "It is one of the favorite devices of hackers penetration testers as it is very fast and did not detect by ant PC."
},
{
"code": null,
"e": 984,
"s": 876,
"text": "USB Rubber Ducky can also be used for targeting vulnerable systems or programming processes and save times."
},
{
"code": null,
"e": 1055,
"s": 984,
"text": "USB rubber ducky acts as a keyboard and has keystrokes installed in it"
},
{
"code": null,
"e": 1114,
"s": 1055,
"text": "When we connect it to PC the keystrokes run automatically."
},
{
"code": null,
"e": 1250,
"s": 1114,
"text": "It has a high speed of approx. 1000 words per minute. So those works which can be done by keyboard can also be done by USB rubber ducky"
},
{
"code": null,
"e": 1360,
"s": 1250,
"text": "When ever it is connected to a System it acts as a keyboard and executes the command which is uploaded on it."
},
{
"code": null,
"e": 1472,
"s": 1360,
"text": "The commands used in this are known as payloads and written in Ducky script. One basic script is written below."
},
{
"code": null,
"e": 1737,
"s": 1472,
"text": "Example: Anyone who wants to steal the data from other computers has just to command the keystrokes into the rubber ducky and has to plug-in the device to the victim’s computer, then the device automatically runs a command and steals the data at a very high speed."
},
{
"code": null,
"e": 1856,
"s": 1737,
"text": "The payload used in this device has its payload script known as Ducky Script, And we can write this script in Notepad."
},
{
"code": null,
"e": 1868,
"s": 1856,
"text": "Ducky Code:"
},
{
"code": null,
"e": 2032,
"s": 1868,
"text": "REM Type Hello World into Windows notepad. Target: Windows 95 and beyond\nDELAY 500\nGUI r\nDELAY 50\nSTRING c:\\windows\\notepad.exe\nENTER\nDELAY 500\nSTRING Hello World\n"
},
{
"code": null,
"e": 2245,
"s": 2032,
"text": "The microSD card: This is a storage device in which all your payloads are saved, so when you attach a device to the victim’s system it will steal data. The keyboard adapter used microSD card to send the payloads."
},
{
"code": null,
"e": 2348,
"s": 2245,
"text": "microSD-to-USB adapter: This is a simple plastic Dongle which is used to mount the SD card to machine."
},
{
"code": null,
"e": 2493,
"s": 2348,
"text": "mini “keyboard” adapter: This is a silicon chip to insert a micro SD card to it. This is the main part and sends the keystrokes to the computer."
},
{
"code": null,
"e": 2609,
"s": 2493,
"text": "USB Rubber Ducky costs around 45$ but you can make it at a cheap rate at home also. You can buy this Device Online."
},
{
"code": null,
"e": 2626,
"s": 2609,
"text": "Software Testing"
},
{
"code": null,
"e": 2632,
"s": 2626,
"text": "GBlog"
}
] |
Clone a linked list with next and random pointer in O(1) space
|
07 Jul, 2022
Given a linked list having two pointers in each node. The first one points to the next node of the list, however, the other pointer is random and can point to any node of the list. Write a program that clones the given list in O(1) space, i.e., without any extra space.
Examples:
Input : Head of the below-linked list
Output :
A new linked list identical to the original list.
In the previous posts Set-1 and Set-2 various methods are discussed, and O(n) space complexity implementation is also available.In this post, we’ll be implementing an algorithm that’d require no additional space as discussed in Set-1.
Below is the Algorithm:
Create the copy of node 1 and insert it between node 1 & node 2 in the original Linked List, create a copy of 2 and insert it between 2 & 3. Continue in this fashion, add the copy of N after the Nth node
Now copy the random link in this fashion
original->next->random= original->random->next; /*TRAVERSE
TWO NODES*/
This works because original->next is nothing but a copy of the original and Original->random->next is nothing but a copy of the random.
Now restore the original and copy linked lists in this fashion in a single loop.
original->next = original->next->next;
copy->next = copy->next->next;
Ensure that original->next is NULL and return the cloned list
Below is the implementation.
C++
Java
C#
Python
Javascript
// C++ program to clone a linked list with next// and arbit pointers in O(n) time#include <bits/stdc++.h>using namespace std; // Structure of linked list Nodestruct Node{ int data; Node *next,*random; Node(int x) { data = x; next = random = NULL; }}; // Utility function to print the list.void print(Node *start){ Node *ptr = start; while (ptr) { cout << "Data = " << ptr->data << ", Random = " << ptr->random->data << endl; ptr = ptr->next; }} // This function clones a given linked list// in O(1) spaceNode* clone(Node *start){ Node* curr = start, *temp; // insert additional node after // every node of original list while (curr) { temp = curr->next; // Inserting node curr->next = new Node(curr->data); curr->next->next = temp; curr = temp; } curr = start; // adjust the random pointers of the // newly added nodes while (curr) { if(curr->next) curr->next->random = curr->random ? curr->random->next : curr->random; // move to the next newly added node by // skipping an original node curr = curr->next?curr->next->next:curr->next; } Node* original = start, *copy = start->next; // save the start of copied linked list temp = copy; // now separate the original list and copied list while (original && copy) { original->next = original->next? original->next->next : original->next; copy->next = copy->next?copy->next->next:copy->next; original = original->next; copy = copy->next; } return temp;} // Driver codeint main(){ Node* start = new Node(1); start->next = new Node(2); start->next->next = new Node(3); start->next->next->next = new Node(4); start->next->next->next->next = new Node(5); // 1's random points to 3 start->random = start->next->next; // 2's random points to 1 start->next->random = start; // 3's and 4's random points to 5 start->next->next->random = start->next->next->next->next; start->next->next->next->random = start->next->next->next->next; // 5's random points to 2 start->next->next->next->next->random = start->next; cout << "Original list : \n"; print(start); cout << "\nCloned list : \n"; Node *cloned_list = clone(start); print(cloned_list); return 0;}
// Java program to clone a linked list with next// and arbit pointers in O(n) timeclass GfG { // Structure of linked list Node static class Node { int data; Node next, random; Node(int x) { data = x; next = random = null; } } // Utility function to print the list. static void print(Node start) { Node ptr = start; while (ptr != null) { System.out.println("Data = " + ptr.data + ", Random = " + ptr.random.data); ptr = ptr.next; } } // This function clones a given // linked list in O(1) space static Node clone(Node start) { Node curr = start, temp = null; // insert additional node after // every node of original list while (curr != null) { temp = curr.next; // Inserting node curr.next = new Node(curr.data); curr.next.next = temp; curr = temp; } curr = start; // adjust the random pointers of the // newly added nodes while (curr != null) { if (curr.next != null) curr.next.random = (curr.random != null) ? curr.random.next : curr.random; // move to the next newly added node by // skipping an original node curr = curr.next.next; } Node original = start, copy = start.next; // save the start of copied linked list temp = copy; // now separate the original list and copied list while (original != null) { original.next =original.next.next; copy.next = (copy.next != null) ? copy.next.next : copy.next; original = original.next; copy = copy.next; } return temp; } // Driver code public static void main(String[] args) { Node start = new Node(1); start.next = new Node(2); start.next.next = new Node(3); start.next.next.next = new Node(4); start.next.next.next.next = new Node(5); // 1's random points to 3 start.random = start.next.next; // 2's random points to 1 start.next.random = start; // 3's and 4's random points to 5 start.next.next.random = start.next.next.next.next; start.next.next.next.random = start.next.next.next.next; // 5's random points to 2 start.next.next.next.next.random = start.next; System.out.println("Original list : "); print(start); System.out.println("Cloned list : "); Node cloned_list = clone(start); print(cloned_list); }} // This code is contributed by Prerna Saini.
// C# program to clone a linked list with// next and arbit pointers in O(n) timeusing System; class GFG{ // Structure of linked list Nodeclass Node{ public int data; public Node next, random; public Node(int x) { data = x; next = random = null; }} // Utility function to print the list.static void print(Node start){ Node ptr = start; while (ptr != null) { Console.WriteLine("Data = " + ptr.data + ", Random = " + ptr.random.data); ptr = ptr.next; }} // This function clones a given// linked list in O(1) spacestatic Node clone(Node start){ Node curr = start, temp = null; // insert additional node after // every node of original list while (curr != null) { temp = curr.next; // Inserting node curr.next = new Node(curr.data); curr.next.next = temp; curr = temp; } curr = start; // adjust the random pointers of // the newly added nodes while (curr != null) { if(curr.next != null) curr.next.random = (curr.random != null) ? curr.random.next : curr.random; // move to the next newly added node // by skipping an original node curr = (curr.next != null) ? curr.next.next : curr.next; } Node original = start, copy = start.next; // save the start of copied linked list temp = copy; // now separate the original list // and copied list while (original != null && copy != null) { original.next = (original.next != null)? original.next.next : original.next; copy.next = (copy.next != null) ? copy.next.next : copy.next; original = original.next; copy = copy.next; } return temp;} // Driver codepublic static void Main(String[] args){ Node start = new Node(1); start.next = new Node(2); start.next.next = new Node(3); start.next.next.next = new Node(4); start.next.next.next.next = new Node(5); // 1's random points to 3 start.random = start.next.next; // 2's random points to 1 start.next.random = start; // 3's and 4's random points to 5 start.next.next.random = start.next.next.next.next; start.next.next.next.random = start.next.next.next.next; // 5's random points to 2 start.next.next.next.next.random = start.next; Console.WriteLine("Original list : "); print(start); Console.WriteLine("Cloned list : "); Node cloned_list = clone(start); print(cloned_list);}} // This code has been contributed// by Rajput-Ji
'''Python program to clone a linked list with next and arbitrary pointers''''''Done in O(n) time with O(1) extra space''' class Node: '''Structure of linked list node''' def __init__(self, data): self.data = data self.next = None self.random = None def clone(original_root): '''Clone a doubly linked list with random pointer''' '''with O(1) extra space''' '''Insert additional node after every node of original list''' curr = original_root while curr != None: new = Node(curr.data) new.next = curr.next curr.next = new curr = curr.next.next '''Adjust the random pointers of the newly added nodes''' curr = original_root while curr != None: curr.next.random = curr.random.next curr = curr.next.next '''Detach original and duplicate list from each other''' curr = original_root dup_root = original_root.next while curr.next != None: tmp = curr.next curr.next = curr.next.next curr = tmp return dup_root def print_dlist(root): '''Function to print the doubly linked list''' curr = root while curr != None: print('Data =', curr.data, ', Random =', curr.random.data) curr = curr.next ####### Driver code #######'''Create a doubly linked list'''original_list = Node(1)original_list.next = Node(2)original_list.next.next = Node(3)original_list.next.next.next = Node(4)original_list.next.next.next.next = Node(5) '''Set the random pointers''' # 1's random points to 3original_list.random = original_list.next.next # 2's random points to 1original_list.next.random = original_list # 3's random points to 5original_list.next.next.random = original_list.next.next.next.next # 4's random points to 5original_list.next.next.next.random = original_list.next.next.next.next # 5's random points to 2original_list.next.next.next.next.random = original_list.next '''Print the original linked list'''print('Original list:')print_dlist(original_list) '''Create a duplicate linked list'''cloned_list = clone(original_list) '''Print the duplicate linked list'''print('\nCloned list:')print_dlist(cloned_list) '''This code is contributed by Shashank Singh'''
<script> // Javascript program to clone a linked list with next// and arbit pointers in O(n) time // Structure of linked list Node class Node { constructor(x) { this.data = x; this.next = this.random = null; } } // Utility function to print the list. function print(start) {var ptr = start; while (ptr != null) { document.write( "Data = " + ptr.data + ", Random = " + ptr.random.data+"<br/>" ); ptr = ptr.next; } } // This function clones a given // linked list in O(1) space function clone(start) {var curr = start, temp = null; // insert additional node after // every node of original list while (curr != null) { temp = curr.next; // Inserting node curr.next = new Node(curr.data); curr.next.next = temp; curr = temp; } curr = start; // adjust the random pointers of the // newly added nodes while (curr != null) { if (curr.next != null) curr.next.random = (curr.random != null) ? curr.random.next : curr.random; // move to the next newly added node by // skipping an original node curr = (curr.next != null) ? curr.next.next : curr.next; } var original = start, copy = start.next; // save the start of copied linked list temp = copy; // now separate the original list and copied list while (original != null && copy != null) { original.next = (original.next != null) ? original.next.next : original.next; copy.next = (copy.next != null) ? copy.next.next : copy.next; original = original.next; copy = copy.next; } return temp; } // Driver code var start = new Node(1); start.next = new Node(2); start.next.next = new Node(3); start.next.next.next = new Node(4); start.next.next.next.next = new Node(5); // 1's random points to 3 start.random = start.next.next; // 2's random points to 1 start.next.random = start; // 3's and 4's random points to 5 start.next.next.random = start.next.next.next.next; start.next.next.next.random = start.next.next.next.next; // 5's random points to 2 start.next.next.next.next.random = start.next; document.write("Original list : <br/>"); print(start); document.write("<br>"); document.write("Cloned list : <br/>"); var cloned_list = clone(start); print(cloned_list); // This code contributed by aashish1995 </script>
Original list :
Data = 1, Random = 3
Data = 2, Random = 1
Data = 3, Random = 5
Data = 4, Random = 5
Data = 5, Random = 2
Cloned list :
Data = 1, Random = 3
Data = 2, Random = 1
Data = 3, Random = 5
Data = 4, Random = 5
Data = 5, Random = 2
Time Complexity: O(n) As we are moving through the list twice, i.e. 2n , but in asymptotic notations we drop the constant termsAuxiliary Space: O(1) As no extra space is used. The n nodes which are inserted in between the nodes was already required to clone the list, so we can say that we did not use any extra space.
This article is contributed by Ashutosh Kumar If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Parinaya Chaturvedi
prerna saini
Rajput-Ji
shashank9830
DivanshuJoshi1
aashish1995
tejas23arya
abhijeet19403
hardikkoriintern
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 323,
"s": 52,
"text": "Given a linked list having two pointers in each node. The first one points to the next node of the list, however, the other pointer is random and can point to any node of the list. Write a program that clones the given list in O(1) space, i.e., without any extra space. "
},
{
"code": null,
"e": 334,
"s": 323,
"text": "Examples: "
},
{
"code": null,
"e": 372,
"s": 334,
"text": "Input : Head of the below-linked list"
},
{
"code": null,
"e": 431,
"s": 372,
"text": "Output :\nA new linked list identical to the original list."
},
{
"code": null,
"e": 666,
"s": 431,
"text": "In the previous posts Set-1 and Set-2 various methods are discussed, and O(n) space complexity implementation is also available.In this post, we’ll be implementing an algorithm that’d require no additional space as discussed in Set-1."
},
{
"code": null,
"e": 691,
"s": 666,
"text": "Below is the Algorithm: "
},
{
"code": null,
"e": 896,
"s": 691,
"text": "Create the copy of node 1 and insert it between node 1 & node 2 in the original Linked List, create a copy of 2 and insert it between 2 & 3. Continue in this fashion, add the copy of N after the Nth node "
},
{
"code": null,
"e": 938,
"s": 896,
"text": "Now copy the random link in this fashion "
},
{
"code": null,
"e": 1012,
"s": 938,
"text": " original->next->random= original->random->next; /*TRAVERSE \nTWO NODES*/"
},
{
"code": null,
"e": 1150,
"s": 1012,
"text": "This works because original->next is nothing but a copy of the original and Original->random->next is nothing but a copy of the random. "
},
{
"code": null,
"e": 1232,
"s": 1150,
"text": "Now restore the original and copy linked lists in this fashion in a single loop. "
},
{
"code": null,
"e": 1307,
"s": 1232,
"text": "original->next = original->next->next;\n copy->next = copy->next->next;"
},
{
"code": null,
"e": 1369,
"s": 1307,
"text": "Ensure that original->next is NULL and return the cloned list"
},
{
"code": null,
"e": 1399,
"s": 1369,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 1403,
"s": 1399,
"text": "C++"
},
{
"code": null,
"e": 1408,
"s": 1403,
"text": "Java"
},
{
"code": null,
"e": 1411,
"s": 1408,
"text": "C#"
},
{
"code": null,
"e": 1418,
"s": 1411,
"text": "Python"
},
{
"code": null,
"e": 1429,
"s": 1418,
"text": "Javascript"
},
{
"code": "// C++ program to clone a linked list with next// and arbit pointers in O(n) time#include <bits/stdc++.h>using namespace std; // Structure of linked list Nodestruct Node{ int data; Node *next,*random; Node(int x) { data = x; next = random = NULL; }}; // Utility function to print the list.void print(Node *start){ Node *ptr = start; while (ptr) { cout << \"Data = \" << ptr->data << \", Random = \" << ptr->random->data << endl; ptr = ptr->next; }} // This function clones a given linked list// in O(1) spaceNode* clone(Node *start){ Node* curr = start, *temp; // insert additional node after // every node of original list while (curr) { temp = curr->next; // Inserting node curr->next = new Node(curr->data); curr->next->next = temp; curr = temp; } curr = start; // adjust the random pointers of the // newly added nodes while (curr) { if(curr->next) curr->next->random = curr->random ? curr->random->next : curr->random; // move to the next newly added node by // skipping an original node curr = curr->next?curr->next->next:curr->next; } Node* original = start, *copy = start->next; // save the start of copied linked list temp = copy; // now separate the original list and copied list while (original && copy) { original->next = original->next? original->next->next : original->next; copy->next = copy->next?copy->next->next:copy->next; original = original->next; copy = copy->next; } return temp;} // Driver codeint main(){ Node* start = new Node(1); start->next = new Node(2); start->next->next = new Node(3); start->next->next->next = new Node(4); start->next->next->next->next = new Node(5); // 1's random points to 3 start->random = start->next->next; // 2's random points to 1 start->next->random = start; // 3's and 4's random points to 5 start->next->next->random = start->next->next->next->next; start->next->next->next->random = start->next->next->next->next; // 5's random points to 2 start->next->next->next->next->random = start->next; cout << \"Original list : \\n\"; print(start); cout << \"\\nCloned list : \\n\"; Node *cloned_list = clone(start); print(cloned_list); return 0;}",
"e": 3940,
"s": 1429,
"text": null
},
{
"code": "// Java program to clone a linked list with next// and arbit pointers in O(n) timeclass GfG { // Structure of linked list Node static class Node { int data; Node next, random; Node(int x) { data = x; next = random = null; } } // Utility function to print the list. static void print(Node start) { Node ptr = start; while (ptr != null) { System.out.println(\"Data = \" + ptr.data + \", Random = \" + ptr.random.data); ptr = ptr.next; } } // This function clones a given // linked list in O(1) space static Node clone(Node start) { Node curr = start, temp = null; // insert additional node after // every node of original list while (curr != null) { temp = curr.next; // Inserting node curr.next = new Node(curr.data); curr.next.next = temp; curr = temp; } curr = start; // adjust the random pointers of the // newly added nodes while (curr != null) { if (curr.next != null) curr.next.random = (curr.random != null) ? curr.random.next : curr.random; // move to the next newly added node by // skipping an original node curr = curr.next.next; } Node original = start, copy = start.next; // save the start of copied linked list temp = copy; // now separate the original list and copied list while (original != null) { original.next =original.next.next; copy.next = (copy.next != null) ? copy.next.next : copy.next; original = original.next; copy = copy.next; } return temp; } // Driver code public static void main(String[] args) { Node start = new Node(1); start.next = new Node(2); start.next.next = new Node(3); start.next.next.next = new Node(4); start.next.next.next.next = new Node(5); // 1's random points to 3 start.random = start.next.next; // 2's random points to 1 start.next.random = start; // 3's and 4's random points to 5 start.next.next.random = start.next.next.next.next; start.next.next.next.random = start.next.next.next.next; // 5's random points to 2 start.next.next.next.next.random = start.next; System.out.println(\"Original list : \"); print(start); System.out.println(\"Cloned list : \"); Node cloned_list = clone(start); print(cloned_list); }} // This code is contributed by Prerna Saini.",
"e": 6827,
"s": 3940,
"text": null
},
{
"code": "// C# program to clone a linked list with// next and arbit pointers in O(n) timeusing System; class GFG{ // Structure of linked list Nodeclass Node{ public int data; public Node next, random; public Node(int x) { data = x; next = random = null; }} // Utility function to print the list.static void print(Node start){ Node ptr = start; while (ptr != null) { Console.WriteLine(\"Data = \" + ptr.data + \", Random = \" + ptr.random.data); ptr = ptr.next; }} // This function clones a given// linked list in O(1) spacestatic Node clone(Node start){ Node curr = start, temp = null; // insert additional node after // every node of original list while (curr != null) { temp = curr.next; // Inserting node curr.next = new Node(curr.data); curr.next.next = temp; curr = temp; } curr = start; // adjust the random pointers of // the newly added nodes while (curr != null) { if(curr.next != null) curr.next.random = (curr.random != null) ? curr.random.next : curr.random; // move to the next newly added node // by skipping an original node curr = (curr.next != null) ? curr.next.next : curr.next; } Node original = start, copy = start.next; // save the start of copied linked list temp = copy; // now separate the original list // and copied list while (original != null && copy != null) { original.next = (original.next != null)? original.next.next : original.next; copy.next = (copy.next != null) ? copy.next.next : copy.next; original = original.next; copy = copy.next; } return temp;} // Driver codepublic static void Main(String[] args){ Node start = new Node(1); start.next = new Node(2); start.next.next = new Node(3); start.next.next.next = new Node(4); start.next.next.next.next = new Node(5); // 1's random points to 3 start.random = start.next.next; // 2's random points to 1 start.next.random = start; // 3's and 4's random points to 5 start.next.next.random = start.next.next.next.next; start.next.next.next.random = start.next.next.next.next; // 5's random points to 2 start.next.next.next.next.random = start.next; Console.WriteLine(\"Original list : \"); print(start); Console.WriteLine(\"Cloned list : \"); Node cloned_list = clone(start); print(cloned_list);}} // This code has been contributed// by Rajput-Ji",
"e": 9500,
"s": 6827,
"text": null
},
{
"code": "'''Python program to clone a linked list with next and arbitrary pointers''''''Done in O(n) time with O(1) extra space''' class Node: '''Structure of linked list node''' def __init__(self, data): self.data = data self.next = None self.random = None def clone(original_root): '''Clone a doubly linked list with random pointer''' '''with O(1) extra space''' '''Insert additional node after every node of original list''' curr = original_root while curr != None: new = Node(curr.data) new.next = curr.next curr.next = new curr = curr.next.next '''Adjust the random pointers of the newly added nodes''' curr = original_root while curr != None: curr.next.random = curr.random.next curr = curr.next.next '''Detach original and duplicate list from each other''' curr = original_root dup_root = original_root.next while curr.next != None: tmp = curr.next curr.next = curr.next.next curr = tmp return dup_root def print_dlist(root): '''Function to print the doubly linked list''' curr = root while curr != None: print('Data =', curr.data, ', Random =', curr.random.data) curr = curr.next ####### Driver code #######'''Create a doubly linked list'''original_list = Node(1)original_list.next = Node(2)original_list.next.next = Node(3)original_list.next.next.next = Node(4)original_list.next.next.next.next = Node(5) '''Set the random pointers''' # 1's random points to 3original_list.random = original_list.next.next # 2's random points to 1original_list.next.random = original_list # 3's random points to 5original_list.next.next.random = original_list.next.next.next.next # 4's random points to 5original_list.next.next.next.random = original_list.next.next.next.next # 5's random points to 2original_list.next.next.next.next.random = original_list.next '''Print the original linked list'''print('Original list:')print_dlist(original_list) '''Create a duplicate linked list'''cloned_list = clone(original_list) '''Print the duplicate linked list'''print('\\nCloned list:')print_dlist(cloned_list) '''This code is contributed by Shashank Singh'''",
"e": 11694,
"s": 9500,
"text": null
},
{
"code": "<script> // Javascript program to clone a linked list with next// and arbit pointers in O(n) time // Structure of linked list Node class Node { constructor(x) { this.data = x; this.next = this.random = null; } } // Utility function to print the list. function print(start) {var ptr = start; while (ptr != null) { document.write( \"Data = \" + ptr.data + \", Random = \" + ptr.random.data+\"<br/>\" ); ptr = ptr.next; } } // This function clones a given // linked list in O(1) space function clone(start) {var curr = start, temp = null; // insert additional node after // every node of original list while (curr != null) { temp = curr.next; // Inserting node curr.next = new Node(curr.data); curr.next.next = temp; curr = temp; } curr = start; // adjust the random pointers of the // newly added nodes while (curr != null) { if (curr.next != null) curr.next.random = (curr.random != null) ? curr.random.next : curr.random; // move to the next newly added node by // skipping an original node curr = (curr.next != null) ? curr.next.next : curr.next; } var original = start, copy = start.next; // save the start of copied linked list temp = copy; // now separate the original list and copied list while (original != null && copy != null) { original.next = (original.next != null) ? original.next.next : original.next; copy.next = (copy.next != null) ? copy.next.next : copy.next; original = original.next; copy = copy.next; } return temp; } // Driver code var start = new Node(1); start.next = new Node(2); start.next.next = new Node(3); start.next.next.next = new Node(4); start.next.next.next.next = new Node(5); // 1's random points to 3 start.random = start.next.next; // 2's random points to 1 start.next.random = start; // 3's and 4's random points to 5 start.next.next.random = start.next.next.next.next; start.next.next.next.random = start.next.next.next.next; // 5's random points to 2 start.next.next.next.next.random = start.next; document.write(\"Original list : <br/>\"); print(start); document.write(\"<br>\"); document.write(\"Cloned list : <br/>\"); var cloned_list = clone(start); print(cloned_list); // This code contributed by aashish1995 </script>",
"e": 14477,
"s": 11694,
"text": null
},
{
"code": null,
"e": 14730,
"s": 14477,
"text": "Original list : \nData = 1, Random = 3\nData = 2, Random = 1\nData = 3, Random = 5\nData = 4, Random = 5\nData = 5, Random = 2\n\nCloned list : \nData = 1, Random = 3\nData = 2, Random = 1\nData = 3, Random = 5\nData = 4, Random = 5\nData = 5, Random = 2"
},
{
"code": null,
"e": 15050,
"s": 14730,
"text": "Time Complexity: O(n) As we are moving through the list twice, i.e. 2n , but in asymptotic notations we drop the constant termsAuxiliary Space: O(1) As no extra space is used. The n nodes which are inserted in between the nodes was already required to clone the list, so we can say that we did not use any extra space."
},
{
"code": null,
"e": 15348,
"s": 15050,
"text": "This article is contributed by Ashutosh Kumar If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 15368,
"s": 15348,
"text": "Parinaya Chaturvedi"
},
{
"code": null,
"e": 15381,
"s": 15368,
"text": "prerna saini"
},
{
"code": null,
"e": 15391,
"s": 15381,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 15404,
"s": 15391,
"text": "shashank9830"
},
{
"code": null,
"e": 15419,
"s": 15404,
"text": "DivanshuJoshi1"
},
{
"code": null,
"e": 15431,
"s": 15419,
"text": "aashish1995"
},
{
"code": null,
"e": 15443,
"s": 15431,
"text": "tejas23arya"
},
{
"code": null,
"e": 15457,
"s": 15443,
"text": "abhijeet19403"
},
{
"code": null,
"e": 15474,
"s": 15457,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 15486,
"s": 15474,
"text": "Linked List"
},
{
"code": null,
"e": 15498,
"s": 15486,
"text": "Linked List"
}
] |
HTML | DOM Audio load() Method
|
30 Mar, 2021
The Audio load() method is used for reload the audio element. The Audio load() method is used to update the audio element after changing the source or other settings. The Audio load() method does not accept any parameters and does not return any values.Syntax
audio.load()
Example:
html
<!DOCTYPE html><html> <body style="text-align:center;"> <h1 style="color:green">GeeksforGeeks</h1> <h2>HTML DOM Audio load() Method</h2> <button onclick="my_Audio()" type="button"> Change Audio </button> <br> <audio id="my_Audio" controls autoplay> <source id="mp4_src" src="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg" type="audio/mp3"> <source id="ogg_src" src="https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3" type="audio/ogg"> </audio> <script> function my_Audio() { document.getElementById("ogg_src").src ="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg"; document.getElementById("mp4_src").src ="https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3"; document.getElementById("my_Audio").load(); } </script></body> </html>
Output:
Supported Browsers: The browsers supported by HTML DOM Audio load() Method are listed below:
Google ChromeOperaMozilla Firefox
Google Chrome
Opera
Mozilla Firefox
arorakashish0911
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Mar, 2021"
},
{
"code": null,
"e": 290,
"s": 28,
"text": "The Audio load() method is used for reload the audio element. The Audio load() method is used to update the audio element after changing the source or other settings. The Audio load() method does not accept any parameters and does not return any values.Syntax "
},
{
"code": null,
"e": 303,
"s": 290,
"text": "audio.load()"
},
{
"code": null,
"e": 314,
"s": 303,
"text": "Example: "
},
{
"code": null,
"e": 319,
"s": 314,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>HTML DOM Audio load() Method</h2> <button onclick=\"my_Audio()\" type=\"button\"> Change Audio </button> <br> <audio id=\"my_Audio\" controls autoplay> <source id=\"mp4_src\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg\" type=\"audio/mp3\"> <source id=\"ogg_src\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3\" type=\"audio/ogg\"> </audio> <script> function my_Audio() { document.getElementById(\"ogg_src\").src =\"https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg\"; document.getElementById(\"mp4_src\").src =\"https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3\"; document.getElementById(\"my_Audio\").load(); } </script></body> </html>",
"e": 1334,
"s": 319,
"text": null
},
{
"code": null,
"e": 1344,
"s": 1334,
"text": "Output: "
},
{
"code": null,
"e": 1439,
"s": 1344,
"text": "Supported Browsers: The browsers supported by HTML DOM Audio load() Method are listed below: "
},
{
"code": null,
"e": 1473,
"s": 1439,
"text": "Google ChromeOperaMozilla Firefox"
},
{
"code": null,
"e": 1487,
"s": 1473,
"text": "Google Chrome"
},
{
"code": null,
"e": 1493,
"s": 1487,
"text": "Opera"
},
{
"code": null,
"e": 1509,
"s": 1493,
"text": "Mozilla Firefox"
},
{
"code": null,
"e": 1528,
"s": 1511,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1537,
"s": 1528,
"text": "HTML-DOM"
},
{
"code": null,
"e": 1542,
"s": 1537,
"text": "HTML"
},
{
"code": null,
"e": 1559,
"s": 1542,
"text": "Web Technologies"
},
{
"code": null,
"e": 1564,
"s": 1559,
"text": "HTML"
}
] |
HTML | form Attribute - GeeksforGeeks
|
20 Sep, 2021
The HTML form Attribute is used to specify that the element can contain one or more forms. This attributes can be used on the following elements such as:
HTML | <button> form Attribute
HTML | <fieldset> form Attribute
HTML | <input> form Attribute
HTML | <label> form Attribute
HTML | <meter> form Attribute
HTML | <object> form Attribute
HTML | <output> form Attribute
HTML | <select> form Attribute
HTML | <textarea> form Attribute
HTML | <keygen> form Attribute
Syntax:
<element form="form_id">
Attribute Value: It contains single value form_id which contains the value i.e form_id which specify the one or more than the button element belongs to. The value of this attribute should be the id of the <form> element.Example:
html
<!DOCTYPE html><html> <head> <title> HTML button form Attribute </title></head> <body style="text-align:center"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2> HTML <button> form Attribute </h2> <form id="myGeeks"></form> <button id="btn" name="myGeeks" form="myGeeks" onclick="geek()"> Click me! </button></body> </html>
Output:
Supported Browsers: The browser supported by HTML form Attribute are listed below:
Google Chrome
Internet Explorer 10.0 +
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Design a web page using HTML and 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": 24179,
"s": 24151,
"text": "\n20 Sep, 2021"
},
{
"code": null,
"e": 24335,
"s": 24179,
"text": "The HTML form Attribute is used to specify that the element can contain one or more forms. This attributes can be used on the following elements such as: "
},
{
"code": null,
"e": 24366,
"s": 24335,
"text": "HTML | <button> form Attribute"
},
{
"code": null,
"e": 24399,
"s": 24366,
"text": "HTML | <fieldset> form Attribute"
},
{
"code": null,
"e": 24429,
"s": 24399,
"text": "HTML | <input> form Attribute"
},
{
"code": null,
"e": 24459,
"s": 24429,
"text": "HTML | <label> form Attribute"
},
{
"code": null,
"e": 24489,
"s": 24459,
"text": "HTML | <meter> form Attribute"
},
{
"code": null,
"e": 24520,
"s": 24489,
"text": "HTML | <object> form Attribute"
},
{
"code": null,
"e": 24551,
"s": 24520,
"text": "HTML | <output> form Attribute"
},
{
"code": null,
"e": 24582,
"s": 24551,
"text": "HTML | <select> form Attribute"
},
{
"code": null,
"e": 24615,
"s": 24582,
"text": "HTML | <textarea> form Attribute"
},
{
"code": null,
"e": 24646,
"s": 24615,
"text": "HTML | <keygen> form Attribute"
},
{
"code": null,
"e": 24656,
"s": 24646,
"text": "Syntax: "
},
{
"code": null,
"e": 24682,
"s": 24656,
"text": "<element form=\"form_id\"> "
},
{
"code": null,
"e": 24913,
"s": 24682,
"text": "Attribute Value: It contains single value form_id which contains the value i.e form_id which specify the one or more than the button element belongs to. The value of this attribute should be the id of the <form> element.Example: "
},
{
"code": null,
"e": 24918,
"s": 24913,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML button form Attribute </title></head> <body style=\"text-align:center\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2> HTML <button> form Attribute </h2> <form id=\"myGeeks\"></form> <button id=\"btn\" name=\"myGeeks\" form=\"myGeeks\" onclick=\"geek()\"> Click me! </button></body> </html> ",
"e": 25345,
"s": 24918,
"text": null
},
{
"code": null,
"e": 25355,
"s": 25345,
"text": "Output: "
},
{
"code": null,
"e": 25440,
"s": 25355,
"text": "Supported Browsers: The browser supported by HTML form Attribute are listed below: "
},
{
"code": null,
"e": 25454,
"s": 25440,
"text": "Google Chrome"
},
{
"code": null,
"e": 25479,
"s": 25454,
"text": "Internet Explorer 10.0 +"
},
{
"code": null,
"e": 25487,
"s": 25479,
"text": "Firefox"
},
{
"code": null,
"e": 25493,
"s": 25487,
"text": "Opera"
},
{
"code": null,
"e": 25500,
"s": 25493,
"text": "Safari"
},
{
"code": null,
"e": 25639,
"s": 25502,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 25659,
"s": 25639,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 25675,
"s": 25659,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 25680,
"s": 25675,
"text": "HTML"
},
{
"code": null,
"e": 25697,
"s": 25680,
"text": "Web Technologies"
},
{
"code": null,
"e": 25702,
"s": 25697,
"text": "HTML"
},
{
"code": null,
"e": 25800,
"s": 25702,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25809,
"s": 25800,
"text": "Comments"
},
{
"code": null,
"e": 25822,
"s": 25809,
"text": "Old Comments"
},
{
"code": null,
"e": 25870,
"s": 25822,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 25907,
"s": 25870,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 25957,
"s": 25907,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 25981,
"s": 25957,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26018,
"s": 25981,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26074,
"s": 26018,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26107,
"s": 26074,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26150,
"s": 26107,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26211,
"s": 26150,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
How to create a MenuButton in JavaFX?
|
A menu is a list of options or commands presented to the user, typically menus contain items that perform some action. The contents of a menu are known as menu items and a menu bar holds multiple menus.
A button controls in user interface applications, in general, on clicking the button it performs the respective action.
A MenuButton is simply, a button that shows a menu on clicking it. You can create a menu button by instantiating the javafx.scene.control.MenuButton class.
To populate its menu, create a required number of objects of the MenuItem class, add them to the observable list of MenuButton as −
menuButton.getItems(item1, item2, item3);
The following Example demonstrates the creation of a MenuButton.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class MenuButtonExample extends Application {
@Override
public void start(Stage stage) {
//Creating a menu
MenuButton menu = new MenuButton("Technology");
//Creating menu Items
menu.setMnemonicParsing(true);
MenuItem item1 = new MenuItem("Java");
MenuItem item2 = new MenuItem("Python");
MenuItem item3 = new MenuItem("C++");
MenuItem item4 = new MenuItem("Big Data");
MenuItem item5 = new MenuItem("Machine Learning");
//Adding all the menu items to the menu
menu.getItems().addAll(item1, item2, item3, item4, item5);
//Adding the choice box to the scene
HBox layout = new HBox(25);
layout.getChildren().addAll(menu);
layout.setPadding(new Insets(15, 50, 50, 150));
layout.setStyle("-fx-background-color: BEIGE");
//Setting the stage
Scene scene = new Scene(layout, 595, 200);
stage.setTitle("Menu Button");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
[
{
"code": null,
"e": 1265,
"s": 1062,
"text": "A menu is a list of options or commands presented to the user, typically menus contain items that perform some action. The contents of a menu are known as menu items and a menu bar holds multiple menus."
},
{
"code": null,
"e": 1385,
"s": 1265,
"text": "A button controls in user interface applications, in general, on clicking the button it performs the respective action."
},
{
"code": null,
"e": 1541,
"s": 1385,
"text": "A MenuButton is simply, a button that shows a menu on clicking it. You can create a menu button by instantiating the javafx.scene.control.MenuButton class."
},
{
"code": null,
"e": 1673,
"s": 1541,
"text": "To populate its menu, create a required number of objects of the MenuItem class, add them to the observable list of MenuButton as −"
},
{
"code": null,
"e": 1715,
"s": 1673,
"text": "menuButton.getItems(item1, item2, item3);"
},
{
"code": null,
"e": 1780,
"s": 1715,
"text": "The following Example demonstrates the creation of a MenuButton."
},
{
"code": null,
"e": 3075,
"s": 1780,
"text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.MenuButton;\nimport javafx.scene.control.MenuItem;\nimport javafx.scene.layout.HBox;\nimport javafx.stage.Stage;\npublic class MenuButtonExample extends Application {\n @Override\n public void start(Stage stage) {\n //Creating a menu\n MenuButton menu = new MenuButton(\"Technology\");\n //Creating menu Items\n menu.setMnemonicParsing(true);\n MenuItem item1 = new MenuItem(\"Java\");\n MenuItem item2 = new MenuItem(\"Python\");\n MenuItem item3 = new MenuItem(\"C++\");\n MenuItem item4 = new MenuItem(\"Big Data\");\n MenuItem item5 = new MenuItem(\"Machine Learning\");\n //Adding all the menu items to the menu\n menu.getItems().addAll(item1, item2, item3, item4, item5);\n //Adding the choice box to the scene\n HBox layout = new HBox(25);\n layout.getChildren().addAll(menu);\n layout.setPadding(new Insets(15, 50, 50, 150));\n layout.setStyle(\"-fx-background-color: BEIGE\");\n //Setting the stage\n Scene scene = new Scene(layout, 595, 200);\n stage.setTitle(\"Menu Button\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
Convert Yelp Dataset to CSV. Loading massive files in Jupyter... | by George Hou | Towards Data Science
|
Round 13 of the Yelp dataset challenge started in January 2019 providing students the opportunity to win awards and conduct analysis or research for academic use.
This post serves to demonstrate a step-by-step of how to load the gigantic file of the Yelp dataset, notably the 5.2 gigabytes worth of review.json file to a more manageable CSV file. With over 6 million reviews in the review.json file, it could be troublesome to load inside a Jupyter Notebook.
1. Downloading the Yelp dataset (source: Yelp Dataset Challenge https://www.yelp.com/dataset/challenge)
This dataset includes information Yelp obtained on businesses, reviews, users, checkins, tips and photos. The file is 8.69 gigabytes uncompressed in json format (6 json files including business.json, review.json, user.json, checkin.json, tip.json and photo.json).
After unzipping the yelp_dateset file, another file will appear, add .tar to the end of the new file to unzip again. The 6 json files should appear along with 2 PDFs of the Yelp’s dataset agreement and Round 13 description.
2. Loading the Yelp dataset in Jupyter Notebook
Since the review.json does not include business’ details, we would need to merge the review file with the business file if we want to have details of what kind of business each review is for.
Set up the business.json environment path to load using Pandas
import pandas as pdbusiness_json_path = 'data/business.json'df_b = pd.read_json(business_json_path, lines=True)
Only keep the businesses that are still open in the dataset
# 1 = open, 0 = closeddf_b = df_b[df_b['is_open']==1]
Drop any irrelevant columns (Must keep business_id to merge with reviews)
drop_columns = ['hours','is_open','review_count']df_b = df_b.drop(drop_columns, axis=1)
We can find the relevant reviews that we want later on by querying for the relevant businesses first using categories.
For this example, we are only interested in RV related businesses.
business_RV = df_b[df_b['categories'].str.contains( 'RV Repair|RV Dealers|RV Rental|RV Parks|Campgrounds', case=False, na=False)]
Since a business can have multiple categories, it could be difficult to figure out how many different categories there are (hint: 1290 different categories!). We can use the explode function in pandas v0.25 to split the categories.
# Make sure the Pandas version is above 0.25# If not, upgrade Pandas version# !pip3 install --upgrade pandaspd.__version__
Once we confirm we have the updated Pandas version, let’s do the magic.
df_explode = df_b.assign(categories = df_b.categories .str.split(', ')).explode('categories')
We can then list out all the individual category
df_explode.categories.value_counts()
Find the categories containing RV
df_explode[df_explode.categories.str.contains('RV', case=True,na=False)].categories.value_counts()
With a huge file like the Yelp dataset, loading all the data at once will most likely crash the memory of the computer. Luckily, Pandas have an option to load large data by segmenting the file into smaller chunks.
Set up the review.json environment path to load using Pandas.
review_json_path = 'data/review.json'
Identifying the data type of each column can reduce memory usage.Luckily, Yelp provided documentation for their dataset so we can set the data type of each column.
size = 1000000review = pd.read_json(review_json_path, lines=True, dtype={'review_id':str,'user_id':str, 'business_id':str,'stars':int, 'date':str,'text':str,'useful':int, 'funny':int,'cool':int}, chunksize=size)
Here, the chunk size of 1,000,000 means Pandas will be reading 1,000,000 lines each time. In this dataset of review.json, there are more than 6 million reviews (rows). Reducing the chunk size might be easier to load and check the results faster.
By merging only the relevant businesses to the review file, the final dataset will only consist of reviews from those businesses.
A more concise dataset can be loaded and shared much more readily.
csv_name = "yelp_reviews_RV_categories.csv"df.to_csv(csv_name, index=False)
This post demonstrates how we can easily load a JSON file within Jupyter Notebook to a CSV file without the hassle of an external converter. Data is only useful when we know how to read and use it properly. Cleaning and processing the data thoroughly will determine the quality of our analysis.
Now that we have our CSV file, we are ready to analyze the data! In my next article, I will show how to visualize the data with Scattertext spaCy.
Thanks for reading! I would love to hear your thoughts, comment here or send me a message. The code used for this is located in my GitHub repository.
|
[
{
"code": null,
"e": 335,
"s": 172,
"text": "Round 13 of the Yelp dataset challenge started in January 2019 providing students the opportunity to win awards and conduct analysis or research for academic use."
},
{
"code": null,
"e": 631,
"s": 335,
"text": "This post serves to demonstrate a step-by-step of how to load the gigantic file of the Yelp dataset, notably the 5.2 gigabytes worth of review.json file to a more manageable CSV file. With over 6 million reviews in the review.json file, it could be troublesome to load inside a Jupyter Notebook."
},
{
"code": null,
"e": 735,
"s": 631,
"text": "1. Downloading the Yelp dataset (source: Yelp Dataset Challenge https://www.yelp.com/dataset/challenge)"
},
{
"code": null,
"e": 999,
"s": 735,
"text": "This dataset includes information Yelp obtained on businesses, reviews, users, checkins, tips and photos. The file is 8.69 gigabytes uncompressed in json format (6 json files including business.json, review.json, user.json, checkin.json, tip.json and photo.json)."
},
{
"code": null,
"e": 1223,
"s": 999,
"text": "After unzipping the yelp_dateset file, another file will appear, add .tar to the end of the new file to unzip again. The 6 json files should appear along with 2 PDFs of the Yelp’s dataset agreement and Round 13 description."
},
{
"code": null,
"e": 1271,
"s": 1223,
"text": "2. Loading the Yelp dataset in Jupyter Notebook"
},
{
"code": null,
"e": 1463,
"s": 1271,
"text": "Since the review.json does not include business’ details, we would need to merge the review file with the business file if we want to have details of what kind of business each review is for."
},
{
"code": null,
"e": 1526,
"s": 1463,
"text": "Set up the business.json environment path to load using Pandas"
},
{
"code": null,
"e": 1638,
"s": 1526,
"text": "import pandas as pdbusiness_json_path = 'data/business.json'df_b = pd.read_json(business_json_path, lines=True)"
},
{
"code": null,
"e": 1698,
"s": 1638,
"text": "Only keep the businesses that are still open in the dataset"
},
{
"code": null,
"e": 1752,
"s": 1698,
"text": "# 1 = open, 0 = closeddf_b = df_b[df_b['is_open']==1]"
},
{
"code": null,
"e": 1826,
"s": 1752,
"text": "Drop any irrelevant columns (Must keep business_id to merge with reviews)"
},
{
"code": null,
"e": 1914,
"s": 1826,
"text": "drop_columns = ['hours','is_open','review_count']df_b = df_b.drop(drop_columns, axis=1)"
},
{
"code": null,
"e": 2033,
"s": 1914,
"text": "We can find the relevant reviews that we want later on by querying for the relevant businesses first using categories."
},
{
"code": null,
"e": 2100,
"s": 2033,
"text": "For this example, we are only interested in RV related businesses."
},
{
"code": null,
"e": 2256,
"s": 2100,
"text": "business_RV = df_b[df_b['categories'].str.contains( 'RV Repair|RV Dealers|RV Rental|RV Parks|Campgrounds', case=False, na=False)]"
},
{
"code": null,
"e": 2488,
"s": 2256,
"text": "Since a business can have multiple categories, it could be difficult to figure out how many different categories there are (hint: 1290 different categories!). We can use the explode function in pandas v0.25 to split the categories."
},
{
"code": null,
"e": 2611,
"s": 2488,
"text": "# Make sure the Pandas version is above 0.25# If not, upgrade Pandas version# !pip3 install --upgrade pandaspd.__version__"
},
{
"code": null,
"e": 2683,
"s": 2611,
"text": "Once we confirm we have the updated Pandas version, let’s do the magic."
},
{
"code": null,
"e": 2801,
"s": 2683,
"text": "df_explode = df_b.assign(categories = df_b.categories .str.split(', ')).explode('categories')"
},
{
"code": null,
"e": 2850,
"s": 2801,
"text": "We can then list out all the individual category"
},
{
"code": null,
"e": 2887,
"s": 2850,
"text": "df_explode.categories.value_counts()"
},
{
"code": null,
"e": 2921,
"s": 2887,
"text": "Find the categories containing RV"
},
{
"code": null,
"e": 3041,
"s": 2921,
"text": "df_explode[df_explode.categories.str.contains('RV', case=True,na=False)].categories.value_counts()"
},
{
"code": null,
"e": 3255,
"s": 3041,
"text": "With a huge file like the Yelp dataset, loading all the data at once will most likely crash the memory of the computer. Luckily, Pandas have an option to load large data by segmenting the file into smaller chunks."
},
{
"code": null,
"e": 3317,
"s": 3255,
"text": "Set up the review.json environment path to load using Pandas."
},
{
"code": null,
"e": 3355,
"s": 3317,
"text": "review_json_path = 'data/review.json'"
},
{
"code": null,
"e": 3519,
"s": 3355,
"text": "Identifying the data type of each column can reduce memory usage.Luckily, Yelp provided documentation for their dataset so we can set the data type of each column."
},
{
"code": null,
"e": 3857,
"s": 3519,
"text": "size = 1000000review = pd.read_json(review_json_path, lines=True, dtype={'review_id':str,'user_id':str, 'business_id':str,'stars':int, 'date':str,'text':str,'useful':int, 'funny':int,'cool':int}, chunksize=size)"
},
{
"code": null,
"e": 4103,
"s": 3857,
"text": "Here, the chunk size of 1,000,000 means Pandas will be reading 1,000,000 lines each time. In this dataset of review.json, there are more than 6 million reviews (rows). Reducing the chunk size might be easier to load and check the results faster."
},
{
"code": null,
"e": 4233,
"s": 4103,
"text": "By merging only the relevant businesses to the review file, the final dataset will only consist of reviews from those businesses."
},
{
"code": null,
"e": 4300,
"s": 4233,
"text": "A more concise dataset can be loaded and shared much more readily."
},
{
"code": null,
"e": 4376,
"s": 4300,
"text": "csv_name = \"yelp_reviews_RV_categories.csv\"df.to_csv(csv_name, index=False)"
},
{
"code": null,
"e": 4671,
"s": 4376,
"text": "This post demonstrates how we can easily load a JSON file within Jupyter Notebook to a CSV file without the hassle of an external converter. Data is only useful when we know how to read and use it properly. Cleaning and processing the data thoroughly will determine the quality of our analysis."
},
{
"code": null,
"e": 4818,
"s": 4671,
"text": "Now that we have our CSV file, we are ready to analyze the data! In my next article, I will show how to visualize the data with Scattertext spaCy."
}
] |
jQuery UI Tabs active Option - GeeksforGeeks
|
08 Feb, 2021
jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. jQuery UI tabs widget helps us to put some content in different tabs and allow us to switch between them. In this article we will see how to use active option in jQuery UI slider.The active option specifies the current active tab in jQuery UI tabs. By default, value is 0.
Syntax:
$( ".selector" ).tabs(
{ active: 1 }
);
Parameters:
boolean: if set to false will collapse all the panels. If set to true 0th index tab will be active.
number: The zero-based index of the panel that is active.
Approach: First, add jQuery UI scripts needed for your project.
<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>
Example 1:
HTML
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src= "https://code.jquery.com/jquery-1.10.2.js"> </script> <script src= "https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <script> $(function () { $("#gfg").tabs({ active: 2 }); }); </script></head> <body> <h1>GeeksforGeeks</h1> <h3>jQuery UI tabs active option</h3> <div id="gfg"> <ul> <li><a href="#gfg1">Tab 1</a></li> <li><a href="#gfg2">Tab 2</a></li> <li><a href="#gfg3">Tab 3</a></li> </ul> <div id="gfg1"> <p>tab Number -1</p> </div> <div id="gfg2"> <p>tab Number -2</p> </div> <div id="gfg3"> <p>tab Number -3</p> </div> </div></body> </html>
Output:
Example 2:
HTML
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src= "https://code.jquery.com/jquery-1.10.2.js"> </script> <script src= "https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <script> $(function () { $("#gfg").tabs({ active: false }); }); </script></head> <body> <h1>GeeksforGeeks</h1> <h3>jQuery UI tabs active option</h3> <div id="gfg"> <ul> <li><a href="#gfg1">Tab 1</a></li> <li><a href="#gfg2">Tab 2</a></li> <li><a href="#gfg3">Tab 3</a></li> </ul> <div id="gfg1"> <p>tab Number -1</p> </div> <div id="gfg2"> <p>tab Number -2</p> </div> <div id="gfg3"> <p>tab Number -3</p> </div> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
jQuery-UI
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to add options to a select element using jQuery?
|
[
{
"code": null,
"e": 50960,
"s": 50932,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 51400,
"s": 50960,
"text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. jQuery UI tabs widget helps us to put some content in different tabs and allow us to switch between them. In this article we will see how to use active option in jQuery UI slider.The active option specifies the current active tab in jQuery UI tabs. By default, value is 0."
},
{
"code": null,
"e": 51408,
"s": 51400,
"text": "Syntax:"
},
{
"code": null,
"e": 51451,
"s": 51408,
"text": "$( \".selector\" ).tabs(\n { active: 1 }\n);"
},
{
"code": null,
"e": 51463,
"s": 51451,
"text": "Parameters:"
},
{
"code": null,
"e": 51563,
"s": 51463,
"text": "boolean: if set to false will collapse all the panels. If set to true 0th index tab will be active."
},
{
"code": null,
"e": 51621,
"s": 51563,
"text": "number: The zero-based index of the panel that is active."
},
{
"code": null,
"e": 51685,
"s": 51621,
"text": "Approach: First, add jQuery UI scripts needed for your project."
},
{
"code": null,
"e": 51926,
"s": 51685,
"text": "<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>"
},
{
"code": null,
"e": 51937,
"s": 51926,
"text": "Example 1:"
},
{
"code": null,
"e": 51942,
"s": 51937,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"> <script src= \"https://code.jquery.com/jquery-1.10.2.js\"> </script> <script src= \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <script> $(function () { $(\"#gfg\").tabs({ active: 2 }); }); </script></head> <body> <h1>GeeksforGeeks</h1> <h3>jQuery UI tabs active option</h3> <div id=\"gfg\"> <ul> <li><a href=\"#gfg1\">Tab 1</a></li> <li><a href=\"#gfg2\">Tab 2</a></li> <li><a href=\"#gfg3\">Tab 3</a></li> </ul> <div id=\"gfg1\"> <p>tab Number -1</p> </div> <div id=\"gfg2\"> <p>tab Number -2</p> </div> <div id=\"gfg3\"> <p>tab Number -3</p> </div> </div></body> </html>",
"e": 52930,
"s": 51942,
"text": null
},
{
"code": null,
"e": 52938,
"s": 52930,
"text": "Output:"
},
{
"code": null,
"e": 52949,
"s": 52938,
"text": "Example 2:"
},
{
"code": null,
"e": 52954,
"s": 52949,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"> <script src= \"https://code.jquery.com/jquery-1.10.2.js\"> </script> <script src= \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <script> $(function () { $(\"#gfg\").tabs({ active: false }); }); </script></head> <body> <h1>GeeksforGeeks</h1> <h3>jQuery UI tabs active option</h3> <div id=\"gfg\"> <ul> <li><a href=\"#gfg1\">Tab 1</a></li> <li><a href=\"#gfg2\">Tab 2</a></li> <li><a href=\"#gfg3\">Tab 3</a></li> </ul> <div id=\"gfg1\"> <p>tab Number -1</p> </div> <div id=\"gfg2\"> <p>tab Number -2</p> </div> <div id=\"gfg3\"> <p>tab Number -3</p> </div> </div></body> </html>",
"e": 53950,
"s": 52954,
"text": null
},
{
"code": null,
"e": 53958,
"s": 53950,
"text": "Output:"
},
{
"code": null,
"e": 54095,
"s": 53958,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 54105,
"s": 54095,
"text": "jQuery-UI"
},
{
"code": null,
"e": 54110,
"s": 54105,
"text": "HTML"
},
{
"code": null,
"e": 54117,
"s": 54110,
"text": "JQuery"
},
{
"code": null,
"e": 54134,
"s": 54117,
"text": "Web Technologies"
},
{
"code": null,
"e": 54139,
"s": 54134,
"text": "HTML"
},
{
"code": null,
"e": 54237,
"s": 54139,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 54246,
"s": 54237,
"text": "Comments"
},
{
"code": null,
"e": 54259,
"s": 54246,
"text": "Old Comments"
},
{
"code": null,
"e": 54321,
"s": 54259,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 54371,
"s": 54321,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 54431,
"s": 54371,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 54479,
"s": 54431,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 54540,
"s": 54479,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 54586,
"s": 54540,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 54615,
"s": 54586,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 54678,
"s": 54615,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 54755,
"s": 54678,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
CSS - Positioning
|
CSS helps you to position your HTML element. You can put any HTML element at whatever location you like. You can specify whether you want the element positioned relative to its natural position in the page or absolute based on its parent element.
Now, we will see all the CSS positioning related properties with examples −
Relative positioning changes the position of the HTML element relative to where it normally appears. So "left:20" adds 20 pixels to the element's LEFT position.
You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document.
Move Left - Use a negative value for left.
Move Right - Use a positive value for left.
Move Up - Use a negative value for top.
Move Down - Use a positive value for top.
NOTE − You can use bottom or right values as well in the same way as top and left.
Here is the example −
<html>
<head>
</head>
<body>
<div style = "position:relative; left:80px; top:2px; background-color:yellow;">
This div has relative positioning.
</div>
</body>
</html>
It will produce the following result −
An element with position: absolute is positioned at the specified coordinates relative to your screen top-left corner.
You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document.
Move Left - Use a negative value for left.
Move Right - Use a positive value for left.
Move Up - Use a negative value for top.
Move Down - Use a positive value for top.
NOTE − You can use bottom or right values as well in the same way as top and left.
Here is an example −
<html>
<head>
</head>
<body>
<div style = "position:absolute; left:80px; top:20px; background-color:yellow;">
This div has absolute positioning.
</div>
</body>
</html>
Fixed positioning allows you to fix the position of an element to a particular spot on the page, regardless of scrolling. Specified coordinates will be relative to the browser window.
You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document.
Move Left - Use a negative value for left.
Move Right - Use a positive value for left.
Move Up - Use a negative value for top.
Move Down - Use a positive value for top.
NOTE − You can use bottom or right values as well in the same way as top and left.
Here is an example −
<html>
<head>
</head>
<body>
<div style = "position:fixed; left:80px; top:20px; background-color:yellow;">
This div has fixed positioning.
</div>
</body>
</html>
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2873,
"s": 2626,
"text": "CSS helps you to position your HTML element. You can put any HTML element at whatever location you like. You can specify whether you want the element positioned relative to its natural position in the page or absolute based on its parent element."
},
{
"code": null,
"e": 2949,
"s": 2873,
"text": "Now, we will see all the CSS positioning related properties with examples −"
},
{
"code": null,
"e": 3110,
"s": 2949,
"text": "Relative positioning changes the position of the HTML element relative to where it normally appears. So \"left:20\" adds 20 pixels to the element's LEFT position."
},
{
"code": null,
"e": 3234,
"s": 3110,
"text": "You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document."
},
{
"code": null,
"e": 3277,
"s": 3234,
"text": "Move Left - Use a negative value for left."
},
{
"code": null,
"e": 3321,
"s": 3277,
"text": "Move Right - Use a positive value for left."
},
{
"code": null,
"e": 3361,
"s": 3321,
"text": "Move Up - Use a negative value for top."
},
{
"code": null,
"e": 3403,
"s": 3361,
"text": "Move Down - Use a positive value for top."
},
{
"code": null,
"e": 3486,
"s": 3403,
"text": "NOTE − You can use bottom or right values as well in the same way as top and left."
},
{
"code": null,
"e": 3508,
"s": 3486,
"text": "Here is the example −"
},
{
"code": null,
"e": 3709,
"s": 3508,
"text": "<html>\n <head>\n </head>\n\n <body>\n <div style = \"position:relative; left:80px; top:2px; background-color:yellow;\">\n This div has relative positioning.\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 3748,
"s": 3709,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 3867,
"s": 3748,
"text": "An element with position: absolute is positioned at the specified coordinates relative to your screen top-left corner."
},
{
"code": null,
"e": 3991,
"s": 3867,
"text": "You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document."
},
{
"code": null,
"e": 4034,
"s": 3991,
"text": "Move Left - Use a negative value for left."
},
{
"code": null,
"e": 4078,
"s": 4034,
"text": "Move Right - Use a positive value for left."
},
{
"code": null,
"e": 4118,
"s": 4078,
"text": "Move Up - Use a negative value for top."
},
{
"code": null,
"e": 4160,
"s": 4118,
"text": "Move Down - Use a positive value for top."
},
{
"code": null,
"e": 4243,
"s": 4160,
"text": "NOTE − You can use bottom or right values as well in the same way as top and left."
},
{
"code": null,
"e": 4264,
"s": 4243,
"text": "Here is an example −"
},
{
"code": null,
"e": 4467,
"s": 4264,
"text": "<html>\n <head>\n </head>\n\n <body>\n <div style = \"position:absolute; left:80px; top:20px; background-color:yellow;\">\n This div has absolute positioning.\n </div>\n </body>\n</html> "
},
{
"code": null,
"e": 4651,
"s": 4467,
"text": "Fixed positioning allows you to fix the position of an element to a particular spot on the page, regardless of scrolling. Specified coordinates will be relative to the browser window."
},
{
"code": null,
"e": 4775,
"s": 4651,
"text": "You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document."
},
{
"code": null,
"e": 4818,
"s": 4775,
"text": "Move Left - Use a negative value for left."
},
{
"code": null,
"e": 4862,
"s": 4818,
"text": "Move Right - Use a positive value for left."
},
{
"code": null,
"e": 4902,
"s": 4862,
"text": "Move Up - Use a negative value for top."
},
{
"code": null,
"e": 4944,
"s": 4902,
"text": "Move Down - Use a positive value for top."
},
{
"code": null,
"e": 5027,
"s": 4944,
"text": "NOTE − You can use bottom or right values as well in the same way as top and left."
},
{
"code": null,
"e": 5048,
"s": 5027,
"text": "Here is an example −"
},
{
"code": null,
"e": 5244,
"s": 5048,
"text": "<html>\n <head>\n </head>\n\n <body>\n <div style = \"position:fixed; left:80px; top:20px; background-color:yellow;\">\n This div has fixed positioning.\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 5279,
"s": 5244,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5293,
"s": 5279,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5328,
"s": 5293,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5345,
"s": 5328,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5380,
"s": 5345,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5411,
"s": 5380,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5446,
"s": 5411,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5477,
"s": 5446,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5512,
"s": 5477,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5543,
"s": 5512,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5576,
"s": 5543,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5607,
"s": 5576,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5614,
"s": 5607,
"text": " Print"
},
{
"code": null,
"e": 5625,
"s": 5614,
"text": " Add Notes"
}
] |
Calculate score for the given binary string - GeeksforGeeks
|
27 Apr, 2021
Given a binary string str. For n-contiguous 1s the score is updated as score = score + n2 and for n-contiguous 0s, the score is updated as score = score – n2. The task is to find the score of the complete binary string.Examples:
Input: str = 11011 Output: 7 score(“11”) – score(“0”) + score(“11”) = 22 – 12 + 22 = 7Input: str = 1100011 Output: -1
Approach: For solving the problem iterate over the given string and calculate the number of contiguous 1s and 0s. For each contiguous chunk of n 1s add n2 to the current score and similarly for each contiguous chunk of n 0s subtract n2 from the current score.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the score for// the given binary stringint calcScore(string str){ int score = 0; int len = str.length(); // Traverse through string character for (int i = 0; i < len;) { // Initialize current chunk's size int chunkSize = 1; // Get current character char currentChar = str[i++]; // Calculate total chunk size // of same characters while (i < len && str[i] == currentChar) { chunkSize++; i++; } // Add/subtract pow(chunkSize, 2) // depending upon character if (currentChar == '1') score += pow(chunkSize, 2); else score -= pow(chunkSize, 2); } // Return the score return score;} // Driver codeint main(){ string str = "11011"; cout << calcScore(str); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the score for // the given binary string public static int calcScore(String str) { int score = 0; int len = str.length(); // Traverse through string character for (int i = 0; i < len;) { // Initialize current chunk's size int chunkSize = 1; // Get current character char currentChar = str.charAt(i++); // Calculate total chunk size // of same characters while (i < len && str.charAt(i) == currentChar) { chunkSize++; i++; } // Add/subtract pow(chunkSize, 2) // depending upon character if (currentChar == '1') score += Math.pow(chunkSize, 2); else score -= Math.pow(chunkSize, 2); } // Return the score return score; } // Driver code public static void main(String[] args) { String str = "11011"; System.out.println(calcScore(str)); }} // This code is contributed by Naman_Garg
# Python 3 implementation of the approach # Function to return the score for# the given binary stringdef calcScore(str): score = 0 len1 = len(str) # Traverse through string character i = 0 while(i < len1): # Initialize current chunk's size chunkSize = 1 # Get current character currentChar = str[i] i += 1 # Calculate total chunk size # of same characters while (i < len1 and str[i] == currentChar): chunkSize += 1 i += 1 # Add/subtract pow(chunkSize, 2) # depending upon character if (currentChar == '1'): score += pow(chunkSize, 2) else: score -= pow(chunkSize, 2) # Return the score return score # Driver codeif __name__ == '__main__': str = "11011" print(calcScore(str)) # This code is contributed by# Surendra_Gangwar
// C# implementation of the approachusing System; class GFG{ // Function to return the score for // the given binary string public static int calcScore(String str) { int score = 0; int len = str.Length; // Traverse through string character for (int i = 0; i < len;) { // Initialize current chunk's size int chunkSize = 1; // Get current character char currentChar = str[i++]; // Calculate total chunk size // of same characters while (i < len && str[i] == currentChar) { chunkSize++; i++; } // Add/subtract pow(chunkSize, 2) // depending upon character if (currentChar == '1') score += (int)Math.Pow(chunkSize, 2); else score -= (int)Math.Pow(chunkSize, 2); } // Return the score return score; } // Driver code public static void Main(String[] args) { String str = "11011"; Console.WriteLine(calcScore(str)); }} // This code contributed by Rajput-Ji
<?php// Php implementation of the approach // Function to return the score for// the given binary stringfunction calcScore($str){ $score = 0; $len = strlen($str); // Traverse through string character for ($i = 0; $i < $len { // Initialize current chunk's size $chunkSize = 1; // Get current character $currentChar = $str[$i++]; // Calculate total chunk size // of same characters while ($i < $len && $str[$i] == $currentChar) { $chunkSize++; $i++; } // Add/subtract pow(chunkSize, 2) // depending upon character if ($currentChar == '1') $score += pow($chunkSize, 2); else $score -= pow($chunkSize, 2); } // Return the score return $score;} // Driver code $str = "11011"; echo calcScore($str); // This code is contributed by AnkitRai01?>
<script> // Javascript implementation of the approach // Function to return the score for// the given binary stringfunction calcScore(str){ var score = 0; var len = str.length; // Traverse through string character for (var i = 0; i < len;) { // Initialize current chunk's size var chunkSize = 1; // Get current character var currentChar = str[i++]; // Calculate total chunk size // of same characters while (i < len && str[i] == currentChar) { chunkSize++; i++; } // Add/subtract pow(chunkSize, 2) // depending upon character if (currentChar == '1') score += Math.pow(chunkSize, 2); else score -= Math.pow(chunkSize, 2); } // Return the score return score;} // Driver codevar str = "11011";document.write( calcScore(str)); </script>
7
ankthon
Naman_Garg
SURENDRA_GANGWAR
Rajput-Ji
rrrtnx
binary-string
substring
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Naive algorithm for Pattern Searching
Vigenère Cipher
Hill Cipher
Count words in a given string
How to Append a Character to a String in C
Convert character array to string in C++
sprintf() in C
Program to count occurrence of a given character in a string
Converting Roman Numerals to Decimal lying between 1 to 3999
|
[
{
"code": null,
"e": 24828,
"s": 24800,
"text": "\n27 Apr, 2021"
},
{
"code": null,
"e": 25059,
"s": 24828,
"text": "Given a binary string str. For n-contiguous 1s the score is updated as score = score + n2 and for n-contiguous 0s, the score is updated as score = score – n2. The task is to find the score of the complete binary string.Examples: "
},
{
"code": null,
"e": 25179,
"s": 25059,
"text": "Input: str = 11011 Output: 7 score(“11”) – score(“0”) + score(“11”) = 22 – 12 + 22 = 7Input: str = 1100011 Output: -1 "
},
{
"code": null,
"e": 25493,
"s": 25181,
"text": "Approach: For solving the problem iterate over the given string and calculate the number of contiguous 1s and 0s. For each contiguous chunk of n 1s add n2 to the current score and similarly for each contiguous chunk of n 0s subtract n2 from the current score.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25497,
"s": 25493,
"text": "C++"
},
{
"code": null,
"e": 25502,
"s": 25497,
"text": "Java"
},
{
"code": null,
"e": 25510,
"s": 25502,
"text": "Python3"
},
{
"code": null,
"e": 25513,
"s": 25510,
"text": "C#"
},
{
"code": null,
"e": 25517,
"s": 25513,
"text": "PHP"
},
{
"code": null,
"e": 25528,
"s": 25517,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the score for// the given binary stringint calcScore(string str){ int score = 0; int len = str.length(); // Traverse through string character for (int i = 0; i < len;) { // Initialize current chunk's size int chunkSize = 1; // Get current character char currentChar = str[i++]; // Calculate total chunk size // of same characters while (i < len && str[i] == currentChar) { chunkSize++; i++; } // Add/subtract pow(chunkSize, 2) // depending upon character if (currentChar == '1') score += pow(chunkSize, 2); else score -= pow(chunkSize, 2); } // Return the score return score;} // Driver codeint main(){ string str = \"11011\"; cout << calcScore(str); return 0;}",
"e": 26457,
"s": 25528,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the score for // the given binary string public static int calcScore(String str) { int score = 0; int len = str.length(); // Traverse through string character for (int i = 0; i < len;) { // Initialize current chunk's size int chunkSize = 1; // Get current character char currentChar = str.charAt(i++); // Calculate total chunk size // of same characters while (i < len && str.charAt(i) == currentChar) { chunkSize++; i++; } // Add/subtract pow(chunkSize, 2) // depending upon character if (currentChar == '1') score += Math.pow(chunkSize, 2); else score -= Math.pow(chunkSize, 2); } // Return the score return score; } // Driver code public static void main(String[] args) { String str = \"11011\"; System.out.println(calcScore(str)); }} // This code is contributed by Naman_Garg",
"e": 27626,
"s": 26457,
"text": null
},
{
"code": "# Python 3 implementation of the approach # Function to return the score for# the given binary stringdef calcScore(str): score = 0 len1 = len(str) # Traverse through string character i = 0 while(i < len1): # Initialize current chunk's size chunkSize = 1 # Get current character currentChar = str[i] i += 1 # Calculate total chunk size # of same characters while (i < len1 and str[i] == currentChar): chunkSize += 1 i += 1 # Add/subtract pow(chunkSize, 2) # depending upon character if (currentChar == '1'): score += pow(chunkSize, 2) else: score -= pow(chunkSize, 2) # Return the score return score # Driver codeif __name__ == '__main__': str = \"11011\" print(calcScore(str)) # This code is contributed by# Surendra_Gangwar",
"e": 28518,
"s": 27626,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the score for // the given binary string public static int calcScore(String str) { int score = 0; int len = str.Length; // Traverse through string character for (int i = 0; i < len;) { // Initialize current chunk's size int chunkSize = 1; // Get current character char currentChar = str[i++]; // Calculate total chunk size // of same characters while (i < len && str[i] == currentChar) { chunkSize++; i++; } // Add/subtract pow(chunkSize, 2) // depending upon character if (currentChar == '1') score += (int)Math.Pow(chunkSize, 2); else score -= (int)Math.Pow(chunkSize, 2); } // Return the score return score; } // Driver code public static void Main(String[] args) { String str = \"11011\"; Console.WriteLine(calcScore(str)); }} // This code contributed by Rajput-Ji",
"e": 29692,
"s": 28518,
"text": null
},
{
"code": "<?php// Php implementation of the approach // Function to return the score for// the given binary stringfunction calcScore($str){ $score = 0; $len = strlen($str); // Traverse through string character for ($i = 0; $i < $len { // Initialize current chunk's size $chunkSize = 1; // Get current character $currentChar = $str[$i++]; // Calculate total chunk size // of same characters while ($i < $len && $str[$i] == $currentChar) { $chunkSize++; $i++; } // Add/subtract pow(chunkSize, 2) // depending upon character if ($currentChar == '1') $score += pow($chunkSize, 2); else $score -= pow($chunkSize, 2); } // Return the score return $score;} // Driver code $str = \"11011\"; echo calcScore($str); // This code is contributed by AnkitRai01?>",
"e": 30612,
"s": 29692,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the score for// the given binary stringfunction calcScore(str){ var score = 0; var len = str.length; // Traverse through string character for (var i = 0; i < len;) { // Initialize current chunk's size var chunkSize = 1; // Get current character var currentChar = str[i++]; // Calculate total chunk size // of same characters while (i < len && str[i] == currentChar) { chunkSize++; i++; } // Add/subtract pow(chunkSize, 2) // depending upon character if (currentChar == '1') score += Math.pow(chunkSize, 2); else score -= Math.pow(chunkSize, 2); } // Return the score return score;} // Driver codevar str = \"11011\";document.write( calcScore(str)); </script>",
"e": 31501,
"s": 30612,
"text": null
},
{
"code": null,
"e": 31503,
"s": 31501,
"text": "7"
},
{
"code": null,
"e": 31513,
"s": 31505,
"text": "ankthon"
},
{
"code": null,
"e": 31524,
"s": 31513,
"text": "Naman_Garg"
},
{
"code": null,
"e": 31541,
"s": 31524,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 31551,
"s": 31541,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31558,
"s": 31551,
"text": "rrrtnx"
},
{
"code": null,
"e": 31572,
"s": 31558,
"text": "binary-string"
},
{
"code": null,
"e": 31582,
"s": 31572,
"text": "substring"
},
{
"code": null,
"e": 31590,
"s": 31582,
"text": "Strings"
},
{
"code": null,
"e": 31598,
"s": 31590,
"text": "Strings"
},
{
"code": null,
"e": 31696,
"s": 31598,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31741,
"s": 31696,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 31779,
"s": 31741,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 31796,
"s": 31779,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 31808,
"s": 31796,
"text": "Hill Cipher"
},
{
"code": null,
"e": 31838,
"s": 31808,
"text": "Count words in a given string"
},
{
"code": null,
"e": 31881,
"s": 31838,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 31922,
"s": 31881,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 31937,
"s": 31922,
"text": "sprintf() in C"
},
{
"code": null,
"e": 31998,
"s": 31937,
"text": "Program to count occurrence of a given character in a string"
}
] |
Rust - Collections
|
Rust's standard collection library provides efficient implementations of the most common general-purpose programming data structures. This chapter discusses the implementation of the commonly used collections − Vector, HashMap and HashSet.
A Vector is a resizable array. It stores values in contiguous memory blocks. The predefined structure Vec can be used to create vectors. Some important features of a Vector are −
A Vector can grow or shrink at runtime.
A Vector can grow or shrink at runtime.
A Vector is a homogeneous collection.
A Vector is a homogeneous collection.
A Vector stores data as sequence of elements in a particular order. Every element in a Vector is assigned a unique index number. The index starts from 0 and goes up to n-1 where, n is the size of the collection. For example, in a collection of 5 elements, the first element will be at index 0 and the last element will be at index 4.
A Vector stores data as sequence of elements in a particular order. Every element in a Vector is assigned a unique index number. The index starts from 0 and goes up to n-1 where, n is the size of the collection. For example, in a collection of 5 elements, the first element will be at index 0 and the last element will be at index 4.
A Vector will only append values to (or near) the end. In other words, a Vector can be used to implement a stack.
A Vector will only append values to (or near) the end. In other words, a Vector can be used to implement a stack.
Memory for a Vector is allocated in the heap.
Memory for a Vector is allocated in the heap.
let mut instance_name = Vec::new();
The static method new() of the Vecstructure is used to create a vector instance.
Alternatively, a vector can also be created using the vec! macro. The syntax is as given below −
let vector_name = vec![val1,val2,val3]
The following table lists some commonly used functions of the Vec structure.
pub fn new()->Vect
Constructs a new, empty Vec. The vector will not allocate until elements are pushed onto it.
pub fn push(&mut self, value: T)
Appends an element to the back of a collection.
pub fn remove(&mut self, index: usize) -> T
Removes and returns the element at position index within the vector, shifting all elements after it to the left.
pub fn contains(&self, x: &T) -> bool
Returns true if the slice contains an element with the given value.
pub fn len(&self) -> usize
Returns the number of elements in the vector, also referred to as its 'length'.
To create a vector, we use the static method new−
fn main() {
let mut v = Vec::new();
v.push(20);
v.push(30);
v.push(40);
println!("size of vector is :{}",v.len());
println!("{:?}",v);
}
The above example creates a Vector using the static method new() that is defined in structure Vec. The push(val) function appends the value passed as parameter to the collection. The len() function returns the length of the vector.
size of vector is :3
[20, 30, 40]
The following code creates a vector using the vec! macro. The data type of the vector is inferred the first value that is assigned to it.
fn main() {
let v = vec![1,2,3];
println!("{:?}",v);
}
[1, 2, 3]
As mentioned earlier, a vector can only contain values of the same data type. The following snippet will throw a error[E0308]: mismatched types error.
fn main() {
let v = vec![1,2,3,"hello"];
println!("{:?}",v);
}
Appends an element to the end of a collection.
fn main() {
let mut v = Vec::new();
v.push(20);
v.push(30);
v.push(40);
println!("{:?}",v);
}
[20, 30, 40]
Removes and returns the element at position index within the vector, shifting all elements after it to the left.
fn main() {
let mut v = vec![10,20,30];
v.remove(1);
println!("{:?}",v);
}
[10, 30]
Returns true if the slice contains an element with the given value −
fn main() {
let v = vec![10,20,30];
if v.contains(&10) {
println!("found 10");
}
println!("{:?}",v);
}
found 10
[10, 20, 30]
Returns the number of elements in the vector, also referred to as its 'length'.
fn main() {
let v = vec![1,2,3];
println!("size of vector is :{}",v.len());
}
size of vector is :3
Individual elements in a vector can be accessed using their corresponding index numbers. The following example creates a vector ad prints the value of the first element.
fn main() {
let mut v = Vec::new();
v.push(20);
v.push(30);
println!("{:?}",v[0]);
}
Output: `20`
Values in a vector can also be fetched using reference to the collection.
fn main() {
let mut v = Vec::new();
v.push(20);
v.push(30);
v.push(40);
v.push(500);
for i in &v {
println!("{}",i);
}
println!("{:?}",v);
}
20
30
40
500
[20, 30, 40, 500]
A map is a collection of key-value pairs (called entries). No two entries in a map can have the same key. In short, a map is a lookup table. A HashMap stores the keys and values in a hash table. The entries are stored in an arbitrary order. The key is used to search for values in the HashMap. The HashMap structure is defined in the std::collections module. This module should be explicitly imported to access the HashMap structure.
let mut instance_name = HashMap::new();
The static method new() of the HashMap structure is used to create a HashMap object. This method creates an empty HashMap.
The commonly used functions of HashMap are discussed below −
pub fn insert(&mut self, k: K, v: V) -> Option
Inserts a key/value pair, if no key then None is returned. After update, old value is returned.
pub fn len(&self) -> usize
Returns the number of elements in the map.
pub fn get<Q: ?Sized>(&lself, k: &Q) -> Option<&V> where K:Borrow Q:Hash+ Eq
Returns a reference to the value corresponding to the key.
pub fn iter(&self) -> Iter<K, V>
An iterator visiting all key-value pairs in arbitrary order. The iterator element type is (&'a K, &'a V).
pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
Returns true if the map contains a value for the specified key.
pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
Removes a key from the map, returning the stored key and value if the key was previously in the map.
Inserts a key/value pair into the HashMap.
use std::collections::HashMap;
fn main(){
let mut stateCodes = HashMap::new();
stateCodes.insert("KL","Kerala");
stateCodes.insert("MH","Maharashtra");
println!("{:?}",stateCodes);
}
The above program creates a HashMap and initializes it with 2 key-value pairs.
{"KL": "Kerala", "MH": "Maharashtra"}
Returns the number of elements in the map
use std::collections::HashMap;
fn main() {
let mut stateCodes = HashMap::new();
stateCodes.insert("KL","Kerala");
stateCodes.insert("MH","Maharashtra");
println!("size of map is {}",stateCodes.len());
}
The above example creates a HashMap and prints the total number of elements in it.
size of map is 2
Returns a reference to the value corresponding to the key. The following example retrieves the value for key KL in the HashMap.
use std::collections::HashMap;
fn main() {
let mut stateCodes = HashMap::new();
stateCodes.insert("KL","Kerala");
stateCodes.insert("MH","Maharashtra");
println!("size of map is {}",stateCodes.len());
println!("{:?}",stateCodes);
match stateCodes.get(&"KL") {
Some(value)=> {
println!("Value for key KL is {}",value);
}
None => {
println!("nothing found");
}
}
}
size of map is 2
{"KL": "Kerala", "MH": "Maharashtra"}
Value for key KL is Kerala
Returns an iterator containing reference to all key-value pairs in an arbitrary order.
use std::collections::HashMap;
fn main() {
let mut stateCodes = HashMap::new();
stateCodes.insert("KL","Kerala");
stateCodes.insert("MH","Maharashtra");
for (key, val) in stateCodes.iter() {
println!("key: {} val: {}", key, val);
}
}
key: MH val: Maharashtra
key: KL val: Kerala
Returns true if the map contains a value for the specified key.
use std::collections::HashMap;
fn main() {
let mut stateCodes = HashMap::new();
stateCodes.insert("KL","Kerala");
stateCodes.insert("MH","Maharashtra");
stateCodes.insert("GJ","Gujarat");
if stateCodes.contains_key(&"GJ") {
println!("found key");
}
}
found key
Removes a key from the map.
use std::collections::HashMap;
fn main() {
let mut stateCodes = HashMap::new();
stateCodes.insert("KL","Kerala");
stateCodes.insert("MH","Maharashtra");
stateCodes.insert("GJ","Gujarat");
println!("length of the hashmap {}",stateCodes.len());
stateCodes.remove(&"GJ");
println!("length of the hashmap after remove() {}",stateCodes.len());
}
length of the hashmap 3
length of the hashmap after remove() 2
HashSet is a set of unique values of type T. Adding and removing values is fast, and it is fast to ask whether a given value is in the set or not. The HashSet structure is defined in the std::collections module. This module should be explicitly imported to access the HashSet structure.
let mut hash_set_name = HashSet::new();
The static method, new, of HashSet structure is used to create a HashSet. This method creates an empty HashSet.
The following table lists some of the commonly used methods of the HashSet structure.
pub fn insert(&mut self, value: T) -> bool
Adds a value to the set. If the set did not have this value present, true is returned else false.
pub fn len(&self) -> usize
Returns the number of elements in the set.
pub fn get<Q:?Sized>(&self, value: &Q) -> Option<&T> where T: Borrow,Q: Hash + Eq,
Returns a reference to the value in the set, if any that is equal to the given value.
pub fn iter(&self) -> Iter
Returns an iterator visiting all elements in arbitrary order. The iterator element type is &'a T.
pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
Returns true if the set contains a value.
pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
Removes a value from the set. Returns true if the value was present in the set.
Adds a value to the set. A HashSet does not add duplicate values to the collection.
use std::collections::HashSet;
fn main() {
let mut names = HashSet::new();
names.insert("Mohtashim");
names.insert("Kannan");
names.insert("TutorialsPoint");
names.insert("Mohtashim");//duplicates not added
println!("{:?}",names);
}
{"TutorialsPoint", "Kannan", "Mohtashim"}
Returns the number of elements in the set.
use std::collections::HashSet;
fn main() {
let mut names = HashSet::new();
names.insert("Mohtashim");
names.insert("Kannan");
names.insert("TutorialsPoint");
println!("size of the set is {}",names.len());
}
size of the set is 3
Retruns an iterator visiting all elements in arbitrary order.
use std::collections::HashSet;
fn main() {
let mut names = HashSet::new();
names.insert("Mohtashim");
names.insert("Kannan");
names.insert("TutorialsPoint");
names.insert("Mohtashim");
for name in names.iter() {
println!("{}",name);
}
}
TutorialsPoint
Mohtashim
Kannan
Returns a reference to the value in the set, if any, which is equal to the given value.
use std::collections::HashSet;
fn main() {
let mut names = HashSet::new();
names.insert("Mohtashim");
names.insert("Kannan");
names.insert("TutorialsPoint");
names.insert("Mohtashim");
match names.get(&"Mohtashim"){
Some(value)=>{
println!("found {}",value);
}
None =>{
println!("not found");
}
}
println!("{:?}",names);
}
found Mohtashim
{"Kannan", "Mohtashim", "TutorialsPoint"}
Returns true if the set contains a value.
use std::collections::HashSet;
fn main() {
let mut names = HashSet::new();
names.insert("Mohtashim");
names.insert("Kannan");
names.insert("TutorialsPoint");
if names.contains(&"Kannan") {
println!("found name");
}
}
found name
Removes a value from the set.
use std::collections::HashSet;
fn main() {
let mut names = HashSet::new();
names.insert("Mohtashim");
names.insert("Kannan");
names.insert("TutorialsPoint");
println!("length of the Hashset: {}",names.len());
names.remove(&"Kannan");
println!("length of the Hashset after remove() : {}",names.len());
}
length of the Hashset: 3
length of the Hashset after remove() : 2
45 Lectures
4.5 hours
Stone River ELearning
10 Lectures
33 mins
Ken Burke
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2327,
"s": 2087,
"text": "Rust's standard collection library provides efficient implementations of the most common general-purpose programming data structures. This chapter discusses the implementation of the commonly used collections − Vector, HashMap and HashSet."
},
{
"code": null,
"e": 2506,
"s": 2327,
"text": "A Vector is a resizable array. It stores values in contiguous memory blocks. The predefined structure Vec can be used to create vectors. Some important features of a Vector are −"
},
{
"code": null,
"e": 2546,
"s": 2506,
"text": "A Vector can grow or shrink at runtime."
},
{
"code": null,
"e": 2586,
"s": 2546,
"text": "A Vector can grow or shrink at runtime."
},
{
"code": null,
"e": 2624,
"s": 2586,
"text": "A Vector is a homogeneous collection."
},
{
"code": null,
"e": 2662,
"s": 2624,
"text": "A Vector is a homogeneous collection."
},
{
"code": null,
"e": 2996,
"s": 2662,
"text": "A Vector stores data as sequence of elements in a particular order. Every element in a Vector is assigned a unique index number. The index starts from 0 and goes up to n-1 where, n is the size of the collection. For example, in a collection of 5 elements, the first element will be at index 0 and the last element will be at index 4."
},
{
"code": null,
"e": 3330,
"s": 2996,
"text": "A Vector stores data as sequence of elements in a particular order. Every element in a Vector is assigned a unique index number. The index starts from 0 and goes up to n-1 where, n is the size of the collection. For example, in a collection of 5 elements, the first element will be at index 0 and the last element will be at index 4."
},
{
"code": null,
"e": 3444,
"s": 3330,
"text": "A Vector will only append values to (or near) the end. In other words, a Vector can be used to implement a stack."
},
{
"code": null,
"e": 3558,
"s": 3444,
"text": "A Vector will only append values to (or near) the end. In other words, a Vector can be used to implement a stack."
},
{
"code": null,
"e": 3604,
"s": 3558,
"text": "Memory for a Vector is allocated in the heap."
},
{
"code": null,
"e": 3650,
"s": 3604,
"text": "Memory for a Vector is allocated in the heap."
},
{
"code": null,
"e": 3687,
"s": 3650,
"text": "let mut instance_name = Vec::new();\n"
},
{
"code": null,
"e": 3768,
"s": 3687,
"text": "The static method new() of the Vecstructure is used to create a vector instance."
},
{
"code": null,
"e": 3865,
"s": 3768,
"text": "Alternatively, a vector can also be created using the vec! macro. The syntax is as given below −"
},
{
"code": null,
"e": 3905,
"s": 3865,
"text": "let vector_name = vec![val1,val2,val3]\n"
},
{
"code": null,
"e": 3982,
"s": 3905,
"text": "The following table lists some commonly used functions of the Vec structure."
},
{
"code": null,
"e": 4001,
"s": 3982,
"text": "pub fn new()->Vect"
},
{
"code": null,
"e": 4094,
"s": 4001,
"text": "Constructs a new, empty Vec. The vector will not allocate until elements are pushed onto it."
},
{
"code": null,
"e": 4127,
"s": 4094,
"text": "pub fn push(&mut self, value: T)"
},
{
"code": null,
"e": 4175,
"s": 4127,
"text": "Appends an element to the back of a collection."
},
{
"code": null,
"e": 4219,
"s": 4175,
"text": "pub fn remove(&mut self, index: usize) -> T"
},
{
"code": null,
"e": 4332,
"s": 4219,
"text": "Removes and returns the element at position index within the vector, shifting all elements after it to the left."
},
{
"code": null,
"e": 4370,
"s": 4332,
"text": "pub fn contains(&self, x: &T) -> bool"
},
{
"code": null,
"e": 4438,
"s": 4370,
"text": "Returns true if the slice contains an element with the given value."
},
{
"code": null,
"e": 4465,
"s": 4438,
"text": "pub fn len(&self) -> usize"
},
{
"code": null,
"e": 4545,
"s": 4465,
"text": "Returns the number of elements in the vector, also referred to as its 'length'."
},
{
"code": null,
"e": 4595,
"s": 4545,
"text": "To create a vector, we use the static method new−"
},
{
"code": null,
"e": 4751,
"s": 4595,
"text": "fn main() {\n let mut v = Vec::new();\n v.push(20);\n v.push(30);\n v.push(40);\n\n println!(\"size of vector is :{}\",v.len());\n println!(\"{:?}\",v);\n}"
},
{
"code": null,
"e": 4983,
"s": 4751,
"text": "The above example creates a Vector using the static method new() that is defined in structure Vec. The push(val) function appends the value passed as parameter to the collection. The len() function returns the length of the vector."
},
{
"code": null,
"e": 5018,
"s": 4983,
"text": "size of vector is :3\n[20, 30, 40]\n"
},
{
"code": null,
"e": 5156,
"s": 5018,
"text": "The following code creates a vector using the vec! macro. The data type of the vector is inferred the first value that is assigned to it."
},
{
"code": null,
"e": 5217,
"s": 5156,
"text": "fn main() {\n let v = vec![1,2,3];\n println!(\"{:?}\",v);\n}"
},
{
"code": null,
"e": 5228,
"s": 5217,
"text": "[1, 2, 3]\n"
},
{
"code": null,
"e": 5379,
"s": 5228,
"text": "As mentioned earlier, a vector can only contain values of the same data type. The following snippet will throw a error[E0308]: mismatched types error."
},
{
"code": null,
"e": 5448,
"s": 5379,
"text": "fn main() {\n let v = vec![1,2,3,\"hello\"];\n println!(\"{:?}\",v);\n}"
},
{
"code": null,
"e": 5495,
"s": 5448,
"text": "Appends an element to the end of a collection."
},
{
"code": null,
"e": 5608,
"s": 5495,
"text": "fn main() {\n let mut v = Vec::new();\n v.push(20);\n v.push(30);\n v.push(40);\n \n println!(\"{:?}\",v);\n}"
},
{
"code": null,
"e": 5622,
"s": 5608,
"text": "[20, 30, 40]\n"
},
{
"code": null,
"e": 5735,
"s": 5622,
"text": "Removes and returns the element at position index within the vector, shifting all elements after it to the left."
},
{
"code": null,
"e": 5819,
"s": 5735,
"text": "fn main() {\n let mut v = vec![10,20,30];\n v.remove(1);\n println!(\"{:?}\",v);\n}"
},
{
"code": null,
"e": 5829,
"s": 5819,
"text": "[10, 30]\n"
},
{
"code": null,
"e": 5898,
"s": 5829,
"text": "Returns true if the slice contains an element with the given value −"
},
{
"code": null,
"e": 6019,
"s": 5898,
"text": "fn main() {\n let v = vec![10,20,30];\n if v.contains(&10) {\n println!(\"found 10\");\n }\n println!(\"{:?}\",v);\n}"
},
{
"code": null,
"e": 6042,
"s": 6019,
"text": "found 10\n[10, 20, 30]\n"
},
{
"code": null,
"e": 6122,
"s": 6042,
"text": "Returns the number of elements in the vector, also referred to as its 'length'."
},
{
"code": null,
"e": 6206,
"s": 6122,
"text": "fn main() {\n let v = vec![1,2,3];\n println!(\"size of vector is :{}\",v.len());\n}"
},
{
"code": null,
"e": 6228,
"s": 6206,
"text": "size of vector is :3\n"
},
{
"code": null,
"e": 6398,
"s": 6228,
"text": "Individual elements in a vector can be accessed using their corresponding index numbers. The following example creates a vector ad prints the value of the first element."
},
{
"code": null,
"e": 6509,
"s": 6398,
"text": "fn main() {\n let mut v = Vec::new();\n v.push(20);\n v.push(30);\n\n println!(\"{:?}\",v[0]);\n}\nOutput: `20`"
},
{
"code": null,
"e": 6583,
"s": 6509,
"text": "Values in a vector can also be fetched using reference to the collection."
},
{
"code": null,
"e": 6755,
"s": 6583,
"text": "fn main() {\n let mut v = Vec::new();\n v.push(20);\n v.push(30);\n v.push(40);\n v.push(500);\n\n for i in &v {\n println!(\"{}\",i);\n }\n println!(\"{:?}\",v);\n}"
},
{
"code": null,
"e": 6787,
"s": 6755,
"text": "20\n30\n40\n500\n[20, 30, 40, 500]\n"
},
{
"code": null,
"e": 7221,
"s": 6787,
"text": "A map is a collection of key-value pairs (called entries). No two entries in a map can have the same key. In short, a map is a lookup table. A HashMap stores the keys and values in a hash table. The entries are stored in an arbitrary order. The key is used to search for values in the HashMap. The HashMap structure is defined in the std::collections module. This module should be explicitly imported to access the HashMap structure."
},
{
"code": null,
"e": 7262,
"s": 7221,
"text": "let mut instance_name = HashMap::new();\n"
},
{
"code": null,
"e": 7385,
"s": 7262,
"text": "The static method new() of the HashMap structure is used to create a HashMap object. This method creates an empty HashMap."
},
{
"code": null,
"e": 7446,
"s": 7385,
"text": "The commonly used functions of HashMap are discussed below −"
},
{
"code": null,
"e": 7493,
"s": 7446,
"text": "pub fn insert(&mut self, k: K, v: V) -> Option"
},
{
"code": null,
"e": 7589,
"s": 7493,
"text": "Inserts a key/value pair, if no key then None is returned. After update, old value is returned."
},
{
"code": null,
"e": 7616,
"s": 7589,
"text": "pub fn len(&self) -> usize"
},
{
"code": null,
"e": 7659,
"s": 7616,
"text": "Returns the number of elements in the map."
},
{
"code": null,
"e": 7736,
"s": 7659,
"text": "pub fn get<Q: ?Sized>(&lself, k: &Q) -> Option<&V> where K:Borrow Q:Hash+ Eq"
},
{
"code": null,
"e": 7795,
"s": 7736,
"text": "Returns a reference to the value corresponding to the key."
},
{
"code": null,
"e": 7828,
"s": 7795,
"text": "pub fn iter(&self) -> Iter<K, V>"
},
{
"code": null,
"e": 7934,
"s": 7828,
"text": "An iterator visiting all key-value pairs in arbitrary order. The iterator element type is (&'a K, &'a V)."
},
{
"code": null,
"e": 7987,
"s": 7934,
"text": "pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool"
},
{
"code": null,
"e": 8051,
"s": 7987,
"text": "Returns true if the map contains a value for the specified key."
},
{
"code": null,
"e": 8118,
"s": 8051,
"text": "pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>"
},
{
"code": null,
"e": 8219,
"s": 8118,
"text": "Removes a key from the map, returning the stored key and value if the key was previously in the map."
},
{
"code": null,
"e": 8262,
"s": 8219,
"text": "Inserts a key/value pair into the HashMap."
},
{
"code": null,
"e": 8457,
"s": 8262,
"text": "use std::collections::HashMap;\nfn main(){\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n println!(\"{:?}\",stateCodes);\n}"
},
{
"code": null,
"e": 8536,
"s": 8457,
"text": "The above program creates a HashMap and initializes it with 2 key-value pairs."
},
{
"code": null,
"e": 8575,
"s": 8536,
"text": "{\"KL\": \"Kerala\", \"MH\": \"Maharashtra\"}\n"
},
{
"code": null,
"e": 8617,
"s": 8575,
"text": "Returns the number of elements in the map"
},
{
"code": null,
"e": 8832,
"s": 8617,
"text": "use std::collections::HashMap;\nfn main() {\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n println!(\"size of map is {}\",stateCodes.len());\n}"
},
{
"code": null,
"e": 8915,
"s": 8832,
"text": "The above example creates a HashMap and prints the total number of elements in it."
},
{
"code": null,
"e": 8933,
"s": 8915,
"text": "size of map is 2\n"
},
{
"code": null,
"e": 9061,
"s": 8933,
"text": "Returns a reference to the value corresponding to the key. The following example retrieves the value for key KL in the HashMap."
},
{
"code": null,
"e": 9488,
"s": 9061,
"text": "use std::collections::HashMap;\nfn main() {\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n println!(\"size of map is {}\",stateCodes.len());\n println!(\"{:?}\",stateCodes);\n\n match stateCodes.get(&\"KL\") {\n Some(value)=> {\n println!(\"Value for key KL is {}\",value);\n }\n None => {\n println!(\"nothing found\");\n }\n }\n}"
},
{
"code": null,
"e": 9571,
"s": 9488,
"text": "size of map is 2\n{\"KL\": \"Kerala\", \"MH\": \"Maharashtra\"}\nValue for key KL is Kerala\n"
},
{
"code": null,
"e": 9658,
"s": 9571,
"text": "Returns an iterator containing reference to all key-value pairs in an arbitrary order."
},
{
"code": null,
"e": 9914,
"s": 9658,
"text": "use std::collections::HashMap;\nfn main() {\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n\n for (key, val) in stateCodes.iter() {\n println!(\"key: {} val: {}\", key, val);\n }\n}"
},
{
"code": null,
"e": 9960,
"s": 9914,
"text": "key: MH val: Maharashtra\nkey: KL val: Kerala\n"
},
{
"code": null,
"e": 10024,
"s": 9960,
"text": "Returns true if the map contains a value for the specified key."
},
{
"code": null,
"e": 10300,
"s": 10024,
"text": "use std::collections::HashMap;\nfn main() {\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n stateCodes.insert(\"GJ\",\"Gujarat\");\n\n if stateCodes.contains_key(&\"GJ\") {\n println!(\"found key\");\n }\n}"
},
{
"code": null,
"e": 10311,
"s": 10300,
"text": "found key\n"
},
{
"code": null,
"e": 10339,
"s": 10311,
"text": "Removes a key from the map."
},
{
"code": null,
"e": 10702,
"s": 10339,
"text": "use std::collections::HashMap;\nfn main() {\n let mut stateCodes = HashMap::new();\n stateCodes.insert(\"KL\",\"Kerala\");\n stateCodes.insert(\"MH\",\"Maharashtra\");\n stateCodes.insert(\"GJ\",\"Gujarat\");\n\n println!(\"length of the hashmap {}\",stateCodes.len());\n stateCodes.remove(&\"GJ\");\n println!(\"length of the hashmap after remove() {}\",stateCodes.len());\n}"
},
{
"code": null,
"e": 10766,
"s": 10702,
"text": "length of the hashmap 3\nlength of the hashmap after remove() 2\n"
},
{
"code": null,
"e": 11053,
"s": 10766,
"text": "HashSet is a set of unique values of type T. Adding and removing values is fast, and it is fast to ask whether a given value is in the set or not. The HashSet structure is defined in the std::collections module. This module should be explicitly imported to access the HashSet structure."
},
{
"code": null,
"e": 11094,
"s": 11053,
"text": "let mut hash_set_name = HashSet::new();\n"
},
{
"code": null,
"e": 11206,
"s": 11094,
"text": "The static method, new, of HashSet structure is used to create a HashSet. This method creates an empty HashSet."
},
{
"code": null,
"e": 11292,
"s": 11206,
"text": "The following table lists some of the commonly used methods of the HashSet structure."
},
{
"code": null,
"e": 11335,
"s": 11292,
"text": "pub fn insert(&mut self, value: T) -> bool"
},
{
"code": null,
"e": 11433,
"s": 11335,
"text": "Adds a value to the set. If the set did not have this value present, true is returned else false."
},
{
"code": null,
"e": 11460,
"s": 11433,
"text": "pub fn len(&self) -> usize"
},
{
"code": null,
"e": 11503,
"s": 11460,
"text": "Returns the number of elements in the set."
},
{
"code": null,
"e": 11586,
"s": 11503,
"text": "pub fn get<Q:?Sized>(&self, value: &Q) -> Option<&T> where T: Borrow,Q: Hash + Eq,"
},
{
"code": null,
"e": 11672,
"s": 11586,
"text": "Returns a reference to the value in the set, if any that is equal to the given value."
},
{
"code": null,
"e": 11699,
"s": 11672,
"text": "pub fn iter(&self) -> Iter"
},
{
"code": null,
"e": 11797,
"s": 11699,
"text": "Returns an iterator visiting all elements in arbitrary order. The iterator element type is &'a T."
},
{
"code": null,
"e": 11850,
"s": 11797,
"text": "pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool"
},
{
"code": null,
"e": 11892,
"s": 11850,
"text": "Returns true if the set contains a value."
},
{
"code": null,
"e": 11947,
"s": 11892,
"text": "pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool"
},
{
"code": null,
"e": 12027,
"s": 11947,
"text": "Removes a value from the set. Returns true if the value was present in the set."
},
{
"code": null,
"e": 12111,
"s": 12027,
"text": "Adds a value to the set. A HashSet does not add duplicate values to the collection."
},
{
"code": null,
"e": 12364,
"s": 12111,
"text": "use std::collections::HashSet;\nfn main() {\n let mut names = HashSet::new();\n\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n names.insert(\"Mohtashim\");//duplicates not added\n\n println!(\"{:?}\",names);\n}"
},
{
"code": null,
"e": 12407,
"s": 12364,
"text": "{\"TutorialsPoint\", \"Kannan\", \"Mohtashim\"}\n"
},
{
"code": null,
"e": 12450,
"s": 12407,
"text": "Returns the number of elements in the set."
},
{
"code": null,
"e": 12672,
"s": 12450,
"text": "use std::collections::HashSet;\nfn main() {\n let mut names = HashSet::new();\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n println!(\"size of the set is {}\",names.len());\n}"
},
{
"code": null,
"e": 12694,
"s": 12672,
"text": "size of the set is 3\n"
},
{
"code": null,
"e": 12756,
"s": 12694,
"text": "Retruns an iterator visiting all elements in arbitrary order."
},
{
"code": null,
"e": 13021,
"s": 12756,
"text": "use std::collections::HashSet;\nfn main() {\n let mut names = HashSet::new();\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n names.insert(\"Mohtashim\");\n\n for name in names.iter() {\n println!(\"{}\",name);\n }\n}"
},
{
"code": null,
"e": 13054,
"s": 13021,
"text": "TutorialsPoint\nMohtashim\nKannan\n"
},
{
"code": null,
"e": 13142,
"s": 13054,
"text": "Returns a reference to the value in the set, if any, which is equal to the given value."
},
{
"code": null,
"e": 13532,
"s": 13142,
"text": "use std::collections::HashSet;\nfn main() {\n let mut names = HashSet::new();\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n names.insert(\"Mohtashim\");\n\n match names.get(&\"Mohtashim\"){\n Some(value)=>{\n println!(\"found {}\",value);\n }\n None =>{\n println!(\"not found\");\n }\n }\n println!(\"{:?}\",names);\n}"
},
{
"code": null,
"e": 13591,
"s": 13532,
"text": "found Mohtashim\n{\"Kannan\", \"Mohtashim\", \"TutorialsPoint\"}\n"
},
{
"code": null,
"e": 13633,
"s": 13591,
"text": "Returns true if the set contains a value."
},
{
"code": null,
"e": 13878,
"s": 13633,
"text": "use std::collections::HashSet;\n\nfn main() {\n let mut names = HashSet::new();\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n\n if names.contains(&\"Kannan\") {\n println!(\"found name\");\n } \n}"
},
{
"code": null,
"e": 13890,
"s": 13878,
"text": "found name\n"
},
{
"code": null,
"e": 13920,
"s": 13890,
"text": "Removes a value from the set."
},
{
"code": null,
"e": 14245,
"s": 13920,
"text": "use std::collections::HashSet;\n\nfn main() {\n let mut names = HashSet::new();\n names.insert(\"Mohtashim\");\n names.insert(\"Kannan\");\n names.insert(\"TutorialsPoint\");\n println!(\"length of the Hashset: {}\",names.len());\n names.remove(&\"Kannan\");\n println!(\"length of the Hashset after remove() : {}\",names.len());\n}"
},
{
"code": null,
"e": 14312,
"s": 14245,
"text": "length of the Hashset: 3\nlength of the Hashset after remove() : 2\n"
},
{
"code": null,
"e": 14347,
"s": 14312,
"text": "\n 45 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 14370,
"s": 14347,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 14402,
"s": 14370,
"text": "\n 10 Lectures \n 33 mins\n"
},
{
"code": null,
"e": 14413,
"s": 14402,
"text": " Ken Burke"
},
{
"code": null,
"e": 14420,
"s": 14413,
"text": " Print"
},
{
"code": null,
"e": 14431,
"s": 14420,
"text": " Add Notes"
}
] |
Save a dictionary to a file
|
29 Dec, 2020
A dictionary in Python is a collection where every value is mapped to a key. They are unordered, mutable and there is no constraint on the data type of values and keys stored in the dictionary. This makes it tricky for dictionaries to be stored as files. Know more about dictionaries here.
Syntax:
dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'}
There are two main approaches for saving dictionaries into files using Python.
1. Text Files
The most basic way to save dictionaries in Python would be to store them as strings in text files. This method would include the following steps:
Opening a file in write/append text mode
Converting the dictionary into a string
Entering the converted string into the file using write function
filehandler = open(filename, 'wt')
data = str(dictionary)
filehander.write(data)
Reading from the dictionary back from the stored text files is cumbersome and this method should only be used for smaller and non-critical programs.
2. Pickle Module (Recommended)
The pickle module in Python is mostly used in fields like Data Science where data persistence is critical. The pickle module stores the given data as a serialized byte sequence into files which can be easily retrieved at a later time. Pickle module supports various Python objects and dictionaries are one among them. This method would include the following steps:
Importing the pickle module
Opening the file in write/append binary mode
Entering the data into the file using pickle module’s dump method
filehandler = open(filename, 'wb')
pickle.dump(dictionary, filehandler)
Below is the implementation of the above methods.
Example 1: Writing to Text File
Python3
dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'} try: geeky_file = open('geekyfile.txt', 'wt') geeky_file.write(str(dictionary)) geeky_file.close() except: print("Unable to write to file")
Output:
Example 2: Appending to Text File
Python3
dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'} try: geeky_file = open('geekyfile.txt', 'a') geeky_file.write(str(dictionary)) geeky_file.close() except: print("Unable to append to file")
Output:
Example 3: Writing using Pickle Module
Python3
import pickle dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'} try: geeky_file = open('geekyfile', 'wb') pickle.dump(dictionary, geeky_file) geeky_file.close() except: print("Something went wrong")
Note: As the pickle module stores data in binary form, the data in the file is unreadable by humans.
Python file-handling-programs
python-dict
python-file-handling
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 318,
"s": 28,
"text": "A dictionary in Python is a collection where every value is mapped to a key. They are unordered, mutable and there is no constraint on the data type of values and keys stored in the dictionary. This makes it tricky for dictionaries to be stored as files. Know more about dictionaries here."
},
{
"code": null,
"e": 326,
"s": 318,
"text": "Syntax:"
},
{
"code": null,
"e": 383,
"s": 326,
"text": "dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'}\n"
},
{
"code": null,
"e": 462,
"s": 383,
"text": "There are two main approaches for saving dictionaries into files using Python."
},
{
"code": null,
"e": 476,
"s": 462,
"text": "1. Text Files"
},
{
"code": null,
"e": 622,
"s": 476,
"text": "The most basic way to save dictionaries in Python would be to store them as strings in text files. This method would include the following steps:"
},
{
"code": null,
"e": 663,
"s": 622,
"text": "Opening a file in write/append text mode"
},
{
"code": null,
"e": 703,
"s": 663,
"text": "Converting the dictionary into a string"
},
{
"code": null,
"e": 768,
"s": 703,
"text": "Entering the converted string into the file using write function"
},
{
"code": null,
"e": 850,
"s": 768,
"text": "filehandler = open(filename, 'wt')\ndata = str(dictionary)\nfilehander.write(data)\n"
},
{
"code": null,
"e": 999,
"s": 850,
"text": "Reading from the dictionary back from the stored text files is cumbersome and this method should only be used for smaller and non-critical programs."
},
{
"code": null,
"e": 1030,
"s": 999,
"text": "2. Pickle Module (Recommended)"
},
{
"code": null,
"e": 1395,
"s": 1030,
"text": "The pickle module in Python is mostly used in fields like Data Science where data persistence is critical. The pickle module stores the given data as a serialized byte sequence into files which can be easily retrieved at a later time. Pickle module supports various Python objects and dictionaries are one among them. This method would include the following steps:"
},
{
"code": null,
"e": 1423,
"s": 1395,
"text": "Importing the pickle module"
},
{
"code": null,
"e": 1468,
"s": 1423,
"text": "Opening the file in write/append binary mode"
},
{
"code": null,
"e": 1534,
"s": 1468,
"text": "Entering the data into the file using pickle module’s dump method"
},
{
"code": null,
"e": 1607,
"s": 1534,
"text": "filehandler = open(filename, 'wb')\npickle.dump(dictionary, filehandler)\n"
},
{
"code": null,
"e": 1657,
"s": 1607,
"text": "Below is the implementation of the above methods."
},
{
"code": null,
"e": 1689,
"s": 1657,
"text": "Example 1: Writing to Text File"
},
{
"code": null,
"e": 1697,
"s": 1689,
"text": "Python3"
},
{
"code": "dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'} try: geeky_file = open('geekyfile.txt', 'wt') geeky_file.write(str(dictionary)) geeky_file.close() except: print(\"Unable to write to file\")",
"e": 1907,
"s": 1697,
"text": null
},
{
"code": null,
"e": 1915,
"s": 1907,
"text": "Output:"
},
{
"code": null,
"e": 1949,
"s": 1915,
"text": "Example 2: Appending to Text File"
},
{
"code": null,
"e": 1957,
"s": 1949,
"text": "Python3"
},
{
"code": "dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'} try: geeky_file = open('geekyfile.txt', 'a') geeky_file.write(str(dictionary)) geeky_file.close() except: print(\"Unable to append to file\")",
"e": 2167,
"s": 1957,
"text": null
},
{
"code": null,
"e": 2175,
"s": 2167,
"text": "Output:"
},
{
"code": null,
"e": 2214,
"s": 2175,
"text": "Example 3: Writing using Pickle Module"
},
{
"code": null,
"e": 2222,
"s": 2214,
"text": "Python3"
},
{
"code": "import pickle dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'} try: geeky_file = open('geekyfile', 'wb') pickle.dump(dictionary, geeky_file) geeky_file.close() except: print(\"Something went wrong\")",
"e": 2442,
"s": 2222,
"text": null
},
{
"code": null,
"e": 2543,
"s": 2442,
"text": "Note: As the pickle module stores data in binary form, the data in the file is unreadable by humans."
},
{
"code": null,
"e": 2573,
"s": 2543,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 2585,
"s": 2573,
"text": "python-dict"
},
{
"code": null,
"e": 2606,
"s": 2585,
"text": "python-file-handling"
},
{
"code": null,
"e": 2613,
"s": 2606,
"text": "Python"
},
{
"code": null,
"e": 2625,
"s": 2613,
"text": "python-dict"
}
] |
Short Note on Size-Oriented Metrics
|
30 Jun, 2020
Size Oriented Metrics derived by normalizing quality and productivity Point Metrics measures by considering size of the software that has been produced. The organization builds a simple record of size measure for the software projects. It is built on past experiences of organizations. It is a direct measure of software.
This metrics is one of simplest and earliest metrics that is used for computer program to measure size. Size Oriented Metrics are also used for measuring and comparing productivity of programmers. It is a direct measure of a Software. The size measurement is based on lines of code computation. The lines of code are defined as one line of text in a source file.
While counting lines of code, simplest standard is:
Don’t count blank lines
Don’t count comments
Count everything else
The size-oriented measure is not a universally accepted method.
Simple set of size measure that can be developed is as given below:
Size = Kilo Lines of Code (KLOC)
Effort = Person / month
Productivity = KLOC / person-month
Quality = Number of faults / KLOC
Cost = $ / KLOC
Documentation = Pages of documentation / KLOC
Advantages :
Using these metrics, it is very simple to measure size.
Artifact of Software development which is easily counted.
LOC is used by many methods that are already existing as a key input.
A large body of literature and data based on LOC already exists.
Disadvantages :
This measure is dependent upon programming language.
This method is well designed upon programming language.
It does not accommodate non-procedural languages.
Sometimes, it is very difficult to estimate LOC in early stage of development.
Though it is simple to measure but it is very hard to understand it for users.
It cannot measure size of specification as it is defined on code.
Example –For a size oriented metrics, software organization maintains records in tabular form. The typical table entries are: Project Name, LOC, Efforts, Pages of documents, Errors, Defects, Total number of people working on it.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2020"
},
{
"code": null,
"e": 374,
"s": 52,
"text": "Size Oriented Metrics derived by normalizing quality and productivity Point Metrics measures by considering size of the software that has been produced. The organization builds a simple record of size measure for the software projects. It is built on past experiences of organizations. It is a direct measure of software."
},
{
"code": null,
"e": 737,
"s": 374,
"text": "This metrics is one of simplest and earliest metrics that is used for computer program to measure size. Size Oriented Metrics are also used for measuring and comparing productivity of programmers. It is a direct measure of a Software. The size measurement is based on lines of code computation. The lines of code are defined as one line of text in a source file."
},
{
"code": null,
"e": 789,
"s": 737,
"text": "While counting lines of code, simplest standard is:"
},
{
"code": null,
"e": 813,
"s": 789,
"text": "Don’t count blank lines"
},
{
"code": null,
"e": 834,
"s": 813,
"text": "Don’t count comments"
},
{
"code": null,
"e": 856,
"s": 834,
"text": "Count everything else"
},
{
"code": null,
"e": 920,
"s": 856,
"text": "The size-oriented measure is not a universally accepted method."
},
{
"code": null,
"e": 988,
"s": 920,
"text": "Simple set of size measure that can be developed is as given below:"
},
{
"code": null,
"e": 1178,
"s": 988,
"text": "Size = Kilo Lines of Code (KLOC) \nEffort = Person / month\nProductivity = KLOC / person-month\nQuality = Number of faults / KLOC\nCost = $ / KLOC\nDocumentation = Pages of documentation / KLOC "
},
{
"code": null,
"e": 1191,
"s": 1178,
"text": "Advantages :"
},
{
"code": null,
"e": 1247,
"s": 1191,
"text": "Using these metrics, it is very simple to measure size."
},
{
"code": null,
"e": 1305,
"s": 1247,
"text": "Artifact of Software development which is easily counted."
},
{
"code": null,
"e": 1375,
"s": 1305,
"text": "LOC is used by many methods that are already existing as a key input."
},
{
"code": null,
"e": 1440,
"s": 1375,
"text": "A large body of literature and data based on LOC already exists."
},
{
"code": null,
"e": 1456,
"s": 1440,
"text": "Disadvantages :"
},
{
"code": null,
"e": 1509,
"s": 1456,
"text": "This measure is dependent upon programming language."
},
{
"code": null,
"e": 1565,
"s": 1509,
"text": "This method is well designed upon programming language."
},
{
"code": null,
"e": 1615,
"s": 1565,
"text": "It does not accommodate non-procedural languages."
},
{
"code": null,
"e": 1694,
"s": 1615,
"text": "Sometimes, it is very difficult to estimate LOC in early stage of development."
},
{
"code": null,
"e": 1773,
"s": 1694,
"text": "Though it is simple to measure but it is very hard to understand it for users."
},
{
"code": null,
"e": 1839,
"s": 1773,
"text": "It cannot measure size of specification as it is defined on code."
},
{
"code": null,
"e": 2068,
"s": 1839,
"text": "Example –For a size oriented metrics, software organization maintains records in tabular form. The typical table entries are: Project Name, LOC, Efforts, Pages of documents, Errors, Defects, Total number of people working on it."
},
{
"code": null,
"e": 2089,
"s": 2068,
"text": "Software Engineering"
}
] |
Python | Average of two lists
|
19 Feb, 2020
The problem of finding a average values in a list is quite common. But sometimes this problem can be extended in two lists and hence becomes a modified problem. This article discusses shorthands by which this task can be performed easily. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using sum() + len() + “+” operatorThe average value can be determined by the conventional sum() and len function of python and the extension of one to two lists can be dealt using the “+” operator.
# Python3 code to demonstrate# Average of two lists# using sum() + len() + "+" operator # initializing liststest_list1 = [1, 3, 4, 5, 2, 6]test_list2 = [3, 4, 8, 3, 10, 1] # printing the original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # Average of two lists# using sum() + len() + "+" operatorres = sum(test_list1 + test_list2) / len(test_list1 + test_list2) # printing resultprint ("The Average of both lists is : " + str(res))
The original list 1 is : [1, 3, 4, 5, 2, 6]
The original list 2 is : [3, 4, 8, 3, 10, 1]
The Average of both lists is : 4.166666666666667
Method #2 : Using sum() + len() + chain()Another method to perform this particular task is by using the chain function which performs the task similar to the “+” operator but using an iterator, hence faster.
# Python3 code to demonstrate# Average of two lists# using sum() + len() + "+" operatorfrom itertools import chain # initializing liststest_list1 = [1, 3, 4, 5, 2, 6]test_list2 = [3, 4, 8, 3, 10, 1] # printing the original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # Average of two lists# using sum() + len() + "+" operatorres = sum(chain(test_list1, test_list2)) / len(list(chain(test_list1, test_list2))) # printing resultprint ("The Average of both lists is : " + str(res))
The original list 1 is : [1, 3, 4, 5, 2, 6]
The original list 2 is : [3, 4, 8, 3, 10, 1]
The Average of both lists is : 4.166666666666667
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 356,
"s": 53,
"text": "The problem of finding a average values in a list is quite common. But sometimes this problem can be extended in two lists and hence becomes a modified problem. This article discusses shorthands by which this task can be performed easily. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 566,
"s": 356,
"text": "Method #1 : Using sum() + len() + “+” operatorThe average value can be determined by the conventional sum() and len function of python and the extension of one to two lists can be dealt using the “+” operator."
},
{
"code": "# Python3 code to demonstrate# Average of two lists# using sum() + len() + \"+\" operator # initializing liststest_list1 = [1, 3, 4, 5, 2, 6]test_list2 = [3, 4, 8, 3, 10, 1] # printing the original listsprint (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # Average of two lists# using sum() + len() + \"+\" operatorres = sum(test_list1 + test_list2) / len(test_list1 + test_list2) # printing resultprint (\"The Average of both lists is : \" + str(res))",
"e": 1072,
"s": 566,
"text": null
},
{
"code": null,
"e": 1211,
"s": 1072,
"text": "The original list 1 is : [1, 3, 4, 5, 2, 6]\nThe original list 2 is : [3, 4, 8, 3, 10, 1]\nThe Average of both lists is : 4.166666666666667\n"
},
{
"code": null,
"e": 1421,
"s": 1213,
"text": "Method #2 : Using sum() + len() + chain()Another method to perform this particular task is by using the chain function which performs the task similar to the “+” operator but using an iterator, hence faster."
},
{
"code": "# Python3 code to demonstrate# Average of two lists# using sum() + len() + \"+\" operatorfrom itertools import chain # initializing liststest_list1 = [1, 3, 4, 5, 2, 6]test_list2 = [3, 4, 8, 3, 10, 1] # printing the original listsprint (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # Average of two lists# using sum() + len() + \"+\" operatorres = sum(chain(test_list1, test_list2)) / len(list(chain(test_list1, test_list2))) # printing resultprint (\"The Average of both lists is : \" + str(res))",
"e": 1972,
"s": 1421,
"text": null
},
{
"code": null,
"e": 2111,
"s": 1972,
"text": "The original list 1 is : [1, 3, 4, 5, 2, 6]\nThe original list 2 is : [3, 4, 8, 3, 10, 1]\nThe Average of both lists is : 4.166666666666667\n"
},
{
"code": null,
"e": 2132,
"s": 2111,
"text": "Python list-programs"
},
{
"code": null,
"e": 2139,
"s": 2132,
"text": "Python"
},
{
"code": null,
"e": 2155,
"s": 2139,
"text": "Python Programs"
},
{
"code": null,
"e": 2253,
"s": 2155,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2285,
"s": 2253,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2306,
"s": 2285,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2333,
"s": 2306,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2356,
"s": 2333,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2387,
"s": 2356,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2409,
"s": 2387,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2448,
"s": 2409,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2486,
"s": 2448,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2523,
"s": 2486,
"text": "Python Program for Fibonacci numbers"
}
] |
How to Clone a List in Java?
|
03 Apr, 2019
Given a list in Java, the task is to clone this list.
Example:
Input: list = [“Geeks”, “for”, “Geeks”]Output: clonedList = [“Geeks”, “for”, “Geeks”]
Input: list = [“GeeksForGeeks”, “A Computer Science”, “Portal”]Output: clonedList = [“GeeksForGeeks”, “A Computer Science”, “Portal”]
In Java, there are various methods to clone a list. This article will explain some of the main methods used to achieve the same.
Using a Copy Constructor: Using the ArrayList constructor in Java, a new list can be initialized with the elements from another collection.Syntax:ArrayList cloned = new ArrayList(collection c);
where c is the collection containing
elements to be added to this list.
Approach:Create a list to be cloned.Clone the list by passing the original list as the parameter of the copy constructor of ArrayList.The following code illustrated this example.// Program to clone a List in Java import java.util.ArrayList;import java.util.Arrays;import java.util.List; class Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( "GeeksForGeeks", "A Computer Science", "Portal"); // Clone the list List<String> cloned_list = new ArrayList<String>(original); System.out.println(cloned_list); }}Output:[GeeksForGeeks, A Computer Science, Portal]
ArrayList cloned = new ArrayList(collection c);
where c is the collection containing
elements to be added to this list.
Approach:
Create a list to be cloned.Clone the list by passing the original list as the parameter of the copy constructor of ArrayList.
Create a list to be cloned.
Clone the list by passing the original list as the parameter of the copy constructor of ArrayList.
The following code illustrated this example.
// Program to clone a List in Java import java.util.ArrayList;import java.util.Arrays;import java.util.List; class Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( "GeeksForGeeks", "A Computer Science", "Portal"); // Clone the list List<String> cloned_list = new ArrayList<String>(original); System.out.println(cloned_list); }}
[GeeksForGeeks, A Computer Science, Portal]
Using the addAll() method: The List class has a method called addAll(), which appends all the elements of one collection to the list.Syntax:boolean addAll(Collection c);
where c is the collection containing
elements to be added to this list.
Approach:Create a list to be cloned.Create an empty list using the ArrayList constructor.Append the original list to the empty list using the addAll() method.The following example will illustrate this method.// Program to clone a List in Java import java.util.ArrayList;import java.util.Arrays;import java.util.List; class Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( "GeeksForGeeks", "A Computer Science", "Portal"); List<String> cloned_list = new ArrayList<String>(); // Cloning a list cloned_list.addAll(original); System.out.println(cloned_list); }}Output:[GeeksForGeeks, A Computer Science, Portal]
Syntax:
boolean addAll(Collection c);
where c is the collection containing
elements to be added to this list.
Approach:
Create a list to be cloned.Create an empty list using the ArrayList constructor.Append the original list to the empty list using the addAll() method.
Create a list to be cloned.
Create an empty list using the ArrayList constructor.
Append the original list to the empty list using the addAll() method.
The following example will illustrate this method.
// Program to clone a List in Java import java.util.ArrayList;import java.util.Arrays;import java.util.List; class Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( "GeeksForGeeks", "A Computer Science", "Portal"); List<String> cloned_list = new ArrayList<String>(); // Cloning a list cloned_list.addAll(original); System.out.println(cloned_list); }}
[GeeksForGeeks, A Computer Science, Portal]
Using streams in Java 8 Using the Streams API introduced in JAVA 8, cloning of a list is possible. The collect() method (along with toList() method) is used to clone a list.Approach:Create a classCreate a list of the class objects from an array using the asList method.Convert list of objects to a stream of objects using the stream() method.Use the collect(Collectors.toList()) methods to collect all the stream elements list instances and returning them to the cloned_list.The following program illustrates this concept.import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors; // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( "GeeksForGeeks", "A Computer Science", "Portal"); // Clone a list List<String> cloned_list = original.stream() .collect(Collectors.toList()); System.out.println(cloned_list); }}Output:[GeeksForGeeks, A Computer Science, Portal]
Approach:
Create a classCreate a list of the class objects from an array using the asList method.Convert list of objects to a stream of objects using the stream() method.Use the collect(Collectors.toList()) methods to collect all the stream elements list instances and returning them to the cloned_list.
Create a class
Create a list of the class objects from an array using the asList method.
Convert list of objects to a stream of objects using the stream() method.
Use the collect(Collectors.toList()) methods to collect all the stream elements list instances and returning them to the cloned_list.
The following program illustrates this concept.
import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors; // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( "GeeksForGeeks", "A Computer Science", "Portal"); // Clone a list List<String> cloned_list = original.stream() .collect(Collectors.toList()); System.out.println(cloned_list); }}
[GeeksForGeeks, A Computer Science, Portal]
Using the clone() method: Clone() method of a class in Java is used to create a new instance of a class of the current object and initialized all its fields with the contents of the specified object. To clone a list, one can iterate through the original list and use the clone method to copy all the list elements and use the add method to append them to the list.Syntax:protected Object clone()
throws CloneNotSupportedException
Approach:Create a cloneable class, which has the clone method overridden.Create a list of the class objects from an array using the asList method.Create an empty list.Loop through each element of the original list, and invoke the class object’s clone() method (which returns the class instance) and use the add() method to append it to the new list.The following example illustrates this concept.import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class needs to be cloneableclass GfG implements Cloneable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // To print the objects in the desired format @Override public String toString() { return "\nHello " + username + " !\n" + msg + "\n"; } // Overriding the inbuilt clone class @Override protected GfG clone() { return new GfG(username, msg); }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating a list List<GfG> original = Arrays.asList( new GfG("Geeks", "GeeksForGeeks"), new GfG("GFG", "A computer science portal for geeks")); // Creating an empty list List<GfG> cloned_list = new ArrayList<GfG>(); // Looping through the list // and cloning each element for (GfG temp : original) cloned_list.add(temp.clone()); System.out.println(cloned_list); }}Output:[
Hello Geeks !
GeeksForGeeks,
Hello GFG !
A computer science portal for geeks
]
Syntax:
protected Object clone()
throws CloneNotSupportedException
Approach:
Create a cloneable class, which has the clone method overridden.Create a list of the class objects from an array using the asList method.Create an empty list.Loop through each element of the original list, and invoke the class object’s clone() method (which returns the class instance) and use the add() method to append it to the new list.
Create a cloneable class, which has the clone method overridden.
Create a list of the class objects from an array using the asList method.
Create an empty list.
Loop through each element of the original list, and invoke the class object’s clone() method (which returns the class instance) and use the add() method to append it to the new list.
The following example illustrates this concept.
import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class needs to be cloneableclass GfG implements Cloneable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // To print the objects in the desired format @Override public String toString() { return "\nHello " + username + " !\n" + msg + "\n"; } // Overriding the inbuilt clone class @Override protected GfG clone() { return new GfG(username, msg); }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating a list List<GfG> original = Arrays.asList( new GfG("Geeks", "GeeksForGeeks"), new GfG("GFG", "A computer science portal for geeks")); // Creating an empty list List<GfG> cloned_list = new ArrayList<GfG>(); // Looping through the list // and cloning each element for (GfG temp : original) cloned_list.add(temp.clone()); System.out.println(cloned_list); }}
[
Hello Geeks !
GeeksForGeeks,
Hello GFG !
A computer science portal for geeks
]
Using Apache Commons Lang: The same can also be aschieved by using the clone method provided by third party libraries such as Apache Commons Lang.Syntax:public static T clone(T object)
where T is the type of the object
and object is the Serializable object
to be cloned
Approach:Create a Serializable class.Create a list of the class objects from an array using the asList method.Create an empty list.Loop through each element of the original list, and invoke the SerializationUtils.clone() method of the serializable objects (which returns the class instance) and use the add() method to append it to the new list.The following program illustrates this case.import org.apache.commons.lang3.SerializationUtils;import java.io.Serializable;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class should be Serializableclass GfG implements Serializable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the objects // in the desired manner @Override public String toString() { return "\nHello " + username + " !\n" + msg + "\n"; }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating the list List<GfG> original = Arrays.asList( new GfG("Mukkesh", "Hey there fellows!"), new GfG("McKenzie", "Welcome to my page!")); // Creating an empty list List<GfG> cloned_list = new ArrayList<GfG>(); // Looping through the list // and cloning each element // using SerializationUtils.clone for (GfG temp : original) cloned_list.add( SerializationUtils.clone(temp)); System.out.println(cloned_list); }}Output:[
Hello Mukkesh !
Hey there fellows!,
Hello McKenzie !
Welcome to my page!
]
public static T clone(T object)
where T is the type of the object
and object is the Serializable object
to be cloned
Approach:
Create a Serializable class.Create a list of the class objects from an array using the asList method.Create an empty list.Loop through each element of the original list, and invoke the SerializationUtils.clone() method of the serializable objects (which returns the class instance) and use the add() method to append it to the new list.
Create a Serializable class.
Create a list of the class objects from an array using the asList method.
Create an empty list.
Loop through each element of the original list, and invoke the SerializationUtils.clone() method of the serializable objects (which returns the class instance) and use the add() method to append it to the new list.
The following program illustrates this case.
import org.apache.commons.lang3.SerializationUtils;import java.io.Serializable;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class should be Serializableclass GfG implements Serializable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the objects // in the desired manner @Override public String toString() { return "\nHello " + username + " !\n" + msg + "\n"; }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating the list List<GfG> original = Arrays.asList( new GfG("Mukkesh", "Hey there fellows!"), new GfG("McKenzie", "Welcome to my page!")); // Creating an empty list List<GfG> cloned_list = new ArrayList<GfG>(); // Looping through the list // and cloning each element // using SerializationUtils.clone for (GfG temp : original) cloned_list.add( SerializationUtils.clone(temp)); System.out.println(cloned_list); }}
Output:
[
Hello Mukkesh !
Hey there fellows!,
Hello McKenzie !
Welcome to my page!
]
Using Gson library to convert list to JSON: Using Google’s Gson library, a list can be converted to JSON. This JSON string can be converted to an object of type List and can be used to initialize the new List.Syntax:String gson.toJson(List a);
Returns a JSON string of the List object a.
List gson.fromJson(String b, Class T)
Returns a list of type Class T, from the JSON string b.
Approach:Create a classCreate a list of the class objects from an array using the asList method.Use the toJson() function to create a JSON string of the original list, by passing the same as a parameter to this function.Store the returned JSON stringCreate an empty list and directly initialize it to the original list’s value by using the fromJson() function and passing the stored JSON string as a parameter.The following program illustrates this.import com.google.gson.Gson;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class should be Serializableclass GfG implements Serializable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the object // in the desired format @Override public String toString() { return "\nHello " + username + " !\n" + msg + "\n"; }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating a new list List<GfG> original = Arrays.asList(new GfG("Mukkesh", "Hey there fellows!"), new GfG("McKenzie", "Welcome to my page!")); // Creating a gson object Gson gson = new Gson(); // Converting the list into a json string String jsonstring = gson.toJson(original); // Converting the json string // back into a list List<GfG> cloned_list = gson.fromJson(jsonstring, GfG); System.out.println(cloned_list); }}Output:[
Hello Mukkesh !
Hey there fellows!,
Hello McKenzie !
Welcome to my page!
]
Syntax:
String gson.toJson(List a);
Returns a JSON string of the List object a.
List gson.fromJson(String b, Class T)
Returns a list of type Class T, from the JSON string b.
Approach:
Create a classCreate a list of the class objects from an array using the asList method.Use the toJson() function to create a JSON string of the original list, by passing the same as a parameter to this function.Store the returned JSON stringCreate an empty list and directly initialize it to the original list’s value by using the fromJson() function and passing the stored JSON string as a parameter.
Create a class
Create a list of the class objects from an array using the asList method.
Use the toJson() function to create a JSON string of the original list, by passing the same as a parameter to this function.
Store the returned JSON string
Create an empty list and directly initialize it to the original list’s value by using the fromJson() function and passing the stored JSON string as a parameter.
The following program illustrates this.
import com.google.gson.Gson;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class should be Serializableclass GfG implements Serializable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the object // in the desired format @Override public String toString() { return "\nHello " + username + " !\n" + msg + "\n"; }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating a new list List<GfG> original = Arrays.asList(new GfG("Mukkesh", "Hey there fellows!"), new GfG("McKenzie", "Welcome to my page!")); // Creating a gson object Gson gson = new Gson(); // Converting the list into a json string String jsonstring = gson.toJson(original); // Converting the json string // back into a list List<GfG> cloned_list = gson.fromJson(jsonstring, GfG); System.out.println(cloned_list); }}
Output:
[
Hello Mukkesh !
Hey there fellows!,
Hello McKenzie !
Welcome to my page!
]
Using the Reflection package: The Reflection package can also be used to clone a List.Approach:Create a cloneable class, which has the clone method overridden.Create a list of the class objects from an array using the asList method.Create an empty list.Get the clone method from the class by using the getClass().getDeclaredMethod(“clone”) method (on one element of the list), and store it as a method instance.Loop through each element of the list, and invoke the stored method, which will return a class instance, which can be appended to the new list.import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // GfGclass implements Cloneable Interfaceclass GfG implements Cloneable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the object // in the desired format @Override public String toString() { return "\nHello " + username + "!\n" + msg + "\n"; } // Overriding the clone function @Override protected Object clone() throws CloneNotSupportedException { return new GfG(username, msg); }} class ListUtils { // Create a cloning function public static <T extends Cloneable> List<T> clone(List<T> original) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Boundary conditions checked if (original == null || original.size() == 0) { return new ArrayList<>(); } // Get the clone method from the GfG class Method method = original.get(0) .getClass() .getDeclaredMethod("clone"); // Create an empty list for cloning List<T> clone = new ArrayList<>(); // Loop through the list and // invoke the clone method of each element for (T item : original) { clone.add((T)method.invoke(item)); } // Return the cloned list return clone; } public static void main(String[] args) { // Creating a list List<GfG> original = Arrays.asList( new GfG("Geeks", "GeeksForGeeks"), new GfG("GFG", "A computer science portal for geeks")); // Create an empty list for cloning List<GfG> cloned_list = null; // Use try and catch for exception handling try { cloned_list = clone(original); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } // Print the cloned list System.out.println(cloned_list); }}Output:[
Hello Geeks!
GeeksForGeeks,
Hello GFG!
A computer science portal for geeks
]
Approach:
Create a cloneable class, which has the clone method overridden.Create a list of the class objects from an array using the asList method.Create an empty list.Get the clone method from the class by using the getClass().getDeclaredMethod(“clone”) method (on one element of the list), and store it as a method instance.Loop through each element of the list, and invoke the stored method, which will return a class instance, which can be appended to the new list.
Create a cloneable class, which has the clone method overridden.
Create a list of the class objects from an array using the asList method.
Create an empty list.
Get the clone method from the class by using the getClass().getDeclaredMethod(“clone”) method (on one element of the list), and store it as a method instance.
Loop through each element of the list, and invoke the stored method, which will return a class instance, which can be appended to the new list.
import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // GfGclass implements Cloneable Interfaceclass GfG implements Cloneable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the object // in the desired format @Override public String toString() { return "\nHello " + username + "!\n" + msg + "\n"; } // Overriding the clone function @Override protected Object clone() throws CloneNotSupportedException { return new GfG(username, msg); }} class ListUtils { // Create a cloning function public static <T extends Cloneable> List<T> clone(List<T> original) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Boundary conditions checked if (original == null || original.size() == 0) { return new ArrayList<>(); } // Get the clone method from the GfG class Method method = original.get(0) .getClass() .getDeclaredMethod("clone"); // Create an empty list for cloning List<T> clone = new ArrayList<>(); // Loop through the list and // invoke the clone method of each element for (T item : original) { clone.add((T)method.invoke(item)); } // Return the cloned list return clone; } public static void main(String[] args) { // Creating a list List<GfG> original = Arrays.asList( new GfG("Geeks", "GeeksForGeeks"), new GfG("GFG", "A computer science portal for geeks")); // Create an empty list for cloning List<GfG> cloned_list = null; // Use try and catch for exception handling try { cloned_list = clone(original); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } // Print the cloned list System.out.println(cloned_list); }}
[
Hello Geeks!
GeeksForGeeks,
Hello GFG!
A computer science portal for geeks
]
java-list
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Apr, 2019"
},
{
"code": null,
"e": 82,
"s": 28,
"text": "Given a list in Java, the task is to clone this list."
},
{
"code": null,
"e": 91,
"s": 82,
"text": "Example:"
},
{
"code": null,
"e": 177,
"s": 91,
"text": "Input: list = [“Geeks”, “for”, “Geeks”]Output: clonedList = [“Geeks”, “for”, “Geeks”]"
},
{
"code": null,
"e": 311,
"s": 177,
"text": "Input: list = [“GeeksForGeeks”, “A Computer Science”, “Portal”]Output: clonedList = [“GeeksForGeeks”, “A Computer Science”, “Portal”]"
},
{
"code": null,
"e": 440,
"s": 311,
"text": "In Java, there are various methods to clone a list. This article will explain some of the main methods used to achieve the same."
},
{
"code": null,
"e": 1440,
"s": 440,
"text": "Using a Copy Constructor: Using the ArrayList constructor in Java, a new list can be initialized with the elements from another collection.Syntax:ArrayList cloned = new ArrayList(collection c);\n\nwhere c is the collection containing \nelements to be added to this list.\nApproach:Create a list to be cloned.Clone the list by passing the original list as the parameter of the copy constructor of ArrayList.The following code illustrated this example.// Program to clone a List in Java import java.util.ArrayList;import java.util.Arrays;import java.util.List; class Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( \"GeeksForGeeks\", \"A Computer Science\", \"Portal\"); // Clone the list List<String> cloned_list = new ArrayList<String>(original); System.out.println(cloned_list); }}Output:[GeeksForGeeks, A Computer Science, Portal]\n"
},
{
"code": null,
"e": 1563,
"s": 1440,
"text": "ArrayList cloned = new ArrayList(collection c);\n\nwhere c is the collection containing \nelements to be added to this list.\n"
},
{
"code": null,
"e": 1573,
"s": 1563,
"text": "Approach:"
},
{
"code": null,
"e": 1699,
"s": 1573,
"text": "Create a list to be cloned.Clone the list by passing the original list as the parameter of the copy constructor of ArrayList."
},
{
"code": null,
"e": 1727,
"s": 1699,
"text": "Create a list to be cloned."
},
{
"code": null,
"e": 1826,
"s": 1727,
"text": "Clone the list by passing the original list as the parameter of the copy constructor of ArrayList."
},
{
"code": null,
"e": 1871,
"s": 1826,
"text": "The following code illustrated this example."
},
{
"code": "// Program to clone a List in Java import java.util.ArrayList;import java.util.Arrays;import java.util.List; class Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( \"GeeksForGeeks\", \"A Computer Science\", \"Portal\"); // Clone the list List<String> cloned_list = new ArrayList<String>(original); System.out.println(cloned_list); }}",
"e": 2374,
"s": 1871,
"text": null
},
{
"code": null,
"e": 2419,
"s": 2374,
"text": "[GeeksForGeeks, A Computer Science, Portal]\n"
},
{
"code": null,
"e": 3455,
"s": 2419,
"text": "Using the addAll() method: The List class has a method called addAll(), which appends all the elements of one collection to the list.Syntax:boolean addAll(Collection c);\n\nwhere c is the collection containing\nelements to be added to this list.\nApproach:Create a list to be cloned.Create an empty list using the ArrayList constructor.Append the original list to the empty list using the addAll() method.The following example will illustrate this method.// Program to clone a List in Java import java.util.ArrayList;import java.util.Arrays;import java.util.List; class Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( \"GeeksForGeeks\", \"A Computer Science\", \"Portal\"); List<String> cloned_list = new ArrayList<String>(); // Cloning a list cloned_list.addAll(original); System.out.println(cloned_list); }}Output:[GeeksForGeeks, A Computer Science, Portal]\n"
},
{
"code": null,
"e": 3463,
"s": 3455,
"text": "Syntax:"
},
{
"code": null,
"e": 3567,
"s": 3463,
"text": "boolean addAll(Collection c);\n\nwhere c is the collection containing\nelements to be added to this list.\n"
},
{
"code": null,
"e": 3577,
"s": 3567,
"text": "Approach:"
},
{
"code": null,
"e": 3727,
"s": 3577,
"text": "Create a list to be cloned.Create an empty list using the ArrayList constructor.Append the original list to the empty list using the addAll() method."
},
{
"code": null,
"e": 3755,
"s": 3727,
"text": "Create a list to be cloned."
},
{
"code": null,
"e": 3809,
"s": 3755,
"text": "Create an empty list using the ArrayList constructor."
},
{
"code": null,
"e": 3879,
"s": 3809,
"text": "Append the original list to the empty list using the addAll() method."
},
{
"code": null,
"e": 3930,
"s": 3879,
"text": "The following example will illustrate this method."
},
{
"code": "// Program to clone a List in Java import java.util.ArrayList;import java.util.Arrays;import java.util.List; class Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( \"GeeksForGeeks\", \"A Computer Science\", \"Portal\"); List<String> cloned_list = new ArrayList<String>(); // Cloning a list cloned_list.addAll(original); System.out.println(cloned_list); }}",
"e": 4464,
"s": 3930,
"text": null
},
{
"code": null,
"e": 4509,
"s": 4464,
"text": "[GeeksForGeeks, A Computer Science, Portal]\n"
},
{
"code": null,
"e": 5649,
"s": 4509,
"text": "Using streams in Java 8 Using the Streams API introduced in JAVA 8, cloning of a list is possible. The collect() method (along with toList() method) is used to clone a list.Approach:Create a classCreate a list of the class objects from an array using the asList method.Convert list of objects to a stream of objects using the stream() method.Use the collect(Collectors.toList()) methods to collect all the stream elements list instances and returning them to the cloned_list.The following program illustrates this concept.import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors; // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( \"GeeksForGeeks\", \"A Computer Science\", \"Portal\"); // Clone a list List<String> cloned_list = original.stream() .collect(Collectors.toList()); System.out.println(cloned_list); }}Output:[GeeksForGeeks, A Computer Science, Portal]\n"
},
{
"code": null,
"e": 5659,
"s": 5649,
"text": "Approach:"
},
{
"code": null,
"e": 5953,
"s": 5659,
"text": "Create a classCreate a list of the class objects from an array using the asList method.Convert list of objects to a stream of objects using the stream() method.Use the collect(Collectors.toList()) methods to collect all the stream elements list instances and returning them to the cloned_list."
},
{
"code": null,
"e": 5968,
"s": 5953,
"text": "Create a class"
},
{
"code": null,
"e": 6042,
"s": 5968,
"text": "Create a list of the class objects from an array using the asList method."
},
{
"code": null,
"e": 6116,
"s": 6042,
"text": "Convert list of objects to a stream of objects using the stream() method."
},
{
"code": null,
"e": 6250,
"s": 6116,
"text": "Use the collect(Collectors.toList()) methods to collect all the stream elements list instances and returning them to the cloned_list."
},
{
"code": null,
"e": 6298,
"s": 6250,
"text": "The following program illustrates this concept."
},
{
"code": "import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors; // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Create a list List<String> original = Arrays.asList( \"GeeksForGeeks\", \"A Computer Science\", \"Portal\"); // Clone a list List<String> cloned_list = original.stream() .collect(Collectors.toList()); System.out.println(cloned_list); }}",
"e": 6865,
"s": 6298,
"text": null
},
{
"code": null,
"e": 6910,
"s": 6865,
"text": "[GeeksForGeeks, A Computer Science, Portal]\n"
},
{
"code": null,
"e": 9050,
"s": 6910,
"text": "Using the clone() method: Clone() method of a class in Java is used to create a new instance of a class of the current object and initialized all its fields with the contents of the specified object. To clone a list, one can iterate through the original list and use the clone method to copy all the list elements and use the add method to append them to the list.Syntax:protected Object clone()\nthrows CloneNotSupportedException\nApproach:Create a cloneable class, which has the clone method overridden.Create a list of the class objects from an array using the asList method.Create an empty list.Loop through each element of the original list, and invoke the class object’s clone() method (which returns the class instance) and use the add() method to append it to the new list.The following example illustrates this concept.import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class needs to be cloneableclass GfG implements Cloneable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // To print the objects in the desired format @Override public String toString() { return \"\\nHello \" + username + \" !\\n\" + msg + \"\\n\"; } // Overriding the inbuilt clone class @Override protected GfG clone() { return new GfG(username, msg); }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating a list List<GfG> original = Arrays.asList( new GfG(\"Geeks\", \"GeeksForGeeks\"), new GfG(\"GFG\", \"A computer science portal for geeks\")); // Creating an empty list List<GfG> cloned_list = new ArrayList<GfG>(); // Looping through the list // and cloning each element for (GfG temp : original) cloned_list.add(temp.clone()); System.out.println(cloned_list); }}Output:[\nHello Geeks !\nGeeksForGeeks, \nHello GFG !\nA computer science portal for geeks\n]\n"
},
{
"code": null,
"e": 9058,
"s": 9050,
"text": "Syntax:"
},
{
"code": null,
"e": 9118,
"s": 9058,
"text": "protected Object clone()\nthrows CloneNotSupportedException\n"
},
{
"code": null,
"e": 9128,
"s": 9118,
"text": "Approach:"
},
{
"code": null,
"e": 9469,
"s": 9128,
"text": "Create a cloneable class, which has the clone method overridden.Create a list of the class objects from an array using the asList method.Create an empty list.Loop through each element of the original list, and invoke the class object’s clone() method (which returns the class instance) and use the add() method to append it to the new list."
},
{
"code": null,
"e": 9534,
"s": 9469,
"text": "Create a cloneable class, which has the clone method overridden."
},
{
"code": null,
"e": 9608,
"s": 9534,
"text": "Create a list of the class objects from an array using the asList method."
},
{
"code": null,
"e": 9630,
"s": 9608,
"text": "Create an empty list."
},
{
"code": null,
"e": 9813,
"s": 9630,
"text": "Loop through each element of the original list, and invoke the class object’s clone() method (which returns the class instance) and use the add() method to append it to the new list."
},
{
"code": null,
"e": 9861,
"s": 9813,
"text": "The following example illustrates this concept."
},
{
"code": "import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class needs to be cloneableclass GfG implements Cloneable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // To print the objects in the desired format @Override public String toString() { return \"\\nHello \" + username + \" !\\n\" + msg + \"\\n\"; } // Overriding the inbuilt clone class @Override protected GfG clone() { return new GfG(username, msg); }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating a list List<GfG> original = Arrays.asList( new GfG(\"Geeks\", \"GeeksForGeeks\"), new GfG(\"GFG\", \"A computer science portal for geeks\")); // Creating an empty list List<GfG> cloned_list = new ArrayList<GfG>(); // Looping through the list // and cloning each element for (GfG temp : original) cloned_list.add(temp.clone()); System.out.println(cloned_list); }}",
"e": 11086,
"s": 9861,
"text": null
},
{
"code": null,
"e": 11169,
"s": 11086,
"text": "[\nHello Geeks !\nGeeksForGeeks, \nHello GFG !\nA computer science portal for geeks\n]\n"
},
{
"code": null,
"e": 13182,
"s": 11169,
"text": "Using Apache Commons Lang: The same can also be aschieved by using the clone method provided by third party libraries such as Apache Commons Lang.Syntax:public static T clone(T object)\n\nwhere T is the type of the object\nand object is the Serializable object\nto be cloned\nApproach:Create a Serializable class.Create a list of the class objects from an array using the asList method.Create an empty list.Loop through each element of the original list, and invoke the SerializationUtils.clone() method of the serializable objects (which returns the class instance) and use the add() method to append it to the new list.The following program illustrates this case.import org.apache.commons.lang3.SerializationUtils;import java.io.Serializable;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class should be Serializableclass GfG implements Serializable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the objects // in the desired manner @Override public String toString() { return \"\\nHello \" + username + \" !\\n\" + msg + \"\\n\"; }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating the list List<GfG> original = Arrays.asList( new GfG(\"Mukkesh\", \"Hey there fellows!\"), new GfG(\"McKenzie\", \"Welcome to my page!\")); // Creating an empty list List<GfG> cloned_list = new ArrayList<GfG>(); // Looping through the list // and cloning each element // using SerializationUtils.clone for (GfG temp : original) cloned_list.add( SerializationUtils.clone(temp)); System.out.println(cloned_list); }}Output:[\nHello Mukkesh !\nHey there fellows!, \nHello McKenzie !\nWelcome to my page!\n]\n"
},
{
"code": null,
"e": 13302,
"s": 13182,
"text": "public static T clone(T object)\n\nwhere T is the type of the object\nand object is the Serializable object\nto be cloned\n"
},
{
"code": null,
"e": 13312,
"s": 13302,
"text": "Approach:"
},
{
"code": null,
"e": 13649,
"s": 13312,
"text": "Create a Serializable class.Create a list of the class objects from an array using the asList method.Create an empty list.Loop through each element of the original list, and invoke the SerializationUtils.clone() method of the serializable objects (which returns the class instance) and use the add() method to append it to the new list."
},
{
"code": null,
"e": 13678,
"s": 13649,
"text": "Create a Serializable class."
},
{
"code": null,
"e": 13752,
"s": 13678,
"text": "Create a list of the class objects from an array using the asList method."
},
{
"code": null,
"e": 13774,
"s": 13752,
"text": "Create an empty list."
},
{
"code": null,
"e": 13989,
"s": 13774,
"text": "Loop through each element of the original list, and invoke the SerializationUtils.clone() method of the serializable objects (which returns the class instance) and use the add() method to append it to the new list."
},
{
"code": null,
"e": 14034,
"s": 13989,
"text": "The following program illustrates this case."
},
{
"code": "import org.apache.commons.lang3.SerializationUtils;import java.io.Serializable;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class should be Serializableclass GfG implements Serializable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the objects // in the desired manner @Override public String toString() { return \"\\nHello \" + username + \" !\\n\" + msg + \"\\n\"; }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating the list List<GfG> original = Arrays.asList( new GfG(\"Mukkesh\", \"Hey there fellows!\"), new GfG(\"McKenzie\", \"Welcome to my page!\")); // Creating an empty list List<GfG> cloned_list = new ArrayList<GfG>(); // Looping through the list // and cloning each element // using SerializationUtils.clone for (GfG temp : original) cloned_list.add( SerializationUtils.clone(temp)); System.out.println(cloned_list); }}",
"e": 15301,
"s": 14034,
"text": null
},
{
"code": null,
"e": 15309,
"s": 15301,
"text": "Output:"
},
{
"code": null,
"e": 15388,
"s": 15309,
"text": "[\nHello Mukkesh !\nHey there fellows!, \nHello McKenzie !\nWelcome to my page!\n]\n"
},
{
"code": null,
"e": 17539,
"s": 15388,
"text": "Using Gson library to convert list to JSON: Using Google’s Gson library, a list can be converted to JSON. This JSON string can be converted to an object of type List and can be used to initialize the new List.Syntax:String gson.toJson(List a);\nReturns a JSON string of the List object a.\n\nList gson.fromJson(String b, Class T)\nReturns a list of type Class T, from the JSON string b.\nApproach:Create a classCreate a list of the class objects from an array using the asList method.Use the toJson() function to create a JSON string of the original list, by passing the same as a parameter to this function.Store the returned JSON stringCreate an empty list and directly initialize it to the original list’s value by using the fromJson() function and passing the stored JSON string as a parameter.The following program illustrates this.import com.google.gson.Gson;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class should be Serializableclass GfG implements Serializable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the object // in the desired format @Override public String toString() { return \"\\nHello \" + username + \" !\\n\" + msg + \"\\n\"; }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating a new list List<GfG> original = Arrays.asList(new GfG(\"Mukkesh\", \"Hey there fellows!\"), new GfG(\"McKenzie\", \"Welcome to my page!\")); // Creating a gson object Gson gson = new Gson(); // Converting the list into a json string String jsonstring = gson.toJson(original); // Converting the json string // back into a list List<GfG> cloned_list = gson.fromJson(jsonstring, GfG); System.out.println(cloned_list); }}Output:[\nHello Mukkesh !\nHey there fellows!, \nHello McKenzie !\nWelcome to my page!\n]\n"
},
{
"code": null,
"e": 17547,
"s": 17539,
"text": "Syntax:"
},
{
"code": null,
"e": 17715,
"s": 17547,
"text": "String gson.toJson(List a);\nReturns a JSON string of the List object a.\n\nList gson.fromJson(String b, Class T)\nReturns a list of type Class T, from the JSON string b.\n"
},
{
"code": null,
"e": 17725,
"s": 17715,
"text": "Approach:"
},
{
"code": null,
"e": 18127,
"s": 17725,
"text": "Create a classCreate a list of the class objects from an array using the asList method.Use the toJson() function to create a JSON string of the original list, by passing the same as a parameter to this function.Store the returned JSON stringCreate an empty list and directly initialize it to the original list’s value by using the fromJson() function and passing the stored JSON string as a parameter."
},
{
"code": null,
"e": 18142,
"s": 18127,
"text": "Create a class"
},
{
"code": null,
"e": 18216,
"s": 18142,
"text": "Create a list of the class objects from an array using the asList method."
},
{
"code": null,
"e": 18341,
"s": 18216,
"text": "Use the toJson() function to create a JSON string of the original list, by passing the same as a parameter to this function."
},
{
"code": null,
"e": 18372,
"s": 18341,
"text": "Store the returned JSON string"
},
{
"code": null,
"e": 18533,
"s": 18372,
"text": "Create an empty list and directly initialize it to the original list’s value by using the fromJson() function and passing the stored JSON string as a parameter."
},
{
"code": null,
"e": 18573,
"s": 18533,
"text": "The following program illustrates this."
},
{
"code": "import com.google.gson.Gson;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // Class should be Serializableclass GfG implements Serializable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the object // in the desired format @Override public String toString() { return \"\\nHello \" + username + \" !\\n\" + msg + \"\\n\"; }} // Program to clone a List in Javaclass Example { public static void main(String[] args) { // Creating a new list List<GfG> original = Arrays.asList(new GfG(\"Mukkesh\", \"Hey there fellows!\"), new GfG(\"McKenzie\", \"Welcome to my page!\")); // Creating a gson object Gson gson = new Gson(); // Converting the list into a json string String jsonstring = gson.toJson(original); // Converting the json string // back into a list List<GfG> cloned_list = gson.fromJson(jsonstring, GfG); System.out.println(cloned_list); }}",
"e": 19807,
"s": 18573,
"text": null
},
{
"code": null,
"e": 19815,
"s": 19807,
"text": "Output:"
},
{
"code": null,
"e": 19894,
"s": 19815,
"text": "[\nHello Mukkesh !\nHey there fellows!, \nHello McKenzie !\nWelcome to my page!\n]\n"
},
{
"code": null,
"e": 23005,
"s": 19894,
"text": "Using the Reflection package: The Reflection package can also be used to clone a List.Approach:Create a cloneable class, which has the clone method overridden.Create a list of the class objects from an array using the asList method.Create an empty list.Get the clone method from the class by using the getClass().getDeclaredMethod(“clone”) method (on one element of the list), and store it as a method instance.Loop through each element of the list, and invoke the stored method, which will return a class instance, which can be appended to the new list.import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // GfGclass implements Cloneable Interfaceclass GfG implements Cloneable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the object // in the desired format @Override public String toString() { return \"\\nHello \" + username + \"!\\n\" + msg + \"\\n\"; } // Overriding the clone function @Override protected Object clone() throws CloneNotSupportedException { return new GfG(username, msg); }} class ListUtils { // Create a cloning function public static <T extends Cloneable> List<T> clone(List<T> original) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Boundary conditions checked if (original == null || original.size() == 0) { return new ArrayList<>(); } // Get the clone method from the GfG class Method method = original.get(0) .getClass() .getDeclaredMethod(\"clone\"); // Create an empty list for cloning List<T> clone = new ArrayList<>(); // Loop through the list and // invoke the clone method of each element for (T item : original) { clone.add((T)method.invoke(item)); } // Return the cloned list return clone; } public static void main(String[] args) { // Creating a list List<GfG> original = Arrays.asList( new GfG(\"Geeks\", \"GeeksForGeeks\"), new GfG(\"GFG\", \"A computer science portal for geeks\")); // Create an empty list for cloning List<GfG> cloned_list = null; // Use try and catch for exception handling try { cloned_list = clone(original); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } // Print the cloned list System.out.println(cloned_list); }}Output:[\nHello Geeks!\nGeeksForGeeks, \nHello GFG!\nA computer science portal for geeks\n]\n"
},
{
"code": null,
"e": 23015,
"s": 23005,
"text": "Approach:"
},
{
"code": null,
"e": 23475,
"s": 23015,
"text": "Create a cloneable class, which has the clone method overridden.Create a list of the class objects from an array using the asList method.Create an empty list.Get the clone method from the class by using the getClass().getDeclaredMethod(“clone”) method (on one element of the list), and store it as a method instance.Loop through each element of the list, and invoke the stored method, which will return a class instance, which can be appended to the new list."
},
{
"code": null,
"e": 23540,
"s": 23475,
"text": "Create a cloneable class, which has the clone method overridden."
},
{
"code": null,
"e": 23614,
"s": 23540,
"text": "Create a list of the class objects from an array using the asList method."
},
{
"code": null,
"e": 23636,
"s": 23614,
"text": "Create an empty list."
},
{
"code": null,
"e": 23795,
"s": 23636,
"text": "Get the clone method from the class by using the getClass().getDeclaredMethod(“clone”) method (on one element of the list), and store it as a method instance."
},
{
"code": null,
"e": 23939,
"s": 23795,
"text": "Loop through each element of the list, and invoke the stored method, which will return a class instance, which can be appended to the new list."
},
{
"code": "import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Arrays;import java.util.List; // GfGclass implements Cloneable Interfaceclass GfG implements Cloneable { String username; String msg; // Constructor GfG(String username, String msg) { this.username = username; this.msg = msg; } // Overriding to print the object // in the desired format @Override public String toString() { return \"\\nHello \" + username + \"!\\n\" + msg + \"\\n\"; } // Overriding the clone function @Override protected Object clone() throws CloneNotSupportedException { return new GfG(username, msg); }} class ListUtils { // Create a cloning function public static <T extends Cloneable> List<T> clone(List<T> original) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Boundary conditions checked if (original == null || original.size() == 0) { return new ArrayList<>(); } // Get the clone method from the GfG class Method method = original.get(0) .getClass() .getDeclaredMethod(\"clone\"); // Create an empty list for cloning List<T> clone = new ArrayList<>(); // Loop through the list and // invoke the clone method of each element for (T item : original) { clone.add((T)method.invoke(item)); } // Return the cloned list return clone; } public static void main(String[] args) { // Creating a list List<GfG> original = Arrays.asList( new GfG(\"Geeks\", \"GeeksForGeeks\"), new GfG(\"GFG\", \"A computer science portal for geeks\")); // Create an empty list for cloning List<GfG> cloned_list = null; // Use try and catch for exception handling try { cloned_list = clone(original); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } // Print the cloned list System.out.println(cloned_list); }}",
"e": 26409,
"s": 23939,
"text": null
},
{
"code": null,
"e": 26490,
"s": 26409,
"text": "[\nHello Geeks!\nGeeksForGeeks, \nHello GFG!\nA computer science portal for geeks\n]\n"
},
{
"code": null,
"e": 26500,
"s": 26490,
"text": "java-list"
},
{
"code": null,
"e": 26507,
"s": 26500,
"text": "Picked"
},
{
"code": null,
"e": 26512,
"s": 26507,
"text": "Java"
},
{
"code": null,
"e": 26526,
"s": 26512,
"text": "Java Programs"
},
{
"code": null,
"e": 26531,
"s": 26526,
"text": "Java"
}
] |
Checked vs Unchecked Exceptions in Java - GeeksforGeeks
|
01 Nov, 2021
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions:
Checked exceptionsUnchecked exceptions
Checked exceptions
Unchecked exceptions
These are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using the throws keyword.
For example, consider the following Java program that opens the file at location “C:\test\a.txt” and prints the first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException
Example:
Java
// Java Program to Illustrate Checked Exceptions// Where FileNotFoundException occured // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Reading file from path in local directory FileReader file = new FileReader("C:\\test\\a.txt"); // Creating object as one of ways of taking input BufferedReader fileInput = new BufferedReader(file); // Printing first 3 lines of file "C:\test\a.txt" for (int counter = 0; counter < 3; counter++) System.out.println(fileInput.readLine()); // Closing file connections // using close() method fileInput.close(); }}
Output:
To fix the above program, we either need to specify a list of exceptions using throws, or we need to use a try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.
Example:
Java
// Java Program to Illustrate Checked Exceptions// Where FileNotFoundException does not occur // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating a file and reading from local repository FileReader file = new FileReader("C:\\test\\a.txt"); // Reading content inside a file BufferedReader fileInput = new BufferedReader(file); // Printing first 3 lines of file "C:\test\a.txt" for (int counter = 0; counter < 3; counter++) System.out.println(fileInput.readLine()); // Closing all file connections // using close() method // Good practice to avoid any memory leakage fileInput.close(); }}
Output:
First three lines of file "C:\test\a.txt"
These are the exceptions that are not checked at compile time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.
Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile because ArithmeticException is an unchecked exception.
Example:
Java
// Java Program to Illustrate Un-checked Exceptions // Main classclass GFG { // Main driver method public static void main(String args[]) { // Here we are dividing by 0 // which will not be caught at compile time // as there is no mistake but caught at runtime // because it is mathematically incorrect int x = 0; int y = 10; int z = y / x; }}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
Java Result: 1
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
sakshamcse
ranjeethnivas
Java-Exceptions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Split() String method in Java with examples
Reverse a string in Java
Arrays.sort() in Java with examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Singleton Class in Java
How to add an element to an Array in Java?
Stream In Java
Initializing a List in Java
Different ways of Reading a text file in Java
|
[
{
"code": null,
"e": 28559,
"s": 28531,
"text": "\n01 Nov, 2021"
},
{
"code": null,
"e": 28777,
"s": 28559,
"text": "An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions:"
},
{
"code": null,
"e": 28816,
"s": 28777,
"text": "Checked exceptionsUnchecked exceptions"
},
{
"code": null,
"e": 28835,
"s": 28816,
"text": "Checked exceptions"
},
{
"code": null,
"e": 28856,
"s": 28835,
"text": "Unchecked exceptions"
},
{
"code": null,
"e": 29081,
"s": 28856,
"text": "These are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using the throws keyword. "
},
{
"code": null,
"e": 29464,
"s": 29081,
"text": "For example, consider the following Java program that opens the file at location “C:\\test\\a.txt” and prints the first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException"
},
{
"code": null,
"e": 29473,
"s": 29464,
"text": "Example:"
},
{
"code": null,
"e": 29478,
"s": 29473,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Checked Exceptions// Where FileNotFoundException occured // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Reading file from path in local directory FileReader file = new FileReader(\"C:\\\\test\\\\a.txt\"); // Creating object as one of ways of taking input BufferedReader fileInput = new BufferedReader(file); // Printing first 3 lines of file \"C:\\test\\a.txt\" for (int counter = 0; counter < 3; counter++) System.out.println(fileInput.readLine()); // Closing file connections // using close() method fileInput.close(); }}",
"e": 30206,
"s": 29478,
"text": null
},
{
"code": null,
"e": 30215,
"s": 30206,
"text": "Output: "
},
{
"code": null,
"e": 30538,
"s": 30215,
"text": "To fix the above program, we either need to specify a list of exceptions using throws, or we need to use a try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free."
},
{
"code": null,
"e": 30547,
"s": 30538,
"text": "Example:"
},
{
"code": null,
"e": 30552,
"s": 30547,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Checked Exceptions// Where FileNotFoundException does not occur // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating a file and reading from local repository FileReader file = new FileReader(\"C:\\\\test\\\\a.txt\"); // Reading content inside a file BufferedReader fileInput = new BufferedReader(file); // Printing first 3 lines of file \"C:\\test\\a.txt\" for (int counter = 0; counter < 3; counter++) System.out.println(fileInput.readLine()); // Closing all file connections // using close() method // Good practice to avoid any memory leakage fileInput.close(); }}",
"e": 31360,
"s": 30552,
"text": null
},
{
"code": null,
"e": 31369,
"s": 31360,
"text": "Output: "
},
{
"code": null,
"e": 31411,
"s": 31369,
"text": "First three lines of file \"C:\\test\\a.txt\""
},
{
"code": null,
"e": 31804,
"s": 31411,
"text": "These are the exceptions that are not checked at compile time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked. "
},
{
"code": null,
"e": 31992,
"s": 31804,
"text": "Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile because ArithmeticException is an unchecked exception."
},
{
"code": null,
"e": 32001,
"s": 31992,
"text": "Example:"
},
{
"code": null,
"e": 32006,
"s": 32001,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Un-checked Exceptions // Main classclass GFG { // Main driver method public static void main(String args[]) { // Here we are dividing by 0 // which will not be caught at compile time // as there is no mistake but caught at runtime // because it is mathematically incorrect int x = 0; int y = 10; int z = y / x; }}",
"e": 32414,
"s": 32006,
"text": null
},
{
"code": null,
"e": 32423,
"s": 32414,
"text": "Output: "
},
{
"code": null,
"e": 32536,
"s": 32423,
"text": "Exception in thread \"main\" java.lang.ArithmeticException: / by zero\n at Main.main(Main.java:5)\nJava Result: 1"
},
{
"code": null,
"e": 32660,
"s": 32536,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 32671,
"s": 32660,
"text": "sakshamcse"
},
{
"code": null,
"e": 32685,
"s": 32671,
"text": "ranjeethnivas"
},
{
"code": null,
"e": 32701,
"s": 32685,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 32706,
"s": 32701,
"text": "Java"
},
{
"code": null,
"e": 32711,
"s": 32706,
"text": "Java"
},
{
"code": null,
"e": 32809,
"s": 32711,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32818,
"s": 32809,
"text": "Comments"
},
{
"code": null,
"e": 32831,
"s": 32818,
"text": "Old Comments"
},
{
"code": null,
"e": 32875,
"s": 32831,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 32900,
"s": 32875,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32936,
"s": 32900,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 32967,
"s": 32936,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 32999,
"s": 32967,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 33023,
"s": 32999,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 33066,
"s": 33023,
"text": "How to add an element to an Array in Java?"
},
{
"code": null,
"e": 33081,
"s": 33066,
"text": "Stream In Java"
},
{
"code": null,
"e": 33109,
"s": 33081,
"text": "Initializing a List in Java"
}
] |
Mean Shift and Cam Shift Object Tracking | by Andrew Udell | Towards Data Science
|
Among the most demanded features of computer vision is object tracking. Unfortunately, this is also one of the most difficult aspects of computer vision to implement.
Not only does an object need to be identified, it needs to be identified quickly enough to render in real time while it moves. The object may change orientation or change its distance from the camera, which further complicates matters.
While still an adamant challenge in computer vision, the mean shift and cam shift algorithms present a simplified solution. Working primarily with color data rather than structural data, these methods can efficiently track objects under the right conditions.
The mean shift algorithm is actually a broader statistical concept related to clustering. Like most other clustering algorithms, the mean shift algorithm attempts to look for places in the data set with a high concentration of data points, or clusters.
The algorithm places a kernel at each data point and sums them together to make a Kernel Density Estimation (KDE). The KDE will have peaks and valleys, which correspond to places with a high and low data point density, respectfully.
The algorithm takes a copy of the data points and shifts the points by a small amount to their nearest KDE peak in a single iteration. The algorithm will continue to go through iterations of shifting the points until the points no longer move much. This can help simplify the data and make the clusters more pronounced.
So how does this related to computer vision? Imagine a rainbow, like in the image below:
The image may be broken down into the HSV color space, essentially turning it into a big data set. When making a KDE, each of the colors of the rainbow and the blue in the sky will create a peak. When shifting the points iteratively, each color of the rainbow will become more distinct by eliminating the subtle fading between colors. Consequently, each stripe become more easily identifiable by a computer.
This process is a form of image segmentation.
To take the concept further, if a particular color in the rainbow needed to be identified, the mean shift algorithm makes it more easily seen. If this color needed to be tracked, each frame of a video of a rainbow would undergo the algorithm in real time.
For a more realistic example, image a top-down view of a tennis match. The court, the players, and the bright yellow ball will each have a KDE peak. If the ball needs to be tracked, the mean shift algorithm will make the mass of bright yellow pixels more defined and track it at each frame as it moves between the players.
Before implementing the mean shift algorithm, an initial tracking box needs to be established. As the mean shift algorithm iteratively shifts points, the tracking box will move until surrounds the object of interest.
Unfortunately, if the object shifts in size or changes orientation, the tracking box doesn’t accommodate the change. The cam shift (Continuously Adaptive Mean Shift)algorithm addresses this issue.
Working very similarly as the mean shift, the cam shift algorithm simply adjusts it so that the tracking box may change in size or even rotate to better correlate to the movements of the tracked object.
Unlike deep neural networks or other methods of identification, mean shift and cam shift don’t require any training. If a tennis ball needs to be tracked, there’s no need to feed the algorithm hundreds or thousands of labeled images of a tennis balls. Instead, the algorithm analyzes the initial color input of the tennis ball and tracks it immediately throughout the rest of its lifetime.
Unfortunately, mean shift and cam shift only work with color analysis. If the object being tracked varies significantly in color or texture, it will be harder to track. Likewise, if an image or video has a “busy” or “noisy” background with a lot of color variation, it may conflict with the object being tracked.
Ultimately, mean shift and cam shift work best under controlled environments. For example, tracking product of uniform colored packaging through a warehouse or assembly line might perfectly suit these algorithms.
As cam shift is the more robust of the two algorithms, its implementation in python and OpenCV will be explained in deeper detail. A brief over of implementing mean shift, however, may be found here.
import numpy as npimport cv2
The only two libraries needed are NumPy and OpenCV. The former helps with efficient calculation and the latter provides many of tools used in computer vision.
# initialize video from the webcamvideo = cv2.VideoCapture(0)# Read the videocap, frame = video.read()
The first line simply activates the webcam (if there’s a camera present). The read method actually captures two important pieces of information:
the cap variable, which indicates whether or not the camera successfully captured a framethe frame variable, which is an actual still image, or frame, from the camera feed
the cap variable, which indicates whether or not the camera successfully captured a frame
the frame variable, which is an actual still image, or frame, from the camera feed
# set up initial coordinates for the tracking windowx, y = 0, 0# Set up initial size of the tracking windowheight, width = 25, 25track_window = (x,y,width,height)# set up region of interest (roi)roi = frame[y:y + height, x:x + width]
This next section establishes the initial Region of Interest (ROI), which is simply the area of the screen that features the object being tracked.
The x and y variables are the coordinates within the frame. In this example, coordinates (0, 0) are used because its easy to find once the camera starts streaming.
The height and width indicate the size of the ROI. It’s very important that the size of the ROI at least roughly correspond with the size of the object being tracked.
The track_window variable stores the position and size of the ROI and the roi variable actually uses splicers to takes a small subsection of the frame corresponding to the ROI.
Whatever the camera “sees” in this ROI will dictate the color range it tracks. For example, if a red ball is in this initial ROI, the algorithm will know to track a red object for the rest of the feed.
If, however, part of the ball is out of the ROI, and more of a white background is captured, the algorithm will be more likely to track a white object. Capturing the correct object in this initial ROI will be critical to ensuring it works properly.
TIP: When I was learning how to do this, I “cheated” by holding the object of interest up close to the camera so that the whole screen was filled. This forced the algorithm to read the correct color information, no matter the initial parameters I used. This, however, is not practical for most applications.
# apply maskhsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)mask = cv2.inRange(hsv_frame, np.array((0, 20, 20)), np.array((180, 250, 250)))hist_frame = cv2.calcHist([hsv_frame], [0], mask, [180], [0,180])cv2.normalize(hist_frame, hist_frame, 0, 255, cv2.NORM_MINMAX)
The next couple of lines convert the frame into the HSV color space and apply a “mask”, which simply looks for pixel values that fit within a certain range.
The histogram is calculated for the frame after the the mask is applied and the values are normalized. This serves to calculate the colors that the algorithm will track moving forward.
# Setup the termination criteria: 10 iteration 1 pxl movementterm_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )
After the initial values are captured, a termination criteria needs to be established. Recalling that both mean shift and cam shift are iterative functions that continuously shift points, some sort of criteria must be established to stop its iteration and return a final set of values.
The above line stop the iterations if either one of two things happen:
the centroid of the ROI hasn’t moved, orthere are more than 10 iterations
the centroid of the ROI hasn’t moved, or
there are more than 10 iterations
The first criteria makes intuitive sense. If an object is being tracked and it doesn’t move, there’s no need to run the algorithm. The ROI doesn’t change, so it doesn’t need to be recalculated. Doing so would only waste computational power.
The second criteria is more concerned with performance. In theory, more iterations will render a more accurate ROI; however, more iterations take more time to run. Setting a higher limit than 10 may build a better bounding box, but the results will be lagging.
while True: cap, frame = video.read() if cap == True: hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) dst = cv2.calcBackProject([hsv],[0],hist_frame,[0,180],1)
The first line starts an infinite loop as the camera will stream indefinitely until an exit command is triggered.
The next line, like before, reads data from the camera. The following if-statement checks to determine if the camera successfully captured a frame.
The last two lines convert the frame into the HSV color space and uses histogram backprojection to find which pixels that best correspond to the color of the object captured in the initial ROI.
# apply camshift to get the new location ret, track_window = cv2.CamShift(dst, track_window, term_crit)
Instead of implementing the cam shift algorithm from scratch, OpenCV has a built-in module to apply it. This will return the size and coordinates of the new ROI.
# Draw a box around the ROI pts = cv2.boxPoints(ret) pts = np.int0(pts) img2 = cv2.polylines(frame,[pts],True, 255,2)
Finally, draw a box around the ROI to visually indicate it.
cv2.imshow('img2',img2) # Use the q button to quit the operation if cv2.waitKey(60) & 0xff == ord('q'): break else: breakcv2.destroyAllWindows()video.release()
The image is shown in real time in the first line. The next line simply creates an exit condition. If the letter “q” on the keyboard is pressed, it breaks the loop and exits the video.
Likewise if the camera is suddenly unable to successfully capture video, it will also break the loop.
Finally, in the last two lines, any related windows are closed and the camera stops streaming.
If all goes well, the final result should look something like this:
Note how the bounding box increases and decreases in size as the envelope goes closer and further away from the camera. It also rotates along with envelope and even compresses when is turned on its side.
The mean shift and cam shift algorithms are both incredibly useful and powerful tools to use in object tracking. The latter, in particular, can shift its ROI as the object rotates or changes distance from the camera. The result is a robust method of tracking.
Using color as a primary method of identification, neither algorithm can identify something with a particular shape, which makes it less powerful than other methods. Likewise, complex or noisy backgrounds will make identification more problematic. As a tradeoff, however, using color allows for immediate implementation without the need for training the model.
Either work well in controlled, well-lit environments and offer an efficient method of object tracking.
|
[
{
"code": null,
"e": 339,
"s": 172,
"text": "Among the most demanded features of computer vision is object tracking. Unfortunately, this is also one of the most difficult aspects of computer vision to implement."
},
{
"code": null,
"e": 575,
"s": 339,
"text": "Not only does an object need to be identified, it needs to be identified quickly enough to render in real time while it moves. The object may change orientation or change its distance from the camera, which further complicates matters."
},
{
"code": null,
"e": 834,
"s": 575,
"text": "While still an adamant challenge in computer vision, the mean shift and cam shift algorithms present a simplified solution. Working primarily with color data rather than structural data, these methods can efficiently track objects under the right conditions."
},
{
"code": null,
"e": 1087,
"s": 834,
"text": "The mean shift algorithm is actually a broader statistical concept related to clustering. Like most other clustering algorithms, the mean shift algorithm attempts to look for places in the data set with a high concentration of data points, or clusters."
},
{
"code": null,
"e": 1320,
"s": 1087,
"text": "The algorithm places a kernel at each data point and sums them together to make a Kernel Density Estimation (KDE). The KDE will have peaks and valleys, which correspond to places with a high and low data point density, respectfully."
},
{
"code": null,
"e": 1640,
"s": 1320,
"text": "The algorithm takes a copy of the data points and shifts the points by a small amount to their nearest KDE peak in a single iteration. The algorithm will continue to go through iterations of shifting the points until the points no longer move much. This can help simplify the data and make the clusters more pronounced."
},
{
"code": null,
"e": 1729,
"s": 1640,
"text": "So how does this related to computer vision? Imagine a rainbow, like in the image below:"
},
{
"code": null,
"e": 2137,
"s": 1729,
"text": "The image may be broken down into the HSV color space, essentially turning it into a big data set. When making a KDE, each of the colors of the rainbow and the blue in the sky will create a peak. When shifting the points iteratively, each color of the rainbow will become more distinct by eliminating the subtle fading between colors. Consequently, each stripe become more easily identifiable by a computer."
},
{
"code": null,
"e": 2183,
"s": 2137,
"text": "This process is a form of image segmentation."
},
{
"code": null,
"e": 2439,
"s": 2183,
"text": "To take the concept further, if a particular color in the rainbow needed to be identified, the mean shift algorithm makes it more easily seen. If this color needed to be tracked, each frame of a video of a rainbow would undergo the algorithm in real time."
},
{
"code": null,
"e": 2762,
"s": 2439,
"text": "For a more realistic example, image a top-down view of a tennis match. The court, the players, and the bright yellow ball will each have a KDE peak. If the ball needs to be tracked, the mean shift algorithm will make the mass of bright yellow pixels more defined and track it at each frame as it moves between the players."
},
{
"code": null,
"e": 2979,
"s": 2762,
"text": "Before implementing the mean shift algorithm, an initial tracking box needs to be established. As the mean shift algorithm iteratively shifts points, the tracking box will move until surrounds the object of interest."
},
{
"code": null,
"e": 3176,
"s": 2979,
"text": "Unfortunately, if the object shifts in size or changes orientation, the tracking box doesn’t accommodate the change. The cam shift (Continuously Adaptive Mean Shift)algorithm addresses this issue."
},
{
"code": null,
"e": 3379,
"s": 3176,
"text": "Working very similarly as the mean shift, the cam shift algorithm simply adjusts it so that the tracking box may change in size or even rotate to better correlate to the movements of the tracked object."
},
{
"code": null,
"e": 3769,
"s": 3379,
"text": "Unlike deep neural networks or other methods of identification, mean shift and cam shift don’t require any training. If a tennis ball needs to be tracked, there’s no need to feed the algorithm hundreds or thousands of labeled images of a tennis balls. Instead, the algorithm analyzes the initial color input of the tennis ball and tracks it immediately throughout the rest of its lifetime."
},
{
"code": null,
"e": 4082,
"s": 3769,
"text": "Unfortunately, mean shift and cam shift only work with color analysis. If the object being tracked varies significantly in color or texture, it will be harder to track. Likewise, if an image or video has a “busy” or “noisy” background with a lot of color variation, it may conflict with the object being tracked."
},
{
"code": null,
"e": 4295,
"s": 4082,
"text": "Ultimately, mean shift and cam shift work best under controlled environments. For example, tracking product of uniform colored packaging through a warehouse or assembly line might perfectly suit these algorithms."
},
{
"code": null,
"e": 4495,
"s": 4295,
"text": "As cam shift is the more robust of the two algorithms, its implementation in python and OpenCV will be explained in deeper detail. A brief over of implementing mean shift, however, may be found here."
},
{
"code": null,
"e": 4524,
"s": 4495,
"text": "import numpy as npimport cv2"
},
{
"code": null,
"e": 4683,
"s": 4524,
"text": "The only two libraries needed are NumPy and OpenCV. The former helps with efficient calculation and the latter provides many of tools used in computer vision."
},
{
"code": null,
"e": 4786,
"s": 4683,
"text": "# initialize video from the webcamvideo = cv2.VideoCapture(0)# Read the videocap, frame = video.read()"
},
{
"code": null,
"e": 4931,
"s": 4786,
"text": "The first line simply activates the webcam (if there’s a camera present). The read method actually captures two important pieces of information:"
},
{
"code": null,
"e": 5103,
"s": 4931,
"text": "the cap variable, which indicates whether or not the camera successfully captured a framethe frame variable, which is an actual still image, or frame, from the camera feed"
},
{
"code": null,
"e": 5193,
"s": 5103,
"text": "the cap variable, which indicates whether or not the camera successfully captured a frame"
},
{
"code": null,
"e": 5276,
"s": 5193,
"text": "the frame variable, which is an actual still image, or frame, from the camera feed"
},
{
"code": null,
"e": 5510,
"s": 5276,
"text": "# set up initial coordinates for the tracking windowx, y = 0, 0# Set up initial size of the tracking windowheight, width = 25, 25track_window = (x,y,width,height)# set up region of interest (roi)roi = frame[y:y + height, x:x + width]"
},
{
"code": null,
"e": 5657,
"s": 5510,
"text": "This next section establishes the initial Region of Interest (ROI), which is simply the area of the screen that features the object being tracked."
},
{
"code": null,
"e": 5821,
"s": 5657,
"text": "The x and y variables are the coordinates within the frame. In this example, coordinates (0, 0) are used because its easy to find once the camera starts streaming."
},
{
"code": null,
"e": 5988,
"s": 5821,
"text": "The height and width indicate the size of the ROI. It’s very important that the size of the ROI at least roughly correspond with the size of the object being tracked."
},
{
"code": null,
"e": 6165,
"s": 5988,
"text": "The track_window variable stores the position and size of the ROI and the roi variable actually uses splicers to takes a small subsection of the frame corresponding to the ROI."
},
{
"code": null,
"e": 6367,
"s": 6165,
"text": "Whatever the camera “sees” in this ROI will dictate the color range it tracks. For example, if a red ball is in this initial ROI, the algorithm will know to track a red object for the rest of the feed."
},
{
"code": null,
"e": 6616,
"s": 6367,
"text": "If, however, part of the ball is out of the ROI, and more of a white background is captured, the algorithm will be more likely to track a white object. Capturing the correct object in this initial ROI will be critical to ensuring it works properly."
},
{
"code": null,
"e": 6924,
"s": 6616,
"text": "TIP: When I was learning how to do this, I “cheated” by holding the object of interest up close to the camera so that the whole screen was filled. This forced the algorithm to read the correct color information, no matter the initial parameters I used. This, however, is not practical for most applications."
},
{
"code": null,
"e": 7194,
"s": 6924,
"text": "# apply maskhsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)mask = cv2.inRange(hsv_frame, np.array((0, 20, 20)), np.array((180, 250, 250)))hist_frame = cv2.calcHist([hsv_frame], [0], mask, [180], [0,180])cv2.normalize(hist_frame, hist_frame, 0, 255, cv2.NORM_MINMAX)"
},
{
"code": null,
"e": 7351,
"s": 7194,
"text": "The next couple of lines convert the frame into the HSV color space and apply a “mask”, which simply looks for pixel values that fit within a certain range."
},
{
"code": null,
"e": 7536,
"s": 7351,
"text": "The histogram is calculated for the frame after the the mask is applied and the values are normalized. This serves to calculate the colors that the algorithm will track moving forward."
},
{
"code": null,
"e": 7667,
"s": 7536,
"text": "# Setup the termination criteria: 10 iteration 1 pxl movementterm_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )"
},
{
"code": null,
"e": 7953,
"s": 7667,
"text": "After the initial values are captured, a termination criteria needs to be established. Recalling that both mean shift and cam shift are iterative functions that continuously shift points, some sort of criteria must be established to stop its iteration and return a final set of values."
},
{
"code": null,
"e": 8024,
"s": 7953,
"text": "The above line stop the iterations if either one of two things happen:"
},
{
"code": null,
"e": 8098,
"s": 8024,
"text": "the centroid of the ROI hasn’t moved, orthere are more than 10 iterations"
},
{
"code": null,
"e": 8139,
"s": 8098,
"text": "the centroid of the ROI hasn’t moved, or"
},
{
"code": null,
"e": 8173,
"s": 8139,
"text": "there are more than 10 iterations"
},
{
"code": null,
"e": 8414,
"s": 8173,
"text": "The first criteria makes intuitive sense. If an object is being tracked and it doesn’t move, there’s no need to run the algorithm. The ROI doesn’t change, so it doesn’t need to be recalculated. Doing so would only waste computational power."
},
{
"code": null,
"e": 8675,
"s": 8414,
"text": "The second criteria is more concerned with performance. In theory, more iterations will render a more accurate ROI; however, more iterations take more time to run. Setting a higher limit than 10 may build a better bounding box, but the results will be lagging."
},
{
"code": null,
"e": 8856,
"s": 8675,
"text": "while True: cap, frame = video.read() if cap == True: hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) dst = cv2.calcBackProject([hsv],[0],hist_frame,[0,180],1)"
},
{
"code": null,
"e": 8970,
"s": 8856,
"text": "The first line starts an infinite loop as the camera will stream indefinitely until an exit command is triggered."
},
{
"code": null,
"e": 9118,
"s": 8970,
"text": "The next line, like before, reads data from the camera. The following if-statement checks to determine if the camera successfully captured a frame."
},
{
"code": null,
"e": 9312,
"s": 9118,
"text": "The last two lines convert the frame into the HSV color space and uses histogram backprojection to find which pixels that best correspond to the color of the object captured in the initial ROI."
},
{
"code": null,
"e": 9431,
"s": 9312,
"text": " # apply camshift to get the new location ret, track_window = cv2.CamShift(dst, track_window, term_crit)"
},
{
"code": null,
"e": 9593,
"s": 9431,
"text": "Instead of implementing the cam shift algorithm from scratch, OpenCV has a built-in module to apply it. This will return the size and coordinates of the new ROI."
},
{
"code": null,
"e": 9739,
"s": 9593,
"text": " # Draw a box around the ROI pts = cv2.boxPoints(ret) pts = np.int0(pts) img2 = cv2.polylines(frame,[pts],True, 255,2)"
},
{
"code": null,
"e": 9799,
"s": 9739,
"text": "Finally, draw a box around the ROI to visually indicate it."
},
{
"code": null,
"e": 10002,
"s": 9799,
"text": " cv2.imshow('img2',img2) # Use the q button to quit the operation if cv2.waitKey(60) & 0xff == ord('q'): break else: breakcv2.destroyAllWindows()video.release()"
},
{
"code": null,
"e": 10187,
"s": 10002,
"text": "The image is shown in real time in the first line. The next line simply creates an exit condition. If the letter “q” on the keyboard is pressed, it breaks the loop and exits the video."
},
{
"code": null,
"e": 10289,
"s": 10187,
"text": "Likewise if the camera is suddenly unable to successfully capture video, it will also break the loop."
},
{
"code": null,
"e": 10384,
"s": 10289,
"text": "Finally, in the last two lines, any related windows are closed and the camera stops streaming."
},
{
"code": null,
"e": 10452,
"s": 10384,
"text": "If all goes well, the final result should look something like this:"
},
{
"code": null,
"e": 10656,
"s": 10452,
"text": "Note how the bounding box increases and decreases in size as the envelope goes closer and further away from the camera. It also rotates along with envelope and even compresses when is turned on its side."
},
{
"code": null,
"e": 10916,
"s": 10656,
"text": "The mean shift and cam shift algorithms are both incredibly useful and powerful tools to use in object tracking. The latter, in particular, can shift its ROI as the object rotates or changes distance from the camera. The result is a robust method of tracking."
},
{
"code": null,
"e": 11277,
"s": 10916,
"text": "Using color as a primary method of identification, neither algorithm can identify something with a particular shape, which makes it less powerful than other methods. Likewise, complex or noisy backgrounds will make identification more problematic. As a tradeoff, however, using color allows for immediate implementation without the need for training the model."
}
] |
GATE | GATE CS 2018 | Question 14 - GeeksforGeeks
|
12 Aug, 2021
Consider the following C program:
#include <stdio.h> int counter = 0; int calc(int a, int b) { int c; counter++; if (b == 3) return (a * a * a); else { c = calc(a, b / 3); return (c * c * c); }} int main() { calc(4, 81); printf("%d", counter);}
The output of this program is ________ .
Note – This was Numerical Type question.(A) 5(B) 4(C) 3(D) None of theseAnswer: (B)Explanation:
YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersGATE PYQs 2017 and 2018 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0048:42 / 1:11:13•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=j9Vmf5yRw-I" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE CS 2018
GATE-GATE CS 2018
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
|
[
{
"code": null,
"e": 24450,
"s": 24422,
"text": "\n12 Aug, 2021"
},
{
"code": null,
"e": 24484,
"s": 24450,
"text": "Consider the following C program:"
},
{
"code": "#include <stdio.h> int counter = 0; int calc(int a, int b) { int c; counter++; if (b == 3) return (a * a * a); else { c = calc(a, b / 3); return (c * c * c); }} int main() { calc(4, 81); printf(\"%d\", counter);}",
"e": 24716,
"s": 24484,
"text": null
},
{
"code": null,
"e": 24757,
"s": 24716,
"text": "The output of this program is ________ ."
},
{
"code": null,
"e": 24854,
"s": 24757,
"text": "Note – This was Numerical Type question.(A) 5(B) 4(C) 3(D) None of theseAnswer: (B)Explanation: "
},
{
"code": null,
"e": 25754,
"s": 24854,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersGATE PYQs 2017 and 2018 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0048:42 / 1:11:13•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=j9Vmf5yRw-I\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 25767,
"s": 25754,
"text": "GATE CS 2018"
},
{
"code": null,
"e": 25785,
"s": 25767,
"text": "GATE-GATE CS 2018"
},
{
"code": null,
"e": 25790,
"s": 25785,
"text": "GATE"
},
{
"code": null,
"e": 25888,
"s": 25790,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25922,
"s": 25888,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 25964,
"s": 25922,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 26006,
"s": 25964,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26040,
"s": 26006,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 26073,
"s": 26040,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 26107,
"s": 26073,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 26141,
"s": 26107,
"text": "GATE | GATE CS 2011 | Question 65"
},
{
"code": null,
"e": 26175,
"s": 26141,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 26217,
"s": 26175,
"text": "GATE | GATE CS 2021 | Set 1 | Question 47"
}
] |
How you can quickly build ML apps with Streamlit. | Towards Data Science
|
If you’re a data scientist or a machine learning engineer, you are probably reasonably confident in your ability to build models to solve real-world business problems. But how good are you at front-end web development? Can you build a visually appealing web application to showcase your models? Chances are, you may be a Python specialist, but not a front-end Javascript expert.
But thankfully, you don’t have to be one! Streamlit is a Python framework that makes it very easy for machine learning and data science practitioners to build web apps in pure Python. That’s right, you don’t even have to worry about HTML tags, Bootstrap components, or writing your own Javascript functions.
In this article, I will demonstrate how you can use Streamlit to quickly build a web app that showcases a text classification model.
You can easily install Streamlit with pip using the command below.
pip install streamlit
In this section, I will train a simple spam classification model that determines if a text message is spam. Since the main focus of this tutorial is demonstrating how to use Streamlit, I will include the code used to build this model with minimal comments. I used this Spam Classification Dataset from Kaggle to train a neural network for spam classification. The original dataset is available here as the SMS Spam Collection. You can find the full code for this tutorial on GitHub.
The code above performs the following steps:
Reads the spam dataset.Splits the spam dataset into training and testing sets.Creates a text preprocessing and deep learning pipeline for spam classification.Trains the model pipeline on the training set.Evaluates the model pipeline on the testing set.Saves the trained model pipeline.
Reads the spam dataset.
Splits the spam dataset into training and testing sets.
Creates a text preprocessing and deep learning pipeline for spam classification.
Trains the model pipeline on the training set.
Evaluates the model pipeline on the testing set.
Saves the trained model pipeline.
In the same folder as the saved model pipeline, I created a file called streamlit_app.py and added code incrementally as demonstrated in the sections below. Refer to this GitHub repository if you want to see the full code for this tutorial.
I imported the necessary libraries and modules, including Streamlit, needed to run this app as shown below.
import joblibimport refrom sklearn.neural_network import MLPClassifierfrom sklearn.feature_extraction.text import TfidfVectorizerimport streamlit as st
Now that we have imported Streamlit, we can quickly create a heading using Streamlit’s Markdown support.
st.write("# Spam Detection Engine")
To see the results of this code, we can run the following command.
streamlit run streamlit_app.py
Running the code and navigating to localhost:8501 gives us the following result.
With just one line of code (not counting the import statements), you now have a running Streamlit app! Next, we can add some interactivity to the app with a text input field.
message_text = st.text_input("Enter a message for spam evaluation")
Refreshing the app page at localhost:8501 gives us a neat text input field under the heading.
Now, we can add our trained spam classification model to the app.
Before loading the model, I included the predefined text preprocessing function since this is a part of the saved model.
def preprocessor(text): text = re.sub('<[^>]*>', '', text) emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text) text = re.sub('[\W]+', ' ', text.lower()) + ' '.join(emoticons).replace('-', '') return textmodel = joblib.load('spam_classifier.joblib')
We can define a special function for returning both the label predicted by the model (spam or ham) and the probability of the message being spam as demonstrated below.
def classify_message(model, message): label = model.predict([message])[0] spam_prob = model.predict_proba([message]) return {'label': label, 'spam_probability': spam_prob[0][1]}
Using this function we can output the model’s predictions as a dictionary.
if message_text != '': result = classify_message(model, message_text) st.write(result)
We can refresh the app again and pass in some sample text inputs. Let’s start with something that is obviously spam.
From the screenshot above, we can see that the model predicts that this message has a very high chance (99.98 percent) of being spam.
Now, let’s write a message about a doctor’s appointment and see if the model classifies it as spam or ham.
As we can see above, the message has a very low probability of being spam based on the predictions generated by the model.
We can add some explanations for the predictions generated by the model using LIME, a library for explainable machine learning. For an in-depth tutorial on how to use this library, take a look at my article about explainable machine learning below.
towardsdatascience.com
To use LIME and embed a LIME explanation in the web app, add the following import statements to the top of the code.
from lime.lime_text import LimeTextExplainerimport streamlit.components.v1 as components
The components module from Streamlit allows us to embed custom HTML components in the application. We can create a visualization with LIME and display it on a Streamlit app as an HTML component.
Next, we can add the following code at the end of the last if-block to create a button for explaining the model’s predictions.
explain_pred = st.button('Explain Predictions')
The value of the variable explain_pred will be set to True when the button is clicked on once. We can now generate a text explanation with LIME as demonstrated in the code below.
if explain_pred: with st.spinner('Generating explanations'): class_names = ['ham', 'spam'] explainer = LimeTextExplainer(class_names=class_names) exp = explainer.explain_instance(message_text, model.predict_proba, num_features=10) components.html(exp.as_html(), height=800)
Refreshing the app allows us to generate explanations for the model’s predictions as shown in the GIF below. Notice how the LIME TextExplainer allows the user to understand why the model classified the message as spam by highlighting the most important words that the model used in its decision-making process.
At this point, the app is fully functional and can be used to showcase and explain the predictions generated by the spam classification model. Check out the full code for this app below.
The app that I created in this article is definitely useful and can serve as a starting point for similar projects, but it only covers a few of the powerful features of Streamlit. Here are some additional features of Streamlit that you should definitely check out:
Streamlit supports Markdown and Latex commands, allowing you to include equations in a web app.
Streamlit allows you to display tables and pandas data frames with a single line of code.
Streamlit allows you to display charts and visualizations from a wide range of libraries including Matplotlib, Bokeh, Pyplot, Pydeck, and even Graphviz.
Streamlit allows you to easily display points on a map.
Streamlit also supports embedding image, audio, and video files in your apps.
Streamlit makes it easy to deploy open-source applications with Streamlit sharing.
To find out more about what Streamlit can do, check out the Streamlit documentation.
In this article, I demonstrated how you can use Streamlit to build a web app that showcases a simple text classification model in less than 50 lines of code. Streamlit is definitely a powerful, high-level tool that makes web development easy and simple for data scientists. As usual, you can find all the code for this article on GitHub.
Do you want to get better at data science and machine learning? Do you want to stay up to date with the latest libraries, developments, and research in the data science and machine learning community?
Join my mailing list to get updates on my data science content. You’ll also get my free Step-By-Step Guide to Solving Machine Learning Problems when you sign up!
T. A., Almedia and J. M. Gomez Hidalgo, SMS Spam Collection, (2011), Proceedings of the 2011 ACM Symposium on Document Engineering (DOCENG’11).Streamlit Inc., Streamlit Documentation, (2020), streamlit.io.
T. A., Almedia and J. M. Gomez Hidalgo, SMS Spam Collection, (2011), Proceedings of the 2011 ACM Symposium on Document Engineering (DOCENG’11).
Streamlit Inc., Streamlit Documentation, (2020), streamlit.io.
|
[
{
"code": null,
"e": 550,
"s": 171,
"text": "If you’re a data scientist or a machine learning engineer, you are probably reasonably confident in your ability to build models to solve real-world business problems. But how good are you at front-end web development? Can you build a visually appealing web application to showcase your models? Chances are, you may be a Python specialist, but not a front-end Javascript expert."
},
{
"code": null,
"e": 858,
"s": 550,
"text": "But thankfully, you don’t have to be one! Streamlit is a Python framework that makes it very easy for machine learning and data science practitioners to build web apps in pure Python. That’s right, you don’t even have to worry about HTML tags, Bootstrap components, or writing your own Javascript functions."
},
{
"code": null,
"e": 991,
"s": 858,
"text": "In this article, I will demonstrate how you can use Streamlit to quickly build a web app that showcases a text classification model."
},
{
"code": null,
"e": 1058,
"s": 991,
"text": "You can easily install Streamlit with pip using the command below."
},
{
"code": null,
"e": 1080,
"s": 1058,
"text": "pip install streamlit"
},
{
"code": null,
"e": 1563,
"s": 1080,
"text": "In this section, I will train a simple spam classification model that determines if a text message is spam. Since the main focus of this tutorial is demonstrating how to use Streamlit, I will include the code used to build this model with minimal comments. I used this Spam Classification Dataset from Kaggle to train a neural network for spam classification. The original dataset is available here as the SMS Spam Collection. You can find the full code for this tutorial on GitHub."
},
{
"code": null,
"e": 1608,
"s": 1563,
"text": "The code above performs the following steps:"
},
{
"code": null,
"e": 1894,
"s": 1608,
"text": "Reads the spam dataset.Splits the spam dataset into training and testing sets.Creates a text preprocessing and deep learning pipeline for spam classification.Trains the model pipeline on the training set.Evaluates the model pipeline on the testing set.Saves the trained model pipeline."
},
{
"code": null,
"e": 1918,
"s": 1894,
"text": "Reads the spam dataset."
},
{
"code": null,
"e": 1974,
"s": 1918,
"text": "Splits the spam dataset into training and testing sets."
},
{
"code": null,
"e": 2055,
"s": 1974,
"text": "Creates a text preprocessing and deep learning pipeline for spam classification."
},
{
"code": null,
"e": 2102,
"s": 2055,
"text": "Trains the model pipeline on the training set."
},
{
"code": null,
"e": 2151,
"s": 2102,
"text": "Evaluates the model pipeline on the testing set."
},
{
"code": null,
"e": 2185,
"s": 2151,
"text": "Saves the trained model pipeline."
},
{
"code": null,
"e": 2426,
"s": 2185,
"text": "In the same folder as the saved model pipeline, I created a file called streamlit_app.py and added code incrementally as demonstrated in the sections below. Refer to this GitHub repository if you want to see the full code for this tutorial."
},
{
"code": null,
"e": 2534,
"s": 2426,
"text": "I imported the necessary libraries and modules, including Streamlit, needed to run this app as shown below."
},
{
"code": null,
"e": 2686,
"s": 2534,
"text": "import joblibimport refrom sklearn.neural_network import MLPClassifierfrom sklearn.feature_extraction.text import TfidfVectorizerimport streamlit as st"
},
{
"code": null,
"e": 2791,
"s": 2686,
"text": "Now that we have imported Streamlit, we can quickly create a heading using Streamlit’s Markdown support."
},
{
"code": null,
"e": 2827,
"s": 2791,
"text": "st.write(\"# Spam Detection Engine\")"
},
{
"code": null,
"e": 2894,
"s": 2827,
"text": "To see the results of this code, we can run the following command."
},
{
"code": null,
"e": 2925,
"s": 2894,
"text": "streamlit run streamlit_app.py"
},
{
"code": null,
"e": 3006,
"s": 2925,
"text": "Running the code and navigating to localhost:8501 gives us the following result."
},
{
"code": null,
"e": 3181,
"s": 3006,
"text": "With just one line of code (not counting the import statements), you now have a running Streamlit app! Next, we can add some interactivity to the app with a text input field."
},
{
"code": null,
"e": 3249,
"s": 3181,
"text": "message_text = st.text_input(\"Enter a message for spam evaluation\")"
},
{
"code": null,
"e": 3343,
"s": 3249,
"text": "Refreshing the app page at localhost:8501 gives us a neat text input field under the heading."
},
{
"code": null,
"e": 3409,
"s": 3343,
"text": "Now, we can add our trained spam classification model to the app."
},
{
"code": null,
"e": 3530,
"s": 3409,
"text": "Before loading the model, I included the predefined text preprocessing function since this is a part of the saved model."
},
{
"code": null,
"e": 3801,
"s": 3530,
"text": "def preprocessor(text): text = re.sub('<[^>]*>', '', text) emoticons = re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', text) text = re.sub('[\\W]+', ' ', text.lower()) + ' '.join(emoticons).replace('-', '') return textmodel = joblib.load('spam_classifier.joblib')"
},
{
"code": null,
"e": 3969,
"s": 3801,
"text": "We can define a special function for returning both the label predicted by the model (spam or ham) and the probability of the message being spam as demonstrated below."
},
{
"code": null,
"e": 4150,
"s": 3969,
"text": "def classify_message(model, message): label = model.predict([message])[0] spam_prob = model.predict_proba([message]) return {'label': label, 'spam_probability': spam_prob[0][1]}"
},
{
"code": null,
"e": 4225,
"s": 4150,
"text": "Using this function we can output the model’s predictions as a dictionary."
},
{
"code": null,
"e": 4314,
"s": 4225,
"text": "if message_text != '': result = classify_message(model, message_text) st.write(result)"
},
{
"code": null,
"e": 4431,
"s": 4314,
"text": "We can refresh the app again and pass in some sample text inputs. Let’s start with something that is obviously spam."
},
{
"code": null,
"e": 4565,
"s": 4431,
"text": "From the screenshot above, we can see that the model predicts that this message has a very high chance (99.98 percent) of being spam."
},
{
"code": null,
"e": 4672,
"s": 4565,
"text": "Now, let’s write a message about a doctor’s appointment and see if the model classifies it as spam or ham."
},
{
"code": null,
"e": 4795,
"s": 4672,
"text": "As we can see above, the message has a very low probability of being spam based on the predictions generated by the model."
},
{
"code": null,
"e": 5044,
"s": 4795,
"text": "We can add some explanations for the predictions generated by the model using LIME, a library for explainable machine learning. For an in-depth tutorial on how to use this library, take a look at my article about explainable machine learning below."
},
{
"code": null,
"e": 5067,
"s": 5044,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5184,
"s": 5067,
"text": "To use LIME and embed a LIME explanation in the web app, add the following import statements to the top of the code."
},
{
"code": null,
"e": 5273,
"s": 5184,
"text": "from lime.lime_text import LimeTextExplainerimport streamlit.components.v1 as components"
},
{
"code": null,
"e": 5468,
"s": 5273,
"text": "The components module from Streamlit allows us to embed custom HTML components in the application. We can create a visualization with LIME and display it on a Streamlit app as an HTML component."
},
{
"code": null,
"e": 5595,
"s": 5468,
"text": "Next, we can add the following code at the end of the last if-block to create a button for explaining the model’s predictions."
},
{
"code": null,
"e": 5643,
"s": 5595,
"text": "explain_pred = st.button('Explain Predictions')"
},
{
"code": null,
"e": 5822,
"s": 5643,
"text": "The value of the variable explain_pred will be set to True when the button is clicked on once. We can now generate a text explanation with LIME as demonstrated in the code below."
},
{
"code": null,
"e": 6108,
"s": 5822,
"text": "if explain_pred: with st.spinner('Generating explanations'): class_names = ['ham', 'spam'] explainer = LimeTextExplainer(class_names=class_names) exp = explainer.explain_instance(message_text, model.predict_proba, num_features=10) components.html(exp.as_html(), height=800)"
},
{
"code": null,
"e": 6419,
"s": 6108,
"text": "Refreshing the app allows us to generate explanations for the model’s predictions as shown in the GIF below. Notice how the LIME TextExplainer allows the user to understand why the model classified the message as spam by highlighting the most important words that the model used in its decision-making process."
},
{
"code": null,
"e": 6606,
"s": 6419,
"text": "At this point, the app is fully functional and can be used to showcase and explain the predictions generated by the spam classification model. Check out the full code for this app below."
},
{
"code": null,
"e": 6871,
"s": 6606,
"text": "The app that I created in this article is definitely useful and can serve as a starting point for similar projects, but it only covers a few of the powerful features of Streamlit. Here are some additional features of Streamlit that you should definitely check out:"
},
{
"code": null,
"e": 6967,
"s": 6871,
"text": "Streamlit supports Markdown and Latex commands, allowing you to include equations in a web app."
},
{
"code": null,
"e": 7057,
"s": 6967,
"text": "Streamlit allows you to display tables and pandas data frames with a single line of code."
},
{
"code": null,
"e": 7210,
"s": 7057,
"text": "Streamlit allows you to display charts and visualizations from a wide range of libraries including Matplotlib, Bokeh, Pyplot, Pydeck, and even Graphviz."
},
{
"code": null,
"e": 7266,
"s": 7210,
"text": "Streamlit allows you to easily display points on a map."
},
{
"code": null,
"e": 7344,
"s": 7266,
"text": "Streamlit also supports embedding image, audio, and video files in your apps."
},
{
"code": null,
"e": 7427,
"s": 7344,
"text": "Streamlit makes it easy to deploy open-source applications with Streamlit sharing."
},
{
"code": null,
"e": 7512,
"s": 7427,
"text": "To find out more about what Streamlit can do, check out the Streamlit documentation."
},
{
"code": null,
"e": 7850,
"s": 7512,
"text": "In this article, I demonstrated how you can use Streamlit to build a web app that showcases a simple text classification model in less than 50 lines of code. Streamlit is definitely a powerful, high-level tool that makes web development easy and simple for data scientists. As usual, you can find all the code for this article on GitHub."
},
{
"code": null,
"e": 8051,
"s": 7850,
"text": "Do you want to get better at data science and machine learning? Do you want to stay up to date with the latest libraries, developments, and research in the data science and machine learning community?"
},
{
"code": null,
"e": 8213,
"s": 8051,
"text": "Join my mailing list to get updates on my data science content. You’ll also get my free Step-By-Step Guide to Solving Machine Learning Problems when you sign up!"
},
{
"code": null,
"e": 8419,
"s": 8213,
"text": "T. A., Almedia and J. M. Gomez Hidalgo, SMS Spam Collection, (2011), Proceedings of the 2011 ACM Symposium on Document Engineering (DOCENG’11).Streamlit Inc., Streamlit Documentation, (2020), streamlit.io."
},
{
"code": null,
"e": 8563,
"s": 8419,
"text": "T. A., Almedia and J. M. Gomez Hidalgo, SMS Spam Collection, (2011), Proceedings of the 2011 ACM Symposium on Document Engineering (DOCENG’11)."
}
] |
Sentence Embeddings. Fast, please! | by Dr. Oliver Borchers | Towards Data Science
|
The fse code in this article is deprecated. Please make sure to use the updated code as outlined on Github.
When working with textual data in a machine learning pipeline, you may come across the need to compute sentence embeddings. Similar to regular word embeddings (like Word2Vec, GloVE, Elmo, Bert, or Fasttext), sentence embeddings embed a full sentence into a vector space. In practice, a sentence embedding might look like this:
“I shot the sheriff” → [0.2 ; 0.1 ; -0.3 ; 0.9 ; ...]
These sentence embeddings retain some nice properties, as they inherit features from their underlying word embeddings [1]. Thus, we might use sentence embeddings for varying purposes:
Compute a similarity matrix of sentences based on their embeddings.
Plot sentences using a common mapping technique, like t-SNE.
Predict some value for the sentence, i.e. sentiment.
A very simple supervised application of sentence embeddings can be seen in “deep averaging networks” [2], where the authors use sentence embeddings in sentiment analysis and question answering. In fact, sentence embeddings are a deceptively simple baseline to start from when you are working with textual data. Fortunately, they do not require any form of gradient based optimization if (pre-trained) word embeddings are already available.
This post is intended for a technical data-science audience. We are going to explore smooth inverse frequency (SIF) sentence embeddings [1]. Specifically, we are optimizing the computation of SIF embeddings by hand-crafting a function, which is specifically tailored to compute SIF embeddings as fast as possible. For this purpose we first use Python, then we migrate to Cython and finally to Basic Linear Algebra Subprograms (BLAS). Cython and BLAS are core ingredients used in Gensims Word2Vec implementation. I have to thank Radim Řehůřek, as Gensims implementation is the foundation of this post. For a similar post, feel free to read the original Word2Vec optimization blog. The following optimizations allow us to speed up the computation of SIF embeddings by a factor of 38 (!).
Smooth inverse frequency embeddings were originally conceived by [1] and the corresponding paper has been presented at the 2017 ICLR. The code for the original paper is available at Github. The authors present a nice probabilistic motivation for the inverse frequency weighted continuous bag-of-words model. We are not going into the technical details of the math, but rather into the optimization of the algorithm for computing the SIF embeddings. If you have to compute the SIF embeddings for millions of sentences, you need a routine to accomplish the task in a lifetime. In this post, we are just looking for speed. And Gensim offers quite a lot of it.
Discerning the algorithm, we can infer that most work is to be done in line 1 & 2. While it might seem straightforward, there is plenty of room to optimize line 1 & 2 when you are working with Python. The task is as follows: Compute the SIF embeddings as fast as possible for all sentences in the brown corpus. We will rely on Gensims Word2Vec implementation to obtain word vectors and only use a little preprocessing.
The whole code for this project is available on Github. You can install the fast sentence embedding library which I wrote using pip:
pip install fse
You will need regular Python packages, specifically Numpy, Scipy, Cython, and Gensim. TL;DR: If you need sentence embeddings fast, just use:
from gensim.models import Word2Vecsentences = [[“cat”, “say”, “meow”], [“dog”, “say”, “woof”]]model = Word2Vec(sentences, min_count=1)from fse.models import Sentence2Vecse = Sentence2Vec(model)sentences_emb = se.train(sentences)
In order to optimize the SIF function, we first need a prototype that is working correctly. Let’s have a look at the prototpye:
The code should be pretty self-explanatory. We first define the variable vlookup, which points us to gensims vocab class. Hereby we can access a words index and count. Vectors points us to the gensim wv class, which contains the word vectors themselves. Then we iterate over all sentences. For each sentence, we sum the vectors of all the words in the sentence up, while multiplying them with their SIF weight. Finally, we divide the vector by the length of the sentence. Nothing too fancy.
We need an embedding to measure the execution time of this function. Let us use a 100 dimensional Word2Vec embedding, that was trained on the commonly available Brown corpus. Then we use the first 400 sentences of the corpus and time the function. 5.70 seconds.
That is way to slow. The keen eye will have already noticed the pitfall: I’ve been using a for-loop in the vector addition. That is precisely the reason to not use python for-loops in such a scenario. They are way too slow. To circumvent this, let us rewrite line 37–40 to use the numpy routines.
The results is astonishing: 0.041434 seconds. That is 137x faster than the baseline version. However, we can still do better. Much better. As you might have noticed, vectors[w] acts as a lookup table for the word-vectors. If we pre-compute the word indices of the sentence, we can directly use numpy indexing to access all vectors at once, which is much faster. In the same step, we have to pre-compute the SIF weights for the vectors to access them via indexing.
With a runtime of 0.011987 seconds, these small additions cause the function to be 476x faster than the baseline we established.
To further speed up the implementation, we might actually pre-compute all the weighted vectors, as the weights and word vectors themselves do not change. Thereby, we decrease the runtime to 0.008674 seconds, marking a 658x increase over the baseline. But wait. There is a catch:
By pre-computing the SIF vectors, we might have to compute a fairly large matrix, which is not time-efficient if we only have a few sentences and a large vocabulary. Nor is it space-efficient, as we have to store a separate weighted embedding matrix in RAM. Thus, we are running into a tradeoff between memory and time efficency. Pre-computing the weighted vectors does only make sense if the effective number of words in our sentences to train on is larger than the vocabulary.
I will spoil a little bit by stating that this is not necessary due to the BLAS function we are going to use later, but keep it in mind for now.
We have already obtained quite some considerable speedups. The next thing we want to optimize is the summation of the vectors, where we can still obtain a significant speedup. However, to better benchmark the results, we are taking the conversion of the sentences to indices out of the equation. We thus pre-compute all sentence-indices for the following benchmarks:
sentences_idx = [np.asarray([int(model.wv.vocab[w].index) for w in s if w in model.wv.vocab], dtype=np.intc) for s in sentences]
You will immediately realize that this is a pretty bad idea in practice, as we now essentially have to store a second dataset. However, it serves our benchmarking purposes quite well for the moment.
With 0.004472 seconds the new function — using pre-computed weighted vectors and sentence indices — clocks in at 1276x the speed of the baseline implementation. However, the comparison is a bit off, as the baseline did not use pre-computed indices. Thus, this is our new benchmark for the moment.
The next step is to migrate to Cython. Note that we are still working with pre-computed indices and weighted vectors. We wrap everything into a nice Cython file and then compile it.
The cdef float[:,:] command gives us access to the memory view of the pre-computed vectors. For a more detailed explanation, the Cython website provides a neat tutorial on memory views. Remember to use
# cython: boundscheck=False# cython: wraparound=False
at the beginning of the file. These two commands remove the safety nets, which might possibly slow us down. The former checks whether we are running out of bounds of the array, whilst the latter allows us to perform negative indexing (which we are not going to use). We are now running 2.42x faster than the previous pure numpy implementation, which also relied on pre-computed indices for the sentences. Thus the comparison is fair again.
Note that we have pre-defined all of the necessary structures as C variables that we can use in a pure C-loop without any Pythonic interference. Thereby, we can also release the global interpreter lock (GIL), which might come in handy at some future point in time, when we are thinking about a multi-threaded implementation of fse. We essentially rewrite the part of the code used to sum all words in a sentence:
Thereby, we decrease the runtime to 0.000805 seconds, which marks another 2.28 fold increase over the first Cython implementation.
Finally, we are going for BLAS. The Basic Linear Algebra Subprograms describe low-level linear algebra routines. They are categorized in three levels: Level 1: vector ops, Level 2: vector-matrix ops, Level 3: matrix-matrix ops. We only need access to Level 1 for our purposes. Precisely, we need:
SAXPY: (Single) constant times a vector plus a vector
SSCAL: (Single) scales a vector by a constant
Gensims core classes make heavy use of these highly optimized routines to speed up Word2Vec, Doc2Vec, and Fasttext.
Now recall what we wrote about pre-computing the SIF weighted vectors earlier. The SAXPY function takes the argument a, which is used in y = a*x + y. Thus, we have to do the weight*vector multiplication anyways. Therefore, pre-computing the SIF vectors is actually an inefficient idea after all.
Additionally, we are dropping Cython memory view for direct unsafe access to the numpy variables via pointers & memory addresses.
We have to define the sscal and saxpy pointers elsewhere, which is spared in the code snippet (usually in a *.pxd file).
What did we get from all of the additional hassle? A runtime of 0.000267 seconds, which again marks a 3.01x increase(!) over the previous implementation. If we only look at the functions that used pre-computed vectors and indices, we decreased the runtime from 0.004472 to 0.000267 seconds, a 16.76x increase in speed. These values can change significantly as we increase the size of the vectors and the data. In total, we sped up the code over the baseline by a factor of 21,400, although it is a bit of a comparison of apples and oranges, due to the differences in pre-computation.
To test if everything is working correctly, we are now looking at two tasks:the STS sentence similarity benchmark [3] and predicting emotions on a sentence level [4]. You can find the scripts in the corresponding Jupyter notebook. Let’s use the pre-trained GoogleNews-vectors-negative300 vectors for the estimation of the sentence embeddings.
The reddit dataset for predicting emotions contains four classes: creepy, gore, happy, and rage. After some preprocessing we end up with 2,460 sentences and an equal balance of all four emotion classes.
As for timing: Computing the sentence embeddings using our 2nd variant developed earlier takes about 991 ms ± 19.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each). The final implementation that is contained in fse.models.Sentence2Vec completes the task in 25.9 ms ± 615 μs per loop (mean ± std. dev. of 7 runs, 10 loops each), a 38x speed increase and a fair comparison.
In terms of predicting emotions we are also able to accomplish the task pretty well. Note: Multinomial Logistic Regression, Train/Test split 50%.
Finally we approach the sentence similarity benchmark. The data is available here. We only look at the DEV set. The original paper reported a spearman correlation of 71.7, but they used Glove vectors. According to the other benchmarks, the implementation works as expected.
Sentence embeddings are an essential part of NLP pipelines. This blog post shows how to implement average and SIF-weighted CBOW embeddings, which can serve as a nice baseline for subsequent tasks. Due to their simplicity and modularity, we anticipate a broad variety of applications. The corresponding fse package is available on pip / Github and offers a fast way of computing sentence embeddings for data scientists.
For inquiries and questions, feel free to contact me.
The code for this post is available on Github and via pip:
pip install fse
Arora S, Liang Y, Ma T (2017) A Simple but Tough-to-Beat Baseline for Sentence Embeddings. Int. Conf. Learn. Represent. (Toulon, France), 1–16.Iyyer M, Manjunatha V, Boyd-Graber J, Daumé III H (2015) Deep Unordered Composition Rivals Syntactic Methods for Text Classification. Proc. 53rd Annu. Meet. Assoc. Comput. Linguist. 7th Int. Jt. Conf. Nat. Lang. Process., 1681–1691.Eneko Agirre, Daniel Cer, Mona Diab, Iñigo Lopez-Gazpio, Lucia Specia. Semeval-2017 Task 1: Semantic Textual Similarity Multilingual and Crosslingual Focused Evaluation. Proceedings of SemEval 2017.Duong, Chi Thang, Remi Lebret, and Karl Aberer. “Multimodal Classification for Analysing Social Media.” The 27th European Conference on Machine Learning and Principles and Practice of Knowledge Discovery in Databases (ECML-PKDD), 2017
Arora S, Liang Y, Ma T (2017) A Simple but Tough-to-Beat Baseline for Sentence Embeddings. Int. Conf. Learn. Represent. (Toulon, France), 1–16.
Iyyer M, Manjunatha V, Boyd-Graber J, Daumé III H (2015) Deep Unordered Composition Rivals Syntactic Methods for Text Classification. Proc. 53rd Annu. Meet. Assoc. Comput. Linguist. 7th Int. Jt. Conf. Nat. Lang. Process., 1681–1691.
Eneko Agirre, Daniel Cer, Mona Diab, Iñigo Lopez-Gazpio, Lucia Specia. Semeval-2017 Task 1: Semantic Textual Similarity Multilingual and Crosslingual Focused Evaluation. Proceedings of SemEval 2017.
Duong, Chi Thang, Remi Lebret, and Karl Aberer. “Multimodal Classification for Analysing Social Media.” The 27th European Conference on Machine Learning and Principles and Practice of Knowledge Discovery in Databases (ECML-PKDD), 2017
Opinions expressed are solely my own and do not express the views or opinions of my employer. The author assumes no responsibility or liability for any errors or omissions in the content of this site. The information contained in this site is provided on an “as is” basis with no guarantees of completeness, accuracy, usefulness or timeliness.
|
[
{
"code": null,
"e": 280,
"s": 172,
"text": "The fse code in this article is deprecated. Please make sure to use the updated code as outlined on Github."
},
{
"code": null,
"e": 607,
"s": 280,
"text": "When working with textual data in a machine learning pipeline, you may come across the need to compute sentence embeddings. Similar to regular word embeddings (like Word2Vec, GloVE, Elmo, Bert, or Fasttext), sentence embeddings embed a full sentence into a vector space. In practice, a sentence embedding might look like this:"
},
{
"code": null,
"e": 661,
"s": 607,
"text": "“I shot the sheriff” → [0.2 ; 0.1 ; -0.3 ; 0.9 ; ...]"
},
{
"code": null,
"e": 845,
"s": 661,
"text": "These sentence embeddings retain some nice properties, as they inherit features from their underlying word embeddings [1]. Thus, we might use sentence embeddings for varying purposes:"
},
{
"code": null,
"e": 913,
"s": 845,
"text": "Compute a similarity matrix of sentences based on their embeddings."
},
{
"code": null,
"e": 974,
"s": 913,
"text": "Plot sentences using a common mapping technique, like t-SNE."
},
{
"code": null,
"e": 1027,
"s": 974,
"text": "Predict some value for the sentence, i.e. sentiment."
},
{
"code": null,
"e": 1467,
"s": 1027,
"text": "A very simple supervised application of sentence embeddings can be seen in “deep averaging networks” [2], where the authors use sentence embeddings in sentiment analysis and question answering. In fact, sentence embeddings are a deceptively simple baseline to start from when you are working with textual data. Fortunately, they do not require any form of gradient based optimization if (pre-trained) word embeddings are already available."
},
{
"code": null,
"e": 2256,
"s": 1467,
"text": "This post is intended for a technical data-science audience. We are going to explore smooth inverse frequency (SIF) sentence embeddings [1]. Specifically, we are optimizing the computation of SIF embeddings by hand-crafting a function, which is specifically tailored to compute SIF embeddings as fast as possible. For this purpose we first use Python, then we migrate to Cython and finally to Basic Linear Algebra Subprograms (BLAS). Cython and BLAS are core ingredients used in Gensims Word2Vec implementation. I have to thank Radim Řehůřek, as Gensims implementation is the foundation of this post. For a similar post, feel free to read the original Word2Vec optimization blog. The following optimizations allow us to speed up the computation of SIF embeddings by a factor of 38 (!)."
},
{
"code": null,
"e": 2913,
"s": 2256,
"text": "Smooth inverse frequency embeddings were originally conceived by [1] and the corresponding paper has been presented at the 2017 ICLR. The code for the original paper is available at Github. The authors present a nice probabilistic motivation for the inverse frequency weighted continuous bag-of-words model. We are not going into the technical details of the math, but rather into the optimization of the algorithm for computing the SIF embeddings. If you have to compute the SIF embeddings for millions of sentences, you need a routine to accomplish the task in a lifetime. In this post, we are just looking for speed. And Gensim offers quite a lot of it."
},
{
"code": null,
"e": 3332,
"s": 2913,
"text": "Discerning the algorithm, we can infer that most work is to be done in line 1 & 2. While it might seem straightforward, there is plenty of room to optimize line 1 & 2 when you are working with Python. The task is as follows: Compute the SIF embeddings as fast as possible for all sentences in the brown corpus. We will rely on Gensims Word2Vec implementation to obtain word vectors and only use a little preprocessing."
},
{
"code": null,
"e": 3465,
"s": 3332,
"text": "The whole code for this project is available on Github. You can install the fast sentence embedding library which I wrote using pip:"
},
{
"code": null,
"e": 3481,
"s": 3465,
"text": "pip install fse"
},
{
"code": null,
"e": 3622,
"s": 3481,
"text": "You will need regular Python packages, specifically Numpy, Scipy, Cython, and Gensim. TL;DR: If you need sentence embeddings fast, just use:"
},
{
"code": null,
"e": 3851,
"s": 3622,
"text": "from gensim.models import Word2Vecsentences = [[“cat”, “say”, “meow”], [“dog”, “say”, “woof”]]model = Word2Vec(sentences, min_count=1)from fse.models import Sentence2Vecse = Sentence2Vec(model)sentences_emb = se.train(sentences)"
},
{
"code": null,
"e": 3979,
"s": 3851,
"text": "In order to optimize the SIF function, we first need a prototype that is working correctly. Let’s have a look at the prototpye:"
},
{
"code": null,
"e": 4470,
"s": 3979,
"text": "The code should be pretty self-explanatory. We first define the variable vlookup, which points us to gensims vocab class. Hereby we can access a words index and count. Vectors points us to the gensim wv class, which contains the word vectors themselves. Then we iterate over all sentences. For each sentence, we sum the vectors of all the words in the sentence up, while multiplying them with their SIF weight. Finally, we divide the vector by the length of the sentence. Nothing too fancy."
},
{
"code": null,
"e": 4732,
"s": 4470,
"text": "We need an embedding to measure the execution time of this function. Let us use a 100 dimensional Word2Vec embedding, that was trained on the commonly available Brown corpus. Then we use the first 400 sentences of the corpus and time the function. 5.70 seconds."
},
{
"code": null,
"e": 5029,
"s": 4732,
"text": "That is way to slow. The keen eye will have already noticed the pitfall: I’ve been using a for-loop in the vector addition. That is precisely the reason to not use python for-loops in such a scenario. They are way too slow. To circumvent this, let us rewrite line 37–40 to use the numpy routines."
},
{
"code": null,
"e": 5493,
"s": 5029,
"text": "The results is astonishing: 0.041434 seconds. That is 137x faster than the baseline version. However, we can still do better. Much better. As you might have noticed, vectors[w] acts as a lookup table for the word-vectors. If we pre-compute the word indices of the sentence, we can directly use numpy indexing to access all vectors at once, which is much faster. In the same step, we have to pre-compute the SIF weights for the vectors to access them via indexing."
},
{
"code": null,
"e": 5622,
"s": 5493,
"text": "With a runtime of 0.011987 seconds, these small additions cause the function to be 476x faster than the baseline we established."
},
{
"code": null,
"e": 5901,
"s": 5622,
"text": "To further speed up the implementation, we might actually pre-compute all the weighted vectors, as the weights and word vectors themselves do not change. Thereby, we decrease the runtime to 0.008674 seconds, marking a 658x increase over the baseline. But wait. There is a catch:"
},
{
"code": null,
"e": 6380,
"s": 5901,
"text": "By pre-computing the SIF vectors, we might have to compute a fairly large matrix, which is not time-efficient if we only have a few sentences and a large vocabulary. Nor is it space-efficient, as we have to store a separate weighted embedding matrix in RAM. Thus, we are running into a tradeoff between memory and time efficency. Pre-computing the weighted vectors does only make sense if the effective number of words in our sentences to train on is larger than the vocabulary."
},
{
"code": null,
"e": 6525,
"s": 6380,
"text": "I will spoil a little bit by stating that this is not necessary due to the BLAS function we are going to use later, but keep it in mind for now."
},
{
"code": null,
"e": 6892,
"s": 6525,
"text": "We have already obtained quite some considerable speedups. The next thing we want to optimize is the summation of the vectors, where we can still obtain a significant speedup. However, to better benchmark the results, we are taking the conversion of the sentences to indices out of the equation. We thus pre-compute all sentence-indices for the following benchmarks:"
},
{
"code": null,
"e": 7021,
"s": 6892,
"text": "sentences_idx = [np.asarray([int(model.wv.vocab[w].index) for w in s if w in model.wv.vocab], dtype=np.intc) for s in sentences]"
},
{
"code": null,
"e": 7220,
"s": 7021,
"text": "You will immediately realize that this is a pretty bad idea in practice, as we now essentially have to store a second dataset. However, it serves our benchmarking purposes quite well for the moment."
},
{
"code": null,
"e": 7517,
"s": 7220,
"text": "With 0.004472 seconds the new function — using pre-computed weighted vectors and sentence indices — clocks in at 1276x the speed of the baseline implementation. However, the comparison is a bit off, as the baseline did not use pre-computed indices. Thus, this is our new benchmark for the moment."
},
{
"code": null,
"e": 7699,
"s": 7517,
"text": "The next step is to migrate to Cython. Note that we are still working with pre-computed indices and weighted vectors. We wrap everything into a nice Cython file and then compile it."
},
{
"code": null,
"e": 7901,
"s": 7699,
"text": "The cdef float[:,:] command gives us access to the memory view of the pre-computed vectors. For a more detailed explanation, the Cython website provides a neat tutorial on memory views. Remember to use"
},
{
"code": null,
"e": 7955,
"s": 7901,
"text": "# cython: boundscheck=False# cython: wraparound=False"
},
{
"code": null,
"e": 8395,
"s": 7955,
"text": "at the beginning of the file. These two commands remove the safety nets, which might possibly slow us down. The former checks whether we are running out of bounds of the array, whilst the latter allows us to perform negative indexing (which we are not going to use). We are now running 2.42x faster than the previous pure numpy implementation, which also relied on pre-computed indices for the sentences. Thus the comparison is fair again."
},
{
"code": null,
"e": 8808,
"s": 8395,
"text": "Note that we have pre-defined all of the necessary structures as C variables that we can use in a pure C-loop without any Pythonic interference. Thereby, we can also release the global interpreter lock (GIL), which might come in handy at some future point in time, when we are thinking about a multi-threaded implementation of fse. We essentially rewrite the part of the code used to sum all words in a sentence:"
},
{
"code": null,
"e": 8939,
"s": 8808,
"text": "Thereby, we decrease the runtime to 0.000805 seconds, which marks another 2.28 fold increase over the first Cython implementation."
},
{
"code": null,
"e": 9236,
"s": 8939,
"text": "Finally, we are going for BLAS. The Basic Linear Algebra Subprograms describe low-level linear algebra routines. They are categorized in three levels: Level 1: vector ops, Level 2: vector-matrix ops, Level 3: matrix-matrix ops. We only need access to Level 1 for our purposes. Precisely, we need:"
},
{
"code": null,
"e": 9290,
"s": 9236,
"text": "SAXPY: (Single) constant times a vector plus a vector"
},
{
"code": null,
"e": 9336,
"s": 9290,
"text": "SSCAL: (Single) scales a vector by a constant"
},
{
"code": null,
"e": 9452,
"s": 9336,
"text": "Gensims core classes make heavy use of these highly optimized routines to speed up Word2Vec, Doc2Vec, and Fasttext."
},
{
"code": null,
"e": 9748,
"s": 9452,
"text": "Now recall what we wrote about pre-computing the SIF weighted vectors earlier. The SAXPY function takes the argument a, which is used in y = a*x + y. Thus, we have to do the weight*vector multiplication anyways. Therefore, pre-computing the SIF vectors is actually an inefficient idea after all."
},
{
"code": null,
"e": 9878,
"s": 9748,
"text": "Additionally, we are dropping Cython memory view for direct unsafe access to the numpy variables via pointers & memory addresses."
},
{
"code": null,
"e": 9999,
"s": 9878,
"text": "We have to define the sscal and saxpy pointers elsewhere, which is spared in the code snippet (usually in a *.pxd file)."
},
{
"code": null,
"e": 10583,
"s": 9999,
"text": "What did we get from all of the additional hassle? A runtime of 0.000267 seconds, which again marks a 3.01x increase(!) over the previous implementation. If we only look at the functions that used pre-computed vectors and indices, we decreased the runtime from 0.004472 to 0.000267 seconds, a 16.76x increase in speed. These values can change significantly as we increase the size of the vectors and the data. In total, we sped up the code over the baseline by a factor of 21,400, although it is a bit of a comparison of apples and oranges, due to the differences in pre-computation."
},
{
"code": null,
"e": 10926,
"s": 10583,
"text": "To test if everything is working correctly, we are now looking at two tasks:the STS sentence similarity benchmark [3] and predicting emotions on a sentence level [4]. You can find the scripts in the corresponding Jupyter notebook. Let’s use the pre-trained GoogleNews-vectors-negative300 vectors for the estimation of the sentence embeddings."
},
{
"code": null,
"e": 11129,
"s": 10926,
"text": "The reddit dataset for predicting emotions contains four classes: creepy, gore, happy, and rage. After some preprocessing we end up with 2,460 sentences and an equal balance of all four emotion classes."
},
{
"code": null,
"e": 11506,
"s": 11129,
"text": "As for timing: Computing the sentence embeddings using our 2nd variant developed earlier takes about 991 ms ± 19.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each). The final implementation that is contained in fse.models.Sentence2Vec completes the task in 25.9 ms ± 615 μs per loop (mean ± std. dev. of 7 runs, 10 loops each), a 38x speed increase and a fair comparison."
},
{
"code": null,
"e": 11652,
"s": 11506,
"text": "In terms of predicting emotions we are also able to accomplish the task pretty well. Note: Multinomial Logistic Regression, Train/Test split 50%."
},
{
"code": null,
"e": 11926,
"s": 11652,
"text": "Finally we approach the sentence similarity benchmark. The data is available here. We only look at the DEV set. The original paper reported a spearman correlation of 71.7, but they used Glove vectors. According to the other benchmarks, the implementation works as expected."
},
{
"code": null,
"e": 12345,
"s": 11926,
"text": "Sentence embeddings are an essential part of NLP pipelines. This blog post shows how to implement average and SIF-weighted CBOW embeddings, which can serve as a nice baseline for subsequent tasks. Due to their simplicity and modularity, we anticipate a broad variety of applications. The corresponding fse package is available on pip / Github and offers a fast way of computing sentence embeddings for data scientists."
},
{
"code": null,
"e": 12399,
"s": 12345,
"text": "For inquiries and questions, feel free to contact me."
},
{
"code": null,
"e": 12458,
"s": 12399,
"text": "The code for this post is available on Github and via pip:"
},
{
"code": null,
"e": 12474,
"s": 12458,
"text": "pip install fse"
},
{
"code": null,
"e": 13284,
"s": 12474,
"text": "Arora S, Liang Y, Ma T (2017) A Simple but Tough-to-Beat Baseline for Sentence Embeddings. Int. Conf. Learn. Represent. (Toulon, France), 1–16.Iyyer M, Manjunatha V, Boyd-Graber J, Daumé III H (2015) Deep Unordered Composition Rivals Syntactic Methods for Text Classification. Proc. 53rd Annu. Meet. Assoc. Comput. Linguist. 7th Int. Jt. Conf. Nat. Lang. Process., 1681–1691.Eneko Agirre, Daniel Cer, Mona Diab, Iñigo Lopez-Gazpio, Lucia Specia. Semeval-2017 Task 1: Semantic Textual Similarity Multilingual and Crosslingual Focused Evaluation. Proceedings of SemEval 2017.Duong, Chi Thang, Remi Lebret, and Karl Aberer. “Multimodal Classification for Analysing Social Media.” The 27th European Conference on Machine Learning and Principles and Practice of Knowledge Discovery in Databases (ECML-PKDD), 2017"
},
{
"code": null,
"e": 13428,
"s": 13284,
"text": "Arora S, Liang Y, Ma T (2017) A Simple but Tough-to-Beat Baseline for Sentence Embeddings. Int. Conf. Learn. Represent. (Toulon, France), 1–16."
},
{
"code": null,
"e": 13662,
"s": 13428,
"text": "Iyyer M, Manjunatha V, Boyd-Graber J, Daumé III H (2015) Deep Unordered Composition Rivals Syntactic Methods for Text Classification. Proc. 53rd Annu. Meet. Assoc. Comput. Linguist. 7th Int. Jt. Conf. Nat. Lang. Process., 1681–1691."
},
{
"code": null,
"e": 13862,
"s": 13662,
"text": "Eneko Agirre, Daniel Cer, Mona Diab, Iñigo Lopez-Gazpio, Lucia Specia. Semeval-2017 Task 1: Semantic Textual Similarity Multilingual and Crosslingual Focused Evaluation. Proceedings of SemEval 2017."
},
{
"code": null,
"e": 14097,
"s": 13862,
"text": "Duong, Chi Thang, Remi Lebret, and Karl Aberer. “Multimodal Classification for Analysing Social Media.” The 27th European Conference on Machine Learning and Principles and Practice of Knowledge Discovery in Databases (ECML-PKDD), 2017"
}
] |
Multiclass classification Neural Network implementation using Numpy’s einsum | by ManiShankar Singh | Towards Data Science
|
We all start our machine learning journey by implementing a small classification or regression problem. Today I will implement a multiclass classification neural network using pure numpy. I will use the iris dataset. Below is the link to my code on colab notebook.
MulticlassClassificationNeuralNetwork
I will be creating a 2 layer neural network. First hidden layer will use leaky_relu activation function and second hidden layer will use softmax activation function.
Softmax function gives back probability of belonging to each class.
Derivative of softmax is a bit hairy to implement as it involves creating a Jacobian matrix. For all practical purposes, softmax will always be used in the outermost layer of neural network for multiclass classification and hence calculating its derivative is not important as long as we can get the derivative of cost function J with respect to logits z. Calculating this derivative is quite simple as compared to calculating the derivative of softmax function itself. I have shown the derivative in the image below:
If you are still persistent to get the derivative of softmax, its implementation is written in softmax_prime function shown in the picture below.
Pay special attention to softmax and binarize functions as shown above.
Now lets understand binarize function. It converts the labels 0,1,2,etc. into one hot encoded arrays like:
+=======+===========+| Label | Binarize |+=======+===========+| 0 | [1,0,0,0] |+ — — — -+ — — — — — -+| 1 | [0,1,0,0] |+ — — — -+ — — — — — -+| 2 | [0,0,1,0] |+ — — — -+ — — — — — -+| 3 | [0,0,0,1] |+ — — — -+ — — — — — -+
This is important because in multiclass classification the target will belong to one of the multiple classes present in data. Also the final softmax layer will return the probability of a record belonging to each of those class labels. So it is important to convert the class labels into one hot encoded record. In the implementation, binarize function is written in a clever way to utilize broadcasting concept of numpy.
I have used the dreaded and notorious as_strided function of numpy in the beginning to create a sliding window view of the array containing number of units in each layer. It is riskier to use this function because it does not check the boundaries of a given array while creating the view, which can easily lead to buffer overflow. Even though it is riskier to use, I have used it because why not. In deft hands it is like a swiss army knife. I wish tensorflow had something equivalent like as_strided function.
def murals_batch(units_count, x, y, lr, epochs, bias=False, _seed=42): batch_size, ni = x.shape[-2:] units_count.insert(0,ni) units_count_arr = np.array(units_count) L, = units_count_arr.shape # Number of layers + 1 # RED ALERT - `as_strided` function is like a LAND-MINE ready to explode in wrong hands! arr_view = as_strided(units_count_arr, shape=(L-1,2), strides=(4,4))# print(arr_view) rng = np.random.default_rng(seed=_seed) wghts = [None]*(L-1) intercepts = [None]*(L-1) # WEIGHTS INITIALIZATION for i in range(L-1): w_cols, w_rows = arr_view[i,:] wghts[i] = rng.random((w_rows, w_cols)) if bias: intercepts[i] = rng.random((w_rows,)) costs = np.zeros(epochs) # Gradient Descent for epoch in range(epochs): # FORWARD PROPAGATION # hidden layer 1 implementation, relu activation h1a = np.einsum('hi,Bi -> Bh', wghts[0], x) if bias: h1a = h1a + intercepts[0] h1 = relu(h1a) # hidden layer 2 implementation, softmax activation h2a = np.einsum('ho,Bo -> Bh', wghts[1], h1) if bias: h2a = h2a + intercepts[1] hyp = softmax(h2a, _axis=1) current_epoch_cost = -np.einsum('Bi,Bi', y, np.log(hyp))/batch_size# print(current_epoch_cost) costs[epoch] = current_epoch_cost # BACKWARD PROPAGATION # layer 2 dJ_dH2a = hyp - y dJ_dW1 = np.einsum('Bi,Bj -> ij',dJ_dH2a, h1)/batch_size # layer 1 dJ_dH1 = np.einsum('Bi,ij -> Bj', dJ_dH2a, wghts[1]) dJ_dH1a = dJ_dH1*relu_prime(h1a) dJ_dW0 = np.einsum('Bi,Bj -> ij',dJ_dH1a, x)/batch_size if bias: dJ_dB1 = np.einsum("Bi -> i", dJ_dH2a)/batch_size dJ_dB0 = np.einsum("Bi -> i",dJ_dH1a)/batch_size # WEIGHTS ADJUSTMENT wghts[1] = wghts[1] - lr*dJ_dW1 wghts[0] = wghts[0] - lr*dJ_dW0 if bias: intercepts[1] = intercepts[1] - lr*dJ_dB1 intercepts[0] = intercepts[0] - lr*dJ_dB0 if bias: return (costs, wghts, intercepts) else: return (costs, wghts)iris = load_iris()x = iris.datay = iris.target# NORMALIZEx_norm = normalize(x)x_train, x_test, y_train, y_test = train_test_split(x_norm, y, test_size=0.33, shuffle=True, random_state=42)# BINARIZEy_train = binarize(y_train)y_test = binarize(y_test)unit_per_layer_counts = [10,3]costs, fw, fb = murals_batch(unit_per_layer_counts, x_train, y_train, lr=0.01, epochs=19000, bias=True)plt.plot(costs)def predict(x,fw,fb): h1a = np.einsum(’hi,Bi -> Bh’, fw[0], x)+fb[0] h1 = relu(h1a) h2a = np.einsum(’ho,Bo-> Bh’,fw[1],h1)+fb[1] return softmax(h2a)
Also look at the fabulous time taken by the efficient code to execute 19000 epochs!!!
This efficiency is due to numpy’s Einstein summation function used to implement the neural network. I have discussed it in some details in my previous blog https://manishankar.medium.com/batch-gradient-descent-algorithm-using-numpy-einsum-f442ef798ee2
Please let me know your views about this blog post and code implementation with your comments.
I am a machine learning engineer at TCS and my (Digital Software & Solutions) team is building amazing products. Check out more about our products in the link below:
|
[
{
"code": null,
"e": 436,
"s": 171,
"text": "We all start our machine learning journey by implementing a small classification or regression problem. Today I will implement a multiclass classification neural network using pure numpy. I will use the iris dataset. Below is the link to my code on colab notebook."
},
{
"code": null,
"e": 474,
"s": 436,
"text": "MulticlassClassificationNeuralNetwork"
},
{
"code": null,
"e": 640,
"s": 474,
"text": "I will be creating a 2 layer neural network. First hidden layer will use leaky_relu activation function and second hidden layer will use softmax activation function."
},
{
"code": null,
"e": 708,
"s": 640,
"text": "Softmax function gives back probability of belonging to each class."
},
{
"code": null,
"e": 1226,
"s": 708,
"text": "Derivative of softmax is a bit hairy to implement as it involves creating a Jacobian matrix. For all practical purposes, softmax will always be used in the outermost layer of neural network for multiclass classification and hence calculating its derivative is not important as long as we can get the derivative of cost function J with respect to logits z. Calculating this derivative is quite simple as compared to calculating the derivative of softmax function itself. I have shown the derivative in the image below:"
},
{
"code": null,
"e": 1372,
"s": 1226,
"text": "If you are still persistent to get the derivative of softmax, its implementation is written in softmax_prime function shown in the picture below."
},
{
"code": null,
"e": 1444,
"s": 1372,
"text": "Pay special attention to softmax and binarize functions as shown above."
},
{
"code": null,
"e": 1551,
"s": 1444,
"text": "Now lets understand binarize function. It converts the labels 0,1,2,etc. into one hot encoded arrays like:"
},
{
"code": null,
"e": 1794,
"s": 1551,
"text": "+=======+===========+| Label | Binarize |+=======+===========+| 0 | [1,0,0,0] |+ — — — -+ — — — — — -+| 1 | [0,1,0,0] |+ — — — -+ — — — — — -+| 2 | [0,0,1,0] |+ — — — -+ — — — — — -+| 3 | [0,0,0,1] |+ — — — -+ — — — — — -+"
},
{
"code": null,
"e": 2216,
"s": 1794,
"text": "This is important because in multiclass classification the target will belong to one of the multiple classes present in data. Also the final softmax layer will return the probability of a record belonging to each of those class labels. So it is important to convert the class labels into one hot encoded record. In the implementation, binarize function is written in a clever way to utilize broadcasting concept of numpy."
},
{
"code": null,
"e": 2727,
"s": 2216,
"text": "I have used the dreaded and notorious as_strided function of numpy in the beginning to create a sliding window view of the array containing number of units in each layer. It is riskier to use this function because it does not check the boundaries of a given array while creating the view, which can easily lead to buffer overflow. Even though it is riskier to use, I have used it because why not. In deft hands it is like a swiss army knife. I wish tensorflow had something equivalent like as_strided function."
},
{
"code": null,
"e": 5413,
"s": 2727,
"text": "def murals_batch(units_count, x, y, lr, epochs, bias=False, _seed=42): batch_size, ni = x.shape[-2:] units_count.insert(0,ni) units_count_arr = np.array(units_count) L, = units_count_arr.shape # Number of layers + 1 # RED ALERT - `as_strided` function is like a LAND-MINE ready to explode in wrong hands! arr_view = as_strided(units_count_arr, shape=(L-1,2), strides=(4,4))# print(arr_view) rng = np.random.default_rng(seed=_seed) wghts = [None]*(L-1) intercepts = [None]*(L-1) # WEIGHTS INITIALIZATION for i in range(L-1): w_cols, w_rows = arr_view[i,:] wghts[i] = rng.random((w_rows, w_cols)) if bias: intercepts[i] = rng.random((w_rows,)) costs = np.zeros(epochs) # Gradient Descent for epoch in range(epochs): # FORWARD PROPAGATION # hidden layer 1 implementation, relu activation h1a = np.einsum('hi,Bi -> Bh', wghts[0], x) if bias: h1a = h1a + intercepts[0] h1 = relu(h1a) # hidden layer 2 implementation, softmax activation h2a = np.einsum('ho,Bo -> Bh', wghts[1], h1) if bias: h2a = h2a + intercepts[1] hyp = softmax(h2a, _axis=1) current_epoch_cost = -np.einsum('Bi,Bi', y, np.log(hyp))/batch_size# print(current_epoch_cost) costs[epoch] = current_epoch_cost # BACKWARD PROPAGATION # layer 2 dJ_dH2a = hyp - y dJ_dW1 = np.einsum('Bi,Bj -> ij',dJ_dH2a, h1)/batch_size # layer 1 dJ_dH1 = np.einsum('Bi,ij -> Bj', dJ_dH2a, wghts[1]) dJ_dH1a = dJ_dH1*relu_prime(h1a) dJ_dW0 = np.einsum('Bi,Bj -> ij',dJ_dH1a, x)/batch_size if bias: dJ_dB1 = np.einsum(\"Bi -> i\", dJ_dH2a)/batch_size dJ_dB0 = np.einsum(\"Bi -> i\",dJ_dH1a)/batch_size # WEIGHTS ADJUSTMENT wghts[1] = wghts[1] - lr*dJ_dW1 wghts[0] = wghts[0] - lr*dJ_dW0 if bias: intercepts[1] = intercepts[1] - lr*dJ_dB1 intercepts[0] = intercepts[0] - lr*dJ_dB0 if bias: return (costs, wghts, intercepts) else: return (costs, wghts)iris = load_iris()x = iris.datay = iris.target# NORMALIZEx_norm = normalize(x)x_train, x_test, y_train, y_test = train_test_split(x_norm, y, test_size=0.33, shuffle=True, random_state=42)# BINARIZEy_train = binarize(y_train)y_test = binarize(y_test)unit_per_layer_counts = [10,3]costs, fw, fb = murals_batch(unit_per_layer_counts, x_train, y_train, lr=0.01, epochs=19000, bias=True)plt.plot(costs)def predict(x,fw,fb): h1a = np.einsum(’hi,Bi -> Bh’, fw[0], x)+fb[0] h1 = relu(h1a) h2a = np.einsum(’ho,Bo-> Bh’,fw[1],h1)+fb[1] return softmax(h2a)"
},
{
"code": null,
"e": 5499,
"s": 5413,
"text": "Also look at the fabulous time taken by the efficient code to execute 19000 epochs!!!"
},
{
"code": null,
"e": 5751,
"s": 5499,
"text": "This efficiency is due to numpy’s Einstein summation function used to implement the neural network. I have discussed it in some details in my previous blog https://manishankar.medium.com/batch-gradient-descent-algorithm-using-numpy-einsum-f442ef798ee2"
},
{
"code": null,
"e": 5846,
"s": 5751,
"text": "Please let me know your views about this blog post and code implementation with your comments."
}
] |
Combining Two Optimizers for a Powerful Method to Train Your Model | by Albers Uzila | Towards Data Science
|
Table of Contents (read till the end to see how you can get the complete python code of this story)· Seeing the Big Picture· Defining The Problem· A Hybrid Method ∘ Objective Function ∘ General Algorithm ∘ Levenberg-Marquardt Step ∘ Quasi-Newton Step· Implementation· Conclusion
In previous articles, we’ve seen Gradient Descent and Conjugate Gradient algorithm in action, as two of the simplest optimization method there is. We implemented line search for searching the direction to which the objective function is optimized.
There is another way to generate steps called trust-region. Trust-region methods define a region around the current iterate within which they trust the model to be an adequate representation of the objective function, and then choose the step to be the approximate minimizer of the model in this region. In effect, unlike line search, they choose the direction and length of the step simultaneously.
There is also a whole lot of other optimization methods such as Newton’s method and Quasi-Newton methods. In this article, we will use a hybrid of the Levenberg-Marquardt and Quasi-Newton method, utilizing trust-region for the step choice. Furthermore, this article brings a different problem. Instead of finding an optimizer of an objective function, we will be given a dataset and a non-linear model of the data, and then find the best optimized parameters of the model. Optimized parameters are defined by those who give the least squares of residuals. Some people might call this a curve-fitting problem.
Let’s import some libraries.
Create a fictional dataset as follows. It has 11 observations and 2 features with the first feature acting like an index of the second.
t y------------------[[ 0.0000 0.0000] [ 2.0000 3.5500] [ 4.0000 3.8200] [ 6.0000 2.9800] [ 8.0000 2.3200] [10.0000 1.4800] [12.0000 1.0200] [14.0000 0.8100] [16.0000 0.4100] [18.0000 0.4200] [20.0000 0.1500]]Data shape: (11, 2)
Visualize the data as points (t, y) = (ti, yi) with i = 1, 2, ..., 11 in the cartesius plane.
We immediately realize that the data has no linear trend (the point (0,0) here is not an outlier). Hence, the model that we use is also non-linear. Instead, we will use a linear combination of two exponential functions, which by definition is declared as
As mentioned before, parameters x = [x1, x2, x3, x4] will be estimated using a hybrid method of Levenberg-Marquardt (LM) dan Quasi-Newton (QN).
In general, we want to build a model M(x, t) for a collection of m data points (ti, yi). To do that, a concrete definition of the objective function is necessary. For a least-squares problem, this objective function is the sum of squares of the residual of each data point. A data point’s residual is defined by how far the actual data to the model prediction is, that is, by subtracting the actual data point by the model prediction of that point. Mathematically speaking, the residual for the i-th data point is
or in the vector form
Since the objective function is the sum of squares of the residual of each data point, it can be written as
The coefficient 1⁄2 above is attached for convenience in derivating F.
Let ǁ⋅ǁ be a symbol for the maximum norm of a vector. Our mission is to find x which minimizes F. To do that, we will find x at which ǁg(x)ǁ ≈ 0 where g = F’ is the first derivative of F. Derivating
w.r.t. each xj using the chain rule, we obtain
Define the Jacobian matrix
the value of g can then be calculated as
For the python function below, besides returning g, it also returns J, which will come in handy later.
Let x* be the minimizer of the sum of squared residuals. The least-squares problem can be solved by general optimization methods, but we shall present special methods that are more efficient. In 1988, Madsen [1] presented a hybrid method that combines the LM method (quadratic convergence if F(x*) = 0, linear convergence otherwise) with a QN method, which gives superlinear convergence, even if F(x*) ≠ 0.
In the trust region method, the algorithm generates a trust model L of the behavior of F in the neighborhood of the current iterate x,
where h is the step to be taken. We assume that we know a positive number Δ such that the model is sufficiently accurate inside a ball with radius Δ, centered at x, and the algorithm determines the step as
In a damped version, the step is determined as
where the damping parameter μ ≥ 0. The term
is introduced to penalize large steps.
From now on, we will begin iterating. Hence, we will introduce an index k which means the variable in question is for the k-th iteration. For example, xk is the value of x at k-th iteration, and so Fk = F(xk), gk = g(xk), Jk = J(xk), and so on.
Before the iteration begins, it’s important to initialize the damping parameter μ = μ0 and Hessian approximation B0 (Hessian at iterate x is defined by F’’(x) and its approximation B is used by the QN method).
A reasonable choice for B0 is a symmetric, positive definite matrix I, that is, the identity matrix. The choice of μ0 should be related to the size of the elements in
e.g. by letting
where aii0 is the i-th diagonal component of A0, and τ is chosen by the user. In this article, we will set τ = 1 × 10−3.
For the python function below, besides returning μ0, it also returns A0, which will come in handy later.
After initializing μ0 and B0, the iteration starts with a series of steps with the LM method. If the performance indicates that F(x*) is significantly nonzero, then we switch to the QN method for better performance. We may get an indication that it is better to switch back to the LM method, so there is also a mechanism for that which will be covered later. The iteration keeps going until one of the following stopping criteria is satisfied:
The norm of the gradient of the objective function is close enough to zero, that is,
The norm of the step satisfies
The number of steps taken is 1000
In this article, ε1 and ε2 will be set 1 × 10−5.
After each step, whether it’s through the LM or QN method, Bk is updated by first defining
If
then update Bk by
where vk = Bkhk. Otherwise, Bk stays the same, that is, Bk+1 = Bk.
The new xk+1 = xk + hk found by the LM or QN method is then passed to the next iteration. This whole process could be written as the code below.
Now, let’s go into the detail of each step. What’s going on in the LMstep() and QNstep() functions above?
At the beginning of hybrid iterations, the LM method is used first. At k-th iteration, step hk is found by solving
and then calculate
where Fk+1 is just F(xk + hk).
We then consider two cases:
If ρ > 0, this means the iteration is a success and we can update xk+1 = xk + hk. At this point, we need to check whether F(x*) is far from zero, that is, by checking: if ǁgkǁ < 0.02 ⋅ Fk for three consecutive successful iterations, then we will change to the QN method for the next iteration. Also, update
If ρ > 0, this means the iteration is a success and we can update xk+1 = xk + hk. At this point, we need to check whether F(x*) is far from zero, that is, by checking: if ǁgkǁ < 0.02 ⋅ Fk for three consecutive successful iterations, then we will change to the QN method for the next iteration. Also, update
2. If ρ ≤ 0, then the iteration does not succeed and we won’t update xk, that is, xk+1 = xk. For this case, update μk+1 = μkν and ν := 2ν.
The update method of μ mentioned above is developed by Nielsen. We also have another variation by Marquardt as can be observed below.
The overall LM step can be seen as follows. Note that in the code below, we are passing Δk, which is the trust-region radius that will be used by the QN step in case we change the step calculation method to QN in future iterations. We don’t use Δk here.
Since the QN method uses trust-region for step calculation, at the beginning when we move to the QN method, it’s important to initialize the trust-region radius
where hlm is the step acquired by the previous LM step. But don’t worry, this initialization part is not needed since we always calculate Δk in both LM and QN steps. As you can see, the last formula above is already embedded in the LMstep() function line 14.
At k-th iteration, step hk is found by solving
If ǁhkǁ > Δk, then reduce the length of hk to be Δk, that is, by setting
Δk is then updated under several conditions of ρ, which is calculated using the same formula as that we use at LM step:
If ρ < 0.25, then set Δk+1 = Δk / 2
If ρ > 0.75, then set Δk+1 = max{Δk, 3 ǁhkǁ}
Otherwise, Δk+1 = Δk
Next, we consider two cases:
If Fk+1 ≤ (1 + δ) Fk and ǁgk+1ǁ < ǁgkǁ, or Fk+1 < Fk, then the iteration succeed and we can update xk+1 = xk + hk. At this point, we focus on getting g closer to zero, so we accept a slight increase in the value of F, e.g. as little as δ = √ε times the previous F, where ε is the machine epsilon.Otherwise, the iteration is considered a failure, and xk won’t be updated, that is, xk+1 = xk.
If Fk+1 ≤ (1 + δ) Fk and ǁgk+1ǁ < ǁgkǁ, or Fk+1 < Fk, then the iteration succeed and we can update xk+1 = xk + hk. At this point, we focus on getting g closer to zero, so we accept a slight increase in the value of F, e.g. as little as δ = √ε times the previous F, where ε is the machine epsilon.
Otherwise, the iteration is considered a failure, and xk won’t be updated, that is, xk+1 = xk.
If the gradient does not decrease fast enough, that is, ǁgk+1ǁ ≥ ǁgkǁ, then we move to the LM step for the next iteration.
The overall QN step can be seen as follows. Note that in the code below, we calculate ρ as we do in the LM step.
We are now ready to apply our knowledge to the problem defined at the beginning of this article. We will vary the initial point in three different scenarios:
x0 = [-1, 1, -10, 10]
x0 = [-4, 1, 2, -3]
x0 = [0, 0, 0, 0]
But first, let’s introduce a python function MakeAnimation() to animate the learning process of the algorithm.
Iteration:1 x = [-1.0000 0.9500 -10.0000 9.9997], gradient = 64932772695986634752.0000, step = LMIteration:2 x = [-1.0000 0.9001 -10.0000 9.9994], gradient = 8871075343566318592.0000, step = LMIteration:3 x = [-1.0000 0.8510 -10.0000 9.9992], gradient = 1250145055141384192.0000, step = LMIteration:4 x = [-1.0000 0.8050 -10.0000 9.9990], gradient = 199964648437467488.0000, step = LMIteration:5 x = [-1.0000 0.7686 -10.0000 9.9988], gradient = 46950703393293552.0000, step = LMIteration:6 x = [-1.0000 0.7454 -10.0000 9.9987], gradient = 18613190948807260.0000, step = LMIteration:7 x = [-1.0000 0.7283 -10.0000 9.9986], gradient = 9421138350386658.0000, step = LMIteration:8 x = [-1.0000 0.7127 -10.0000 9.9985], gradient = 5067642599353893.0000, step = LMIteration:9 x = [-1.0000 0.6974 -10.0000 9.9984], gradient = 2761173975265880.5000, step = LMIteration:10 x = [-1.0000 0.6822 -10.0000 9.9983], gradient = 1508437660486741.0000, step = LMIteration:11 x = [-1.0000 0.6670 -10.0000 9.9983], gradient = 824513384402736.2500, step = LMIteration:12 x = [-1.0000 0.6518 -10.0000 9.9982], gradient = 450734053994430.5000, step = LMIteration:13 x = [-1.0000 0.6366 -10.0000 9.9981], gradient = 246409971021028.8438, step = LMIteration:14 x = [-1.0000 0.6214 -10.0000 9.9980], gradient = 134711382454059.4531, step = LMIteration:15 x = [-1.0000 0.6062 -10.0000 9.9980], gradient = 73647395414745.6094, step = LMIteration:16 x = [-1.0000 0.5909 -10.0000 9.9979], gradient = 40264084923738.5469, step = LMIteration:17 x = [-1.0000 0.5757 -10.0000 9.9978], gradient = 22013352246245.9766, step = LMIteration:18 x = [-1.0000 0.5605 -10.0000 9.9977], gradient = 12035471978657.0332, step = LMIteration:19 x = [-1.0000 0.5452 -10.0000 9.9976], gradient = 6580356674017.7891, step = LMIteration:20 x = [-1.0000 0.5299 -10.0000 9.9976], gradient = 3597874150520.1475, step = LMIteration:21 x = [-1.0000 0.5146 -10.0000 9.9975], gradient = 1967223429070.2634, step = LMIteration:22 x = [-1.0000 0.4993 -10.0000 9.9974], gradient = 1075656653534.5968, step = LMIteration:23 x = [-1.0000 0.4840 -10.0000 9.9973], gradient = 588175745878.2034, step = LMIteration:24 x = [-1.0000 0.4687 -10.0000 9.9973], gradient = 321629128815.2425, step = LMIteration:25 x = [-1.0000 0.4534 -10.0000 9.9972], gradient = 175881428072.9430, step = LMIteration:26 x = [-1.0000 0.4380 -10.0000 9.9971], gradient = 96183963098.1861, step = LMIteration:27 x = [-1.0000 0.4226 -10.0000 9.9970], gradient = 52602379508.8333, step = LMIteration:28 x = [-1.0000 0.4072 -10.0000 9.9969], gradient = 28769372395.6593, step = LMIteration:29 x = [-1.0000 0.3918 -10.0000 9.9969], gradient = 15735488020.7650, step = LMIteration:30 x = [-1.0000 0.3763 -10.0000 9.9968], gradient = 8607119032.2862, step = LMIteration:31 x = [-1.0000 0.3609 -10.0000 9.9967], gradient = 4708326165.4597, step = LMIteration:32 x = [-1.0000 0.3454 -10.0000 9.9966], gradient = 2575789155.9012, step = LMIteration:33 x = [-1.0000 0.3298 -10.0000 9.9965], gradient = 1409268155.2911, step = LMIteration:34 x = [-1.0000 0.3142 -10.0000 9.9965], gradient = 771119669.0625, step = LMIteration:35 x = [-1.0000 0.2986 -10.0000 9.9964], gradient = 421988746.9021, step = LMIteration:36 x = [-1.0000 0.2829 -10.0000 9.9963], gradient = 230960695.7163, step = LMIteration:37 x = [-1.0000 0.2672 -10.0000 9.9962], gradient = 126427578.6262, step = LMIteration:38 x = [-1.0000 0.2514 -10.0000 9.9961], gradient = 69218466.4778, step = LMIteration:39 x = [-1.0000 0.2356 -10.0000 9.9960], gradient = 37904445.7661, step = LMIteration:40 x = [-1.0000 0.2197 -10.0000 9.9960], gradient = 20761560.5190, step = LMIteration:41 x = [-1.0000 0.2036 -10.0000 9.9959], gradient = 11374897.3379, step = LMIteration:42 x = [-1.0000 0.1875 -10.0000 9.9958], gradient = 6234064.0376, step = LMIteration:43 x = [-1.0000 0.1713 -10.0000 9.9957], gradient = 3417848.7040, step = LMIteration:44 x = [-1.0000 0.1550 -10.0000 9.9956], gradient = 1874634.8523, step = LMIteration:45 x = [-1.0000 0.1385 -10.0000 9.9955], gradient = 1028702.8782, step = LMIteration:46 x = [-1.0000 0.1218 -10.0000 9.9954], gradient = 564808.7854, step = LMIteration:47 x = [-1.0000 0.1049 -10.0000 9.9953], gradient = 310298.2705, step = LMIteration:48 x = [-1.0000 0.0877 -10.0000 9.9952], gradient = 170587.3249, step = LMIteration:49 x = [-1.0000 0.0703 -10.0000 9.9951], gradient = 93845.4326, step = LMIteration:50 x = [-1.0000 0.0524 -10.0000 9.9950], gradient = 51660.5782, step = LMIteration:51 x = [-1.0000 0.0341 -10.0000 9.9949], gradient = 28451.8639, step = LMIteration:52 x = [-1.0000 0.0153 -10.0000 9.9947], gradient = 15670.8490, step = LMIteration:53 x = [-0.9999 -0.0043 -10.0000 9.9946], gradient = 8624.8546, step = LMIteration:54 x = [-0.9999 -0.0246 -10.0000 9.9944], gradient = 4736.1605, step = LMIteration:55 x = [-0.9998 -0.0461 -10.0000 9.9941], gradient = 2587.7373, step = LMIteration:56 x = [-0.9996 -0.0687 -10.0000 9.9939], gradient = 1399.9325, step = LMIteration:57 x = [-0.9993 -0.0928 -10.0000 9.9936], gradient = 743.3551, step = LMIteration:58 x = [-0.9987 -0.1184 -10.0001 9.9931], gradient = 381.2687, step = LMIteration:59 x = [-0.9976 -0.1456 -10.0001 9.9925], gradient = 183.0379, step = LMIteration:60 x = [-0.9952 -0.1736 -10.0002 9.9917], gradient = 76.6425, step = LMIteration:61 x = [-0.9894 -0.1972 -10.0005 9.9901], gradient = 26.4382, step = LMIteration:62 x = [-0.9744 -0.2105 -10.0012 9.9871], gradient = 6.8472, step = LMIteration:63 x = [-0.9336 -0.2136 -10.0030 9.9797], gradient = 4.4702, step = LMIteration:64 x = [-0.8269 -0.2088 -10.0070 9.9631], gradient = 4.2573, step = LMIteration:65 x = [-0.6379 -0.1953 -10.0103 9.9430], gradient = 6.5882, step = LMIteration:66 x = [-0.5576 -0.1832 -10.0023 9.9499], gradient = 1.3240, step = LMIteration:67 x = [-0.5559 -0.1827 -9.9933 9.9681], gradient = 0.0227, step = LMIteration:68 x = [-0.5544 -0.1829 -10.0000 9.9888], gradient = 0.0087, step = LMIteration:69 x = [-0.5527 -0.1832 -10.0389 10.0305], gradient = 0.0117, step = LMIteration:70 x = [-0.5482 -0.1843 -10.1523 10.1442], gradient = 0.0548, step = LMIteration:71 x = [-0.5372 -0.1868 -10.4402 10.4325], gradient = 0.2795, step = LMIteration:72 x = [-0.5173 -0.1916 -11.0244 11.0175], gradient = 1.0133, step = LMIteration:73 x = [-0.5025 -0.1958 -11.5877 11.5812], gradient = 0.7806, step = LMIteration:74 x = [-0.4883 -0.2000 -12.1891 12.1835], gradient = 0.8407, step = LMIteration:75 x = [-0.4787 -0.2030 -12.6707 12.6659], gradient = 0.4784, step = LMIteration:76 x = [-0.4704 -0.2057 -13.1195 13.1156], gradient = 0.4040, step = LMIteration:77 x = [-0.4656 -0.2073 -13.4055 13.4021], gradient = 0.1502, step = LMIteration:78 x = [-0.4629 -0.2083 -13.5758 13.5728], gradient = 0.0525, step = LMIteration:79 x = [-0.4622 -0.2085 -13.6183 13.6154], gradient = 0.0030, step = LMIteration:80 x = [-0.4622 -0.2085 -13.6218 13.6188], gradient = 0.0000, step = LMIteration:81 x = [-0.4622 -0.2085 -13.6218 13.6188], gradient = 0.0000, step = LMFinal estimated parameters: [-0.4622 -0.2085 -13.6218 13.6188]
The algorithm runs for 81 iterations and produces parameter estimation result x* = [-0.46, -0.21, -13.62, 13.62] with ǁg(x*)ǁ ≈ 0. In other words, the algorithm successfully converges with the stopping criterion ǁgkǁ ≤ ε1 being met. It can also be seen that the algorithm always uses the LM method in curve-fitting the given data. This means that for every 3 successive iterations, there is one iterate xk that satisfies ǁgkǁ ≥ 0.02 ⋅ Fk.
Iteration:1 x = [-4.0000 0.9500 2.0000 -2.9990], gradient = 5843944048763837440.0000, step = LMIteration:2 x = [-4.0000 0.9001 2.0000 -2.9981], gradient = 798393836723220864.0000, step = LMIteration:3 x = [-4.0000 0.8510 2.0000 -2.9973], gradient = 112511464378970688.0000, step = LMIteration:4 x = [-4.0000 0.8050 2.0000 -2.9965], gradient = 17995869734728704.0000, step = LMIteration:5 x = [-4.0000 0.7687 2.0000 -2.9959], gradient = 4224958744295105.0000, step = LMIteration:6 x = [-4.0000 0.7454 2.0000 -2.9955], gradient = 1674832246409442.5000, step = LMIteration:7 x = [-4.0000 0.7283 2.0000 -2.9952], gradient = 847705835813273.6250, step = LMIteration:8 x = [-4.0000 0.7128 2.0000 -2.9950], gradient = 455980000478269.1875, step = LMIteration:9 x = [-4.0000 0.6975 2.0000 -2.9947], gradient = 248446618239291.2812, step = LMIteration:10 x = [-4.0000 0.6823 2.0000 -2.9945], gradient = 135727074063636.5469, step = LMIteration:11 x = [-4.0000 0.6671 2.0000 -2.9942], gradient = 74188516827416.2656, step = LMIteration:12 x = [-4.0000 0.6519 2.0000 -2.9940], gradient = 40556383042130.0234, step = LMIteration:13 x = [-4.0000 0.6367 2.0000 -2.9937], gradient = 22171597557325.9102, step = LMIteration:14 x = [-4.0000 0.6215 2.0000 -2.9934], gradient = 12121123175141.8398, step = LMIteration:15 x = [-4.0000 0.6063 2.0000 -2.9932], gradient = 6626677353862.0400, step = LMIteration:16 x = [-4.0000 0.5910 2.0000 -2.9929], gradient = 3622898207455.6821, step = LMIteration:17 x = [-4.0000 0.5758 2.0000 -2.9927], gradient = 1980725783949.0017, step = LMIteration:18 x = [-4.0000 0.5606 2.0000 -2.9924], gradient = 1082932002365.9087, step = LMIteration:19 x = [-4.0000 0.5453 2.0000 -2.9922], gradient = 592089574010.1783, step = LMIteration:20 x = [-4.0000 0.5300 2.0000 -2.9919], gradient = 323730717048.8542, step = LMIteration:21 x = [-4.0000 0.5148 2.0000 -2.9916], gradient = 177007495788.6531, step = LMIteration:22 x = [-4.0000 0.4995 2.0000 -2.9914], gradient = 96785827387.7305, step = LMIteration:23 x = [-4.0000 0.4842 2.0000 -2.9911], gradient = 52923125898.6776, step = LMIteration:24 x = [-4.0000 0.4688 2.0000 -2.9909], gradient = 28939714442.5817, step = LMIteration:25 x = [-4.0000 0.4535 2.0000 -2.9906], gradient = 15825580540.4678, step = LMIteration:26 x = [-4.0000 0.4381 2.0000 -2.9903], gradient = 8654531799.0783, step = LMIteration:27 x = [-4.0000 0.4228 2.0000 -2.9901], gradient = 4733127210.2534, step = LMIteration:28 x = [-4.0000 0.4074 2.0000 -2.9898], gradient = 2588665603.7885, step = LMIteration:29 x = [-4.0000 0.3919 2.0000 -2.9895], gradient = 1415891078.6356, step = LMIteration:30 x = [-4.0000 0.3765 2.0000 -2.9893], gradient = 774485568.1282, step = LMIteration:31 x = [-4.0000 0.3610 2.0000 -2.9890], gradient = 423672773.1613, step = LMIteration:32 x = [-4.0000 0.3455 2.0000 -2.9887], gradient = 231785640.8201, step = LMIteration:33 x = [-4.0000 0.3300 2.0000 -2.9885], gradient = 126819882.7775, step = LMIteration:34 x = [-4.0000 0.3144 2.0000 -2.9882], gradient = 69396974.7767, step = LMIteration:35 x = [-4.0000 0.2988 2.0000 -2.9879], gradient = 37980046.8186, step = LMIteration:36 x = [-4.0000 0.2831 2.0000 -2.9876], gradient = 20789502.5936, step = LMIteration:37 x = [-4.0000 0.2674 2.0000 -2.9874], gradient = 11382078.3240, step = LMIteration:38 x = [-4.0000 0.2516 2.0000 -2.9871], gradient = 6233151.4407, step = LMIteration:39 x = [-4.0000 0.2358 2.0000 -2.9868], gradient = 3414510.4438, step = LMIteration:40 x = [-4.0000 0.2198 2.0000 -2.9865], gradient = 1871192.9516, step = LMIteration:41 x = [-4.0000 0.2038 2.0000 -2.9862], gradient = 1025947.0256, step = LMIteration:42 x = [-4.0000 0.1877 2.0000 -2.9859], gradient = 562874.5612, step = LMIteration:43 x = [-4.0000 0.1714 2.0000 -2.9856], gradient = 309077.3735, step = LMIteration:44 x = [-4.0000 0.1550 2.0000 -2.9853], gradient = 169908.6045, step = LMIteration:45 x = [-4.0000 0.1384 2.0000 -2.9850], gradient = 93547.0603, step = LMIteration:46 x = [-4.0000 0.1215 2.0000 -2.9847], gradient = 51612.8671, step = LMIteration:47 x = [-4.0000 0.1044 2.0000 -2.9843], gradient = 28559.4009, step = LMIteration:48 x = [-4.0000 0.0869 2.0000 -2.9839], gradient = 15867.2252, step = LMIteration:49 x = [-4.0000 0.0688 2.0000 -2.9835], gradient = 8865.7762, step = LMIteration:50 x = [-4.0000 0.0500 2.0000 -2.9830], gradient = 4993.1844, step = LMIteration:51 x = [-4.0000 0.0303 2.0000 -2.9825], gradient = 2843.2836, step = LMIteration:52 x = [-4.0000 0.0092 2.0000 -2.9818], gradient = 1643.5749, step = LMIteration:53 x = [-4.0000 -0.0138 2.0000 -2.9809], gradient = 969.1664, step = LMIteration:54 x = [-4.0000 -0.0397 2.0001 -2.9798], gradient = 585.9656, step = LMIteration:55 x = [-4.0000 -0.0695 2.0001 -2.9782], gradient = 364.7187, step = LMIteration:56 x = [-4.0000 -0.1047 2.0003 -2.9760], gradient = 233.9465, step = LMIteration:57 x = [-4.0000 -0.1465 2.0005 -2.9730], gradient = 154.2224, step = LMIteration:58 x = [-4.0000 -0.1954 2.0008 -2.9690], gradient = 103.9455, step = LMIteration:59 x = [-4.0000 -0.2516 2.0014 -2.9638], gradient = 71.2219, step = LMIteration:60 x = [-4.0000 -0.3152 2.0023 -2.9571], gradient = 49.3390, step = LMIteration:61 x = [-4.0000 -0.3865 2.0037 -2.9486], gradient = 34.3994, step = LMIteration:62 x = [-4.0000 -0.4659 2.0060 -2.9378], gradient = 24.0583, step = LMIteration:63 x = [-3.9999 -0.5540 2.0095 -2.9242], gradient = 16.8404, step = LMIteration:64 x = [-3.9999 -0.6510 2.0148 -2.9069], gradient = 11.7791, step = LMIteration:65 x = [-3.9998 -0.7574 2.0228 -2.8848], gradient = 8.2216, step = LMIteration:66 x = [-3.9998 -0.8733 2.0348 -2.8567], gradient = 5.7186, step = LMIteration:67 x = [-3.9996 -0.9990 2.0522 -2.8209], gradient = 3.9571, step = LMIteration:68 x = [-3.9995 -1.1349 2.0768 -2.7754], gradient = 2.7180, step = LMIteration:69 x = [-3.9992 -1.2813 2.1103 -2.7183], gradient = 1.8476, step = LMIteration:70 x = [-3.9987 -1.4390 2.1533 -2.6485], gradient = 1.2392, step = LMIteration:71 x = [-3.9980 -1.6079 2.2038 -2.5681], gradient = 0.8190, step = LMIteration:72 x = [-3.9968 -1.7865 2.2547 -2.4842], gradient = 0.5357, step = LMIteration:73 x = [-3.9949 -1.9699 2.2945 -2.4089], gradient = 0.3513, step = LMIteration:74 x = [-3.9920 -2.1517 2.3148 -2.3524], gradient = 0.2345, step = LMIteration:75 x = [-3.9878 -2.3283 2.3156 -2.3155], gradient = 0.1603, step = LMIteration:76 x = [-3.9863 -2.3635 2.3124 -2.3081], gradient = 0.1487, step = QNIteration:77 x = [-3.9803 -2.4682 2.2972 -2.2863], gradient = 0.1189, step = QNIteration:78 x = [-3.9577 -2.7803 2.2395 -2.2211], gradient = 0.0613, step = QNIteration:79 x = [-3.9319 -3.0541 2.1785 -2.1639], gradient = 0.0344, step = QNIteration:80 x = [-3.9000 -3.3271 2.1135 -2.1068], gradient = 0.0193, step = QNIteration:81 x = [-3.8784 -3.4807 2.0776 -2.0748], gradient = 0.0140, step = QNIteration:82 x = [-3.8657 -3.5574 2.0604 -2.0588], gradient = 0.0119, step = QNIteration:83 x = [-3.8510 -3.6338 2.0437 -2.0428], gradient = 0.0101, step = QNIteration:84 x = [-3.8335 -3.7098 2.0276 -2.0269], gradient = 0.0086, step = QNIteration:85 x = [-3.8227 -3.7473 2.0198 -2.0191], gradient = 0.0080, step = QNIteration:86 x = [-3.8090 -3.7840 2.0123 -2.0114], gradient = 0.0074, step = QNIteration:87 x = [-3.7911 -3.8190 2.0053 -2.0041], gradient = 0.0073, step = QNIteration:88 x = [-3.7664 -3.8489 1.9996 -1.9979], gradient = 0.0076, step = QNIteration:89 x = [-3.7581 -3.8559 1.9998 -1.9981], gradient = 0.0077, step = LMIteration:90 x = [-3.7330 -3.8766 2.0004 -1.9986], gradient = 0.0081, step = LMIteration:91 x = [-3.6535 -3.9361 2.0028 -2.0011], gradient = 0.0096, step = LMIteration:92 x = [-3.3739 -4.0948 2.0180 -2.0161], gradient = 0.0168, step = LMIteration:93 x = [-1.8970 -4.4431 2.1579 -2.1553], gradient = 0.3573, step = LMIteration:94 x = [-1.8970 -4.4431 2.1579 -2.1553], gradient = 0.3573, step = LMIteration:95 x = [-1.8970 -4.4431 2.1579 -2.1553], gradient = 0.3573, step = LMIteration:96 x = [-1.8970 -4.4431 2.1579 -2.1553], gradient = 0.3573, step = LMIteration:97 x = [-0.4821 -4.4514 2.3330 -2.2979], gradient = 12.9667, step = LMIteration:98 x = [-0.4821 -4.4514 2.3330 -2.2979], gradient = 12.9667, step = LMIteration:99 x = [-0.4821 -4.4514 2.3330 -2.2979], gradient = 12.9667, step = LMIteration:100 x = [-0.4821 -4.4514 2.3330 -2.2979], gradient = 12.9667, step = LMIteration:101 x = [-0.4821 -4.4514 2.3330 -2.2979], gradient = 12.9667, step = LMIteration:102 x = [-0.3361 -4.4514 2.3517 -2.2985], gradient = 23.2634, step = LMIteration:103 x = [-0.3361 -4.4514 2.3517 -2.2985], gradient = 23.2634, step = LMIteration:104 x = [-0.0195 -4.4514 2.3844 -2.3000], gradient = 141.8487, step = LMIteration:105 x = [-0.0542 -4.4514 2.5491 -2.3129], gradient = 2.7825, step = LMIteration:106 x = [-0.0622 -4.4515 2.7408 -2.3468], gradient = 3.8567, step = LMIteration:107 x = [-0.0733 -4.4516 3.1240 -2.5063], gradient = 5.6536, step = LMIteration:108 x = [-0.0887 -4.4519 3.7063 -3.0302], gradient = 7.1668, step = LMIteration:109 x = [-0.1056 -4.4518 4.4259 -4.0061], gradient = 6.3086, step = LMIteration:110 x = [-0.1190 -4.4484 5.0608 -4.9286], gradient = 3.4276, step = LMIteration:111 x = [-0.1236 -4.4311 5.3256 -5.3076], gradient = 0.7579, step = LMIteration:112 x = [-0.1239 -4.3717 5.3572 -5.3565], gradient = 0.0396, step = LMIteration:113 x = [-0.1239 -4.1687 5.3583 -5.3584], gradient = 0.0016, step = LMIteration:114 x = [-0.1240 -3.2559 5.3610 -5.3611], gradient = 0.0427, step = LMIteration:115 x = [-0.1240 -3.2559 5.3610 -5.3611], gradient = 0.0427, step = LMIteration:116 x = [-0.1240 -3.2559 5.3610 -5.3611], gradient = 0.0427, step = LMIteration:117 x = [-0.1248 -1.1768 5.4018 -5.4026], gradient = 4.7877, step = LMIteration:118 x = [-0.1248 -1.1768 5.4018 -5.4026], gradient = 4.7877, step = LMIteration:119 x = [-0.1248 -1.1768 5.4018 -5.4026], gradient = 4.7877, step = LMIteration:120 x = [-0.1248 -1.1768 5.4018 -5.4026], gradient = 4.7877, step = LMIteration:121 x = [-0.1248 -1.1768 5.4018 -5.4026], gradient = 4.7877, step = LMIteration:122 x = [-0.1244 -1.1290 5.5183 -5.4517], gradient = 0.1904, step = LMIteration:123 x = [-0.1292 -1.0057 5.7614 -5.6610], gradient = 1.1816, step = LMIteration:124 x = [-0.1382 -0.8383 6.2791 -6.1944], gradient = 3.1482, step = LMIteration:125 x = [-0.1464 -0.7806 6.8138 -6.7630], gradient = 1.7846, step = LMIteration:126 x = [-0.1599 -0.6524 7.7451 -7.7208], gradient = 5.7805, step = LMIteration:127 x = [-0.1658 -0.6428 8.2978 -8.2944], gradient = 0.8161, step = LMIteration:128 x = [-0.1770 -0.5710 9.2787 -9.2788], gradient = 4.5341, step = LMIteration:129 x = [-0.1818 -0.5588 9.8477 -9.8546], gradient = 0.7032, step = LMIteration:130 x = [-0.1902 -0.5204 10.7897 -10.7955], gradient = 2.9184, step = LMIteration:131 x = [-0.1941 -0.5090 11.3439 -11.3510], gradient = 0.6201, step = LMIteration:132 x = [-0.1999 -0.4878 12.1563 -12.1617], gradient = 1.6519, step = LMIteration:133 x = [-0.2027 -0.4799 12.6128 -12.6178], gradient = 0.3816, step = LMIteration:134 x = [-0.2059 -0.4697 13.1434 -13.1472], gradient = 0.5800, step = LMIteration:135 x = [-0.2073 -0.4656 13.4035 -13.4068], gradient = 0.1173, step = LMIteration:136 x = [-0.2082 -0.4629 13.5699 -13.5729], gradient = 0.0504, step = LMIteration:137 x = [-0.2085 -0.4622 13.6148 -13.6177], gradient = 0.0034, step = LMIteration:138 x = [-0.2085 -0.4622 13.6188 -13.6218], gradient = 0.0000, step = LMIteration:139 x = [-0.2085 -0.4622 13.6188 -13.6218], gradient = 0.0000, step = LMFinal estimated parameters: [-0.2085 -0.4622 13.6188 -13.6218]
The algorithm runs as many as 139 iterations and produces parameter estimation result x* = [-0.21, -0.46, 13.62, -13.62] with ǁg(x*)ǁ ≈ 0. In other words, the algorithm successfully converges with the stopping criterion ǁgkǁ ≤ ε1 being met. It can also be seen that during the curve fitting of the given data, the algorithm changes the step method to QN at iterations 76–88 before changing back to LM. This means that in the last 3 iterations before iteration 76, no iterate xk satisfies ǁgkǁ ≥ 0.02 ⋅ Fk so that the QN method is considered able to converge more quickly than the LM method after iteration 76. Then, at iteration 88, we get ǁgk+1ǁ ≥ ǁgkǁ which means the gradient does not decrease fast enough using the QN method so that the method switches to LM for the next iteration.
Because the initial value x0 is quite far from the solution, more iterations are needed than that in Scenario 1. Also, note that so far there are two solutions that satisfy the convergence value x*, namely x* = [-0.46, -0.21, -13.62, 13.62] and x* = [-0.21, -0.46, 13.62, -13.62].
Iteration:1 x = [0.0000 0.0000 0.7705 0.7705], gradient = 42.5292, step = LMIteration:2 x = [-0.0815 -0.0815 1.3987 1.3987], gradient = 16.7516, step = LMIteration:3 x = [-0.0400 -0.0400 1.2150 1.2150], gradient = 18.3468, step = LMIteration:4 x = [-0.0607 -0.0695 1.3851 1.3851], gradient = 4.8184, step = LMIteration:5 x = [-0.0607 -0.0695 1.3851 1.3851], gradient = 4.8184, step = LMIteration:6 x = [-0.0607 -0.0695 1.3851 1.3851], gradient = 4.8184, step = LMIteration:7 x = [-0.0607 -0.0695 1.3851 1.3851], gradient = 4.8184, step = LMIteration:8 x = [-0.0607 -0.0695 1.3851 1.3851], gradient = 4.8184, step = LMIteration:9 x = [-0.0607 -0.0695 1.3851 1.3851], gradient = 4.8184, step = LMIteration:10 x = [-0.0631 -0.0584 1.3830 1.3830], gradient = 1.3008, step = LMIteration:11 x = [-0.0596 -0.0627 1.3811 1.3811], gradient = 0.4178, step = LMIteration:12 x = [-0.0620 -0.0601 1.3793 1.3792], gradient = 0.2770, step = LMIteration:13 x = [-0.0604 -0.0616 1.3775 1.3775], gradient = 0.2522, step = LMIteration:14 x = [-0.0613 -0.0605 1.3758 1.3757], gradient = 0.2432, step = LMIteration:15 x = [-0.0604 -0.0612 1.3737 1.3737], gradient = 0.2332, step = LMIteration:16 x = [-0.0615 -0.0597 1.3708 1.3708], gradient = 0.2541, step = LMIteration:17 x = [-0.0582 -0.0627 1.3678 1.3677], gradient = 0.6396, step = LMIteration:18 x = [-0.0582 -0.0627 1.3678 1.3677], gradient = 0.6396, step = LMIteration:19 x = [-0.0607 -0.0600 1.3668 1.3668], gradient = 0.1995, step = LMIteration:20 x = [-0.0603 -0.0604 1.3658 1.3658], gradient = 0.1930, step = LMIteration:21 x = [-0.0603 -0.0601 1.3639 1.3638], gradient = 0.1840, step = LMIteration:22 x = [-0.0593 -0.0605 1.3587 1.3586], gradient = 0.2076, step = LMIteration:23 x = [-0.0593 -0.0605 1.3587 1.3586], gradient = 0.2076, step = LMIteration:24 x = [-0.0593 -0.0605 1.3587 1.3586], gradient = 0.2076, step = LMIteration:25 x = [-0.0608 -0.0590 1.3571 1.3570], gradient = 0.2311, step = LMIteration:26 x = [-0.0584 -0.0611 1.3556 1.3555], gradient = 0.3672, step = LMIteration:27 x = [-0.0609 -0.0586 1.3545 1.3544], gradient = 0.3171, step = LMIteration:28 x = [-0.0590 -0.0603 1.3536 1.3536], gradient = 0.1788, step = LMIteration:29 x = [-0.0600 -0.0593 1.3528 1.3527], gradient = 0.1280, step = LMIteration:30 x = [-0.0594 -0.0598 1.3519 1.3519], gradient = 0.1237, step = LMIteration:31 x = [-0.0597 -0.0594 1.3510 1.3510], gradient = 0.1192, step = LMIteration:32 x = [-0.0597 -0.0594 1.3508 1.3510], gradient = 0.1183, step = QNIteration:33 x = [-0.0597 -0.0594 1.3500 1.3510], gradient = 0.1155, step = QNIteration:34 x = [-0.0596 -0.0594 1.3475 1.3510], gradient = 0.1084, step = QNIteration:35 x = [-0.0592 -0.0594 1.3401 1.3510], gradient = 0.1055, step = QNIteration:36 x = [-0.0589 -0.0594 1.3328 1.3510], gradient = 0.2028, step = QNIteration:37 x = [-0.0595 -0.0585 1.3319 1.3501], gradient = 0.1538, step = LMIteration:38 x = [-0.0595 -0.0585 1.3319 1.3501], gradient = 0.1538, step = LMIteration:39 x = [-0.0587 -0.0592 1.3314 1.3496], gradient = 0.0704, step = LMIteration:40 x = [-0.0591 -0.0588 1.3310 1.3492], gradient = 0.0640, step = LMIteration:41 x = [-0.0588 -0.0590 1.3306 1.3488], gradient = 0.0618, step = LMIteration:42 x = [-0.0588 -0.0590 1.3304 1.3488], gradient = 0.0615, step = QNIteration:43 x = [-0.0588 -0.0590 1.3300 1.3488], gradient = 0.0610, step = QNIteration:44 x = [-0.0587 -0.0590 1.3288 1.3488], gradient = 0.0582, step = QNIteration:45 x = [-0.0586 -0.0590 1.3275 1.3488], gradient = 0.0571, step = QNIteration:46 x = [-0.0586 -0.0590 1.3263 1.3488], gradient = 0.0554, step = QNIteration:47 x = [-0.0585 -0.0590 1.3251 1.3488], gradient = 0.0646, step = QNIteration:48 x = [-0.0590 -0.0585 1.3247 1.3484], gradient = 0.0576, step = LMIteration:49 x = [-0.0585 -0.0589 1.3243 1.3481], gradient = 0.0494, step = LMIteration:50 x = [-0.0589 -0.0585 1.3240 1.3477], gradient = 0.0455, step = LMIteration:51 x = [-0.0585 -0.0588 1.3237 1.3474], gradient = 0.0409, step = LMIteration:52 x = [-0.0588 -0.0585 1.3233 1.3471], gradient = 0.0393, step = LMIteration:53 x = [-0.0585 -0.0588 1.3230 1.3468], gradient = 0.0377, step = LMIteration:54 x = [-0.0588 -0.0585 1.3228 1.3465], gradient = 0.0363, step = LMIteration:55 x = [-0.0585 -0.0587 1.3225 1.3462], gradient = 0.0348, step = LMIteration:56 x = [-0.0587 -0.0585 1.3222 1.3459], gradient = 0.0335, step = LMIteration:57 x = [-0.0585 -0.0587 1.3219 1.3457], gradient = 0.0321, step = LMIteration:58 x = [-0.0587 -0.0585 1.3217 1.3454], gradient = 0.0307, step = LMIteration:59 x = [-0.0584 -0.0587 1.3214 1.3452], gradient = 0.0294, step = LMIteration:60 x = [-0.0587 -0.0584 1.3212 1.3449], gradient = 0.0319, step = LMIteration:61 x = [-0.0584 -0.0587 1.3209 1.3447], gradient = 0.0330, step = LMIteration:62 x = [-0.0587 -0.0584 1.3207 1.3445], gradient = 0.0357, step = LMIteration:63 x = [-0.0584 -0.0587 1.3205 1.3442], gradient = 0.0362, step = LMIteration:64 x = [-0.0586 -0.0584 1.3203 1.3440], gradient = 0.0363, step = LMIteration:65 x = [-0.0584 -0.0586 1.3201 1.3439], gradient = 0.0321, step = LMIteration:66 x = [-0.0586 -0.0584 1.3199 1.3437], gradient = 0.0281, step = LMIteration:67 x = [-0.0584 -0.0586 1.3198 1.3435], gradient = 0.0228, step = LMIteration:68 x = [-0.0585 -0.0584 1.3196 1.3434], gradient = 0.0203, step = LMIteration:69 x = [-0.0584 -0.0585 1.3195 1.3432], gradient = 0.0195, step = LMIteration:70 x = [-0.0585 -0.0584 1.3193 1.3431], gradient = 0.0188, step = LMIteration:71 x = [-0.0584 -0.0585 1.3192 1.3429], gradient = 0.0181, step = LMIteration:72 x = [-0.0585 -0.0584 1.3190 1.3428], gradient = 0.0174, step = LMIteration:73 x = [-0.0584 -0.0585 1.3189 1.3426], gradient = 0.0166, step = LMIteration:74 x = [-0.0585 -0.0583 1.3187 1.3425], gradient = 0.0175, step = LMIteration:75 x = [-0.0583 -0.0585 1.3186 1.3423], gradient = 0.0212, step = LMIteration:76 x = [-0.0585 -0.0583 1.3185 1.3422], gradient = 0.0264, step = LMIteration:77 x = [-0.0583 -0.0585 1.3183 1.3421], gradient = 0.0264, step = LMIteration:78 x = [-0.0585 -0.0583 1.3182 1.3420], gradient = 0.0201, step = LMIteration:79 x = [-0.0583 -0.0584 1.3182 1.3419], gradient = 0.0130, step = LMIteration:80 x = [-0.0584 -0.0583 1.3181 1.3418], gradient = 0.0124, step = LMIteration:81 x = [-0.0584 -0.0584 1.3180 1.3417], gradient = 0.0120, step = LMIteration:82 x = [-0.0584 -0.0583 1.3179 1.3416], gradient = 0.0115, step = LMIteration:83 x = [-0.0583 -0.0584 1.3178 1.3415], gradient = 0.0110, step = LMIteration:84 x = [-0.0584 -0.0583 1.3176 1.3414], gradient = 0.0186, step = LMIteration:85 x = [-0.0584 -0.0583 1.3176 1.3414], gradient = 0.0186, step = LMIteration:86 x = [-0.0583 -0.0584 1.3176 1.3413], gradient = 0.0112, step = LMIteration:87 x = [-0.0584 -0.0583 1.3175 1.3412], gradient = 0.0095, step = LMIteration:88 x = [-0.0583 -0.0584 1.3174 1.3412], gradient = 0.0092, step = LMIteration:89 x = [-0.0583 -0.0584 1.3174 1.3412], gradient = 0.0090, step = QNIteration:90 x = [-0.0583 -0.0584 1.3173 1.3412], gradient = 0.0260, step = QNIteration:91 x = [-0.0584 -0.0583 1.3173 1.3411], gradient = 0.0085, step = LMIteration:92 x = [-0.0583 -0.0584 1.3172 1.3411], gradient = 0.0083, step = LMIteration:93 x = [-0.0583 -0.0583 1.3171 1.3410], gradient = 0.0080, step = LMIteration:94 x = [-0.0583 -0.0583 1.3171 1.3409], gradient = 0.0077, step = LMIteration:95 x = [-0.0584 -0.0583 1.3170 1.3409], gradient = 0.0075, step = LMIteration:96 x = [-0.0583 -0.0584 1.3169 1.3408], gradient = 0.0110, step = LMIteration:97 x = [-0.0584 -0.0582 1.3169 1.3407], gradient = 0.0165, step = LMIteration:98 x = [-0.0583 -0.0584 1.3168 1.3407], gradient = 0.0109, step = LMIteration:99 x = [-0.0583 -0.0583 1.3168 1.3406], gradient = 0.0062, step = LMIteration:100 x = [-0.0583 -0.0583 1.3167 1.3406], gradient = 0.0059, step = LMIteration:101 x = [-0.0583 -0.0583 1.3167 1.3406], gradient = 0.0057, step = LMIteration:102 x = [-0.0583 -0.0583 1.3167 1.3405], gradient = 0.0055, step = LMIteration:103 x = [-0.0583 -0.0583 1.3166 1.3404], gradient = 0.0075, step = LMIteration:104 x = [-0.0583 -0.0583 1.3166 1.3404], gradient = 0.0075, step = LMIteration:105 x = [-0.0583 -0.0583 1.3165 1.3404], gradient = 0.0090, step = LMIteration:106 x = [-0.0583 -0.0583 1.3165 1.3403], gradient = 0.0099, step = LMIteration:107 x = [-0.0583 -0.0583 1.3164 1.3403], gradient = 0.0064, step = LMIteration:108 x = [-0.0583 -0.0583 1.3164 1.3403], gradient = 0.0064, step = QNIteration:109 x = [-0.0583 -0.0583 1.3164 1.3403], gradient = 0.0043, step = LMIteration:110 x = [-0.0583 -0.0583 1.3164 1.3402], gradient = 0.0041, step = LMIteration:111 x = [-0.0583 -0.0583 1.3164 1.3402], gradient = 0.0040, step = LMIteration:112 x = [-0.0583 -0.0583 1.3163 1.3402], gradient = 0.0038, step = LMIteration:113 x = [-0.0583 -0.0583 1.3163 1.3401], gradient = 0.0050, step = LMIteration:114 x = [-0.0583 -0.0583 1.3163 1.3401], gradient = 0.0050, step = LMIteration:115 x = [-0.0583 -0.0583 1.3162 1.3401], gradient = 0.0045, step = LMIteration:116 x = [-0.0583 -0.0583 1.3162 1.3401], gradient = 0.0044, step = LMIteration:117 x = [-0.0583 -0.0583 1.3162 1.3400], gradient = 0.0040, step = LMIteration:118 x = [-0.0583 -0.0583 1.3162 1.3400], gradient = 0.0040, step = QNIteration:119 x = [-0.0583 -0.0583 1.3162 1.3400], gradient = 0.0037, step = LMIteration:120 x = [-0.0583 -0.0583 1.3161 1.3400], gradient = 0.0032, step = LMIteration:121 x = [-0.0583 -0.0583 1.3161 1.3400], gradient = 0.0030, step = LMIteration:122 x = [-0.0583 -0.0583 1.3161 1.3400], gradient = 0.0027, step = LMIteration:123 x = [-0.0583 -0.0583 1.3161 1.3399], gradient = 0.0026, step = LMIteration:124 x = [-0.0583 -0.0583 1.3161 1.3399], gradient = 0.0025, step = LMIteration:125 x = [-0.0583 -0.0583 1.3160 1.3399], gradient = 0.0024, step = LMIteration:126 x = [-0.0583 -0.0583 1.3160 1.3399], gradient = 0.0023, step = LMIteration:127 x = [-0.0583 -0.0583 1.3160 1.3399], gradient = 0.0022, step = LMIteration:128 x = [-0.0583 -0.0583 1.3160 1.3398], gradient = 0.0021, step = LMIteration:129 x = [-0.0583 -0.0583 1.3160 1.3398], gradient = 0.0020, step = LMIteration:130 x = [-0.0583 -0.0583 1.3160 1.3398], gradient = 0.0020, step = LMIteration:131 x = [-0.0583 -0.0583 1.3159 1.3398], gradient = 0.0022, step = LMIteration:132 x = [-0.0583 -0.0583 1.3159 1.3398], gradient = 0.0024, step = LMIteration:133 x = [-0.0583 -0.0583 1.3159 1.3398], gradient = 0.0026, step = LMIteration:134 x = [-0.0583 -0.0583 1.3159 1.3397], gradient = 0.0025, step = LMIteration:135 x = [-0.0583 -0.0583 1.3159 1.3397], gradient = 0.0023, step = LMIteration:136 x = [-0.0583 -0.0583 1.3159 1.3397], gradient = 0.0018, step = LMIteration:137 x = [-0.0583 -0.0583 1.3159 1.3397], gradient = 0.0015, step = LMIteration:138 x = [-0.0583 -0.0583 1.3158 1.3397], gradient = 0.0014, step = LMIteration:139 x = [-0.0583 -0.0583 1.3158 1.3397], gradient = 0.0014, step = LMFinal estimated parameters: [-0.0583 -0.0583 1.3158 1.3397]
The algorithm runs for 139 iterations and produces parameter estimation result x* = [-0.06, -0.06, 1.32, 1.34] with ǁgkǁ ≈ 0.0014 > ε1. In other words, the algorithm has not successfully converged, but the iteration has been terminated because the stopping criterion ǁhkǁ ≤ ε2 (ǁxkǁ + ε2) has been met. It can also be seen that during the curve fitting of the given data, the algorithm repeatedly changed the step method to QN and vice versa to LM for the reasons described in Scenario 2. From the graph above, obviously, the solution x* found is not good enough.
By looking at the value of x during iteration, it’s observed that x1 ≈ x2 and x3 ≈ x4. Hence, we can conclude that the selection of the initial value x0 = [0, 0, 0, 0] is a bad choice because the value is symmetrical and the algorithm is not able to break the symmetry. You can try and see the same thing happens in choosing other initial symmetrical values such as x0 = [-1, -1, -1, -1], x0 = [1, 1, 1, 1], or x0 = [2, 2, 2, 2]. Orrr, this is just a coincidence. What do you think?
What else do you find interesting from the experiment?
We’ve developed an efficient algorithm to solve a non-linear least squares problem. This algorithm combines Levenberg-Marquardt and Quasi-Newton methods, utilizing trust-region for the step choice. The algorithm can accurately find the best parameters of the model in superlinear convergence rate. However, poor parameter initialization may lead to bad results. In our study case, this algorithm finds the following two models that fit the data:
Of course, these two models are equivalent by rearranging the components of parameter x.
You might want to continue reading my related stories:
Albers Uzila
Thanks! If you enjoy this story and want to support me as a writer, consider becoming a member. For only $5 a month, you’ll get unlimited access to all stories on Medium. If you sign up using my link, I’ll earn a small commission.
If you’re one of my referred Medium members, feel free to email me at geoclid.members[at]gmail.com to get the complete python code of this story.
[1] K. Madsen (1988): A Combined Gauss-Newton and Quasi-Newton Method for Non-Linear Least Squares. Institute for Numerical Analysis (now part of IMM), DTU. Report NI-88–10.
|
[
{
"code": null,
"e": 454,
"s": 171,
"text": "Table of Contents (read till the end to see how you can get the complete python code of this story)· Seeing the Big Picture· Defining The Problem· A Hybrid Method ∘ Objective Function ∘ General Algorithm ∘ Levenberg-Marquardt Step ∘ Quasi-Newton Step· Implementation· Conclusion"
},
{
"code": null,
"e": 702,
"s": 454,
"text": "In previous articles, we’ve seen Gradient Descent and Conjugate Gradient algorithm in action, as two of the simplest optimization method there is. We implemented line search for searching the direction to which the objective function is optimized."
},
{
"code": null,
"e": 1102,
"s": 702,
"text": "There is another way to generate steps called trust-region. Trust-region methods define a region around the current iterate within which they trust the model to be an adequate representation of the objective function, and then choose the step to be the approximate minimizer of the model in this region. In effect, unlike line search, they choose the direction and length of the step simultaneously."
},
{
"code": null,
"e": 1711,
"s": 1102,
"text": "There is also a whole lot of other optimization methods such as Newton’s method and Quasi-Newton methods. In this article, we will use a hybrid of the Levenberg-Marquardt and Quasi-Newton method, utilizing trust-region for the step choice. Furthermore, this article brings a different problem. Instead of finding an optimizer of an objective function, we will be given a dataset and a non-linear model of the data, and then find the best optimized parameters of the model. Optimized parameters are defined by those who give the least squares of residuals. Some people might call this a curve-fitting problem."
},
{
"code": null,
"e": 1740,
"s": 1711,
"text": "Let’s import some libraries."
},
{
"code": null,
"e": 1876,
"s": 1740,
"text": "Create a fictional dataset as follows. It has 11 observations and 2 features with the first feature acting like an index of the second."
},
{
"code": null,
"e": 2108,
"s": 1876,
"text": "t \t y------------------[[ 0.0000 0.0000] [ 2.0000 3.5500] [ 4.0000 3.8200] [ 6.0000 2.9800] [ 8.0000 2.3200] [10.0000 1.4800] [12.0000 1.0200] [14.0000 0.8100] [16.0000 0.4100] [18.0000 0.4200] [20.0000 0.1500]]Data shape: (11, 2)"
},
{
"code": null,
"e": 2202,
"s": 2108,
"text": "Visualize the data as points (t, y) = (ti, yi) with i = 1, 2, ..., 11 in the cartesius plane."
},
{
"code": null,
"e": 2457,
"s": 2202,
"text": "We immediately realize that the data has no linear trend (the point (0,0) here is not an outlier). Hence, the model that we use is also non-linear. Instead, we will use a linear combination of two exponential functions, which by definition is declared as"
},
{
"code": null,
"e": 2601,
"s": 2457,
"text": "As mentioned before, parameters x = [x1, x2, x3, x4] will be estimated using a hybrid method of Levenberg-Marquardt (LM) dan Quasi-Newton (QN)."
},
{
"code": null,
"e": 3115,
"s": 2601,
"text": "In general, we want to build a model M(x, t) for a collection of m data points (ti, yi). To do that, a concrete definition of the objective function is necessary. For a least-squares problem, this objective function is the sum of squares of the residual of each data point. A data point’s residual is defined by how far the actual data to the model prediction is, that is, by subtracting the actual data point by the model prediction of that point. Mathematically speaking, the residual for the i-th data point is"
},
{
"code": null,
"e": 3137,
"s": 3115,
"text": "or in the vector form"
},
{
"code": null,
"e": 3245,
"s": 3137,
"text": "Since the objective function is the sum of squares of the residual of each data point, it can be written as"
},
{
"code": null,
"e": 3316,
"s": 3245,
"text": "The coefficient 1⁄2 above is attached for convenience in derivating F."
},
{
"code": null,
"e": 3515,
"s": 3316,
"text": "Let ǁ⋅ǁ be a symbol for the maximum norm of a vector. Our mission is to find x which minimizes F. To do that, we will find x at which ǁg(x)ǁ ≈ 0 where g = F’ is the first derivative of F. Derivating"
},
{
"code": null,
"e": 3562,
"s": 3515,
"text": "w.r.t. each xj using the chain rule, we obtain"
},
{
"code": null,
"e": 3589,
"s": 3562,
"text": "Define the Jacobian matrix"
},
{
"code": null,
"e": 3630,
"s": 3589,
"text": "the value of g can then be calculated as"
},
{
"code": null,
"e": 3733,
"s": 3630,
"text": "For the python function below, besides returning g, it also returns J, which will come in handy later."
},
{
"code": null,
"e": 4141,
"s": 3733,
"text": "Let x* be the minimizer of the sum of squared residuals. The least-squares problem can be solved by general optimization methods, but we shall present special methods that are more efficient. In 1988, Madsen [1] presented a hybrid method that combines the LM method (quadratic convergence if F(x*) = 0, linear convergence otherwise) with a QN method, which gives superlinear convergence, even if F(x*) ≠ 0."
},
{
"code": null,
"e": 4276,
"s": 4141,
"text": "In the trust region method, the algorithm generates a trust model L of the behavior of F in the neighborhood of the current iterate x,"
},
{
"code": null,
"e": 4482,
"s": 4276,
"text": "where h is the step to be taken. We assume that we know a positive number Δ such that the model is sufficiently accurate inside a ball with radius Δ, centered at x, and the algorithm determines the step as"
},
{
"code": null,
"e": 4529,
"s": 4482,
"text": "In a damped version, the step is determined as"
},
{
"code": null,
"e": 4573,
"s": 4529,
"text": "where the damping parameter μ ≥ 0. The term"
},
{
"code": null,
"e": 4612,
"s": 4573,
"text": "is introduced to penalize large steps."
},
{
"code": null,
"e": 4857,
"s": 4612,
"text": "From now on, we will begin iterating. Hence, we will introduce an index k which means the variable in question is for the k-th iteration. For example, xk is the value of x at k-th iteration, and so Fk = F(xk), gk = g(xk), Jk = J(xk), and so on."
},
{
"code": null,
"e": 5067,
"s": 4857,
"text": "Before the iteration begins, it’s important to initialize the damping parameter μ = μ0 and Hessian approximation B0 (Hessian at iterate x is defined by F’’(x) and its approximation B is used by the QN method)."
},
{
"code": null,
"e": 5234,
"s": 5067,
"text": "A reasonable choice for B0 is a symmetric, positive definite matrix I, that is, the identity matrix. The choice of μ0 should be related to the size of the elements in"
},
{
"code": null,
"e": 5250,
"s": 5234,
"text": "e.g. by letting"
},
{
"code": null,
"e": 5371,
"s": 5250,
"text": "where aii0 is the i-th diagonal component of A0, and τ is chosen by the user. In this article, we will set τ = 1 × 10−3."
},
{
"code": null,
"e": 5476,
"s": 5371,
"text": "For the python function below, besides returning μ0, it also returns A0, which will come in handy later."
},
{
"code": null,
"e": 5920,
"s": 5476,
"text": "After initializing μ0 and B0, the iteration starts with a series of steps with the LM method. If the performance indicates that F(x*) is significantly nonzero, then we switch to the QN method for better performance. We may get an indication that it is better to switch back to the LM method, so there is also a mechanism for that which will be covered later. The iteration keeps going until one of the following stopping criteria is satisfied:"
},
{
"code": null,
"e": 6005,
"s": 5920,
"text": "The norm of the gradient of the objective function is close enough to zero, that is,"
},
{
"code": null,
"e": 6036,
"s": 6005,
"text": "The norm of the step satisfies"
},
{
"code": null,
"e": 6070,
"s": 6036,
"text": "The number of steps taken is 1000"
},
{
"code": null,
"e": 6119,
"s": 6070,
"text": "In this article, ε1 and ε2 will be set 1 × 10−5."
},
{
"code": null,
"e": 6210,
"s": 6119,
"text": "After each step, whether it’s through the LM or QN method, Bk is updated by first defining"
},
{
"code": null,
"e": 6213,
"s": 6210,
"text": "If"
},
{
"code": null,
"e": 6231,
"s": 6213,
"text": "then update Bk by"
},
{
"code": null,
"e": 6298,
"s": 6231,
"text": "where vk = Bkhk. Otherwise, Bk stays the same, that is, Bk+1 = Bk."
},
{
"code": null,
"e": 6443,
"s": 6298,
"text": "The new xk+1 = xk + hk found by the LM or QN method is then passed to the next iteration. This whole process could be written as the code below."
},
{
"code": null,
"e": 6549,
"s": 6443,
"text": "Now, let’s go into the detail of each step. What’s going on in the LMstep() and QNstep() functions above?"
},
{
"code": null,
"e": 6664,
"s": 6549,
"text": "At the beginning of hybrid iterations, the LM method is used first. At k-th iteration, step hk is found by solving"
},
{
"code": null,
"e": 6683,
"s": 6664,
"text": "and then calculate"
},
{
"code": null,
"e": 6714,
"s": 6683,
"text": "where Fk+1 is just F(xk + hk)."
},
{
"code": null,
"e": 6742,
"s": 6714,
"text": "We then consider two cases:"
},
{
"code": null,
"e": 7049,
"s": 6742,
"text": "If ρ > 0, this means the iteration is a success and we can update xk+1 = xk + hk. At this point, we need to check whether F(x*) is far from zero, that is, by checking: if ǁgkǁ < 0.02 ⋅ Fk for three consecutive successful iterations, then we will change to the QN method for the next iteration. Also, update"
},
{
"code": null,
"e": 7356,
"s": 7049,
"text": "If ρ > 0, this means the iteration is a success and we can update xk+1 = xk + hk. At this point, we need to check whether F(x*) is far from zero, that is, by checking: if ǁgkǁ < 0.02 ⋅ Fk for three consecutive successful iterations, then we will change to the QN method for the next iteration. Also, update"
},
{
"code": null,
"e": 7495,
"s": 7356,
"text": "2. If ρ ≤ 0, then the iteration does not succeed and we won’t update xk, that is, xk+1 = xk. For this case, update μk+1 = μkν and ν := 2ν."
},
{
"code": null,
"e": 7629,
"s": 7495,
"text": "The update method of μ mentioned above is developed by Nielsen. We also have another variation by Marquardt as can be observed below."
},
{
"code": null,
"e": 7883,
"s": 7629,
"text": "The overall LM step can be seen as follows. Note that in the code below, we are passing Δk, which is the trust-region radius that will be used by the QN step in case we change the step calculation method to QN in future iterations. We don’t use Δk here."
},
{
"code": null,
"e": 8044,
"s": 7883,
"text": "Since the QN method uses trust-region for step calculation, at the beginning when we move to the QN method, it’s important to initialize the trust-region radius"
},
{
"code": null,
"e": 8303,
"s": 8044,
"text": "where hlm is the step acquired by the previous LM step. But don’t worry, this initialization part is not needed since we always calculate Δk in both LM and QN steps. As you can see, the last formula above is already embedded in the LMstep() function line 14."
},
{
"code": null,
"e": 8350,
"s": 8303,
"text": "At k-th iteration, step hk is found by solving"
},
{
"code": null,
"e": 8423,
"s": 8350,
"text": "If ǁhkǁ > Δk, then reduce the length of hk to be Δk, that is, by setting"
},
{
"code": null,
"e": 8543,
"s": 8423,
"text": "Δk is then updated under several conditions of ρ, which is calculated using the same formula as that we use at LM step:"
},
{
"code": null,
"e": 8579,
"s": 8543,
"text": "If ρ < 0.25, then set Δk+1 = Δk / 2"
},
{
"code": null,
"e": 8624,
"s": 8579,
"text": "If ρ > 0.75, then set Δk+1 = max{Δk, 3 ǁhkǁ}"
},
{
"code": null,
"e": 8645,
"s": 8624,
"text": "Otherwise, Δk+1 = Δk"
},
{
"code": null,
"e": 8674,
"s": 8645,
"text": "Next, we consider two cases:"
},
{
"code": null,
"e": 9065,
"s": 8674,
"text": "If Fk+1 ≤ (1 + δ) Fk and ǁgk+1ǁ < ǁgkǁ, or Fk+1 < Fk, then the iteration succeed and we can update xk+1 = xk + hk. At this point, we focus on getting g closer to zero, so we accept a slight increase in the value of F, e.g. as little as δ = √ε times the previous F, where ε is the machine epsilon.Otherwise, the iteration is considered a failure, and xk won’t be updated, that is, xk+1 = xk."
},
{
"code": null,
"e": 9362,
"s": 9065,
"text": "If Fk+1 ≤ (1 + δ) Fk and ǁgk+1ǁ < ǁgkǁ, or Fk+1 < Fk, then the iteration succeed and we can update xk+1 = xk + hk. At this point, we focus on getting g closer to zero, so we accept a slight increase in the value of F, e.g. as little as δ = √ε times the previous F, where ε is the machine epsilon."
},
{
"code": null,
"e": 9457,
"s": 9362,
"text": "Otherwise, the iteration is considered a failure, and xk won’t be updated, that is, xk+1 = xk."
},
{
"code": null,
"e": 9580,
"s": 9457,
"text": "If the gradient does not decrease fast enough, that is, ǁgk+1ǁ ≥ ǁgkǁ, then we move to the LM step for the next iteration."
},
{
"code": null,
"e": 9693,
"s": 9580,
"text": "The overall QN step can be seen as follows. Note that in the code below, we calculate ρ as we do in the LM step."
},
{
"code": null,
"e": 9851,
"s": 9693,
"text": "We are now ready to apply our knowledge to the problem defined at the beginning of this article. We will vary the initial point in three different scenarios:"
},
{
"code": null,
"e": 9873,
"s": 9851,
"text": "x0 = [-1, 1, -10, 10]"
},
{
"code": null,
"e": 9893,
"s": 9873,
"text": "x0 = [-4, 1, 2, -3]"
},
{
"code": null,
"e": 9911,
"s": 9893,
"text": "x0 = [0, 0, 0, 0]"
},
{
"code": null,
"e": 10022,
"s": 9911,
"text": "But first, let’s introduce a python function MakeAnimation() to animate the learning process of the algorithm."
},
{
"code": null,
"e": 17242,
"s": 10022,
"text": "Iteration:1\tx = [-1.0000 0.9500 -10.0000 9.9997], \t\tgradient = 64932772695986634752.0000, step = LMIteration:2\tx = [-1.0000 0.9001 -10.0000 9.9994], \t\tgradient = 8871075343566318592.0000, step = LMIteration:3\tx = [-1.0000 0.8510 -10.0000 9.9992], \t\tgradient = 1250145055141384192.0000, step = LMIteration:4\tx = [-1.0000 0.8050 -10.0000 9.9990], \t\tgradient = 199964648437467488.0000, step = LMIteration:5\tx = [-1.0000 0.7686 -10.0000 9.9988], \t\tgradient = 46950703393293552.0000, step = LMIteration:6\tx = [-1.0000 0.7454 -10.0000 9.9987], \t\tgradient = 18613190948807260.0000, step = LMIteration:7\tx = [-1.0000 0.7283 -10.0000 9.9986], \t\tgradient = 9421138350386658.0000, step = LMIteration:8\tx = [-1.0000 0.7127 -10.0000 9.9985], \t\tgradient = 5067642599353893.0000, step = LMIteration:9\tx = [-1.0000 0.6974 -10.0000 9.9984], \t\tgradient = 2761173975265880.5000, step = LMIteration:10\tx = [-1.0000 0.6822 -10.0000 9.9983], \t\tgradient = 1508437660486741.0000, step = LMIteration:11\tx = [-1.0000 0.6670 -10.0000 9.9983], \t\tgradient = 824513384402736.2500, step = LMIteration:12\tx = [-1.0000 0.6518 -10.0000 9.9982], \t\tgradient = 450734053994430.5000, step = LMIteration:13\tx = [-1.0000 0.6366 -10.0000 9.9981], \t\tgradient = 246409971021028.8438, step = LMIteration:14\tx = [-1.0000 0.6214 -10.0000 9.9980], \t\tgradient = 134711382454059.4531, step = LMIteration:15\tx = [-1.0000 0.6062 -10.0000 9.9980], \t\tgradient = 73647395414745.6094, step = LMIteration:16\tx = [-1.0000 0.5909 -10.0000 9.9979], \t\tgradient = 40264084923738.5469, step = LMIteration:17\tx = [-1.0000 0.5757 -10.0000 9.9978], \t\tgradient = 22013352246245.9766, step = LMIteration:18\tx = [-1.0000 0.5605 -10.0000 9.9977], \t\tgradient = 12035471978657.0332, step = LMIteration:19\tx = [-1.0000 0.5452 -10.0000 9.9976], \t\tgradient = 6580356674017.7891, step = LMIteration:20\tx = [-1.0000 0.5299 -10.0000 9.9976], \t\tgradient = 3597874150520.1475, step = LMIteration:21\tx = [-1.0000 0.5146 -10.0000 9.9975], \t\tgradient = 1967223429070.2634, step = LMIteration:22\tx = [-1.0000 0.4993 -10.0000 9.9974], \t\tgradient = 1075656653534.5968, step = LMIteration:23\tx = [-1.0000 0.4840 -10.0000 9.9973], \t\tgradient = 588175745878.2034, step = LMIteration:24\tx = [-1.0000 0.4687 -10.0000 9.9973], \t\tgradient = 321629128815.2425, step = LMIteration:25\tx = [-1.0000 0.4534 -10.0000 9.9972], \t\tgradient = 175881428072.9430, step = LMIteration:26\tx = [-1.0000 0.4380 -10.0000 9.9971], \t\tgradient = 96183963098.1861, step = LMIteration:27\tx = [-1.0000 0.4226 -10.0000 9.9970], \t\tgradient = 52602379508.8333, step = LMIteration:28\tx = [-1.0000 0.4072 -10.0000 9.9969], \t\tgradient = 28769372395.6593, step = LMIteration:29\tx = [-1.0000 0.3918 -10.0000 9.9969], \t\tgradient = 15735488020.7650, step = LMIteration:30\tx = [-1.0000 0.3763 -10.0000 9.9968], \t\tgradient = 8607119032.2862, step = LMIteration:31\tx = [-1.0000 0.3609 -10.0000 9.9967], \t\tgradient = 4708326165.4597, step = LMIteration:32\tx = [-1.0000 0.3454 -10.0000 9.9966], \t\tgradient = 2575789155.9012, step = LMIteration:33\tx = [-1.0000 0.3298 -10.0000 9.9965], \t\tgradient = 1409268155.2911, step = LMIteration:34\tx = [-1.0000 0.3142 -10.0000 9.9965], \t\tgradient = 771119669.0625, step = LMIteration:35\tx = [-1.0000 0.2986 -10.0000 9.9964], \t\tgradient = 421988746.9021, step = LMIteration:36\tx = [-1.0000 0.2829 -10.0000 9.9963], \t\tgradient = 230960695.7163, step = LMIteration:37\tx = [-1.0000 0.2672 -10.0000 9.9962], \t\tgradient = 126427578.6262, step = LMIteration:38\tx = [-1.0000 0.2514 -10.0000 9.9961], \t\tgradient = 69218466.4778, step = LMIteration:39\tx = [-1.0000 0.2356 -10.0000 9.9960], \t\tgradient = 37904445.7661, step = LMIteration:40\tx = [-1.0000 0.2197 -10.0000 9.9960], \t\tgradient = 20761560.5190, step = LMIteration:41\tx = [-1.0000 0.2036 -10.0000 9.9959], \t\tgradient = 11374897.3379, step = LMIteration:42\tx = [-1.0000 0.1875 -10.0000 9.9958], \t\tgradient = 6234064.0376, step = LMIteration:43\tx = [-1.0000 0.1713 -10.0000 9.9957], \t\tgradient = 3417848.7040, step = LMIteration:44\tx = [-1.0000 0.1550 -10.0000 9.9956], \t\tgradient = 1874634.8523, step = LMIteration:45\tx = [-1.0000 0.1385 -10.0000 9.9955], \t\tgradient = 1028702.8782, step = LMIteration:46\tx = [-1.0000 0.1218 -10.0000 9.9954], \t\tgradient = 564808.7854, step = LMIteration:47\tx = [-1.0000 0.1049 -10.0000 9.9953], \t\tgradient = 310298.2705, step = LMIteration:48\tx = [-1.0000 0.0877 -10.0000 9.9952], \t\tgradient = 170587.3249, step = LMIteration:49\tx = [-1.0000 0.0703 -10.0000 9.9951], \t\tgradient = 93845.4326, step = LMIteration:50\tx = [-1.0000 0.0524 -10.0000 9.9950], \t\tgradient = 51660.5782, step = LMIteration:51\tx = [-1.0000 0.0341 -10.0000 9.9949], \t\tgradient = 28451.8639, step = LMIteration:52\tx = [-1.0000 0.0153 -10.0000 9.9947], \t\tgradient = 15670.8490, step = LMIteration:53\tx = [-0.9999 -0.0043 -10.0000 9.9946], \t\tgradient = 8624.8546, step = LMIteration:54\tx = [-0.9999 -0.0246 -10.0000 9.9944], \t\tgradient = 4736.1605, step = LMIteration:55\tx = [-0.9998 -0.0461 -10.0000 9.9941], \t\tgradient = 2587.7373, step = LMIteration:56\tx = [-0.9996 -0.0687 -10.0000 9.9939], \t\tgradient = 1399.9325, step = LMIteration:57\tx = [-0.9993 -0.0928 -10.0000 9.9936], \t\tgradient = 743.3551, step = LMIteration:58\tx = [-0.9987 -0.1184 -10.0001 9.9931], \t\tgradient = 381.2687, step = LMIteration:59\tx = [-0.9976 -0.1456 -10.0001 9.9925], \t\tgradient = 183.0379, step = LMIteration:60\tx = [-0.9952 -0.1736 -10.0002 9.9917], \t\tgradient = 76.6425, step = LMIteration:61\tx = [-0.9894 -0.1972 -10.0005 9.9901], \t\tgradient = 26.4382, step = LMIteration:62\tx = [-0.9744 -0.2105 -10.0012 9.9871], \t\tgradient = 6.8472, step = LMIteration:63\tx = [-0.9336 -0.2136 -10.0030 9.9797], \t\tgradient = 4.4702, step = LMIteration:64\tx = [-0.8269 -0.2088 -10.0070 9.9631], \t\tgradient = 4.2573, step = LMIteration:65\tx = [-0.6379 -0.1953 -10.0103 9.9430], \t\tgradient = 6.5882, step = LMIteration:66\tx = [-0.5576 -0.1832 -10.0023 9.9499], \t\tgradient = 1.3240, step = LMIteration:67\tx = [-0.5559 -0.1827 -9.9933 9.9681], \t\tgradient = 0.0227, step = LMIteration:68\tx = [-0.5544 -0.1829 -10.0000 9.9888], \t\tgradient = 0.0087, step = LMIteration:69\tx = [-0.5527 -0.1832 -10.0389 10.0305], \t\tgradient = 0.0117, step = LMIteration:70\tx = [-0.5482 -0.1843 -10.1523 10.1442], \t\tgradient = 0.0548, step = LMIteration:71\tx = [-0.5372 -0.1868 -10.4402 10.4325], \t\tgradient = 0.2795, step = LMIteration:72\tx = [-0.5173 -0.1916 -11.0244 11.0175], \t\tgradient = 1.0133, step = LMIteration:73\tx = [-0.5025 -0.1958 -11.5877 11.5812], \t\tgradient = 0.7806, step = LMIteration:74\tx = [-0.4883 -0.2000 -12.1891 12.1835], \t\tgradient = 0.8407, step = LMIteration:75\tx = [-0.4787 -0.2030 -12.6707 12.6659], \t\tgradient = 0.4784, step = LMIteration:76\tx = [-0.4704 -0.2057 -13.1195 13.1156], \t\tgradient = 0.4040, step = LMIteration:77\tx = [-0.4656 -0.2073 -13.4055 13.4021], \t\tgradient = 0.1502, step = LMIteration:78\tx = [-0.4629 -0.2083 -13.5758 13.5728], \t\tgradient = 0.0525, step = LMIteration:79\tx = [-0.4622 -0.2085 -13.6183 13.6154], \t\tgradient = 0.0030, step = LMIteration:80\tx = [-0.4622 -0.2085 -13.6218 13.6188], \t\tgradient = 0.0000, step = LMIteration:81\tx = [-0.4622 -0.2085 -13.6218 13.6188], \t\tgradient = 0.0000, step = LMFinal estimated parameters: [-0.4622 -0.2085 -13.6218 13.6188]"
},
{
"code": null,
"e": 17681,
"s": 17242,
"text": "The algorithm runs for 81 iterations and produces parameter estimation result x* = [-0.46, -0.21, -13.62, 13.62] with ǁg(x*)ǁ ≈ 0. In other words, the algorithm successfully converges with the stopping criterion ǁgkǁ ≤ ε1 being met. It can also be seen that the algorithm always uses the LM method in curve-fitting the given data. This means that for every 3 successive iterations, there is one iterate xk that satisfies ǁgkǁ ≥ 0.02 ⋅ Fk."
},
{
"code": null,
"e": 29519,
"s": 17681,
"text": "Iteration:1\tx = [-4.0000 0.9500 2.0000 -2.9990], \t\tgradient = 5843944048763837440.0000, step = LMIteration:2\tx = [-4.0000 0.9001 2.0000 -2.9981], \t\tgradient = 798393836723220864.0000, step = LMIteration:3\tx = [-4.0000 0.8510 2.0000 -2.9973], \t\tgradient = 112511464378970688.0000, step = LMIteration:4\tx = [-4.0000 0.8050 2.0000 -2.9965], \t\tgradient = 17995869734728704.0000, step = LMIteration:5\tx = [-4.0000 0.7687 2.0000 -2.9959], \t\tgradient = 4224958744295105.0000, step = LMIteration:6\tx = [-4.0000 0.7454 2.0000 -2.9955], \t\tgradient = 1674832246409442.5000, step = LMIteration:7\tx = [-4.0000 0.7283 2.0000 -2.9952], \t\tgradient = 847705835813273.6250, step = LMIteration:8\tx = [-4.0000 0.7128 2.0000 -2.9950], \t\tgradient = 455980000478269.1875, step = LMIteration:9\tx = [-4.0000 0.6975 2.0000 -2.9947], \t\tgradient = 248446618239291.2812, step = LMIteration:10\tx = [-4.0000 0.6823 2.0000 -2.9945], \t\tgradient = 135727074063636.5469, step = LMIteration:11\tx = [-4.0000 0.6671 2.0000 -2.9942], \t\tgradient = 74188516827416.2656, step = LMIteration:12\tx = [-4.0000 0.6519 2.0000 -2.9940], \t\tgradient = 40556383042130.0234, step = LMIteration:13\tx = [-4.0000 0.6367 2.0000 -2.9937], \t\tgradient = 22171597557325.9102, step = LMIteration:14\tx = [-4.0000 0.6215 2.0000 -2.9934], \t\tgradient = 12121123175141.8398, step = LMIteration:15\tx = [-4.0000 0.6063 2.0000 -2.9932], \t\tgradient = 6626677353862.0400, step = LMIteration:16\tx = [-4.0000 0.5910 2.0000 -2.9929], \t\tgradient = 3622898207455.6821, step = LMIteration:17\tx = [-4.0000 0.5758 2.0000 -2.9927], \t\tgradient = 1980725783949.0017, step = LMIteration:18\tx = [-4.0000 0.5606 2.0000 -2.9924], \t\tgradient = 1082932002365.9087, step = LMIteration:19\tx = [-4.0000 0.5453 2.0000 -2.9922], \t\tgradient = 592089574010.1783, step = LMIteration:20\tx = [-4.0000 0.5300 2.0000 -2.9919], \t\tgradient = 323730717048.8542, step = LMIteration:21\tx = [-4.0000 0.5148 2.0000 -2.9916], \t\tgradient = 177007495788.6531, step = LMIteration:22\tx = [-4.0000 0.4995 2.0000 -2.9914], \t\tgradient = 96785827387.7305, step = LMIteration:23\tx = [-4.0000 0.4842 2.0000 -2.9911], \t\tgradient = 52923125898.6776, step = LMIteration:24\tx = [-4.0000 0.4688 2.0000 -2.9909], \t\tgradient = 28939714442.5817, step = LMIteration:25\tx = [-4.0000 0.4535 2.0000 -2.9906], \t\tgradient = 15825580540.4678, step = LMIteration:26\tx = [-4.0000 0.4381 2.0000 -2.9903], \t\tgradient = 8654531799.0783, step = LMIteration:27\tx = [-4.0000 0.4228 2.0000 -2.9901], \t\tgradient = 4733127210.2534, step = LMIteration:28\tx = [-4.0000 0.4074 2.0000 -2.9898], \t\tgradient = 2588665603.7885, step = LMIteration:29\tx = [-4.0000 0.3919 2.0000 -2.9895], \t\tgradient = 1415891078.6356, step = LMIteration:30\tx = [-4.0000 0.3765 2.0000 -2.9893], \t\tgradient = 774485568.1282, step = LMIteration:31\tx = [-4.0000 0.3610 2.0000 -2.9890], \t\tgradient = 423672773.1613, step = LMIteration:32\tx = [-4.0000 0.3455 2.0000 -2.9887], \t\tgradient = 231785640.8201, step = LMIteration:33\tx = [-4.0000 0.3300 2.0000 -2.9885], \t\tgradient = 126819882.7775, step = LMIteration:34\tx = [-4.0000 0.3144 2.0000 -2.9882], \t\tgradient = 69396974.7767, step = LMIteration:35\tx = [-4.0000 0.2988 2.0000 -2.9879], \t\tgradient = 37980046.8186, step = LMIteration:36\tx = [-4.0000 0.2831 2.0000 -2.9876], \t\tgradient = 20789502.5936, step = LMIteration:37\tx = [-4.0000 0.2674 2.0000 -2.9874], \t\tgradient = 11382078.3240, step = LMIteration:38\tx = [-4.0000 0.2516 2.0000 -2.9871], \t\tgradient = 6233151.4407, step = LMIteration:39\tx = [-4.0000 0.2358 2.0000 -2.9868], \t\tgradient = 3414510.4438, step = LMIteration:40\tx = [-4.0000 0.2198 2.0000 -2.9865], \t\tgradient = 1871192.9516, step = LMIteration:41\tx = [-4.0000 0.2038 2.0000 -2.9862], \t\tgradient = 1025947.0256, step = LMIteration:42\tx = [-4.0000 0.1877 2.0000 -2.9859], \t\tgradient = 562874.5612, step = LMIteration:43\tx = [-4.0000 0.1714 2.0000 -2.9856], \t\tgradient = 309077.3735, step = LMIteration:44\tx = [-4.0000 0.1550 2.0000 -2.9853], \t\tgradient = 169908.6045, step = LMIteration:45\tx = [-4.0000 0.1384 2.0000 -2.9850], \t\tgradient = 93547.0603, step = LMIteration:46\tx = [-4.0000 0.1215 2.0000 -2.9847], \t\tgradient = 51612.8671, step = LMIteration:47\tx = [-4.0000 0.1044 2.0000 -2.9843], \t\tgradient = 28559.4009, step = LMIteration:48\tx = [-4.0000 0.0869 2.0000 -2.9839], \t\tgradient = 15867.2252, step = LMIteration:49\tx = [-4.0000 0.0688 2.0000 -2.9835], \t\tgradient = 8865.7762, step = LMIteration:50\tx = [-4.0000 0.0500 2.0000 -2.9830], \t\tgradient = 4993.1844, step = LMIteration:51\tx = [-4.0000 0.0303 2.0000 -2.9825], \t\tgradient = 2843.2836, step = LMIteration:52\tx = [-4.0000 0.0092 2.0000 -2.9818], \t\tgradient = 1643.5749, step = LMIteration:53\tx = [-4.0000 -0.0138 2.0000 -2.9809], \t\tgradient = 969.1664, step = LMIteration:54\tx = [-4.0000 -0.0397 2.0001 -2.9798], \t\tgradient = 585.9656, step = LMIteration:55\tx = [-4.0000 -0.0695 2.0001 -2.9782], \t\tgradient = 364.7187, step = LMIteration:56\tx = [-4.0000 -0.1047 2.0003 -2.9760], \t\tgradient = 233.9465, step = LMIteration:57\tx = [-4.0000 -0.1465 2.0005 -2.9730], \t\tgradient = 154.2224, step = LMIteration:58\tx = [-4.0000 -0.1954 2.0008 -2.9690], \t\tgradient = 103.9455, step = LMIteration:59\tx = [-4.0000 -0.2516 2.0014 -2.9638], \t\tgradient = 71.2219, step = LMIteration:60\tx = [-4.0000 -0.3152 2.0023 -2.9571], \t\tgradient = 49.3390, step = LMIteration:61\tx = [-4.0000 -0.3865 2.0037 -2.9486], \t\tgradient = 34.3994, step = LMIteration:62\tx = [-4.0000 -0.4659 2.0060 -2.9378], \t\tgradient = 24.0583, step = LMIteration:63\tx = [-3.9999 -0.5540 2.0095 -2.9242], \t\tgradient = 16.8404, step = LMIteration:64\tx = [-3.9999 -0.6510 2.0148 -2.9069], \t\tgradient = 11.7791, step = LMIteration:65\tx = [-3.9998 -0.7574 2.0228 -2.8848], \t\tgradient = 8.2216, step = LMIteration:66\tx = [-3.9998 -0.8733 2.0348 -2.8567], \t\tgradient = 5.7186, step = LMIteration:67\tx = [-3.9996 -0.9990 2.0522 -2.8209], \t\tgradient = 3.9571, step = LMIteration:68\tx = [-3.9995 -1.1349 2.0768 -2.7754], \t\tgradient = 2.7180, step = LMIteration:69\tx = [-3.9992 -1.2813 2.1103 -2.7183], \t\tgradient = 1.8476, step = LMIteration:70\tx = [-3.9987 -1.4390 2.1533 -2.6485], \t\tgradient = 1.2392, step = LMIteration:71\tx = [-3.9980 -1.6079 2.2038 -2.5681], \t\tgradient = 0.8190, step = LMIteration:72\tx = [-3.9968 -1.7865 2.2547 -2.4842], \t\tgradient = 0.5357, step = LMIteration:73\tx = [-3.9949 -1.9699 2.2945 -2.4089], \t\tgradient = 0.3513, step = LMIteration:74\tx = [-3.9920 -2.1517 2.3148 -2.3524], \t\tgradient = 0.2345, step = LMIteration:75\tx = [-3.9878 -2.3283 2.3156 -2.3155], \t\tgradient = 0.1603, step = LMIteration:76\tx = [-3.9863 -2.3635 2.3124 -2.3081], \t\tgradient = 0.1487, step = QNIteration:77\tx = [-3.9803 -2.4682 2.2972 -2.2863], \t\tgradient = 0.1189, step = QNIteration:78\tx = [-3.9577 -2.7803 2.2395 -2.2211], \t\tgradient = 0.0613, step = QNIteration:79\tx = [-3.9319 -3.0541 2.1785 -2.1639], \t\tgradient = 0.0344, step = QNIteration:80\tx = [-3.9000 -3.3271 2.1135 -2.1068], \t\tgradient = 0.0193, step = QNIteration:81\tx = [-3.8784 -3.4807 2.0776 -2.0748], \t\tgradient = 0.0140, step = QNIteration:82\tx = [-3.8657 -3.5574 2.0604 -2.0588], \t\tgradient = 0.0119, step = QNIteration:83\tx = [-3.8510 -3.6338 2.0437 -2.0428], \t\tgradient = 0.0101, step = QNIteration:84\tx = [-3.8335 -3.7098 2.0276 -2.0269], \t\tgradient = 0.0086, step = QNIteration:85\tx = [-3.8227 -3.7473 2.0198 -2.0191], \t\tgradient = 0.0080, step = QNIteration:86\tx = [-3.8090 -3.7840 2.0123 -2.0114], \t\tgradient = 0.0074, step = QNIteration:87\tx = [-3.7911 -3.8190 2.0053 -2.0041], \t\tgradient = 0.0073, step = QNIteration:88\tx = [-3.7664 -3.8489 1.9996 -1.9979], \t\tgradient = 0.0076, step = QNIteration:89\tx = [-3.7581 -3.8559 1.9998 -1.9981], \t\tgradient = 0.0077, step = LMIteration:90\tx = [-3.7330 -3.8766 2.0004 -1.9986], \t\tgradient = 0.0081, step = LMIteration:91\tx = [-3.6535 -3.9361 2.0028 -2.0011], \t\tgradient = 0.0096, step = LMIteration:92\tx = [-3.3739 -4.0948 2.0180 -2.0161], \t\tgradient = 0.0168, step = LMIteration:93\tx = [-1.8970 -4.4431 2.1579 -2.1553], \t\tgradient = 0.3573, step = LMIteration:94\tx = [-1.8970 -4.4431 2.1579 -2.1553], \t\tgradient = 0.3573, step = LMIteration:95\tx = [-1.8970 -4.4431 2.1579 -2.1553], \t\tgradient = 0.3573, step = LMIteration:96\tx = [-1.8970 -4.4431 2.1579 -2.1553], \t\tgradient = 0.3573, step = LMIteration:97\tx = [-0.4821 -4.4514 2.3330 -2.2979], \t\tgradient = 12.9667, step = LMIteration:98\tx = [-0.4821 -4.4514 2.3330 -2.2979], \t\tgradient = 12.9667, step = LMIteration:99\tx = [-0.4821 -4.4514 2.3330 -2.2979], \t\tgradient = 12.9667, step = LMIteration:100\tx = [-0.4821 -4.4514 2.3330 -2.2979], \t\tgradient = 12.9667, step = LMIteration:101\tx = [-0.4821 -4.4514 2.3330 -2.2979], \t\tgradient = 12.9667, step = LMIteration:102\tx = [-0.3361 -4.4514 2.3517 -2.2985], \t\tgradient = 23.2634, step = LMIteration:103\tx = [-0.3361 -4.4514 2.3517 -2.2985], \t\tgradient = 23.2634, step = LMIteration:104\tx = [-0.0195 -4.4514 2.3844 -2.3000], \t\tgradient = 141.8487, step = LMIteration:105\tx = [-0.0542 -4.4514 2.5491 -2.3129], \t\tgradient = 2.7825, step = LMIteration:106\tx = [-0.0622 -4.4515 2.7408 -2.3468], \t\tgradient = 3.8567, step = LMIteration:107\tx = [-0.0733 -4.4516 3.1240 -2.5063], \t\tgradient = 5.6536, step = LMIteration:108\tx = [-0.0887 -4.4519 3.7063 -3.0302], \t\tgradient = 7.1668, step = LMIteration:109\tx = [-0.1056 -4.4518 4.4259 -4.0061], \t\tgradient = 6.3086, step = LMIteration:110\tx = [-0.1190 -4.4484 5.0608 -4.9286], \t\tgradient = 3.4276, step = LMIteration:111\tx = [-0.1236 -4.4311 5.3256 -5.3076], \t\tgradient = 0.7579, step = LMIteration:112\tx = [-0.1239 -4.3717 5.3572 -5.3565], \t\tgradient = 0.0396, step = LMIteration:113\tx = [-0.1239 -4.1687 5.3583 -5.3584], \t\tgradient = 0.0016, step = LMIteration:114\tx = [-0.1240 -3.2559 5.3610 -5.3611], \t\tgradient = 0.0427, step = LMIteration:115\tx = [-0.1240 -3.2559 5.3610 -5.3611], \t\tgradient = 0.0427, step = LMIteration:116\tx = [-0.1240 -3.2559 5.3610 -5.3611], \t\tgradient = 0.0427, step = LMIteration:117\tx = [-0.1248 -1.1768 5.4018 -5.4026], \t\tgradient = 4.7877, step = LMIteration:118\tx = [-0.1248 -1.1768 5.4018 -5.4026], \t\tgradient = 4.7877, step = LMIteration:119\tx = [-0.1248 -1.1768 5.4018 -5.4026], \t\tgradient = 4.7877, step = LMIteration:120\tx = [-0.1248 -1.1768 5.4018 -5.4026], \t\tgradient = 4.7877, step = LMIteration:121\tx = [-0.1248 -1.1768 5.4018 -5.4026], \t\tgradient = 4.7877, step = LMIteration:122\tx = [-0.1244 -1.1290 5.5183 -5.4517], \t\tgradient = 0.1904, step = LMIteration:123\tx = [-0.1292 -1.0057 5.7614 -5.6610], \t\tgradient = 1.1816, step = LMIteration:124\tx = [-0.1382 -0.8383 6.2791 -6.1944], \t\tgradient = 3.1482, step = LMIteration:125\tx = [-0.1464 -0.7806 6.8138 -6.7630], \t\tgradient = 1.7846, step = LMIteration:126\tx = [-0.1599 -0.6524 7.7451 -7.7208], \t\tgradient = 5.7805, step = LMIteration:127\tx = [-0.1658 -0.6428 8.2978 -8.2944], \t\tgradient = 0.8161, step = LMIteration:128\tx = [-0.1770 -0.5710 9.2787 -9.2788], \t\tgradient = 4.5341, step = LMIteration:129\tx = [-0.1818 -0.5588 9.8477 -9.8546], \t\tgradient = 0.7032, step = LMIteration:130\tx = [-0.1902 -0.5204 10.7897 -10.7955], \t\tgradient = 2.9184, step = LMIteration:131\tx = [-0.1941 -0.5090 11.3439 -11.3510], \t\tgradient = 0.6201, step = LMIteration:132\tx = [-0.1999 -0.4878 12.1563 -12.1617], \t\tgradient = 1.6519, step = LMIteration:133\tx = [-0.2027 -0.4799 12.6128 -12.6178], \t\tgradient = 0.3816, step = LMIteration:134\tx = [-0.2059 -0.4697 13.1434 -13.1472], \t\tgradient = 0.5800, step = LMIteration:135\tx = [-0.2073 -0.4656 13.4035 -13.4068], \t\tgradient = 0.1173, step = LMIteration:136\tx = [-0.2082 -0.4629 13.5699 -13.5729], \t\tgradient = 0.0504, step = LMIteration:137\tx = [-0.2085 -0.4622 13.6148 -13.6177], \t\tgradient = 0.0034, step = LMIteration:138\tx = [-0.2085 -0.4622 13.6188 -13.6218], \t\tgradient = 0.0000, step = LMIteration:139\tx = [-0.2085 -0.4622 13.6188 -13.6218], \t\tgradient = 0.0000, step = LMFinal estimated parameters: [-0.2085 -0.4622 13.6188 -13.6218]"
},
{
"code": null,
"e": 30306,
"s": 29519,
"text": "The algorithm runs as many as 139 iterations and produces parameter estimation result x* = [-0.21, -0.46, 13.62, -13.62] with ǁg(x*)ǁ ≈ 0. In other words, the algorithm successfully converges with the stopping criterion ǁgkǁ ≤ ε1 being met. It can also be seen that during the curve fitting of the given data, the algorithm changes the step method to QN at iterations 76–88 before changing back to LM. This means that in the last 3 iterations before iteration 76, no iterate xk satisfies ǁgkǁ ≥ 0.02 ⋅ Fk so that the QN method is considered able to converge more quickly than the LM method after iteration 76. Then, at iteration 88, we get ǁgk+1ǁ ≥ ǁgkǁ which means the gradient does not decrease fast enough using the QN method so that the method switches to LM for the next iteration."
},
{
"code": null,
"e": 30587,
"s": 30306,
"text": "Because the initial value x0 is quite far from the solution, more iterations are needed than that in Scenario 1. Also, note that so far there are two solutions that satisfy the convergence value x*, namely x* = [-0.46, -0.21, -13.62, 13.62] and x* = [-0.21, -0.46, 13.62, -13.62]."
},
{
"code": null,
"e": 41799,
"s": 30587,
"text": "Iteration:1\tx = [0.0000 0.0000 0.7705 0.7705], \t\tgradient = 42.5292, step = LMIteration:2\tx = [-0.0815 -0.0815 1.3987 1.3987], \t\tgradient = 16.7516, step = LMIteration:3\tx = [-0.0400 -0.0400 1.2150 1.2150], \t\tgradient = 18.3468, step = LMIteration:4\tx = [-0.0607 -0.0695 1.3851 1.3851], \t\tgradient = 4.8184, step = LMIteration:5\tx = [-0.0607 -0.0695 1.3851 1.3851], \t\tgradient = 4.8184, step = LMIteration:6\tx = [-0.0607 -0.0695 1.3851 1.3851], \t\tgradient = 4.8184, step = LMIteration:7\tx = [-0.0607 -0.0695 1.3851 1.3851], \t\tgradient = 4.8184, step = LMIteration:8\tx = [-0.0607 -0.0695 1.3851 1.3851], \t\tgradient = 4.8184, step = LMIteration:9\tx = [-0.0607 -0.0695 1.3851 1.3851], \t\tgradient = 4.8184, step = LMIteration:10\tx = [-0.0631 -0.0584 1.3830 1.3830], \t\tgradient = 1.3008, step = LMIteration:11\tx = [-0.0596 -0.0627 1.3811 1.3811], \t\tgradient = 0.4178, step = LMIteration:12\tx = [-0.0620 -0.0601 1.3793 1.3792], \t\tgradient = 0.2770, step = LMIteration:13\tx = [-0.0604 -0.0616 1.3775 1.3775], \t\tgradient = 0.2522, step = LMIteration:14\tx = [-0.0613 -0.0605 1.3758 1.3757], \t\tgradient = 0.2432, step = LMIteration:15\tx = [-0.0604 -0.0612 1.3737 1.3737], \t\tgradient = 0.2332, step = LMIteration:16\tx = [-0.0615 -0.0597 1.3708 1.3708], \t\tgradient = 0.2541, step = LMIteration:17\tx = [-0.0582 -0.0627 1.3678 1.3677], \t\tgradient = 0.6396, step = LMIteration:18\tx = [-0.0582 -0.0627 1.3678 1.3677], \t\tgradient = 0.6396, step = LMIteration:19\tx = [-0.0607 -0.0600 1.3668 1.3668], \t\tgradient = 0.1995, step = LMIteration:20\tx = [-0.0603 -0.0604 1.3658 1.3658], \t\tgradient = 0.1930, step = LMIteration:21\tx = [-0.0603 -0.0601 1.3639 1.3638], \t\tgradient = 0.1840, step = LMIteration:22\tx = [-0.0593 -0.0605 1.3587 1.3586], \t\tgradient = 0.2076, step = LMIteration:23\tx = [-0.0593 -0.0605 1.3587 1.3586], \t\tgradient = 0.2076, step = LMIteration:24\tx = [-0.0593 -0.0605 1.3587 1.3586], \t\tgradient = 0.2076, step = LMIteration:25\tx = [-0.0608 -0.0590 1.3571 1.3570], \t\tgradient = 0.2311, step = LMIteration:26\tx = [-0.0584 -0.0611 1.3556 1.3555], \t\tgradient = 0.3672, step = LMIteration:27\tx = [-0.0609 -0.0586 1.3545 1.3544], \t\tgradient = 0.3171, step = LMIteration:28\tx = [-0.0590 -0.0603 1.3536 1.3536], \t\tgradient = 0.1788, step = LMIteration:29\tx = [-0.0600 -0.0593 1.3528 1.3527], \t\tgradient = 0.1280, step = LMIteration:30\tx = [-0.0594 -0.0598 1.3519 1.3519], \t\tgradient = 0.1237, step = LMIteration:31\tx = [-0.0597 -0.0594 1.3510 1.3510], \t\tgradient = 0.1192, step = LMIteration:32\tx = [-0.0597 -0.0594 1.3508 1.3510], \t\tgradient = 0.1183, step = QNIteration:33\tx = [-0.0597 -0.0594 1.3500 1.3510], \t\tgradient = 0.1155, step = QNIteration:34\tx = [-0.0596 -0.0594 1.3475 1.3510], \t\tgradient = 0.1084, step = QNIteration:35\tx = [-0.0592 -0.0594 1.3401 1.3510], \t\tgradient = 0.1055, step = QNIteration:36\tx = [-0.0589 -0.0594 1.3328 1.3510], \t\tgradient = 0.2028, step = QNIteration:37\tx = [-0.0595 -0.0585 1.3319 1.3501], \t\tgradient = 0.1538, step = LMIteration:38\tx = [-0.0595 -0.0585 1.3319 1.3501], \t\tgradient = 0.1538, step = LMIteration:39\tx = [-0.0587 -0.0592 1.3314 1.3496], \t\tgradient = 0.0704, step = LMIteration:40\tx = [-0.0591 -0.0588 1.3310 1.3492], \t\tgradient = 0.0640, step = LMIteration:41\tx = [-0.0588 -0.0590 1.3306 1.3488], \t\tgradient = 0.0618, step = LMIteration:42\tx = [-0.0588 -0.0590 1.3304 1.3488], \t\tgradient = 0.0615, step = QNIteration:43\tx = [-0.0588 -0.0590 1.3300 1.3488], \t\tgradient = 0.0610, step = QNIteration:44\tx = [-0.0587 -0.0590 1.3288 1.3488], \t\tgradient = 0.0582, step = QNIteration:45\tx = [-0.0586 -0.0590 1.3275 1.3488], \t\tgradient = 0.0571, step = QNIteration:46\tx = [-0.0586 -0.0590 1.3263 1.3488], \t\tgradient = 0.0554, step = QNIteration:47\tx = [-0.0585 -0.0590 1.3251 1.3488], \t\tgradient = 0.0646, step = QNIteration:48\tx = [-0.0590 -0.0585 1.3247 1.3484], \t\tgradient = 0.0576, step = LMIteration:49\tx = [-0.0585 -0.0589 1.3243 1.3481], \t\tgradient = 0.0494, step = LMIteration:50\tx = [-0.0589 -0.0585 1.3240 1.3477], \t\tgradient = 0.0455, step = LMIteration:51\tx = [-0.0585 -0.0588 1.3237 1.3474], \t\tgradient = 0.0409, step = LMIteration:52\tx = [-0.0588 -0.0585 1.3233 1.3471], \t\tgradient = 0.0393, step = LMIteration:53\tx = [-0.0585 -0.0588 1.3230 1.3468], \t\tgradient = 0.0377, step = LMIteration:54\tx = [-0.0588 -0.0585 1.3228 1.3465], \t\tgradient = 0.0363, step = LMIteration:55\tx = [-0.0585 -0.0587 1.3225 1.3462], \t\tgradient = 0.0348, step = LMIteration:56\tx = [-0.0587 -0.0585 1.3222 1.3459], \t\tgradient = 0.0335, step = LMIteration:57\tx = [-0.0585 -0.0587 1.3219 1.3457], \t\tgradient = 0.0321, step = LMIteration:58\tx = [-0.0587 -0.0585 1.3217 1.3454], \t\tgradient = 0.0307, step = LMIteration:59\tx = [-0.0584 -0.0587 1.3214 1.3452], \t\tgradient = 0.0294, step = LMIteration:60\tx = [-0.0587 -0.0584 1.3212 1.3449], \t\tgradient = 0.0319, step = LMIteration:61\tx = [-0.0584 -0.0587 1.3209 1.3447], \t\tgradient = 0.0330, step = LMIteration:62\tx = [-0.0587 -0.0584 1.3207 1.3445], \t\tgradient = 0.0357, step = LMIteration:63\tx = [-0.0584 -0.0587 1.3205 1.3442], \t\tgradient = 0.0362, step = LMIteration:64\tx = [-0.0586 -0.0584 1.3203 1.3440], \t\tgradient = 0.0363, step = LMIteration:65\tx = [-0.0584 -0.0586 1.3201 1.3439], \t\tgradient = 0.0321, step = LMIteration:66\tx = [-0.0586 -0.0584 1.3199 1.3437], \t\tgradient = 0.0281, step = LMIteration:67\tx = [-0.0584 -0.0586 1.3198 1.3435], \t\tgradient = 0.0228, step = LMIteration:68\tx = [-0.0585 -0.0584 1.3196 1.3434], \t\tgradient = 0.0203, step = LMIteration:69\tx = [-0.0584 -0.0585 1.3195 1.3432], \t\tgradient = 0.0195, step = LMIteration:70\tx = [-0.0585 -0.0584 1.3193 1.3431], \t\tgradient = 0.0188, step = LMIteration:71\tx = [-0.0584 -0.0585 1.3192 1.3429], \t\tgradient = 0.0181, step = LMIteration:72\tx = [-0.0585 -0.0584 1.3190 1.3428], \t\tgradient = 0.0174, step = LMIteration:73\tx = [-0.0584 -0.0585 1.3189 1.3426], \t\tgradient = 0.0166, step = LMIteration:74\tx = [-0.0585 -0.0583 1.3187 1.3425], \t\tgradient = 0.0175, step = LMIteration:75\tx = [-0.0583 -0.0585 1.3186 1.3423], \t\tgradient = 0.0212, step = LMIteration:76\tx = [-0.0585 -0.0583 1.3185 1.3422], \t\tgradient = 0.0264, step = LMIteration:77\tx = [-0.0583 -0.0585 1.3183 1.3421], \t\tgradient = 0.0264, step = LMIteration:78\tx = [-0.0585 -0.0583 1.3182 1.3420], \t\tgradient = 0.0201, step = LMIteration:79\tx = [-0.0583 -0.0584 1.3182 1.3419], \t\tgradient = 0.0130, step = LMIteration:80\tx = [-0.0584 -0.0583 1.3181 1.3418], \t\tgradient = 0.0124, step = LMIteration:81\tx = [-0.0584 -0.0584 1.3180 1.3417], \t\tgradient = 0.0120, step = LMIteration:82\tx = [-0.0584 -0.0583 1.3179 1.3416], \t\tgradient = 0.0115, step = LMIteration:83\tx = [-0.0583 -0.0584 1.3178 1.3415], \t\tgradient = 0.0110, step = LMIteration:84\tx = [-0.0584 -0.0583 1.3176 1.3414], \t\tgradient = 0.0186, step = LMIteration:85\tx = [-0.0584 -0.0583 1.3176 1.3414], \t\tgradient = 0.0186, step = LMIteration:86\tx = [-0.0583 -0.0584 1.3176 1.3413], \t\tgradient = 0.0112, step = LMIteration:87\tx = [-0.0584 -0.0583 1.3175 1.3412], \t\tgradient = 0.0095, step = LMIteration:88\tx = [-0.0583 -0.0584 1.3174 1.3412], \t\tgradient = 0.0092, step = LMIteration:89\tx = [-0.0583 -0.0584 1.3174 1.3412], \t\tgradient = 0.0090, step = QNIteration:90\tx = [-0.0583 -0.0584 1.3173 1.3412], \t\tgradient = 0.0260, step = QNIteration:91\tx = [-0.0584 -0.0583 1.3173 1.3411], \t\tgradient = 0.0085, step = LMIteration:92\tx = [-0.0583 -0.0584 1.3172 1.3411], \t\tgradient = 0.0083, step = LMIteration:93\tx = [-0.0583 -0.0583 1.3171 1.3410], \t\tgradient = 0.0080, step = LMIteration:94\tx = [-0.0583 -0.0583 1.3171 1.3409], \t\tgradient = 0.0077, step = LMIteration:95\tx = [-0.0584 -0.0583 1.3170 1.3409], \t\tgradient = 0.0075, step = LMIteration:96\tx = [-0.0583 -0.0584 1.3169 1.3408], \t\tgradient = 0.0110, step = LMIteration:97\tx = [-0.0584 -0.0582 1.3169 1.3407], \t\tgradient = 0.0165, step = LMIteration:98\tx = [-0.0583 -0.0584 1.3168 1.3407], \t\tgradient = 0.0109, step = LMIteration:99\tx = [-0.0583 -0.0583 1.3168 1.3406], \t\tgradient = 0.0062, step = LMIteration:100\tx = [-0.0583 -0.0583 1.3167 1.3406], \t\tgradient = 0.0059, step = LMIteration:101\tx = [-0.0583 -0.0583 1.3167 1.3406], \t\tgradient = 0.0057, step = LMIteration:102\tx = [-0.0583 -0.0583 1.3167 1.3405], \t\tgradient = 0.0055, step = LMIteration:103\tx = [-0.0583 -0.0583 1.3166 1.3404], \t\tgradient = 0.0075, step = LMIteration:104\tx = [-0.0583 -0.0583 1.3166 1.3404], \t\tgradient = 0.0075, step = LMIteration:105\tx = [-0.0583 -0.0583 1.3165 1.3404], \t\tgradient = 0.0090, step = LMIteration:106\tx = [-0.0583 -0.0583 1.3165 1.3403], \t\tgradient = 0.0099, step = LMIteration:107\tx = [-0.0583 -0.0583 1.3164 1.3403], \t\tgradient = 0.0064, step = LMIteration:108\tx = [-0.0583 -0.0583 1.3164 1.3403], \t\tgradient = 0.0064, step = QNIteration:109\tx = [-0.0583 -0.0583 1.3164 1.3403], \t\tgradient = 0.0043, step = LMIteration:110\tx = [-0.0583 -0.0583 1.3164 1.3402], \t\tgradient = 0.0041, step = LMIteration:111\tx = [-0.0583 -0.0583 1.3164 1.3402], \t\tgradient = 0.0040, step = LMIteration:112\tx = [-0.0583 -0.0583 1.3163 1.3402], \t\tgradient = 0.0038, step = LMIteration:113\tx = [-0.0583 -0.0583 1.3163 1.3401], \t\tgradient = 0.0050, step = LMIteration:114\tx = [-0.0583 -0.0583 1.3163 1.3401], \t\tgradient = 0.0050, step = LMIteration:115\tx = [-0.0583 -0.0583 1.3162 1.3401], \t\tgradient = 0.0045, step = LMIteration:116\tx = [-0.0583 -0.0583 1.3162 1.3401], \t\tgradient = 0.0044, step = LMIteration:117\tx = [-0.0583 -0.0583 1.3162 1.3400], \t\tgradient = 0.0040, step = LMIteration:118\tx = [-0.0583 -0.0583 1.3162 1.3400], \t\tgradient = 0.0040, step = QNIteration:119\tx = [-0.0583 -0.0583 1.3162 1.3400], \t\tgradient = 0.0037, step = LMIteration:120\tx = [-0.0583 -0.0583 1.3161 1.3400], \t\tgradient = 0.0032, step = LMIteration:121\tx = [-0.0583 -0.0583 1.3161 1.3400], \t\tgradient = 0.0030, step = LMIteration:122\tx = [-0.0583 -0.0583 1.3161 1.3400], \t\tgradient = 0.0027, step = LMIteration:123\tx = [-0.0583 -0.0583 1.3161 1.3399], \t\tgradient = 0.0026, step = LMIteration:124\tx = [-0.0583 -0.0583 1.3161 1.3399], \t\tgradient = 0.0025, step = LMIteration:125\tx = [-0.0583 -0.0583 1.3160 1.3399], \t\tgradient = 0.0024, step = LMIteration:126\tx = [-0.0583 -0.0583 1.3160 1.3399], \t\tgradient = 0.0023, step = LMIteration:127\tx = [-0.0583 -0.0583 1.3160 1.3399], \t\tgradient = 0.0022, step = LMIteration:128\tx = [-0.0583 -0.0583 1.3160 1.3398], \t\tgradient = 0.0021, step = LMIteration:129\tx = [-0.0583 -0.0583 1.3160 1.3398], \t\tgradient = 0.0020, step = LMIteration:130\tx = [-0.0583 -0.0583 1.3160 1.3398], \t\tgradient = 0.0020, step = LMIteration:131\tx = [-0.0583 -0.0583 1.3159 1.3398], \t\tgradient = 0.0022, step = LMIteration:132\tx = [-0.0583 -0.0583 1.3159 1.3398], \t\tgradient = 0.0024, step = LMIteration:133\tx = [-0.0583 -0.0583 1.3159 1.3398], \t\tgradient = 0.0026, step = LMIteration:134\tx = [-0.0583 -0.0583 1.3159 1.3397], \t\tgradient = 0.0025, step = LMIteration:135\tx = [-0.0583 -0.0583 1.3159 1.3397], \t\tgradient = 0.0023, step = LMIteration:136\tx = [-0.0583 -0.0583 1.3159 1.3397], \t\tgradient = 0.0018, step = LMIteration:137\tx = [-0.0583 -0.0583 1.3159 1.3397], \t\tgradient = 0.0015, step = LMIteration:138\tx = [-0.0583 -0.0583 1.3158 1.3397], \t\tgradient = 0.0014, step = LMIteration:139\tx = [-0.0583 -0.0583 1.3158 1.3397], \t\tgradient = 0.0014, step = LMFinal estimated parameters: [-0.0583 -0.0583 1.3158 1.3397]"
},
{
"code": null,
"e": 42363,
"s": 41799,
"text": "The algorithm runs for 139 iterations and produces parameter estimation result x* = [-0.06, -0.06, 1.32, 1.34] with ǁgkǁ ≈ 0.0014 > ε1. In other words, the algorithm has not successfully converged, but the iteration has been terminated because the stopping criterion ǁhkǁ ≤ ε2 (ǁxkǁ + ε2) has been met. It can also be seen that during the curve fitting of the given data, the algorithm repeatedly changed the step method to QN and vice versa to LM for the reasons described in Scenario 2. From the graph above, obviously, the solution x* found is not good enough."
},
{
"code": null,
"e": 42846,
"s": 42363,
"text": "By looking at the value of x during iteration, it’s observed that x1 ≈ x2 and x3 ≈ x4. Hence, we can conclude that the selection of the initial value x0 = [0, 0, 0, 0] is a bad choice because the value is symmetrical and the algorithm is not able to break the symmetry. You can try and see the same thing happens in choosing other initial symmetrical values such as x0 = [-1, -1, -1, -1], x0 = [1, 1, 1, 1], or x0 = [2, 2, 2, 2]. Orrr, this is just a coincidence. What do you think?"
},
{
"code": null,
"e": 42901,
"s": 42846,
"text": "What else do you find interesting from the experiment?"
},
{
"code": null,
"e": 43347,
"s": 42901,
"text": "We’ve developed an efficient algorithm to solve a non-linear least squares problem. This algorithm combines Levenberg-Marquardt and Quasi-Newton methods, utilizing trust-region for the step choice. The algorithm can accurately find the best parameters of the model in superlinear convergence rate. However, poor parameter initialization may lead to bad results. In our study case, this algorithm finds the following two models that fit the data:"
},
{
"code": null,
"e": 43436,
"s": 43347,
"text": "Of course, these two models are equivalent by rearranging the components of parameter x."
},
{
"code": null,
"e": 43491,
"s": 43436,
"text": "You might want to continue reading my related stories:"
},
{
"code": null,
"e": 43504,
"s": 43491,
"text": "Albers Uzila"
},
{
"code": null,
"e": 43735,
"s": 43504,
"text": "Thanks! If you enjoy this story and want to support me as a writer, consider becoming a member. For only $5 a month, you’ll get unlimited access to all stories on Medium. If you sign up using my link, I’ll earn a small commission."
},
{
"code": null,
"e": 43881,
"s": 43735,
"text": "If you’re one of my referred Medium members, feel free to email me at geoclid.members[at]gmail.com to get the complete python code of this story."
}
] |
Convert comma separated string to array in PySpark dataframe - GeeksforGeeks
|
23 May, 2021
In this article, we will learn how to convert comma-separated string to array in pyspark dataframe.
In pyspark SQL, the split() function converts the delimiter separated String to an Array. It is done by splitting the string based on delimiters like spaces, commas, and stack them into an array. This function returns pyspark.sql.Column of type Array.
Syntax: pyspark.sql.functions.split(str, pattern, limit=-1)
Parameter:
str:- The string to be split.
limit:- an integer that controls the number of times pattern is applied
pattern:- The delimiter that is used to split the string.
Let’s look at few examples to understand the working of the code.
Example 1: Working with String Values
Let’s look at a sample example to see the split function in action. For this example, we have created our custom dataframe and use the split function to create a name contacting the name of the student. Here we are going to apply split to the string data format columns.
Python3
# import required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import split, col # start the spark sessionspark = SparkSession.builder \ .appName('GeeksforGeeks') \ .getOrCreate() # create the dataframedata = [("Pulkit, Dhingra","M",70), ("Ritika, Pandey","F",85), ("Kaif, Ali","M",63), ("Asha, Deep","F",62) ] columns=["Name","Gender","Marks"]df=spark.createDataFrame(data,columns) # use split function df2 = df.select(split(col("Name"),",").alias("Name_Arr"), col("Gender"),col("Marks")) \ .drop("Name") df2.show() # stop sessionspark.stop()
Output:
Example 2: Working with Integer Values
If we want to convert to the numeric type we can use the cast() function with split() function. In this example we are using the cast() function to build an array of integers, so we will use cast(ArrayType(IntegerType())) where it clearly specifies that we need to cast to an array of integer type.
Python3
# import required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import split, colfrom pyspark.sql.types import ArrayType, IntegerType # start the spark sessionspark = SparkSession.builder \ .appName('GeeksforGeeks') \ .getOrCreate() # create the dataframedata = [("Pulkit, Dhingra","M","70,85"), ("Ritika, Pandey","F","85,95"), ("Kaif, Ali","M","63,72"), ("Asha, Deep","F","62,92") ] columns=["Name","Gender","Marks"]df=spark.createDataFrame(data,columns)df.show() # use split function df2 = df.select(col("Name"),col("Gender"),split(col("Marks"),",").cast( ArrayType(IntegerType())).alias("Marks_Arr")) df2.show() # stop sessionspark.stop()
Output:
Example 3: Working with both Integer and String Values
There may be a condition where we need to check for each column and do split if a comma-separated column value exists. The split() function comes loaded with advantages. There might a condition where the separator is not present in a column. The split() function handles this situation by creating a single array of the column value in place of giving an exception. This may come in handy sometimes.
Python3
# If you want to convert data to numeric# types you can cast as followsimport findsparkfindspark.init('c:/spark') # import required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import split, colfrom pyspark.sql.types import ArrayType, IntegerType def return_array(column): return split(col(column),",") # start the spark sessionspark = SparkSession.builder \ .appName('GeeksforGeeks') \ .getOrCreate() # create the dataframedata = [("Pulkit, Dhingra","M","70,85"), ("Ritika, Pandey","F","85,95"), ("Kaif, Ali","M","63,72"), ("Asha, Deep","F","62,92") ] columns=["Name","Gender","Marks"]df=spark.createDataFrame(data,columns)df.show() # use split function df2 = df.select(split(col("Name"),",").alias("Name"), split(col("Gender"),",").alias("Gender"), split(col("Marks"),",").alias("Marks_Arr"))df2.show() # stop sessionspark.stop()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n23 May, 2021"
},
{
"code": null,
"e": 24392,
"s": 24292,
"text": "In this article, we will learn how to convert comma-separated string to array in pyspark dataframe."
},
{
"code": null,
"e": 24645,
"s": 24392,
"text": "In pyspark SQL, the split() function converts the delimiter separated String to an Array. It is done by splitting the string based on delimiters like spaces, commas, and stack them into an array. This function returns pyspark.sql.Column of type Array."
},
{
"code": null,
"e": 24705,
"s": 24645,
"text": "Syntax: pyspark.sql.functions.split(str, pattern, limit=-1)"
},
{
"code": null,
"e": 24716,
"s": 24705,
"text": "Parameter:"
},
{
"code": null,
"e": 24746,
"s": 24716,
"text": "str:- The string to be split."
},
{
"code": null,
"e": 24818,
"s": 24746,
"text": "limit:- an integer that controls the number of times pattern is applied"
},
{
"code": null,
"e": 24876,
"s": 24818,
"text": "pattern:- The delimiter that is used to split the string."
},
{
"code": null,
"e": 24942,
"s": 24876,
"text": "Let’s look at few examples to understand the working of the code."
},
{
"code": null,
"e": 24980,
"s": 24942,
"text": "Example 1: Working with String Values"
},
{
"code": null,
"e": 25251,
"s": 24980,
"text": "Let’s look at a sample example to see the split function in action. For this example, we have created our custom dataframe and use the split function to create a name contacting the name of the student. Here we are going to apply split to the string data format columns."
},
{
"code": null,
"e": 25259,
"s": 25251,
"text": "Python3"
},
{
"code": "# import required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import split, col # start the spark sessionspark = SparkSession.builder \\ .appName('GeeksforGeeks') \\ .getOrCreate() # create the dataframedata = [(\"Pulkit, Dhingra\",\"M\",70), (\"Ritika, Pandey\",\"F\",85), (\"Kaif, Ali\",\"M\",63), (\"Asha, Deep\",\"F\",62) ] columns=[\"Name\",\"Gender\",\"Marks\"]df=spark.createDataFrame(data,columns) # use split function df2 = df.select(split(col(\"Name\"),\",\").alias(\"Name_Arr\"), col(\"Gender\"),col(\"Marks\")) \\ .drop(\"Name\") df2.show() # stop sessionspark.stop()",
"e": 25912,
"s": 25259,
"text": null
},
{
"code": null,
"e": 25920,
"s": 25912,
"text": "Output:"
},
{
"code": null,
"e": 25959,
"s": 25920,
"text": "Example 2: Working with Integer Values"
},
{
"code": null,
"e": 26258,
"s": 25959,
"text": "If we want to convert to the numeric type we can use the cast() function with split() function. In this example we are using the cast() function to build an array of integers, so we will use cast(ArrayType(IntegerType())) where it clearly specifies that we need to cast to an array of integer type."
},
{
"code": null,
"e": 26266,
"s": 26258,
"text": "Python3"
},
{
"code": "# import required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import split, colfrom pyspark.sql.types import ArrayType, IntegerType # start the spark sessionspark = SparkSession.builder \\ .appName('GeeksforGeeks') \\ .getOrCreate() # create the dataframedata = [(\"Pulkit, Dhingra\",\"M\",\"70,85\"), (\"Ritika, Pandey\",\"F\",\"85,95\"), (\"Kaif, Ali\",\"M\",\"63,72\"), (\"Asha, Deep\",\"F\",\"62,92\") ] columns=[\"Name\",\"Gender\",\"Marks\"]df=spark.createDataFrame(data,columns)df.show() # use split function df2 = df.select(col(\"Name\"),col(\"Gender\"),split(col(\"Marks\"),\",\").cast( ArrayType(IntegerType())).alias(\"Marks_Arr\")) df2.show() # stop sessionspark.stop()",
"e": 26999,
"s": 26266,
"text": null
},
{
"code": null,
"e": 27007,
"s": 26999,
"text": "Output:"
},
{
"code": null,
"e": 27062,
"s": 27007,
"text": "Example 3: Working with both Integer and String Values"
},
{
"code": null,
"e": 27462,
"s": 27062,
"text": "There may be a condition where we need to check for each column and do split if a comma-separated column value exists. The split() function comes loaded with advantages. There might a condition where the separator is not present in a column. The split() function handles this situation by creating a single array of the column value in place of giving an exception. This may come in handy sometimes."
},
{
"code": null,
"e": 27470,
"s": 27462,
"text": "Python3"
},
{
"code": "# If you want to convert data to numeric# types you can cast as followsimport findsparkfindspark.init('c:/spark') # import required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import split, colfrom pyspark.sql.types import ArrayType, IntegerType def return_array(column): return split(col(column),\",\") # start the spark sessionspark = SparkSession.builder \\ .appName('GeeksforGeeks') \\ .getOrCreate() # create the dataframedata = [(\"Pulkit, Dhingra\",\"M\",\"70,85\"), (\"Ritika, Pandey\",\"F\",\"85,95\"), (\"Kaif, Ali\",\"M\",\"63,72\"), (\"Asha, Deep\",\"F\",\"62,92\") ] columns=[\"Name\",\"Gender\",\"Marks\"]df=spark.createDataFrame(data,columns)df.show() # use split function df2 = df.select(split(col(\"Name\"),\",\").alias(\"Name\"), split(col(\"Gender\"),\",\").alias(\"Gender\"), split(col(\"Marks\"),\",\").alias(\"Marks_Arr\"))df2.show() # stop sessionspark.stop()",
"e": 28407,
"s": 27470,
"text": null
},
{
"code": null,
"e": 28415,
"s": 28407,
"text": "Output:"
},
{
"code": null,
"e": 28422,
"s": 28415,
"text": "Picked"
},
{
"code": null,
"e": 28437,
"s": 28422,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 28444,
"s": 28437,
"text": "Python"
},
{
"code": null,
"e": 28542,
"s": 28444,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28574,
"s": 28542,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28616,
"s": 28574,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28672,
"s": 28616,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28714,
"s": 28672,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28745,
"s": 28714,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28800,
"s": 28745,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28822,
"s": 28800,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28861,
"s": 28822,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28890,
"s": 28861,
"text": "Create a directory in Python"
}
] |
Check if frequency of each character is equal to its position in English Alphabet - GeeksforGeeks
|
13 May, 2021
Given string str of lowercase alphabets, the task is to check if the frequency of each distinct characters in the string equals to its position in the English Alphabet. If valid, then print “Yes”, else print “No”.
Examples:
Input: str = “abbcccdddd” Output: Yes Explanation: Since frequency of each distinct character is equals to its position in English Alphabet, i.e. F(a) = 1, F(b) = 2, F(c) = 3, and F(d) = 4 Hence the output is Yes.
Input: str = “geeksforgeeks” Output: No
Approach:
Store the frequency of each character in an array of 26, for hashing purpose.Now traverse the hash array and check if the frequency of each character at an index i is equal to (i + 1) or not.If yes, then print “Yes”, Else print “No”.
Store the frequency of each character in an array of 26, for hashing purpose.
Now traverse the hash array and check if the frequency of each character at an index i is equal to (i + 1) or not.
If yes, then print “Yes”, Else print “No”.
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; bool checkValidString(string str){ // Initialise frequency array int freq[26] = { 0 }; // Traverse the string for (int i = 0; str[i]; i++) { // Update the frequency freq[str[i] - 'a']++; } // Check for valid string for (int i = 0; i < 26; i++) { // If frequency is non-zero if (freq[i] != 0) { // If freq is not equals // to (i+1), then return // false if (freq[i] != i + 1) { return false; } } } // Return true; return true;} // Driver Codeint main(){ // Given string str string str = "abbcccdddd"; if (checkValidString(str)) cout << "Yes"; else cout << "No"; return 0;}
// Java program for the above approachclass GFG{ static boolean checkValidString(String str){ // Initialise frequency array int freq[] = new int[26]; // Traverse the String for(int i = 0; i < str.length(); i++) { // Update the frequency freq[str.charAt(i) - 'a']++; } // Check for valid String for(int i = 0; i < 26; i++) { // If frequency is non-zero if (freq[i] != 0) { // If freq is not equals // to (i+1), then return // false if (freq[i] != i + 1) { return false; } } } // Return true; return true;} // Driver Codepublic static void main(String[] args){ // Given String str String str = "abbcccdddd"; if (checkValidString(str)) { System.out.print("Yes"); } else { System.out.print("No"); }}} // This code is contributed by sapnasingh4991
# Python3 program for the# above approachdef checkValidString(str): # Initialise frequency array freq = [0 for i in range(26)] # Traverse the string for i in range(len(str)): # Update the frequency freq[ord(str[i]) - ord('a')] += 1 # Check for valid string for i in range(26): # If frequency is non-zero if(freq[i] != 0): # If freq is not equals # to (i+1), then return # false if(freq[i] != i + 1): return False # Return true return True # Driver Code # Given string strstr = "abbcccdddd" if(checkValidString(str)): print("Yes")else: print("No") # This code is contributed by avanitrachhadiya2155
// C# program for the above approachusing System;class GFG{ static bool checkValidString(String str){ // Initialise frequency array int []freq = new int[26]; // Traverse the String for(int i = 0; i < str.Length; i++) { // Update the frequency freq[str[i] - 'a']++; } // Check for valid String for(int i = 0; i < 26; i++) { // If frequency is non-zero if (freq[i] != 0) { // If freq is not equals // to (i+1), then return // false if (freq[i] != i + 1) { return false; } } } // Return true; return true;} // Driver Codepublic static void Main(String[] args){ // Given String str String str = "abbcccdddd"; if (checkValidString(str)) { Console.Write("Yes"); } else { Console.Write("No"); }}} // This code is contributed by sapnasingh4991
<script> // Javascript program for the above approachfunction checkValidString(str){ // Initialise frequency array var freq = new Array(26).fill(0); // Traverse the String for(var i = 0; i < str.length; i++) { // Update the frequency freq[str[i].charCodeAt(0) - "a".charCodeAt(0)]++; } // Check for valid String for(var i = 0; i < 26; i++) { // If frequency is non-zero if (freq[i] !== 0) { // If freq is not equals // to (i+1), then return // false if (freq[i] !== i + 1) { return false; } } } // Return true; return true;} // Driver Code // Given String strvar str = "abbcccdddd"; if (checkValidString(str)){ document.write("Yes");}else{ document.write("No");} // This code is contributed by rdtank </script>
Yes
Time Complexity: O(N), where N is the length of the string. Auxiliary Space: O(26)
sapnasingh4991
avanitrachhadiya2155
rdtank
ASCII
frequency-counting
Arrays
Hash
School Programming
Strings
Arrays
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Building Heap from Array
Program to find sum of elements in a given array
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
Hashing | Set 2 (Separate Chaining)
|
[
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 25034,
"s": 24820,
"text": "Given string str of lowercase alphabets, the task is to check if the frequency of each distinct characters in the string equals to its position in the English Alphabet. If valid, then print “Yes”, else print “No”."
},
{
"code": null,
"e": 25045,
"s": 25034,
"text": "Examples: "
},
{
"code": null,
"e": 25259,
"s": 25045,
"text": "Input: str = “abbcccdddd” Output: Yes Explanation: Since frequency of each distinct character is equals to its position in English Alphabet, i.e. F(a) = 1, F(b) = 2, F(c) = 3, and F(d) = 4 Hence the output is Yes."
},
{
"code": null,
"e": 25300,
"s": 25259,
"text": "Input: str = “geeksforgeeks” Output: No "
},
{
"code": null,
"e": 25311,
"s": 25300,
"text": "Approach: "
},
{
"code": null,
"e": 25545,
"s": 25311,
"text": "Store the frequency of each character in an array of 26, for hashing purpose.Now traverse the hash array and check if the frequency of each character at an index i is equal to (i + 1) or not.If yes, then print “Yes”, Else print “No”."
},
{
"code": null,
"e": 25623,
"s": 25545,
"text": "Store the frequency of each character in an array of 26, for hashing purpose."
},
{
"code": null,
"e": 25738,
"s": 25623,
"text": "Now traverse the hash array and check if the frequency of each character at an index i is equal to (i + 1) or not."
},
{
"code": null,
"e": 25781,
"s": 25738,
"text": "If yes, then print “Yes”, Else print “No”."
},
{
"code": null,
"e": 25833,
"s": 25781,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25837,
"s": 25833,
"text": "C++"
},
{
"code": null,
"e": 25842,
"s": 25837,
"text": "Java"
},
{
"code": null,
"e": 25850,
"s": 25842,
"text": "Python3"
},
{
"code": null,
"e": 25853,
"s": 25850,
"text": "C#"
},
{
"code": null,
"e": 25864,
"s": 25853,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include \"bits/stdc++.h\"using namespace std; bool checkValidString(string str){ // Initialise frequency array int freq[26] = { 0 }; // Traverse the string for (int i = 0; str[i]; i++) { // Update the frequency freq[str[i] - 'a']++; } // Check for valid string for (int i = 0; i < 26; i++) { // If frequency is non-zero if (freq[i] != 0) { // If freq is not equals // to (i+1), then return // false if (freq[i] != i + 1) { return false; } } } // Return true; return true;} // Driver Codeint main(){ // Given string str string str = \"abbcccdddd\"; if (checkValidString(str)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 26693,
"s": 25864,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ static boolean checkValidString(String str){ // Initialise frequency array int freq[] = new int[26]; // Traverse the String for(int i = 0; i < str.length(); i++) { // Update the frequency freq[str.charAt(i) - 'a']++; } // Check for valid String for(int i = 0; i < 26; i++) { // If frequency is non-zero if (freq[i] != 0) { // If freq is not equals // to (i+1), then return // false if (freq[i] != i + 1) { return false; } } } // Return true; return true;} // Driver Codepublic static void main(String[] args){ // Given String str String str = \"abbcccdddd\"; if (checkValidString(str)) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); }}} // This code is contributed by sapnasingh4991",
"e": 27662,
"s": 26693,
"text": null
},
{
"code": "# Python3 program for the# above approachdef checkValidString(str): # Initialise frequency array freq = [0 for i in range(26)] # Traverse the string for i in range(len(str)): # Update the frequency freq[ord(str[i]) - ord('a')] += 1 # Check for valid string for i in range(26): # If frequency is non-zero if(freq[i] != 0): # If freq is not equals # to (i+1), then return # false if(freq[i] != i + 1): return False # Return true return True # Driver Code # Given string strstr = \"abbcccdddd\" if(checkValidString(str)): print(\"Yes\")else: print(\"No\") # This code is contributed by avanitrachhadiya2155",
"e": 28383,
"s": 27662,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ static bool checkValidString(String str){ // Initialise frequency array int []freq = new int[26]; // Traverse the String for(int i = 0; i < str.Length; i++) { // Update the frequency freq[str[i] - 'a']++; } // Check for valid String for(int i = 0; i < 26; i++) { // If frequency is non-zero if (freq[i] != 0) { // If freq is not equals // to (i+1), then return // false if (freq[i] != i + 1) { return false; } } } // Return true; return true;} // Driver Codepublic static void Main(String[] args){ // Given String str String str = \"abbcccdddd\"; if (checkValidString(str)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}} // This code is contributed by sapnasingh4991",
"e": 29365,
"s": 28383,
"text": null
},
{
"code": "<script> // Javascript program for the above approachfunction checkValidString(str){ // Initialise frequency array var freq = new Array(26).fill(0); // Traverse the String for(var i = 0; i < str.length; i++) { // Update the frequency freq[str[i].charCodeAt(0) - \"a\".charCodeAt(0)]++; } // Check for valid String for(var i = 0; i < 26; i++) { // If frequency is non-zero if (freq[i] !== 0) { // If freq is not equals // to (i+1), then return // false if (freq[i] !== i + 1) { return false; } } } // Return true; return true;} // Driver Code // Given String strvar str = \"abbcccdddd\"; if (checkValidString(str)){ document.write(\"Yes\");}else{ document.write(\"No\");} // This code is contributed by rdtank </script>",
"e": 30307,
"s": 29365,
"text": null
},
{
"code": null,
"e": 30311,
"s": 30307,
"text": "Yes"
},
{
"code": null,
"e": 30396,
"s": 30313,
"text": "Time Complexity: O(N), where N is the length of the string. Auxiliary Space: O(26)"
},
{
"code": null,
"e": 30411,
"s": 30396,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 30432,
"s": 30411,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 30439,
"s": 30432,
"text": "rdtank"
},
{
"code": null,
"e": 30445,
"s": 30439,
"text": "ASCII"
},
{
"code": null,
"e": 30464,
"s": 30445,
"text": "frequency-counting"
},
{
"code": null,
"e": 30471,
"s": 30464,
"text": "Arrays"
},
{
"code": null,
"e": 30476,
"s": 30471,
"text": "Hash"
},
{
"code": null,
"e": 30495,
"s": 30476,
"text": "School Programming"
},
{
"code": null,
"e": 30503,
"s": 30495,
"text": "Strings"
},
{
"code": null,
"e": 30510,
"s": 30503,
"text": "Arrays"
},
{
"code": null,
"e": 30515,
"s": 30510,
"text": "Hash"
},
{
"code": null,
"e": 30523,
"s": 30515,
"text": "Strings"
},
{
"code": null,
"e": 30621,
"s": 30523,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30646,
"s": 30621,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 30666,
"s": 30646,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 30704,
"s": 30666,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 30729,
"s": 30704,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 30778,
"s": 30729,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30814,
"s": 30778,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 30845,
"s": 30814,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 30879,
"s": 30845,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 30906,
"s": 30879,
"text": "Count pairs with given sum"
}
] |
How to create JLabel to hold multiline of text using HTML in Java?
|
To hold multiline of text, set HTML under JLabel −
JLabel = new JLabel("<html><strong>" + "Line1<br>Line2</strong></html>",JLabel.LEFT);
The above will create multiline text in the JLabel −
Line1
Line2
The following is an example to create JLabel to hold multiline of text −
import java.awt.Font;
import javax.swing.*;
public class SwingDemo {
public static void main(String args[]) {
JFrame frame = new JFrame("Label Example");
JLabel label;
label = new JLabel("" + "Line1
Line2",JLabel.LEFT);
label.setBounds(100, 100, 100, 30);
label.setFont(new Font("Verdana", Font.PLAIN, 13));
frame.add(label);
frame.setSize(500,300);
frame.setLayout(null);
frame.setVisible(true);
}
}
|
[
{
"code": null,
"e": 1113,
"s": 1062,
"text": "To hold multiline of text, set HTML under JLabel −"
},
{
"code": null,
"e": 1199,
"s": 1113,
"text": "JLabel = new JLabel(\"<html><strong>\" + \"Line1<br>Line2</strong></html>\",JLabel.LEFT);"
},
{
"code": null,
"e": 1252,
"s": 1199,
"text": "The above will create multiline text in the JLabel −"
},
{
"code": null,
"e": 1264,
"s": 1252,
"text": "Line1\nLine2"
},
{
"code": null,
"e": 1337,
"s": 1264,
"text": "The following is an example to create JLabel to hold multiline of text −"
},
{
"code": null,
"e": 1804,
"s": 1337,
"text": "import java.awt.Font;\nimport javax.swing.*;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Label Example\");\n JLabel label;\n label = new JLabel(\"\" + \"Line1\n Line2\",JLabel.LEFT);\n label.setBounds(100, 100, 100, 30);\n label.setFont(new Font(\"Verdana\", Font.PLAIN, 13));\n frame.add(label);\n frame.setSize(500,300);\n frame.setLayout(null);\n frame.setVisible(true);\n }\n}"
}
] |
Angular 8 - Creating First Application
|
Let us create a simple angular application and analyse the structure of the basic angular application.
Let us check whether the Angular Framework is installed in our system and the version of the installed Angular version using below command −
ng --version
Here,
ng is the CLI application used to create, manage and run Angular Application. It written in JavaScript and runs in NodeJS environment.
The result will show the details of the Angular version as specified below −
Angular CLI: 8.3.26
Node: 14.2.0
OS: win32 x64
Angular: ...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.803.26
@angular-devkit/core 8.3.26
@angular-devkit/schematics 8.3.26
@schematics/angular 8.3.26
@schematics/update 0.803.26
rxjs 6.4.0
So, Angular is installed in our system and the version is 8.3.26.
Let us create an Angular application to check our day to day expenses. Let us give ExpenseManageras our choice for our new application. Use below command to create the new application.
cd /path/to/workspace
ng new expense-manager
Here,
new is one of the command of the ng CLI application. It will be used to create new application. It will ask some basic question in order to create new application. It is enough to let the application choose the default choices. Regarding routing question as mentioned below, specify No. We will see how to create routing later in the Routing chapter.
Would you like to add Angular routing? No
Once the basic questions are answered, the ng CLI application create a new Angular application under expense-manager folder.
Let us move into the our newly created application folder.
cd expense-manager
Let us check the partial structure of the application. The structure of the application is as follows −
| favicon.ico
| index.html
| main.ts
| polyfills.ts
| styles.css
|
+---app
| app.component.css
| app.component.html
| app.component.spec.ts
| app.component.ts
| app.module.ts
|
+---assets
| .gitkeep
|
+---environments
environment.prod.ts
environment.ts
Here,
We have shown, only the most important file and folder of the application.
We have shown, only the most important file and folder of the application.
favicon.ico and assets are application’s icon and application’s root asset folder.
favicon.ico and assets are application’s icon and application’s root asset folder.
polyfills.ts contains standard code useful for browser compatibility.
polyfills.ts contains standard code useful for browser compatibility.
environments folder will have the application’s setting. It includes production and development setup.
environments folder will have the application’s setting. It includes production and development setup.
main.ts file contains the startup code.
main.ts file contains the startup code.
index.html is the application base HTML code.
index.html is the application base HTML code.
styles.css is the base CSS code.
styles.css is the base CSS code.
app folder contains the Angular application code, which will be learn elaborately in the upcoming chapters.
app folder contains the Angular application code, which will be learn elaborately in the upcoming chapters.
Let us start the application using below command −
ng serve
10% building 3/3 modules 0 activei wds: Project is running at http://localhost:4200/webpack-dev-server/
i wds: webpack output is served from /
i wds: 404s will fallback to //index.html
chunk {main} main.js, main.js.map (main) 49.2 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 269 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 9.75 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 3.81 MB [initial] [rendered]
Date: 2020-05-26T05:02:14.134Z - Hash: 0dec2ff62a4247d58fe2 - Time: 12330ms
** Angular Live Development Server is listening on localhost:4200, open your
browser on http://localhost:4200/ **
i wdm: Compiled successfully.
Here, serve is the sub command used to compile and run the Angular application using a local development web server. ng server will start a development web server and serves the application under port, 4200.
Let us fire up a browser and opens http://localhost:4200. The browser will show the application as shown below −
Let us change the title of the application to better reflect our application. Open src/app/app.component.ts and change the code as specified below −
export class AppComponent {
title = 'Expense Manager';
}
Our final application will be rendered in the browser as shown below −
We will change the application and learn how to code an Angular application in the upcoming chapters.
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": 2491,
"s": 2388,
"text": "Let us create a simple angular application and analyse the structure of the basic angular application."
},
{
"code": null,
"e": 2632,
"s": 2491,
"text": "Let us check whether the Angular Framework is installed in our system and the version of the installed Angular version using below command −"
},
{
"code": null,
"e": 2646,
"s": 2632,
"text": "ng --version\n"
},
{
"code": null,
"e": 2652,
"s": 2646,
"text": "Here,"
},
{
"code": null,
"e": 2787,
"s": 2652,
"text": "ng is the CLI application used to create, manage and run Angular Application. It written in JavaScript and runs in NodeJS environment."
},
{
"code": null,
"e": 2864,
"s": 2787,
"text": "The result will show the details of the Angular version as specified below −"
},
{
"code": null,
"e": 3232,
"s": 2864,
"text": "Angular CLI: 8.3.26 \nNode: 14.2.0 \nOS: win32 x64 \nAngular: ... \nPackage Version \n------------------------------------------------------\n@angular-devkit/architect 0.803.26 \n@angular-devkit/core 8.3.26 \n@angular-devkit/schematics 8.3.26 \n@schematics/angular 8.3.26 \n@schematics/update 0.803.26 \nrxjs 6.4.0\n"
},
{
"code": null,
"e": 3298,
"s": 3232,
"text": "So, Angular is installed in our system and the version is 8.3.26."
},
{
"code": null,
"e": 3483,
"s": 3298,
"text": "Let us create an Angular application to check our day to day expenses. Let us give ExpenseManageras our choice for our new application. Use below command to create the new application."
},
{
"code": null,
"e": 3530,
"s": 3483,
"text": "cd /path/to/workspace \nng new expense-manager\n"
},
{
"code": null,
"e": 3536,
"s": 3530,
"text": "Here,"
},
{
"code": null,
"e": 3887,
"s": 3536,
"text": "new is one of the command of the ng CLI application. It will be used to create new application. It will ask some basic question in order to create new application. It is enough to let the application choose the default choices. Regarding routing question as mentioned below, specify No. We will see how to create routing later in the Routing chapter."
},
{
"code": null,
"e": 3930,
"s": 3887,
"text": "Would you like to add Angular routing? No\n"
},
{
"code": null,
"e": 4055,
"s": 3930,
"text": "Once the basic questions are answered, the ng CLI application create a new Angular application under expense-manager folder."
},
{
"code": null,
"e": 4114,
"s": 4055,
"text": "Let us move into the our newly created application folder."
},
{
"code": null,
"e": 4134,
"s": 4114,
"text": "cd expense-manager\n"
},
{
"code": null,
"e": 4238,
"s": 4134,
"text": "Let us check the partial structure of the application. The structure of the application is as follows −"
},
{
"code": null,
"e": 4522,
"s": 4238,
"text": "| favicon.ico \n| index.html \n| main.ts \n| polyfills.ts \n| styles.css \n| \n+---app \n| app.component.css \n| app.component.html \n| app.component.spec.ts \n| app.component.ts \n| app.module.ts \n| \n+---assets \n| .gitkeep \n| \n+---environments \n environment.prod.ts \n environment.ts\n"
},
{
"code": null,
"e": 4528,
"s": 4522,
"text": "Here,"
},
{
"code": null,
"e": 4603,
"s": 4528,
"text": "We have shown, only the most important file and folder of the application."
},
{
"code": null,
"e": 4678,
"s": 4603,
"text": "We have shown, only the most important file and folder of the application."
},
{
"code": null,
"e": 4761,
"s": 4678,
"text": "favicon.ico and assets are application’s icon and application’s root asset folder."
},
{
"code": null,
"e": 4844,
"s": 4761,
"text": "favicon.ico and assets are application’s icon and application’s root asset folder."
},
{
"code": null,
"e": 4914,
"s": 4844,
"text": "polyfills.ts contains standard code useful for browser compatibility."
},
{
"code": null,
"e": 4984,
"s": 4914,
"text": "polyfills.ts contains standard code useful for browser compatibility."
},
{
"code": null,
"e": 5087,
"s": 4984,
"text": "environments folder will have the application’s setting. It includes production and development setup."
},
{
"code": null,
"e": 5190,
"s": 5087,
"text": "environments folder will have the application’s setting. It includes production and development setup."
},
{
"code": null,
"e": 5230,
"s": 5190,
"text": "main.ts file contains the startup code."
},
{
"code": null,
"e": 5270,
"s": 5230,
"text": "main.ts file contains the startup code."
},
{
"code": null,
"e": 5316,
"s": 5270,
"text": "index.html is the application base HTML code."
},
{
"code": null,
"e": 5362,
"s": 5316,
"text": "index.html is the application base HTML code."
},
{
"code": null,
"e": 5395,
"s": 5362,
"text": "styles.css is the base CSS code."
},
{
"code": null,
"e": 5428,
"s": 5395,
"text": "styles.css is the base CSS code."
},
{
"code": null,
"e": 5536,
"s": 5428,
"text": "app folder contains the Angular application code, which will be learn elaborately in the upcoming chapters."
},
{
"code": null,
"e": 5644,
"s": 5536,
"text": "app folder contains the Angular application code, which will be learn elaborately in the upcoming chapters."
},
{
"code": null,
"e": 5695,
"s": 5644,
"text": "Let us start the application using below command −"
},
{
"code": null,
"e": 6515,
"s": 5695,
"text": "ng serve\n10% building 3/3 modules 0 activei wds: Project is running at http://localhost:4200/webpack-dev-server/\ni wds: webpack output is served from /\n\ni wds: 404s will fallback to //index.html \nchunk {main} main.js, main.js.map (main) 49.2 kB [initial] [rendered] \nchunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 269 kB [initial] [rendered] \nchunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered] \nchunk {styles} styles.js, styles.js.map (styles) 9.75 kB [initial] [rendered] \nchunk {vendor} vendor.js, vendor.js.map (vendor) 3.81 MB [initial] [rendered] \nDate: 2020-05-26T05:02:14.134Z - Hash: 0dec2ff62a4247d58fe2 - Time: 12330ms \n** Angular Live Development Server is listening on localhost:4200, open your \nbrowser on http://localhost:4200/ ** \ni wdm: Compiled successfully.\n"
},
{
"code": null,
"e": 6723,
"s": 6515,
"text": "Here, serve is the sub command used to compile and run the Angular application using a local development web server. ng server will start a development web server and serves the application under port, 4200."
},
{
"code": null,
"e": 6836,
"s": 6723,
"text": "Let us fire up a browser and opens http://localhost:4200. The browser will show the application as shown below −"
},
{
"code": null,
"e": 6985,
"s": 6836,
"text": "Let us change the title of the application to better reflect our application. Open src/app/app.component.ts and change the code as specified below −"
},
{
"code": null,
"e": 7048,
"s": 6985,
"text": "export class AppComponent { \n title = 'Expense Manager'; \n}\n"
},
{
"code": null,
"e": 7119,
"s": 7048,
"text": "Our final application will be rendered in the browser as shown below −"
},
{
"code": null,
"e": 7221,
"s": 7119,
"text": "We will change the application and learn how to code an Angular application in the upcoming chapters."
},
{
"code": null,
"e": 7256,
"s": 7221,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7270,
"s": 7256,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7305,
"s": 7270,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7319,
"s": 7305,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7354,
"s": 7319,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7374,
"s": 7354,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7409,
"s": 7374,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7426,
"s": 7409,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7459,
"s": 7426,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7471,
"s": 7459,
"text": " Senol Atac"
},
{
"code": null,
"e": 7506,
"s": 7471,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7518,
"s": 7506,
"text": " Senol Atac"
},
{
"code": null,
"e": 7525,
"s": 7518,
"text": " Print"
},
{
"code": null,
"e": 7536,
"s": 7525,
"text": " Add Notes"
}
] |
Lodash _.eq() Method - GeeksforGeeks
|
09 Sep, 2020
The _.eq() method is used to find the two values are equivalent or not by performing the SameValueZero comparison. It returns true, if the values are equivalent. Otherwise, it returns false.
Syntax:
_.eq(value, other)
Parameters: This method accepts two parameters as mentioned above and described below:
value: This parameter holds the value to compare.
other: This parameter holds the other value to compare.
Return Value: This method returns true if the values are equivalent, else false.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.eq method console.log(_.eq("Geeks", "Geeks" )); console.log(_.eq("Geeks", Object("Geeks"))); console.log(_.eq(NaN, NaN));
Output:
true
false
true
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Given valuesvar object = { 'gfg': 2020 };var other = { 'gfg': 2020 }; // Use of _.eq method console.log(_.eq(object, object)); console.log(_.eq(object, other));
Output:
true
false
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Hide or show elements in HTML using display property
Set the value of an input field in JavaScript
How to calculate the number of days between two dates in javascript?
Express.js express.Router() Function
Installation of Node.js on Linux
How to set input type date in dd-mm-yyyy format using HTML ?
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
|
[
{
"code": null,
"e": 37045,
"s": 37017,
"text": "\n09 Sep, 2020"
},
{
"code": null,
"e": 37236,
"s": 37045,
"text": "The _.eq() method is used to find the two values are equivalent or not by performing the SameValueZero comparison. It returns true, if the values are equivalent. Otherwise, it returns false."
},
{
"code": null,
"e": 37244,
"s": 37236,
"text": "Syntax:"
},
{
"code": null,
"e": 37264,
"s": 37244,
"text": "_.eq(value, other)\n"
},
{
"code": null,
"e": 37351,
"s": 37264,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 37401,
"s": 37351,
"text": "value: This parameter holds the value to compare."
},
{
"code": null,
"e": 37457,
"s": 37401,
"text": "other: This parameter holds the other value to compare."
},
{
"code": null,
"e": 37538,
"s": 37457,
"text": "Return Value: This method returns true if the values are equivalent, else false."
},
{
"code": null,
"e": 37549,
"s": 37538,
"text": "Example 1:"
},
{
"code": null,
"e": 37560,
"s": 37549,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.eq method console.log(_.eq(\"Geeks\", \"Geeks\" )); console.log(_.eq(\"Geeks\", Object(\"Geeks\"))); console.log(_.eq(NaN, NaN)); ",
"e": 37765,
"s": 37560,
"text": null
},
{
"code": null,
"e": 37773,
"s": 37765,
"text": "Output:"
},
{
"code": null,
"e": 37790,
"s": 37773,
"text": "true\nfalse\ntrue\n"
},
{
"code": null,
"e": 37803,
"s": 37790,
"text": "Example 2: "
},
{
"code": null,
"e": 37814,
"s": 37803,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Given valuesvar object = { 'gfg': 2020 };var other = { 'gfg': 2020 }; // Use of _.eq method console.log(_.eq(object, object)); console.log(_.eq(object, other)); ",
"e": 38045,
"s": 37814,
"text": null
},
{
"code": null,
"e": 38053,
"s": 38045,
"text": "Output:"
},
{
"code": null,
"e": 38065,
"s": 38053,
"text": "true\nfalse\n"
},
{
"code": null,
"e": 38083,
"s": 38065,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 38094,
"s": 38083,
"text": "JavaScript"
},
{
"code": null,
"e": 38111,
"s": 38094,
"text": "Web Technologies"
},
{
"code": null,
"e": 38209,
"s": 38111,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38218,
"s": 38209,
"text": "Comments"
},
{
"code": null,
"e": 38231,
"s": 38218,
"text": "Old Comments"
},
{
"code": null,
"e": 38303,
"s": 38231,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 38348,
"s": 38303,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 38401,
"s": 38348,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 38447,
"s": 38401,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 38516,
"s": 38447,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 38553,
"s": 38516,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 38586,
"s": 38553,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 38647,
"s": 38586,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 38719,
"s": 38647,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Program to find a sublist where first and last values are same in Python
|
Suppose we have a list of numbers called nums, we have to find the number of sublists where the first element and the last element are same.
So, if the input is like nums = [10, 15, 13, 10], then the output will be 5, as the sublists with same first and last element are: [10], [15], [13], [10], [10, 15, 13, 10].
To solve this, we will follow these steps −
num_sublists := size of nums
num_sublists := size of nums
d := an empty map
d := an empty map
for each n in nums, dod[n] := d[n] + 1
for each n in nums, do
d[n] := d[n] + 1
d[n] := d[n] + 1
for each number k and corresponding frequency v of elements in d, doif v is not same as 1, thennum_sublists := num_sublists +(quotient of (v-1) *(v) /2)
for each number k and corresponding frequency v of elements in d, do
if v is not same as 1, thennum_sublists := num_sublists +(quotient of (v-1) *(v) /2)
if v is not same as 1, then
num_sublists := num_sublists +(quotient of (v-1) *(v) /2)
num_sublists := num_sublists +(quotient of (v-1) *(v) /2)
return num_sublists
return num_sublists
Let us see the following implementation to get better understanding −
Live Demo
from collections import defaultdict
class Solution:
def solve(self, nums):
num_sublists = len(nums)
d = defaultdict(int)
for n in nums:
d[n] += 1
for k,v in d.items():
if v != 1:
num_sublists += (v-1)*(v)//2
return num_sublists
ob = Solution()
nums = [10, 15, 13, 10]
print(ob.solve(nums))
[10, 15, 13, 10]
5
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "Suppose we have a list of numbers called nums, we have to find the number of sublists where the first element and the last element are same."
},
{
"code": null,
"e": 1376,
"s": 1203,
"text": "So, if the input is like nums = [10, 15, 13, 10], then the output will be 5, as the sublists with same first and last element are: [10], [15], [13], [10], [10, 15, 13, 10]."
},
{
"code": null,
"e": 1420,
"s": 1376,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1449,
"s": 1420,
"text": "num_sublists := size of nums"
},
{
"code": null,
"e": 1478,
"s": 1449,
"text": "num_sublists := size of nums"
},
{
"code": null,
"e": 1496,
"s": 1478,
"text": "d := an empty map"
},
{
"code": null,
"e": 1514,
"s": 1496,
"text": "d := an empty map"
},
{
"code": null,
"e": 1553,
"s": 1514,
"text": "for each n in nums, dod[n] := d[n] + 1"
},
{
"code": null,
"e": 1576,
"s": 1553,
"text": "for each n in nums, do"
},
{
"code": null,
"e": 1593,
"s": 1576,
"text": "d[n] := d[n] + 1"
},
{
"code": null,
"e": 1610,
"s": 1593,
"text": "d[n] := d[n] + 1"
},
{
"code": null,
"e": 1763,
"s": 1610,
"text": "for each number k and corresponding frequency v of elements in d, doif v is not same as 1, thennum_sublists := num_sublists +(quotient of (v-1) *(v) /2)"
},
{
"code": null,
"e": 1832,
"s": 1763,
"text": "for each number k and corresponding frequency v of elements in d, do"
},
{
"code": null,
"e": 1917,
"s": 1832,
"text": "if v is not same as 1, thennum_sublists := num_sublists +(quotient of (v-1) *(v) /2)"
},
{
"code": null,
"e": 1945,
"s": 1917,
"text": "if v is not same as 1, then"
},
{
"code": null,
"e": 2003,
"s": 1945,
"text": "num_sublists := num_sublists +(quotient of (v-1) *(v) /2)"
},
{
"code": null,
"e": 2061,
"s": 2003,
"text": "num_sublists := num_sublists +(quotient of (v-1) *(v) /2)"
},
{
"code": null,
"e": 2081,
"s": 2061,
"text": "return num_sublists"
},
{
"code": null,
"e": 2101,
"s": 2081,
"text": "return num_sublists"
},
{
"code": null,
"e": 2171,
"s": 2101,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2182,
"s": 2171,
"text": " Live Demo"
},
{
"code": null,
"e": 2540,
"s": 2182,
"text": "from collections import defaultdict\nclass Solution:\n def solve(self, nums):\n num_sublists = len(nums)\n\n d = defaultdict(int)\n for n in nums:\n d[n] += 1\n \n for k,v in d.items():\n if v != 1:\n num_sublists += (v-1)*(v)//2\n return num_sublists\nob = Solution()\nnums = [10, 15, 13, 10]\nprint(ob.solve(nums))"
},
{
"code": null,
"e": 2557,
"s": 2540,
"text": "[10, 15, 13, 10]"
},
{
"code": null,
"e": 2559,
"s": 2557,
"text": "5"
}
] |
Stack.ToString() Method in C# with examples
|
The Stack.ToString() method in C# is used to get the string representation of the Stack class object.
The syntax is as follows −
public string ToString ();
Let us now see an example −
Live Demo
using System;
using System.Collections;
public class Demo {
public static void Main() {
Stack stack = new Stack();
stack.Push(150);
stack.Push(300);
stack.Push(500);
stack.Push(750);
stack.Push(1000);
stack.Push(1250);
stack.Push(1500);
stack.Push(2000);
stack.Push(2500);
Console.WriteLine("Stack elements...");
foreach(int val in stack) {
Console.WriteLine(val.ToString());
}
Console.WriteLine("Count of elements = "+stack.Count);
stack.Push(3000);
stack.Push(3500);
stack.Push(4000);
Console.WriteLine("\nStack elements...updated");
foreach(int val in stack) {
Console.WriteLine(val.ToString());
}
Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
Console.WriteLine("\nCopying the Stack to a new array...");
Object[] objArr = stack.ToArray();
foreach(Object ob in objArr) {
Console.WriteLine(ob);
}
Console.WriteLine("\nCount of elements in array = "+objArr.Length);
}
}
This will produce the following output −
Stack elements...
2500
2000
1500
1250
1000
750
500
300
150
Count of elements = 9
Stack elements...updated
4000
3500
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements (updated) = 12
Copying the Stack to a new array...
4000
3500
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements in array = 12
Let us now see another example −
Live Demo
using System;
using System.Collections;
public class Demo {
public static void Main() {
Stack stack = new Stack();
stack.Push("Inspiron");
stack.Push("Alienware");
stack.Push("Projectors");
stack.Push("Monitors");
stack.Push("XPS");
stack.Push("Laptop");
stack.Push("Notebook");
Console.WriteLine("Stack elements...");
foreach(string val in stack) {
Console.WriteLine(val.ToString());
}
Console.WriteLine("Count of elements = "+stack.Count);
Console.WriteLine("Element at the top = "+ stack.Peek());
stack.Push("Ultrabook");
stack.Push("Cameras");
stack.Push("Keyboards");
Console.WriteLine("\nStack elements...updated");
foreach(string val in stack) {
Console.WriteLine(val.ToString());
}
Console.WriteLine("Element at the top = "+ stack.Peek());
Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
stack.Clear();
Console.Write("Count of elements (updated) = "+stack.Count);
}
}
This will produce the following output −
Stack elements...
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements = 7
Element at the top = Notebook
Stack elements...updated
Keyboards
Cameras
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Element at the top = Keyboards
Count of elements (updated) = 10
Count of elements (updated) = 0
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "The Stack.ToString() method in C# is used to get the string representation of the Stack class object."
},
{
"code": null,
"e": 1191,
"s": 1164,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1218,
"s": 1191,
"text": "public string ToString ();"
},
{
"code": null,
"e": 1246,
"s": 1218,
"text": "Let us now see an example −"
},
{
"code": null,
"e": 1257,
"s": 1246,
"text": " Live Demo"
},
{
"code": null,
"e": 2337,
"s": 1257,
"text": "using System;\nusing System.Collections;\npublic class Demo {\n public static void Main() {\n Stack stack = new Stack();\n stack.Push(150);\n stack.Push(300);\n stack.Push(500);\n stack.Push(750);\n stack.Push(1000);\n stack.Push(1250);\n stack.Push(1500);\n stack.Push(2000);\n stack.Push(2500);\n Console.WriteLine(\"Stack elements...\");\n foreach(int val in stack) {\n Console.WriteLine(val.ToString());\n }\n Console.WriteLine(\"Count of elements = \"+stack.Count);\n stack.Push(3000);\n stack.Push(3500);\n stack.Push(4000);\n Console.WriteLine(\"\\nStack elements...updated\");\n foreach(int val in stack) {\n Console.WriteLine(val.ToString());\n }\n Console.WriteLine(\"\\nCount of elements (updated) = \"+stack.Count);\n Console.WriteLine(\"\\nCopying the Stack to a new array...\");\n Object[] objArr = stack.ToArray();\n foreach(Object ob in objArr) {\n Console.WriteLine(ob);\n }\n Console.WriteLine(\"\\nCount of elements in array = \"+objArr.Length);\n }\n}"
},
{
"code": null,
"e": 2378,
"s": 2337,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2700,
"s": 2378,
"text": "Stack elements...\n2500\n2000\n1500\n1250\n1000\n750\n500\n300\n150\nCount of elements = 9\n\nStack elements...updated\n4000\n3500\n3000\n2500\n2000\n1500\n1250\n1000\n750\n500\n300\n150\nCount of elements (updated) = 12\n\nCopying the Stack to a new array...\n4000\n3500\n3000\n2500\n2000\n1500\n1250\n1000\n750\n500\n300\n150\n\nCount of elements in array = 12"
},
{
"code": null,
"e": 2733,
"s": 2700,
"text": "Let us now see another example −"
},
{
"code": null,
"e": 2744,
"s": 2733,
"text": " Live Demo"
},
{
"code": null,
"e": 3807,
"s": 2744,
"text": "using System;\nusing System.Collections;\npublic class Demo {\n public static void Main() {\n Stack stack = new Stack();\n stack.Push(\"Inspiron\");\n stack.Push(\"Alienware\");\n stack.Push(\"Projectors\");\n stack.Push(\"Monitors\");\n stack.Push(\"XPS\");\n stack.Push(\"Laptop\");\n stack.Push(\"Notebook\");\n Console.WriteLine(\"Stack elements...\");\n foreach(string val in stack) {\n Console.WriteLine(val.ToString());\n }\n Console.WriteLine(\"Count of elements = \"+stack.Count);\n Console.WriteLine(\"Element at the top = \"+ stack.Peek());\n stack.Push(\"Ultrabook\");\n stack.Push(\"Cameras\");\n stack.Push(\"Keyboards\");\n Console.WriteLine(\"\\nStack elements...updated\");\n foreach(string val in stack) {\n Console.WriteLine(val.ToString());\n }\n Console.WriteLine(\"Element at the top = \"+ stack.Peek()); \n Console.WriteLine(\"\\nCount of elements (updated) = \"+stack.Count);\n stack.Clear();\n Console.Write(\"Count of elements (updated) = \"+stack.Count);\n }\n}"
},
{
"code": null,
"e": 3848,
"s": 3807,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 4185,
"s": 3848,
"text": "Stack elements...\nNotebook\nLaptop\nXPS\nMonitors\nProjectors\nAlienware\nInspiron\nCount of elements = 7\nElement at the top = Notebook\nStack elements...updated\nKeyboards\nCameras\nUltrabook\nNotebook\nLaptop\nXPS\nMonitors\nProjectors\nAlienware\nInspiron\nElement at the top = Keyboards\nCount of elements (updated) = 10\nCount of elements (updated) = 0"
}
] |
SQL | Arithmetic Operators - GeeksforGeeks
|
21 Mar, 2018
Prerequisite: Basic Select statement, Insert into clause, Sql Create Clause, SQL Aliases
We can use various Arithmetic Operators on the data stored in the tables.
Arithmetic Operators are:
+ [Addition]
- [Subtraction]
/ [Division]
* [Multiplication]
% [Modulus]
It is used to perform addition operation on the data items, items include either single column or multiple columns.
Implementation:
SELECT employee_id, employee_name, salary, salary + 100
AS "salary + 100" FROM addition;
Output:
Here we have done addition of 100 to each Employee’s salary i.e, addition operation on single column.
Let’s perform addition of 2 columns:
SELECT employee_id, employee_name, salary, salary + employee_id
AS "salary + employee_id" FROM addition;
Output:
Here we have done addition of 2 columns with each other i.e, each employee’s employee_id is added with its salary.
It is use to perform subtraction operation on the data items, items include either single column or multiple columns.
Implementation:
SELECT employee_id, employee_name, salary, salary - 100
AS "salary - 100" FROM subtraction;
Output:
Here we have done subtraction of 100 to each Employee’s salary i.e, subtraction operation on single column.
Let’s perform subtraction of 2 columns:
SELECT employee_id, employee_name, salary, salary - employee_id
AS "salary - employee_id" FROM subtraction;
Output:
Here we have done subtraction of 2 columns with each other i.e, each employee’s employee_id is subtracted from its salary.
Division (/) : For Division refer this link- Division in SQL
It is use to perform multiplication of data items.
Implementation:
SELECT employee_id, employee_name, salary, salary * 100
AS "salary * 100" FROM addition;
Output:
Here we have done multiplication of 100 to each Employee’s salary i.e, multiplication operation on single column.
Let’s perform multiplication of 2 columns:
SELECT employee_id, employee_name, salary, salary * employee_id
AS "salary * employee_id" FROM addition;
Output:
Here we have done multiplication of 2 columns with each other i.e, each employee’s employee_id is multiplied with its salary.
It is use to get remainder when one data is divided by another.
Implementation:
SELECT employee_id, employee_name, salary, salary % 25000
AS "salary % 25000" FROM addition;
Output:
Here we have done modulus of 100 to each Employee’s salary i.e, modulus operation on single column.
Let’s perform modulus operation between 2 columns:
SELECT employee_id, employee_name, salary, salary % employee_id
AS "salary % employee_id" FROM addition;
Output:
Here we have done modulus of 2 columns with each other i.e, each employee’s salary is divided with its id and corresponding remainder is shown.
Basically, modulus is use to check whether a number is Even or Odd. Suppose a given number if divided by 2 and gives 1 as remainder, then it is an odd number or if on dividing by 2 and gives 0 as remainder, then it is an even number.
If we perform any arithmetic operation on NULL, then answer is always null.
Implementation:
SELECT employee_id, employee_name, salary, type, type + 100
AS "type+100" FROM addition;
Output:
Here output always came null, since performing any operation on null will always result in a null value.
Note: Make sure that NULL is unavailable, unassigned, unknown. Null is not same as blank space or zero.To get in depth understanding of NULL, refer THIS link.References: Oracle Docs
SQL-Clauses-Operators
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Clustered and Non-clustered index
SQL | Views
CTE in SQL
Difference between DELETE, DROP and TRUNCATE
Third Normal Form (3NF)
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
SQL | Views
CTE in SQL
Difference between DELETE, DROP and TRUNCATE
|
[
{
"code": null,
"e": 23601,
"s": 23573,
"text": "\n21 Mar, 2018"
},
{
"code": null,
"e": 23690,
"s": 23601,
"text": "Prerequisite: Basic Select statement, Insert into clause, Sql Create Clause, SQL Aliases"
},
{
"code": null,
"e": 23764,
"s": 23690,
"text": "We can use various Arithmetic Operators on the data stored in the tables."
},
{
"code": null,
"e": 23790,
"s": 23764,
"text": "Arithmetic Operators are:"
},
{
"code": null,
"e": 23913,
"s": 23790,
"text": "+ [Addition]\n- [Subtraction]\n/ [Division]\n* [Multiplication]\n% [Modulus]"
},
{
"code": null,
"e": 24029,
"s": 23913,
"text": "It is used to perform addition operation on the data items, items include either single column or multiple columns."
},
{
"code": null,
"e": 24045,
"s": 24029,
"text": "Implementation:"
},
{
"code": null,
"e": 24138,
"s": 24045,
"text": "SELECT employee_id, employee_name, salary, salary + 100\n AS \"salary + 100\" FROM addition;\n"
},
{
"code": null,
"e": 24146,
"s": 24138,
"text": "Output:"
},
{
"code": null,
"e": 24248,
"s": 24146,
"text": "Here we have done addition of 100 to each Employee’s salary i.e, addition operation on single column."
},
{
"code": null,
"e": 24285,
"s": 24248,
"text": "Let’s perform addition of 2 columns:"
},
{
"code": null,
"e": 24394,
"s": 24285,
"text": "SELECT employee_id, employee_name, salary, salary + employee_id\n AS \"salary + employee_id\" FROM addition;\n"
},
{
"code": null,
"e": 24402,
"s": 24394,
"text": "Output:"
},
{
"code": null,
"e": 24517,
"s": 24402,
"text": "Here we have done addition of 2 columns with each other i.e, each employee’s employee_id is added with its salary."
},
{
"code": null,
"e": 24635,
"s": 24517,
"text": "It is use to perform subtraction operation on the data items, items include either single column or multiple columns."
},
{
"code": null,
"e": 24651,
"s": 24635,
"text": "Implementation:"
},
{
"code": null,
"e": 24748,
"s": 24651,
"text": "SELECT employee_id, employee_name, salary, salary - 100\n AS \"salary - 100\" FROM subtraction;\n"
},
{
"code": null,
"e": 24756,
"s": 24748,
"text": "Output:"
},
{
"code": null,
"e": 24864,
"s": 24756,
"text": "Here we have done subtraction of 100 to each Employee’s salary i.e, subtraction operation on single column."
},
{
"code": null,
"e": 24904,
"s": 24864,
"text": "Let’s perform subtraction of 2 columns:"
},
{
"code": null,
"e": 25017,
"s": 24904,
"text": "SELECT employee_id, employee_name, salary, salary - employee_id\n AS \"salary - employee_id\" FROM subtraction;\n"
},
{
"code": null,
"e": 25025,
"s": 25017,
"text": "Output:"
},
{
"code": null,
"e": 25148,
"s": 25025,
"text": "Here we have done subtraction of 2 columns with each other i.e, each employee’s employee_id is subtracted from its salary."
},
{
"code": null,
"e": 25209,
"s": 25148,
"text": "Division (/) : For Division refer this link- Division in SQL"
},
{
"code": null,
"e": 25260,
"s": 25209,
"text": "It is use to perform multiplication of data items."
},
{
"code": null,
"e": 25276,
"s": 25260,
"text": "Implementation:"
},
{
"code": null,
"e": 25370,
"s": 25276,
"text": "SELECT employee_id, employee_name, salary, salary * 100\n AS \"salary * 100\" FROM addition;\n"
},
{
"code": null,
"e": 25378,
"s": 25370,
"text": "Output:"
},
{
"code": null,
"e": 25492,
"s": 25378,
"text": "Here we have done multiplication of 100 to each Employee’s salary i.e, multiplication operation on single column."
},
{
"code": null,
"e": 25535,
"s": 25492,
"text": "Let’s perform multiplication of 2 columns:"
},
{
"code": null,
"e": 25646,
"s": 25535,
"text": "SELECT employee_id, employee_name, salary, salary * employee_id\n AS \"salary * employee_id\" FROM addition;\n"
},
{
"code": null,
"e": 25654,
"s": 25646,
"text": "Output:"
},
{
"code": null,
"e": 25780,
"s": 25654,
"text": "Here we have done multiplication of 2 columns with each other i.e, each employee’s employee_id is multiplied with its salary."
},
{
"code": null,
"e": 25844,
"s": 25780,
"text": "It is use to get remainder when one data is divided by another."
},
{
"code": null,
"e": 25860,
"s": 25844,
"text": "Implementation:"
},
{
"code": null,
"e": 25958,
"s": 25860,
"text": "SELECT employee_id, employee_name, salary, salary % 25000\n AS \"salary % 25000\" FROM addition;\n"
},
{
"code": null,
"e": 25966,
"s": 25958,
"text": "Output:"
},
{
"code": null,
"e": 26066,
"s": 25966,
"text": "Here we have done modulus of 100 to each Employee’s salary i.e, modulus operation on single column."
},
{
"code": null,
"e": 26117,
"s": 26066,
"text": "Let’s perform modulus operation between 2 columns:"
},
{
"code": null,
"e": 26227,
"s": 26117,
"text": "SELECT employee_id, employee_name, salary, salary % employee_id\n AS \"salary % employee_id\" FROM addition;\n"
},
{
"code": null,
"e": 26235,
"s": 26227,
"text": "Output:"
},
{
"code": null,
"e": 26379,
"s": 26235,
"text": "Here we have done modulus of 2 columns with each other i.e, each employee’s salary is divided with its id and corresponding remainder is shown."
},
{
"code": null,
"e": 26613,
"s": 26379,
"text": "Basically, modulus is use to check whether a number is Even or Odd. Suppose a given number if divided by 2 and gives 1 as remainder, then it is an odd number or if on dividing by 2 and gives 0 as remainder, then it is an even number."
},
{
"code": null,
"e": 26689,
"s": 26613,
"text": "If we perform any arithmetic operation on NULL, then answer is always null."
},
{
"code": null,
"e": 26705,
"s": 26689,
"text": "Implementation:"
},
{
"code": null,
"e": 26799,
"s": 26705,
"text": "SELECT employee_id, employee_name, salary, type, type + 100\n AS \"type+100\" FROM addition;\n"
},
{
"code": null,
"e": 26807,
"s": 26799,
"text": "Output:"
},
{
"code": null,
"e": 26912,
"s": 26807,
"text": "Here output always came null, since performing any operation on null will always result in a null value."
},
{
"code": null,
"e": 27094,
"s": 26912,
"text": "Note: Make sure that NULL is unavailable, unassigned, unknown. Null is not same as blank space or zero.To get in depth understanding of NULL, refer THIS link.References: Oracle Docs"
},
{
"code": null,
"e": 27116,
"s": 27094,
"text": "SQL-Clauses-Operators"
},
{
"code": null,
"e": 27121,
"s": 27116,
"text": "DBMS"
},
{
"code": null,
"e": 27125,
"s": 27121,
"text": "SQL"
},
{
"code": null,
"e": 27130,
"s": 27125,
"text": "DBMS"
},
{
"code": null,
"e": 27134,
"s": 27130,
"text": "SQL"
},
{
"code": null,
"e": 27232,
"s": 27134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27241,
"s": 27232,
"text": "Comments"
},
{
"code": null,
"e": 27254,
"s": 27241,
"text": "Old Comments"
},
{
"code": null,
"e": 27307,
"s": 27254,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 27319,
"s": 27307,
"text": "SQL | Views"
},
{
"code": null,
"e": 27330,
"s": 27319,
"text": "CTE in SQL"
},
{
"code": null,
"e": 27375,
"s": 27330,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 27399,
"s": 27375,
"text": "Third Normal Form (3NF)"
},
{
"code": null,
"e": 27443,
"s": 27399,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 27464,
"s": 27443,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 27476,
"s": 27464,
"text": "SQL | Views"
},
{
"code": null,
"e": 27487,
"s": 27476,
"text": "CTE in SQL"
}
] |
Still Using the OS Module in Python? This Alternative is Remarkably Better | by Dario Radečić | Towards Data Science
|
File and folder management with Python’s os module is a nightmare. Yet, it’s an essential part of every data science workflow. Saving reports, reading configuration files, you name it — there’s no way around it.
Picture this — you spend weeks building an API around your model, and it works flawlessly, at least on your machine. Once deployed, it’s a whole different story. Your API fails in unexpected places or even won’t run, as absolute paths you’ve hardcoded simply don’t exist.
There’s a no-brainer solution. The pathlib library comes by default with Python 3.4 and above. It’s by far the most humane way to work with files, folder, and their connection in your apps. The best thing is — today you’ll learn all about it. I’m not saying that the os module serves no purpose, just that pathlib is far superior in file and folder management.
To start, create a new Python file and import the pathlib library:
import pathlib
You’ll need to be inside a .py file for some functionalities to work. For example, you won’t have access to __file__ property in Jupyter Notebooks. Everything else should work perfectly.
Here’s what you’ll learn today:
· Get a path to the current Python file· Get a path to the current working directory· Get a first parent folder path· Get an Nth parent folder path· Join paths· Create a directory if it doesn’t exist· Create files· Check if the path is a folder· Check if the path is a file· Get the name of the file· Get the file extension· Iterate over files in a folder
Every so often, you need an absolute path to your working directory with the included Python file name. You can obtain it quickly with pathlib. Keep in mind, this command won’t work in Jupyter Notebooks, as you can’t access the __file__ property there. Skip this section if you’re a Notebook user.
Anyhow, here’s how to get an absolute path + a file name of the Python script:
curr_file = pathlib.Path(__file__)print(curr_file)
Here’s how it looks on my machine:
>>> /Users/dradecic/Desktop/pathlib_guide/python_pathlib.py
Easy, right? Right.
There’s an easier solution if you don’t need the file name.
This one is equivalent to executing pwd in the Unix shell. It will return a path to the directory you’re currently in, or where the running script is located.
Here’s how to use it:
cwd = pathlib.Path.cwd()print(cwd)
And here’s what it prints on my machine:
>>> /Users/dradecic/Desktop/pathlib_guide
No file name, as you can see.
But what if you need to access a file in a parent folder? That would be Desktop in my case. Let’s cover that next.
This one is easy. You only need to access the parent property of a current working directory. Here’s how it’s done:
one_above = pathlib.Path.cwd().parent print(one_above)
Here’s what it prints on my machine:
>>> /Users/dradecic/Desktop
Great! But what if one parent folder isn’t enough? Let’s see what your options are.
You have options. The first one is to call access the parent property multiple times like a crazy person. Here’s an example:
mul_above = pathlib.Path.cwd().parent.parent.parent
The easier option is to access the parents property array and index it. For instance, here’s how you’d get a path to the second parent folder path:
mul_above = pathlib.Path.cwd().parents[1]print(mul_above)
Here are the results:
>>> /Users/dradecic
Array indexing starts at 0, so accessing parents[1] gets you to the second parent folder.
You now have enough knowledge to start joining paths. Let’s see how next.
Let’s say that a folder with sales reports is located two directories above your current location, and the report is called summer-sales.csv. Is there a way to access it with an absolute path?
Of course there is.
You already know how to access the Nth parent folder path. You’ll extend that functionality by calling joinpath() and providing the report name as an argument:
tgt_path = pathlib.Path.cwd().parents[1]tgt_fname = 'summer-sales.csv'print(tgt_path.joinpath(tgt_fname))
Here’s what it prints on my machine:
>>> /Users/dradecic/summer-sales.csv
The joinpath() function is probably the one I use the most. It’s super useful.
If I had a dollar every time something in production failed because I forgot to create a directory... It’s a pretty common mistake, and pathlib allows you to get around it without too much hassle.
Let’s say you want to store sales reports in a reports folder located in your current working directory. You’ll have to create that folder before you can store files in it. You should create it only if it doesn’t exist.
In a nutshell — use mkdir() to create a folder and exists() to check if a folder already exists.
Here’s the complete code snippet:
tgt_path = pathlib.Path.cwd().joinpath('reports')if not tgt_path.exists(): tgt_path.mkdir()
Executing the above code will, you’ve guessed it, create a reports folder:
Neat. Let’s see how you can create files in that folder next.
You’d typically save reports through some third-party libraries. Nevertheless, you can also use pathlib to create empty files of any type.
Here’s how to create both a CSV and TXT file inside the reports folder:
tgt_path = pathlib.Path.cwd().joinpath('reports')tgt_path.joinpath('summer-sales.csv').touch(exist_ok=True)tgt_path.joinpath('winter-sales.txt').touch(exist_ok=True)
The exist_ok=True parameter tells Python to overwrite a file if it already exists.
Let’s see if the files were created:
Works like a charm.
If you want to check if a given path is a folder, look no further than the is_dir() function. It returns a boolean.
The following example uses the mentioned function both on a folder and on a file:
tgt_path = pathlib.Path.cwd().joinpath('reports')print(tgt_path.is_dir())print(tgt_path.joinpath('summer-sales.csv').is_dir())
Here’s what you should see printed:
>>> True>>> False
And that’s all there is to it!
Similarly to the previous example, you can use the is_file() function to check if a given path results in a file.
The example below uses it both on a folder and on a file:
tgt_path = pathlib.Path.cwd().joinpath('reports')print(tgt_path.is_dir())print(tgt_path.joinpath('summer-sales.csv').is_dir())
As you would imagine, you’ll get the exact opposite results this time:
>>> False>>> True
Let’s explore a few more useful functions before calling it a day.
You can access the name property if you need to extract a file name from an absolute path.
Here’s a simple and not so useful example. It prints the file name of our summer-sales.csv file:
tgt_path = pathlib.Path.cwd().joinpath('reports/summer-sales.csv')print(tgt_path.name)
Here’s what you should see in the console:
>>> summer-sales.csv
Not much to it.
Sometimes all you need is a file extension. Maybe you want to process different file types differently, and you don’t care too much about the file name. The suffix property has you covered.
Here’s how you can get the file extension from the same summer-sales.csv file:
tgt_path = pathlib.Path.cwd().joinpath('reports/summer-sales.csv')print(tgt_path.suffix)
Here’s what you should see printed out:
>>> .csv
And finally, let’s cover iteration.
Let’s say you have a bunch of CSV reports in a single directory, and want to process them one by one. The iterdir() function is all you need.
The entire process couldn’t be any simpler:
tgt_path = pathlib.Path.cwd().joinpath('reports')for file in tgt_path.iterdir(): print(file)
Here’s what it prints on my machine:
>>> /Users/dradecic/Desktop/pathlib_guide/reports/summer-sales.csv /Users/dradecic/Desktop/pathlib_guide/reports/winter-sales.txt
And that does it for today. You now have everything needed to never cause a stupid production mistake again.
What are your thoughts on pathlib? Is it your favourite file and folder management library, or are you a fan of something else? Let me know in the comment section below.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Follow me on Medium for more stories like this
Sign up for my newsletter
Connect on LinkedIn
|
[
{
"code": null,
"e": 384,
"s": 172,
"text": "File and folder management with Python’s os module is a nightmare. Yet, it’s an essential part of every data science workflow. Saving reports, reading configuration files, you name it — there’s no way around it."
},
{
"code": null,
"e": 656,
"s": 384,
"text": "Picture this — you spend weeks building an API around your model, and it works flawlessly, at least on your machine. Once deployed, it’s a whole different story. Your API fails in unexpected places or even won’t run, as absolute paths you’ve hardcoded simply don’t exist."
},
{
"code": null,
"e": 1017,
"s": 656,
"text": "There’s a no-brainer solution. The pathlib library comes by default with Python 3.4 and above. It’s by far the most humane way to work with files, folder, and their connection in your apps. The best thing is — today you’ll learn all about it. I’m not saying that the os module serves no purpose, just that pathlib is far superior in file and folder management."
},
{
"code": null,
"e": 1084,
"s": 1017,
"text": "To start, create a new Python file and import the pathlib library:"
},
{
"code": null,
"e": 1099,
"s": 1084,
"text": "import pathlib"
},
{
"code": null,
"e": 1286,
"s": 1099,
"text": "You’ll need to be inside a .py file for some functionalities to work. For example, you won’t have access to __file__ property in Jupyter Notebooks. Everything else should work perfectly."
},
{
"code": null,
"e": 1318,
"s": 1286,
"text": "Here’s what you’ll learn today:"
},
{
"code": null,
"e": 1674,
"s": 1318,
"text": "· Get a path to the current Python file· Get a path to the current working directory· Get a first parent folder path· Get an Nth parent folder path· Join paths· Create a directory if it doesn’t exist· Create files· Check if the path is a folder· Check if the path is a file· Get the name of the file· Get the file extension· Iterate over files in a folder"
},
{
"code": null,
"e": 1972,
"s": 1674,
"text": "Every so often, you need an absolute path to your working directory with the included Python file name. You can obtain it quickly with pathlib. Keep in mind, this command won’t work in Jupyter Notebooks, as you can’t access the __file__ property there. Skip this section if you’re a Notebook user."
},
{
"code": null,
"e": 2051,
"s": 1972,
"text": "Anyhow, here’s how to get an absolute path + a file name of the Python script:"
},
{
"code": null,
"e": 2102,
"s": 2051,
"text": "curr_file = pathlib.Path(__file__)print(curr_file)"
},
{
"code": null,
"e": 2137,
"s": 2102,
"text": "Here’s how it looks on my machine:"
},
{
"code": null,
"e": 2197,
"s": 2137,
"text": ">>> /Users/dradecic/Desktop/pathlib_guide/python_pathlib.py"
},
{
"code": null,
"e": 2217,
"s": 2197,
"text": "Easy, right? Right."
},
{
"code": null,
"e": 2277,
"s": 2217,
"text": "There’s an easier solution if you don’t need the file name."
},
{
"code": null,
"e": 2436,
"s": 2277,
"text": "This one is equivalent to executing pwd in the Unix shell. It will return a path to the directory you’re currently in, or where the running script is located."
},
{
"code": null,
"e": 2458,
"s": 2436,
"text": "Here’s how to use it:"
},
{
"code": null,
"e": 2493,
"s": 2458,
"text": "cwd = pathlib.Path.cwd()print(cwd)"
},
{
"code": null,
"e": 2534,
"s": 2493,
"text": "And here’s what it prints on my machine:"
},
{
"code": null,
"e": 2576,
"s": 2534,
"text": ">>> /Users/dradecic/Desktop/pathlib_guide"
},
{
"code": null,
"e": 2606,
"s": 2576,
"text": "No file name, as you can see."
},
{
"code": null,
"e": 2721,
"s": 2606,
"text": "But what if you need to access a file in a parent folder? That would be Desktop in my case. Let’s cover that next."
},
{
"code": null,
"e": 2837,
"s": 2721,
"text": "This one is easy. You only need to access the parent property of a current working directory. Here’s how it’s done:"
},
{
"code": null,
"e": 2892,
"s": 2837,
"text": "one_above = pathlib.Path.cwd().parent print(one_above)"
},
{
"code": null,
"e": 2929,
"s": 2892,
"text": "Here’s what it prints on my machine:"
},
{
"code": null,
"e": 2957,
"s": 2929,
"text": ">>> /Users/dradecic/Desktop"
},
{
"code": null,
"e": 3041,
"s": 2957,
"text": "Great! But what if one parent folder isn’t enough? Let’s see what your options are."
},
{
"code": null,
"e": 3166,
"s": 3041,
"text": "You have options. The first one is to call access the parent property multiple times like a crazy person. Here’s an example:"
},
{
"code": null,
"e": 3218,
"s": 3166,
"text": "mul_above = pathlib.Path.cwd().parent.parent.parent"
},
{
"code": null,
"e": 3366,
"s": 3218,
"text": "The easier option is to access the parents property array and index it. For instance, here’s how you’d get a path to the second parent folder path:"
},
{
"code": null,
"e": 3424,
"s": 3366,
"text": "mul_above = pathlib.Path.cwd().parents[1]print(mul_above)"
},
{
"code": null,
"e": 3446,
"s": 3424,
"text": "Here are the results:"
},
{
"code": null,
"e": 3466,
"s": 3446,
"text": ">>> /Users/dradecic"
},
{
"code": null,
"e": 3556,
"s": 3466,
"text": "Array indexing starts at 0, so accessing parents[1] gets you to the second parent folder."
},
{
"code": null,
"e": 3630,
"s": 3556,
"text": "You now have enough knowledge to start joining paths. Let’s see how next."
},
{
"code": null,
"e": 3823,
"s": 3630,
"text": "Let’s say that a folder with sales reports is located two directories above your current location, and the report is called summer-sales.csv. Is there a way to access it with an absolute path?"
},
{
"code": null,
"e": 3843,
"s": 3823,
"text": "Of course there is."
},
{
"code": null,
"e": 4003,
"s": 3843,
"text": "You already know how to access the Nth parent folder path. You’ll extend that functionality by calling joinpath() and providing the report name as an argument:"
},
{
"code": null,
"e": 4109,
"s": 4003,
"text": "tgt_path = pathlib.Path.cwd().parents[1]tgt_fname = 'summer-sales.csv'print(tgt_path.joinpath(tgt_fname))"
},
{
"code": null,
"e": 4146,
"s": 4109,
"text": "Here’s what it prints on my machine:"
},
{
"code": null,
"e": 4183,
"s": 4146,
"text": ">>> /Users/dradecic/summer-sales.csv"
},
{
"code": null,
"e": 4262,
"s": 4183,
"text": "The joinpath() function is probably the one I use the most. It’s super useful."
},
{
"code": null,
"e": 4459,
"s": 4262,
"text": "If I had a dollar every time something in production failed because I forgot to create a directory... It’s a pretty common mistake, and pathlib allows you to get around it without too much hassle."
},
{
"code": null,
"e": 4679,
"s": 4459,
"text": "Let’s say you want to store sales reports in a reports folder located in your current working directory. You’ll have to create that folder before you can store files in it. You should create it only if it doesn’t exist."
},
{
"code": null,
"e": 4776,
"s": 4679,
"text": "In a nutshell — use mkdir() to create a folder and exists() to check if a folder already exists."
},
{
"code": null,
"e": 4810,
"s": 4776,
"text": "Here’s the complete code snippet:"
},
{
"code": null,
"e": 4905,
"s": 4810,
"text": "tgt_path = pathlib.Path.cwd().joinpath('reports')if not tgt_path.exists(): tgt_path.mkdir()"
},
{
"code": null,
"e": 4980,
"s": 4905,
"text": "Executing the above code will, you’ve guessed it, create a reports folder:"
},
{
"code": null,
"e": 5042,
"s": 4980,
"text": "Neat. Let’s see how you can create files in that folder next."
},
{
"code": null,
"e": 5181,
"s": 5042,
"text": "You’d typically save reports through some third-party libraries. Nevertheless, you can also use pathlib to create empty files of any type."
},
{
"code": null,
"e": 5253,
"s": 5181,
"text": "Here’s how to create both a CSV and TXT file inside the reports folder:"
},
{
"code": null,
"e": 5419,
"s": 5253,
"text": "tgt_path = pathlib.Path.cwd().joinpath('reports')tgt_path.joinpath('summer-sales.csv').touch(exist_ok=True)tgt_path.joinpath('winter-sales.txt').touch(exist_ok=True)"
},
{
"code": null,
"e": 5502,
"s": 5419,
"text": "The exist_ok=True parameter tells Python to overwrite a file if it already exists."
},
{
"code": null,
"e": 5539,
"s": 5502,
"text": "Let’s see if the files were created:"
},
{
"code": null,
"e": 5559,
"s": 5539,
"text": "Works like a charm."
},
{
"code": null,
"e": 5675,
"s": 5559,
"text": "If you want to check if a given path is a folder, look no further than the is_dir() function. It returns a boolean."
},
{
"code": null,
"e": 5757,
"s": 5675,
"text": "The following example uses the mentioned function both on a folder and on a file:"
},
{
"code": null,
"e": 5884,
"s": 5757,
"text": "tgt_path = pathlib.Path.cwd().joinpath('reports')print(tgt_path.is_dir())print(tgt_path.joinpath('summer-sales.csv').is_dir())"
},
{
"code": null,
"e": 5920,
"s": 5884,
"text": "Here’s what you should see printed:"
},
{
"code": null,
"e": 5938,
"s": 5920,
"text": ">>> True>>> False"
},
{
"code": null,
"e": 5969,
"s": 5938,
"text": "And that’s all there is to it!"
},
{
"code": null,
"e": 6083,
"s": 5969,
"text": "Similarly to the previous example, you can use the is_file() function to check if a given path results in a file."
},
{
"code": null,
"e": 6141,
"s": 6083,
"text": "The example below uses it both on a folder and on a file:"
},
{
"code": null,
"e": 6268,
"s": 6141,
"text": "tgt_path = pathlib.Path.cwd().joinpath('reports')print(tgt_path.is_dir())print(tgt_path.joinpath('summer-sales.csv').is_dir())"
},
{
"code": null,
"e": 6339,
"s": 6268,
"text": "As you would imagine, you’ll get the exact opposite results this time:"
},
{
"code": null,
"e": 6357,
"s": 6339,
"text": ">>> False>>> True"
},
{
"code": null,
"e": 6424,
"s": 6357,
"text": "Let’s explore a few more useful functions before calling it a day."
},
{
"code": null,
"e": 6515,
"s": 6424,
"text": "You can access the name property if you need to extract a file name from an absolute path."
},
{
"code": null,
"e": 6612,
"s": 6515,
"text": "Here’s a simple and not so useful example. It prints the file name of our summer-sales.csv file:"
},
{
"code": null,
"e": 6699,
"s": 6612,
"text": "tgt_path = pathlib.Path.cwd().joinpath('reports/summer-sales.csv')print(tgt_path.name)"
},
{
"code": null,
"e": 6742,
"s": 6699,
"text": "Here’s what you should see in the console:"
},
{
"code": null,
"e": 6763,
"s": 6742,
"text": ">>> summer-sales.csv"
},
{
"code": null,
"e": 6779,
"s": 6763,
"text": "Not much to it."
},
{
"code": null,
"e": 6969,
"s": 6779,
"text": "Sometimes all you need is a file extension. Maybe you want to process different file types differently, and you don’t care too much about the file name. The suffix property has you covered."
},
{
"code": null,
"e": 7048,
"s": 6969,
"text": "Here’s how you can get the file extension from the same summer-sales.csv file:"
},
{
"code": null,
"e": 7137,
"s": 7048,
"text": "tgt_path = pathlib.Path.cwd().joinpath('reports/summer-sales.csv')print(tgt_path.suffix)"
},
{
"code": null,
"e": 7177,
"s": 7137,
"text": "Here’s what you should see printed out:"
},
{
"code": null,
"e": 7186,
"s": 7177,
"text": ">>> .csv"
},
{
"code": null,
"e": 7222,
"s": 7186,
"text": "And finally, let’s cover iteration."
},
{
"code": null,
"e": 7364,
"s": 7222,
"text": "Let’s say you have a bunch of CSV reports in a single directory, and want to process them one by one. The iterdir() function is all you need."
},
{
"code": null,
"e": 7408,
"s": 7364,
"text": "The entire process couldn’t be any simpler:"
},
{
"code": null,
"e": 7504,
"s": 7408,
"text": "tgt_path = pathlib.Path.cwd().joinpath('reports')for file in tgt_path.iterdir(): print(file)"
},
{
"code": null,
"e": 7541,
"s": 7504,
"text": "Here’s what it prints on my machine:"
},
{
"code": null,
"e": 7674,
"s": 7541,
"text": ">>> /Users/dradecic/Desktop/pathlib_guide/reports/summer-sales.csv /Users/dradecic/Desktop/pathlib_guide/reports/winter-sales.txt"
},
{
"code": null,
"e": 7783,
"s": 7674,
"text": "And that does it for today. You now have everything needed to never cause a stupid production mistake again."
},
{
"code": null,
"e": 7953,
"s": 7783,
"text": "What are your thoughts on pathlib? Is it your favourite file and folder management library, or are you a fan of something else? Let me know in the comment section below."
},
{
"code": null,
"e": 8136,
"s": 7953,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 8147,
"s": 8136,
"text": "medium.com"
},
{
"code": null,
"e": 8194,
"s": 8147,
"text": "Follow me on Medium for more stories like this"
},
{
"code": null,
"e": 8220,
"s": 8194,
"text": "Sign up for my newsletter"
}
] |
Python Program to print a number diamond of any given size N in Rangoli Style - GeeksforGeeks
|
31 Dec, 2020
Given an integer N, the task is to print a number diamond of size N in rangoli style where N means till Nth number from number ‘1’.
Examples:
Input :
2
Output :
--2--
2-1-2
--2--
Input :
3
Output :
----3----
--3-2-3--
3-2-1-2-3
--3-2-3--
----3----
Input :
4
Output :
------4------
----4-3-4----
--4-3-2-3-4--
4-3-2-1-2-3-4
--4-3-2-3-4--
----4-3-4----
------4------
Approach:First of all print from the first row till middle row, and then print from the row after middle row till the last row. The total number of positions in each row will be 4(N-1) + 1. Number of rows will be 2(N-1) + 1. Time complexity is O(N^2).
Below is the implementation.
def print_diamond(size): # print the first triangle # (the upper half) for i in range (size): # print from first row till # middle row rownum = i + 1 num_alphabet = 2 * rownum - 1 space_in_between_alphabets = num_alphabet - 1 total_spots = (2 * size - 1) * 2 - 1 total_space = total_spots - num_alphabet space_leading_trailing = total_space - space_in_between_alphabets lead_space = int(space_leading_trailing / 2) trail_space = int(space_leading_trailing / 2) # print the leading spaces for j in range(lead_space): print('-', end ='') # determine the middle character mid_char = (1 + size - 1) - int(num_alphabet / 2) # start with the last character k = 1 + size - 1 is_alphabet_printed = False mid_char_reached = False # print the numbers alternated by '-' for j in range(num_alphabet + space_in_between_alphabets): if not is_alphabet_printed: print(str(k), end ='') is_alphabet_printed = True if k == mid_char: mid_char_reached = True if mid_char_reached == True: k += 1 else: k -= 1 else: print('-', end ='') is_alphabet_printed = False # print the trailing spaces for j in range(trail_space): print('-', end ='') # go to the next line print('') # print the rows after middle row # till last row (the second triangle # which is inverted, i.e., the lower half) for i in range(size + 1, 2 * size): rownum = i num_alphabet = 2 * (2 * size - rownum) - 1 space_in_between_alphabets = num_alphabet - 1 total_spots = (2 * size - 1) * 2 - 1 total_space = total_spots - num_alphabet space_leading_trailing = total_space - space_in_between_alphabets lead_space = int(space_leading_trailing / 2) trail_space = int(space_leading_trailing / 2) # print the leading spaces for j in range(lead_space): print('-', end ='') mid_char = (1 + size - 1) - int(num_alphabet / 2) # start with the last char k = 1 + size - 1 is_alphabet_printed = False mid_char_reached = False # print the numbers alternated by '-' for j in range(num_alphabet + space_in_between_alphabets): if not is_alphabet_printed: print(str(k), end ='') is_alphabet_printed = True if k == mid_char: mid_char_reached = True if mid_char_reached == True: k += 1 else: k -= 1 else: print('-', end ='') is_alphabet_printed = False # print the trailing spaces for j in range(trail_space): print('-', end ='') # go to the next line print('') # Driver Codeif __name__ == '__main__': n = 5 print_diamond(n)
Output:
--------5--------
------5-4-5------
----5-4-3-4-5----
--5-4-3-2-3-4-5--
5-4-3-2-1-2-3-4-5
--5-4-3-2-3-4-5--
----5-4-3-4-5----
------5-4-5------
--------5--------
pattern-printing
Python Pattern-printing
Python
Python Programs
Write From Home
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 25835,
"s": 25807,
"text": "\n31 Dec, 2020"
},
{
"code": null,
"e": 25967,
"s": 25835,
"text": "Given an integer N, the task is to print a number diamond of size N in rangoli style where N means till Nth number from number ‘1’."
},
{
"code": null,
"e": 25977,
"s": 25967,
"text": "Examples:"
},
{
"code": null,
"e": 26205,
"s": 25977,
"text": "Input : \n2\nOutput :\n--2--\n2-1-2\n--2--\n\nInput : \n3\nOutput :\n----3----\n--3-2-3--\n3-2-1-2-3\n--3-2-3--\n----3----\n\nInput :\n4\nOutput :\n------4------\n----4-3-4----\n--4-3-2-3-4--\n4-3-2-1-2-3-4\n--4-3-2-3-4--\n----4-3-4----\n------4------\n"
},
{
"code": null,
"e": 26457,
"s": 26205,
"text": "Approach:First of all print from the first row till middle row, and then print from the row after middle row till the last row. The total number of positions in each row will be 4(N-1) + 1. Number of rows will be 2(N-1) + 1. Time complexity is O(N^2)."
},
{
"code": null,
"e": 26486,
"s": 26457,
"text": "Below is the implementation."
},
{
"code": "def print_diamond(size): # print the first triangle # (the upper half) for i in range (size): # print from first row till # middle row rownum = i + 1 num_alphabet = 2 * rownum - 1 space_in_between_alphabets = num_alphabet - 1 total_spots = (2 * size - 1) * 2 - 1 total_space = total_spots - num_alphabet space_leading_trailing = total_space - space_in_between_alphabets lead_space = int(space_leading_trailing / 2) trail_space = int(space_leading_trailing / 2) # print the leading spaces for j in range(lead_space): print('-', end ='') # determine the middle character mid_char = (1 + size - 1) - int(num_alphabet / 2) # start with the last character k = 1 + size - 1 is_alphabet_printed = False mid_char_reached = False # print the numbers alternated by '-' for j in range(num_alphabet + space_in_between_alphabets): if not is_alphabet_printed: print(str(k), end ='') is_alphabet_printed = True if k == mid_char: mid_char_reached = True if mid_char_reached == True: k += 1 else: k -= 1 else: print('-', end ='') is_alphabet_printed = False # print the trailing spaces for j in range(trail_space): print('-', end ='') # go to the next line print('') # print the rows after middle row # till last row (the second triangle # which is inverted, i.e., the lower half) for i in range(size + 1, 2 * size): rownum = i num_alphabet = 2 * (2 * size - rownum) - 1 space_in_between_alphabets = num_alphabet - 1 total_spots = (2 * size - 1) * 2 - 1 total_space = total_spots - num_alphabet space_leading_trailing = total_space - space_in_between_alphabets lead_space = int(space_leading_trailing / 2) trail_space = int(space_leading_trailing / 2) # print the leading spaces for j in range(lead_space): print('-', end ='') mid_char = (1 + size - 1) - int(num_alphabet / 2) # start with the last char k = 1 + size - 1 is_alphabet_printed = False mid_char_reached = False # print the numbers alternated by '-' for j in range(num_alphabet + space_in_between_alphabets): if not is_alphabet_printed: print(str(k), end ='') is_alphabet_printed = True if k == mid_char: mid_char_reached = True if mid_char_reached == True: k += 1 else: k -= 1 else: print('-', end ='') is_alphabet_printed = False # print the trailing spaces for j in range(trail_space): print('-', end ='') # go to the next line print('') # Driver Codeif __name__ == '__main__': n = 5 print_diamond(n)",
"e": 29955,
"s": 26486,
"text": null
},
{
"code": null,
"e": 29963,
"s": 29955,
"text": "Output:"
},
{
"code": null,
"e": 30126,
"s": 29963,
"text": "--------5--------\n------5-4-5------\n----5-4-3-4-5----\n--5-4-3-2-3-4-5--\n5-4-3-2-1-2-3-4-5\n--5-4-3-2-3-4-5--\n----5-4-3-4-5----\n------5-4-5------\n--------5--------\n"
},
{
"code": null,
"e": 30143,
"s": 30126,
"text": "pattern-printing"
},
{
"code": null,
"e": 30167,
"s": 30143,
"text": "Python Pattern-printing"
},
{
"code": null,
"e": 30174,
"s": 30167,
"text": "Python"
},
{
"code": null,
"e": 30190,
"s": 30174,
"text": "Python Programs"
},
{
"code": null,
"e": 30206,
"s": 30190,
"text": "Write From Home"
},
{
"code": null,
"e": 30223,
"s": 30206,
"text": "pattern-printing"
},
{
"code": null,
"e": 30321,
"s": 30223,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30339,
"s": 30321,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30371,
"s": 30339,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30406,
"s": 30371,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30428,
"s": 30406,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30470,
"s": 30428,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30513,
"s": 30470,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 30535,
"s": 30513,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30574,
"s": 30535,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 30620,
"s": 30574,
"text": "Python | Split string into list of characters"
}
] |
Python - Find the closest date from a List - GeeksforGeeks
|
09 May, 2021
Given a date and list of dates, the task is to write a python program to find the nearest date in the given input list of dates to the input date.
Examples:
Input : test_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), datetime(2018, 9, 24), datetime(2019, 6, 10), datetime(2021, 8, 10)], test_date = datetime(2017, 6, 6)
Output : 2016-08-18 00:00:00
Explanation : Nearest date to 6 June 2017 is 18 August 2016 in list.
Input : test_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), datetime(2018, 9, 24), datetime(2019, 6, 10), datetime(2021, 8, 10)], test_date = datetime(2016, 6, 6)
Output : 2016-08-18 00:00:00
Explanation : Nearest date to 6 June 2016 is 18 August 2016 in list.
In this, a difference of each date with a given date is computed as key and date as a value using abs(). The min(), is used to get the minimum key difference and its value is the result.
Python3
# Python3 code to demonstrate working of# Nearest date in List# Using min() + dictionary comprehension + abs()from datetime import datetime # initializing datelisttest_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), datetime(2018, 9, 24), datetime(2019, 6, 10), datetime(2021, 8, 10)] # printing original listprint("The original list is : " + str(test_date_list)) # initializing test date test_date = datetime(2017, 6, 6) # get all differences with date as values cloz_dict = { abs(test_date.timestamp() - date.timestamp()) : date for date in test_date_list} # extracting minimum key using min()res = cloz_dict[min(cloz_dict.keys())] # printing resultprint("Nearest date from list : " + str(res))
Output:
The original list is : [datetime.datetime(2020, 4, 8, 0, 0), datetime.datetime(2016, 8, 18, 0, 0), datetime.datetime(2018, 9, 24, 0, 0), datetime.datetime(2019, 6, 10, 0, 0), datetime.datetime(2021, 8, 10, 0, 0)]
Nearest date from list : 2016-08-18 00:00:00
Another simpler way to solve this problem is to get differences and capture the minimum one using min(). This is a flexible method and can be extended to every datatype not only datetime.
Python3
# Python3 code to demonstrate working of# Nearest date in List# Using min() + abs() + lambdafrom datetime import datetime # initializing datelisttest_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), datetime(2018, 9, 24), datetime(2019, 6, 10), datetime(2021, 8, 10)] # printing original listprint("The original list is : " + str(test_date_list)) # initializing test date test_date = datetime(2017, 6, 6) # shorthand using lambda function for compact solutionres = min(test_date_list, key=lambda sub: abs(sub - test_date)) # printing resultprint("Nearest date from list : " + str(res))
Output:
The original list is : [datetime.datetime(2020, 4, 8, 0, 0), datetime.datetime(2016, 8, 18, 0, 0),
datetime.datetime(2018, 9, 24, 0, 0), datetime.datetime(2019, 6, 10, 0, 0), datetime.datetime(2021, 8, 10, 0, 0)]
Nearest date from list : 2016-08-18 00:00:00
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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 dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n09 May, 2021"
},
{
"code": null,
"e": 25684,
"s": 25537,
"text": "Given a date and list of dates, the task is to write a python program to find the nearest date in the given input list of dates to the input date."
},
{
"code": null,
"e": 25694,
"s": 25684,
"text": "Examples:"
},
{
"code": null,
"e": 25868,
"s": 25694,
"text": "Input : test_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), datetime(2018, 9, 24), datetime(2019, 6, 10), datetime(2021, 8, 10)], test_date = datetime(2017, 6, 6)"
},
{
"code": null,
"e": 25897,
"s": 25868,
"text": "Output : 2016-08-18 00:00:00"
},
{
"code": null,
"e": 25966,
"s": 25897,
"text": "Explanation : Nearest date to 6 June 2017 is 18 August 2016 in list."
},
{
"code": null,
"e": 26140,
"s": 25966,
"text": "Input : test_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), datetime(2018, 9, 24), datetime(2019, 6, 10), datetime(2021, 8, 10)], test_date = datetime(2016, 6, 6)"
},
{
"code": null,
"e": 26169,
"s": 26140,
"text": "Output : 2016-08-18 00:00:00"
},
{
"code": null,
"e": 26238,
"s": 26169,
"text": "Explanation : Nearest date to 6 June 2016 is 18 August 2016 in list."
},
{
"code": null,
"e": 26425,
"s": 26238,
"text": "In this, a difference of each date with a given date is computed as key and date as a value using abs(). The min(), is used to get the minimum key difference and its value is the result."
},
{
"code": null,
"e": 26433,
"s": 26425,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Nearest date in List# Using min() + dictionary comprehension + abs()from datetime import datetime # initializing datelisttest_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), datetime(2018, 9, 24), datetime(2019, 6, 10), datetime(2021, 8, 10)] # printing original listprint(\"The original list is : \" + str(test_date_list)) # initializing test date test_date = datetime(2017, 6, 6) # get all differences with date as values cloz_dict = { abs(test_date.timestamp() - date.timestamp()) : date for date in test_date_list} # extracting minimum key using min()res = cloz_dict[min(cloz_dict.keys())] # printing resultprint(\"Nearest date from list : \" + str(res))",
"e": 27198,
"s": 26433,
"text": null
},
{
"code": null,
"e": 27206,
"s": 27198,
"text": "Output:"
},
{
"code": null,
"e": 27419,
"s": 27206,
"text": "The original list is : [datetime.datetime(2020, 4, 8, 0, 0), datetime.datetime(2016, 8, 18, 0, 0), datetime.datetime(2018, 9, 24, 0, 0), datetime.datetime(2019, 6, 10, 0, 0), datetime.datetime(2021, 8, 10, 0, 0)]"
},
{
"code": null,
"e": 27464,
"s": 27419,
"text": "Nearest date from list : 2016-08-18 00:00:00"
},
{
"code": null,
"e": 27653,
"s": 27464,
"text": "Another simpler way to solve this problem is to get differences and capture the minimum one using min(). This is a flexible method and can be extended to every datatype not only datetime. "
},
{
"code": null,
"e": 27661,
"s": 27653,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Nearest date in List# Using min() + abs() + lambdafrom datetime import datetime # initializing datelisttest_date_list = [datetime(2020, 4, 8), datetime(2016, 8, 18), datetime(2018, 9, 24), datetime(2019, 6, 10), datetime(2021, 8, 10)] # printing original listprint(\"The original list is : \" + str(test_date_list)) # initializing test date test_date = datetime(2017, 6, 6) # shorthand using lambda function for compact solutionres = min(test_date_list, key=lambda sub: abs(sub - test_date)) # printing resultprint(\"Nearest date from list : \" + str(res))",
"e": 28309,
"s": 27661,
"text": null
},
{
"code": null,
"e": 28317,
"s": 28309,
"text": "Output:"
},
{
"code": null,
"e": 28417,
"s": 28317,
"text": "The original list is : [datetime.datetime(2020, 4, 8, 0, 0), datetime.datetime(2016, 8, 18, 0, 0), "
},
{
"code": null,
"e": 28531,
"s": 28417,
"text": "datetime.datetime(2018, 9, 24, 0, 0), datetime.datetime(2019, 6, 10, 0, 0), datetime.datetime(2021, 8, 10, 0, 0)]"
},
{
"code": null,
"e": 28576,
"s": 28531,
"text": "Nearest date from list : 2016-08-18 00:00:00"
},
{
"code": null,
"e": 28600,
"s": 28576,
"text": "Python datetime-program"
},
{
"code": null,
"e": 28607,
"s": 28600,
"text": "Python"
},
{
"code": null,
"e": 28623,
"s": 28607,
"text": "Python Programs"
},
{
"code": null,
"e": 28721,
"s": 28623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28753,
"s": 28721,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28795,
"s": 28753,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28837,
"s": 28795,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28864,
"s": 28837,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28920,
"s": 28864,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28942,
"s": 28920,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28981,
"s": 28942,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 29027,
"s": 28981,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 29065,
"s": 29027,
"text": "Python | Convert a list to dictionary"
}
] |
Java Program to Compare two Double Arrays - GeeksforGeeks
|
28 Dec, 2020
Java double array is used to store double data type values only. The default value of the elements in a double array is 0.
We can compare two double arrays by two ways:
By naive approach of traversing through the whole array and comparing each element.By Arrays.equals() method.
By naive approach of traversing through the whole array and comparing each element.
By Arrays.equals() method.
Method 1: Naive Approach
By Comparing one element at a time by traversing through both the arrays using for loop.
Java
// Java program to compare two double arrays import java.util.*;import java.lang.*;import java.io.*; class GFG { public static void main(String[] args) throws java.lang.Exception { // Two double arrays array1 and array2 double[] array1 = { 1.5, 2.5, 3.5, 4.5 }; double[] array2 = { 1.5, 2.5, 3.5 }; // when the length of two arrays are not // same, then both the arrays cannot be equal // so no need of comparing each element if (array1.length != array2.length) System.out.println("Arrays are not Equal"); else { for (int i = 0; i < array1.length; i++) { // comparing each and every element if (array1[i] != array2[i]) { System.out.println("Arrays are not Equal"); System.exit(0); } } System.out.println("Arrays are Equal"); } }}
Arrays are not Equal
Time Complexity: O(n)
Method 2: Using Arrays.equals() method
Syntax :
public static boolean equals(int[] a, int[] a2)
Parameters :
a1 – one array to be tested for equality
a2 – the other array to be tested for equality
Returns : true if the two arrays are equal
Java
// Java program to compare two double arrays import java.util.*;import java.lang.*;import java.io.*; class GFG { public static void main(String[] args) throws java.lang.Exception { double[] array1 = { 1.5, 2.5, 3.5, 4.5 }; double[] array2 = { 1.5, 2.5, 3.5, 4.5 }; // Arrays.equals() compares the equality // of two arrays if (Arrays.equals(array1, array2)) System.out.println("Arrays are Equal"); else System.out.println("Arrays are Not Equal"); }}
Arrays are Equal
Time Complexity: O(1)
Java-Arrays
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.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 25348,
"s": 25225,
"text": "Java double array is used to store double data type values only. The default value of the elements in a double array is 0."
},
{
"code": null,
"e": 25394,
"s": 25348,
"text": "We can compare two double arrays by two ways:"
},
{
"code": null,
"e": 25504,
"s": 25394,
"text": "By naive approach of traversing through the whole array and comparing each element.By Arrays.equals() method."
},
{
"code": null,
"e": 25588,
"s": 25504,
"text": "By naive approach of traversing through the whole array and comparing each element."
},
{
"code": null,
"e": 25615,
"s": 25588,
"text": "By Arrays.equals() method."
},
{
"code": null,
"e": 25640,
"s": 25615,
"text": "Method 1: Naive Approach"
},
{
"code": null,
"e": 25729,
"s": 25640,
"text": "By Comparing one element at a time by traversing through both the arrays using for loop."
},
{
"code": null,
"e": 25734,
"s": 25729,
"text": "Java"
},
{
"code": "// Java program to compare two double arrays import java.util.*;import java.lang.*;import java.io.*; class GFG { public static void main(String[] args) throws java.lang.Exception { // Two double arrays array1 and array2 double[] array1 = { 1.5, 2.5, 3.5, 4.5 }; double[] array2 = { 1.5, 2.5, 3.5 }; // when the length of two arrays are not // same, then both the arrays cannot be equal // so no need of comparing each element if (array1.length != array2.length) System.out.println(\"Arrays are not Equal\"); else { for (int i = 0; i < array1.length; i++) { // comparing each and every element if (array1[i] != array2[i]) { System.out.println(\"Arrays are not Equal\"); System.exit(0); } } System.out.println(\"Arrays are Equal\"); } }}",
"e": 26725,
"s": 25734,
"text": null
},
{
"code": null,
"e": 26746,
"s": 26725,
"text": "Arrays are not Equal"
},
{
"code": null,
"e": 26768,
"s": 26746,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 26807,
"s": 26768,
"text": "Method 2: Using Arrays.equals() method"
},
{
"code": null,
"e": 26816,
"s": 26807,
"text": "Syntax :"
},
{
"code": null,
"e": 26864,
"s": 26816,
"text": "public static boolean equals(int[] a, int[] a2)"
},
{
"code": null,
"e": 26878,
"s": 26864,
"text": "Parameters : "
},
{
"code": null,
"e": 26919,
"s": 26878,
"text": "a1 – one array to be tested for equality"
},
{
"code": null,
"e": 26966,
"s": 26919,
"text": "a2 – the other array to be tested for equality"
},
{
"code": null,
"e": 27009,
"s": 26966,
"text": "Returns : true if the two arrays are equal"
},
{
"code": null,
"e": 27014,
"s": 27009,
"text": "Java"
},
{
"code": "// Java program to compare two double arrays import java.util.*;import java.lang.*;import java.io.*; class GFG { public static void main(String[] args) throws java.lang.Exception { double[] array1 = { 1.5, 2.5, 3.5, 4.5 }; double[] array2 = { 1.5, 2.5, 3.5, 4.5 }; // Arrays.equals() compares the equality // of two arrays if (Arrays.equals(array1, array2)) System.out.println(\"Arrays are Equal\"); else System.out.println(\"Arrays are Not Equal\"); }}",
"e": 27542,
"s": 27014,
"text": null
},
{
"code": null,
"e": 27559,
"s": 27542,
"text": "Arrays are Equal"
},
{
"code": null,
"e": 27581,
"s": 27559,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 27593,
"s": 27581,
"text": "Java-Arrays"
},
{
"code": null,
"e": 27600,
"s": 27593,
"text": "Picked"
},
{
"code": null,
"e": 27624,
"s": 27600,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27629,
"s": 27624,
"text": "Java"
},
{
"code": null,
"e": 27643,
"s": 27629,
"text": "Java Programs"
},
{
"code": null,
"e": 27662,
"s": 27643,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27667,
"s": 27662,
"text": "Java"
},
{
"code": null,
"e": 27765,
"s": 27667,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27780,
"s": 27765,
"text": "Stream In Java"
},
{
"code": null,
"e": 27801,
"s": 27780,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27820,
"s": 27801,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27850,
"s": 27820,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27896,
"s": 27850,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27922,
"s": 27896,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27956,
"s": 27922,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28003,
"s": 27956,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 28035,
"s": 28003,
"text": "How to Iterate HashMap in Java?"
}
] |
Histograms and Density Plots in Python - GeeksforGeeks
|
31 Jul, 2021
Prerequisites: Seaborn
The histogram is the graphical representation that organizes a group of data points into the specified range. Creating the histogram provides the Visual representation of data distribution. By using a histogram we can represent a large amount of data, and its frequency.
Density Plot is the continuous and smoothed version of the Histogram estimated from the data. It is estimated through Kernel Density Estimation.
In this method Kernel (continuous curve) is drawn at every individual data point and then all these curves are added together to make a single smoothened density estimation. Histogram fails when we want to compare the data distribution of a single variable over the multiple categories at that time Density Plot is useful for visualizing the data.
Import the necessary libraries.
Create or import a dataset from seaborn library.
Select the column for which we have to make a plot.
For making the plot we are using distplot() function provided by seaborn library for plotting Histogram and Density Plot together in which we have to pass the dataset column.
We can also make Histogram and Density Plot individually using distplot() function according to our needs.
For creating Histogram individually we have to pass hist=False as a parameter in the distplot() function.
For creating Density Plot individually we have to pass kde=False as a parameter in the distplot() function.
Now after making the plot we have to visualize that, so for visualization, we have to use show() function provided by matplotlib.pyplot library.
For plotting the Histogram and Density Plots together we are using diamond and iris dataset provided by seaborn library.
Example 1: Importing the dataset and Print them.
Python
# importing seaborn libraryimport seaborn as sns # importing dataset from the librarydf = sns.load_dataset('diamonds') # printing the datasetdf
Output:
Example 2: Plotting the Histogram using seaborn library on the default setting.
Python
# importing necessary librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing diamond dataset from the librarydf = sns.load_dataset('diamonds') # plotting histogram for carat using distplot()sns.distplot(a=df.carat, kde=False) # visualizing plot using matplotlib.pyplot libraryplt.show()
Output:
Example 3: Plotting the Density using seaborn library on the default setting.
Python
# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing diamond dataset from the librarydf = sns.load_dataset('diamonds') # plotting density plot for carat using distplot()sns.distplot(a=df.carat, hist=False) # visualizing plot using matplotlib.pyplot libraryplt.show()
Output:
Example 4: Plotting Histogram and Density Plot together on default settings.
Python
# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing diamond dataset from the librarydf = sns.load_dataset('diamonds') # plotting histogram and density# plot for carat using distplot()sns.distplot(a=df.carat) # visualizing plot using matplotlib.pyplot libraryplt.show()
Output:
Example 5: Plotting Histogram and Density Plot together by setting bins and color.
Python
# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing diamond dataset from the librarydf = sns.load_dataset('diamonds') # plotting histogram and density plot# for carat using distplot() by setting colorsns.distplot(a=df.carat, bins=40, color='purple', hist_kws={"edgecolor": 'black'}) # visualizing plot using matplotlib.pyplot libraryplt.show()
Output:
Example 6: Plotting Histogram and Density Plot together using Iris dataset.
Python
# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing iris dataset from the librarydf2 = sns.load_dataset('iris') # plotting histogram and density plot for# petal length using distplot() by setting colorsns.distplot(a=df2.petal_length, color='green', hist_kws={"edgecolor": 'black'}) # visualizing plot using matplotlib.pyplot libraryplt.show()
Output:
We can also print the iris dataset by adding one line of code i.e, print(df2), and dataset looks like.
Example 7: Plotting Histogram and Density Plot together on sepal length.
Python
# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing iris dataset from the librarydf2 = sns.load_dataset('iris') # plotting histogram and density plot for# sepal width using distplot() by setting colorsns.distplot(a=df2.sepal_width, color='red', hist_kws={"edgecolor": 'white'}) # visualizing plot using matplotlib.pyplot libraryplt.show()
Output:
In this way, we can plot Histogram and Density Plot together on any dataset columns according to our needs.
singghakshay
Picked
Python-Seaborn
Technical Scripter 2020
Python
Technical Scripter
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": 25561,
"s": 25533,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 25584,
"s": 25561,
"text": "Prerequisites: Seaborn"
},
{
"code": null,
"e": 25855,
"s": 25584,
"text": "The histogram is the graphical representation that organizes a group of data points into the specified range. Creating the histogram provides the Visual representation of data distribution. By using a histogram we can represent a large amount of data, and its frequency."
},
{
"code": null,
"e": 26000,
"s": 25855,
"text": "Density Plot is the continuous and smoothed version of the Histogram estimated from the data. It is estimated through Kernel Density Estimation."
},
{
"code": null,
"e": 26348,
"s": 26000,
"text": "In this method Kernel (continuous curve) is drawn at every individual data point and then all these curves are added together to make a single smoothened density estimation. Histogram fails when we want to compare the data distribution of a single variable over the multiple categories at that time Density Plot is useful for visualizing the data."
},
{
"code": null,
"e": 26380,
"s": 26348,
"text": "Import the necessary libraries."
},
{
"code": null,
"e": 26429,
"s": 26380,
"text": "Create or import a dataset from seaborn library."
},
{
"code": null,
"e": 26481,
"s": 26429,
"text": "Select the column for which we have to make a plot."
},
{
"code": null,
"e": 26656,
"s": 26481,
"text": "For making the plot we are using distplot() function provided by seaborn library for plotting Histogram and Density Plot together in which we have to pass the dataset column."
},
{
"code": null,
"e": 26763,
"s": 26656,
"text": "We can also make Histogram and Density Plot individually using distplot() function according to our needs."
},
{
"code": null,
"e": 26869,
"s": 26763,
"text": "For creating Histogram individually we have to pass hist=False as a parameter in the distplot() function."
},
{
"code": null,
"e": 26977,
"s": 26869,
"text": "For creating Density Plot individually we have to pass kde=False as a parameter in the distplot() function."
},
{
"code": null,
"e": 27122,
"s": 26977,
"text": "Now after making the plot we have to visualize that, so for visualization, we have to use show() function provided by matplotlib.pyplot library."
},
{
"code": null,
"e": 27243,
"s": 27122,
"text": "For plotting the Histogram and Density Plots together we are using diamond and iris dataset provided by seaborn library."
},
{
"code": null,
"e": 27292,
"s": 27243,
"text": "Example 1: Importing the dataset and Print them."
},
{
"code": null,
"e": 27299,
"s": 27292,
"text": "Python"
},
{
"code": "# importing seaborn libraryimport seaborn as sns # importing dataset from the librarydf = sns.load_dataset('diamonds') # printing the datasetdf",
"e": 27443,
"s": 27299,
"text": null
},
{
"code": null,
"e": 27452,
"s": 27443,
"text": "Output: "
},
{
"code": null,
"e": 27533,
"s": 27452,
"text": "Example 2: Plotting the Histogram using seaborn library on the default setting. "
},
{
"code": null,
"e": 27540,
"s": 27533,
"text": "Python"
},
{
"code": "# importing necessary librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing diamond dataset from the librarydf = sns.load_dataset('diamonds') # plotting histogram for carat using distplot()sns.distplot(a=df.carat, kde=False) # visualizing plot using matplotlib.pyplot libraryplt.show()",
"e": 27846,
"s": 27540,
"text": null
},
{
"code": null,
"e": 27854,
"s": 27846,
"text": "Output:"
},
{
"code": null,
"e": 27932,
"s": 27854,
"text": "Example 3: Plotting the Density using seaborn library on the default setting."
},
{
"code": null,
"e": 27939,
"s": 27932,
"text": "Python"
},
{
"code": "# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing diamond dataset from the librarydf = sns.load_dataset('diamonds') # plotting density plot for carat using distplot()sns.distplot(a=df.carat, hist=False) # visualizing plot using matplotlib.pyplot libraryplt.show()",
"e": 28239,
"s": 27939,
"text": null
},
{
"code": null,
"e": 28247,
"s": 28239,
"text": "Output:"
},
{
"code": null,
"e": 28324,
"s": 28247,
"text": "Example 4: Plotting Histogram and Density Plot together on default settings."
},
{
"code": null,
"e": 28331,
"s": 28324,
"text": "Python"
},
{
"code": "# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing diamond dataset from the librarydf = sns.load_dataset('diamonds') # plotting histogram and density# plot for carat using distplot()sns.distplot(a=df.carat) # visualizing plot using matplotlib.pyplot libraryplt.show()",
"e": 28634,
"s": 28331,
"text": null
},
{
"code": null,
"e": 28642,
"s": 28634,
"text": "Output:"
},
{
"code": null,
"e": 28725,
"s": 28642,
"text": "Example 5: Plotting Histogram and Density Plot together by setting bins and color."
},
{
"code": null,
"e": 28732,
"s": 28725,
"text": "Python"
},
{
"code": "# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing diamond dataset from the librarydf = sns.load_dataset('diamonds') # plotting histogram and density plot# for carat using distplot() by setting colorsns.distplot(a=df.carat, bins=40, color='purple', hist_kws={\"edgecolor\": 'black'}) # visualizing plot using matplotlib.pyplot libraryplt.show()",
"e": 29122,
"s": 28732,
"text": null
},
{
"code": null,
"e": 29131,
"s": 29122,
"text": " Output:"
},
{
"code": null,
"e": 29207,
"s": 29131,
"text": "Example 6: Plotting Histogram and Density Plot together using Iris dataset."
},
{
"code": null,
"e": 29214,
"s": 29207,
"text": "Python"
},
{
"code": "# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing iris dataset from the librarydf2 = sns.load_dataset('iris') # plotting histogram and density plot for# petal length using distplot() by setting colorsns.distplot(a=df2.petal_length, color='green', hist_kws={\"edgecolor\": 'black'}) # visualizing plot using matplotlib.pyplot libraryplt.show()",
"e": 29603,
"s": 29214,
"text": null
},
{
"code": null,
"e": 29611,
"s": 29603,
"text": "Output:"
},
{
"code": null,
"e": 29714,
"s": 29611,
"text": "We can also print the iris dataset by adding one line of code i.e, print(df2), and dataset looks like."
},
{
"code": null,
"e": 29787,
"s": 29714,
"text": "Example 7: Plotting Histogram and Density Plot together on sepal length."
},
{
"code": null,
"e": 29794,
"s": 29787,
"text": "Python"
},
{
"code": "# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # importing iris dataset from the librarydf2 = sns.load_dataset('iris') # plotting histogram and density plot for# sepal width using distplot() by setting colorsns.distplot(a=df2.sepal_width, color='red', hist_kws={\"edgecolor\": 'white'}) # visualizing plot using matplotlib.pyplot libraryplt.show()",
"e": 30179,
"s": 29794,
"text": null
},
{
"code": null,
"e": 30187,
"s": 30179,
"text": "Output:"
},
{
"code": null,
"e": 30295,
"s": 30187,
"text": "In this way, we can plot Histogram and Density Plot together on any dataset columns according to our needs."
},
{
"code": null,
"e": 30308,
"s": 30295,
"text": "singghakshay"
},
{
"code": null,
"e": 30315,
"s": 30308,
"text": "Picked"
},
{
"code": null,
"e": 30330,
"s": 30315,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 30354,
"s": 30330,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 30361,
"s": 30354,
"text": "Python"
},
{
"code": null,
"e": 30380,
"s": 30361,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30478,
"s": 30380,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30510,
"s": 30478,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30552,
"s": 30510,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30594,
"s": 30552,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30621,
"s": 30594,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30677,
"s": 30621,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30699,
"s": 30677,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30738,
"s": 30699,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30769,
"s": 30738,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30798,
"s": 30769,
"text": "Create a directory in Python"
}
] |
How to avoid duplicate columns after join in PySpark ? - GeeksforGeeks
|
19 Dec, 2021
In this article, we will discuss how to avoid duplicate columns in DataFrame after join in PySpark using Python.
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show()
Output:
Python3
# list of employee datadata1 = [["1", "45000", "IT"], ["2", "145000", "Manager"], ["6", "45000", "HR"], ["5", "34000", "Sales"]] # specify column namescolumns = ['ID', 'salary', 'department'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data1, columns) dataframe1.show()
Output:
We can join the dataframes using joins like inner join and after this join, we can use the drop method to remove one duplicate column.
Syntax: dataframe.join(dataframe1,dataframe.column_name == dataframe1.column_name,”inner”).drop(dataframe.column_name)
where,
dataframe is the first dataframe
dataframe1 is the second dataframe
inner specifies inner join
drop() will delete the common column and delete first dataframe column
Python3
# inner join on two dataframes# and remove duplicate columndataframe.join(dataframe1, dataframe.ID == dataframe1.ID, "inner").drop(dataframe.ID).show()
Output:
Here we are simply using join to join two dataframes and then drop duplicate columns.
Syntax: dataframe.join(dataframe1, [‘column_name’]).show()
where,
dataframe is the first dataframe
dataframe1 is the second dataframe
column_name is the common column exists in two dataframes
Python3
# join on two dataframes# and remove duplicate columndataframe.join(dataframe1, ['ID']).show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25995,
"s": 25967,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 26108,
"s": 25995,
"text": "In this article, we will discuss how to avoid duplicate columns in DataFrame after join in PySpark using Python."
},
{
"code": null,
"e": 26116,
"s": 26108,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show()",
"e": 26727,
"s": 26116,
"text": null
},
{
"code": null,
"e": 26735,
"s": 26727,
"text": "Output:"
},
{
"code": null,
"e": 26743,
"s": 26735,
"text": "Python3"
},
{
"code": "# list of employee datadata1 = [[\"1\", \"45000\", \"IT\"], [\"2\", \"145000\", \"Manager\"], [\"6\", \"45000\", \"HR\"], [\"5\", \"34000\", \"Sales\"]] # specify column namescolumns = ['ID', 'salary', 'department'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data1, columns) dataframe1.show()",
"e": 27077,
"s": 26743,
"text": null
},
{
"code": null,
"e": 27085,
"s": 27077,
"text": "Output:"
},
{
"code": null,
"e": 27220,
"s": 27085,
"text": "We can join the dataframes using joins like inner join and after this join, we can use the drop method to remove one duplicate column."
},
{
"code": null,
"e": 27339,
"s": 27220,
"text": "Syntax: dataframe.join(dataframe1,dataframe.column_name == dataframe1.column_name,”inner”).drop(dataframe.column_name)"
},
{
"code": null,
"e": 27346,
"s": 27339,
"text": "where,"
},
{
"code": null,
"e": 27379,
"s": 27346,
"text": "dataframe is the first dataframe"
},
{
"code": null,
"e": 27414,
"s": 27379,
"text": "dataframe1 is the second dataframe"
},
{
"code": null,
"e": 27441,
"s": 27414,
"text": "inner specifies inner join"
},
{
"code": null,
"e": 27512,
"s": 27441,
"text": "drop() will delete the common column and delete first dataframe column"
},
{
"code": null,
"e": 27520,
"s": 27512,
"text": "Python3"
},
{
"code": "# inner join on two dataframes# and remove duplicate columndataframe.join(dataframe1, dataframe.ID == dataframe1.ID, \"inner\").drop(dataframe.ID).show()",
"e": 27700,
"s": 27520,
"text": null
},
{
"code": null,
"e": 27708,
"s": 27700,
"text": "Output:"
},
{
"code": null,
"e": 27794,
"s": 27708,
"text": "Here we are simply using join to join two dataframes and then drop duplicate columns."
},
{
"code": null,
"e": 27853,
"s": 27794,
"text": "Syntax: dataframe.join(dataframe1, [‘column_name’]).show()"
},
{
"code": null,
"e": 27860,
"s": 27853,
"text": "where,"
},
{
"code": null,
"e": 27893,
"s": 27860,
"text": "dataframe is the first dataframe"
},
{
"code": null,
"e": 27928,
"s": 27893,
"text": "dataframe1 is the second dataframe"
},
{
"code": null,
"e": 27986,
"s": 27928,
"text": "column_name is the common column exists in two dataframes"
},
{
"code": null,
"e": 27994,
"s": 27986,
"text": "Python3"
},
{
"code": "# join on two dataframes# and remove duplicate columndataframe.join(dataframe1, ['ID']).show()",
"e": 28089,
"s": 27994,
"text": null
},
{
"code": null,
"e": 28097,
"s": 28089,
"text": "Output:"
},
{
"code": null,
"e": 28104,
"s": 28097,
"text": "Picked"
},
{
"code": null,
"e": 28119,
"s": 28104,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 28126,
"s": 28119,
"text": "Python"
},
{
"code": null,
"e": 28224,
"s": 28126,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28242,
"s": 28224,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28277,
"s": 28242,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28309,
"s": 28277,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28331,
"s": 28309,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28373,
"s": 28331,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28403,
"s": 28373,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28429,
"s": 28403,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28458,
"s": 28429,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28502,
"s": 28458,
"text": "Reading and Writing to text files in Python"
}
] |
Python | Pandas Series.to_clipboard() - GeeksforGeeks
|
05 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.to_clipboard() function copy object to the system clipboard. It write a text representation of object to the system clipboard. This can be pasted into Excel as well.
Syntax: Series.to_clipboard(excel=True, sep=None, **kwargs)
Parameter :excel : bool, default Truesep : str, default ‘\t’**kwargs : These parameters will be passed to DataFrame.to_csv.
Returns : None
Example #1: Use Series.to_clipboard() function to copy the given Series object to the systems clipboard.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)
Output :
Now we will use Series.to_clipboard() function to copy the given series object to the systems clipboard.
# copy to clipboardsr.to_clipboard()
Output :
After executing the last line of code we simply pasted what was copied to the system’s clipboard in Notepad++. This is what it looks like.
Example #2: Use Series.to_clipboard() function to copy the given Series object to the systems clipboard.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None]) # Print the seriesprint(sr)
Output :
Now we will use Series.to_clipboard() function to copy the given series object to the systems clipboard.
# copy to clipboardsr.to_clipboard()
Output :
After executing the last line of code we simply pasted what was copied to the system’s clipboard in Notepad++. This is what it looks like. Notice how missing values has been represented as blanks.
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.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25479,
"s": 25451,
"text": "\n05 Feb, 2019"
},
{
"code": null,
"e": 25736,
"s": 25479,
"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": 25916,
"s": 25736,
"text": "Pandas Series.to_clipboard() function copy object to the system clipboard. It write a text representation of object to the system clipboard. This can be pasted into Excel as well."
},
{
"code": null,
"e": 25976,
"s": 25916,
"text": "Syntax: Series.to_clipboard(excel=True, sep=None, **kwargs)"
},
{
"code": null,
"e": 26100,
"s": 25976,
"text": "Parameter :excel : bool, default Truesep : str, default ‘\\t’**kwargs : These parameters will be passed to DataFrame.to_csv."
},
{
"code": null,
"e": 26115,
"s": 26100,
"text": "Returns : None"
},
{
"code": null,
"e": 26220,
"s": 26115,
"text": "Example #1: Use Series.to_clipboard() function to copy the given Series object to the systems clipboard."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)",
"e": 26572,
"s": 26220,
"text": null
},
{
"code": null,
"e": 26581,
"s": 26572,
"text": "Output :"
},
{
"code": null,
"e": 26686,
"s": 26581,
"text": "Now we will use Series.to_clipboard() function to copy the given series object to the systems clipboard."
},
{
"code": "# copy to clipboardsr.to_clipboard()",
"e": 26723,
"s": 26686,
"text": null
},
{
"code": null,
"e": 26732,
"s": 26723,
"text": "Output :"
},
{
"code": null,
"e": 26871,
"s": 26732,
"text": "After executing the last line of code we simply pasted what was copied to the system’s clipboard in Notepad++. This is what it looks like."
},
{
"code": null,
"e": 26976,
"s": 26871,
"text": "Example #2: Use Series.to_clipboard() function to copy the given Series object to the systems clipboard."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None]) # Print the seriesprint(sr)",
"e": 27148,
"s": 26976,
"text": null
},
{
"code": null,
"e": 27157,
"s": 27148,
"text": "Output :"
},
{
"code": null,
"e": 27262,
"s": 27157,
"text": "Now we will use Series.to_clipboard() function to copy the given series object to the systems clipboard."
},
{
"code": "# copy to clipboardsr.to_clipboard()",
"e": 27299,
"s": 27262,
"text": null
},
{
"code": null,
"e": 27308,
"s": 27299,
"text": "Output :"
},
{
"code": null,
"e": 27505,
"s": 27308,
"text": "After executing the last line of code we simply pasted what was copied to the system’s clipboard in Notepad++. This is what it looks like. Notice how missing values has been represented as blanks."
},
{
"code": null,
"e": 27526,
"s": 27505,
"text": "Python pandas-series"
},
{
"code": null,
"e": 27555,
"s": 27526,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 27569,
"s": 27555,
"text": "Python-pandas"
},
{
"code": null,
"e": 27576,
"s": 27569,
"text": "Python"
},
{
"code": null,
"e": 27674,
"s": 27576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27692,
"s": 27674,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27727,
"s": 27692,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27759,
"s": 27727,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27781,
"s": 27759,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27823,
"s": 27781,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27853,
"s": 27823,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27879,
"s": 27853,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27908,
"s": 27879,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27952,
"s": 27908,
"text": "Reading and Writing to text files in Python"
}
] |
Tailwind CSS Z-index - GeeksforGeeks
|
23 Mar, 2022
The tailwind CSS is a utility CSS framework that provides classes the manage our HTML content in the use of CSS. The tailwind CSS makes our designing part easier and responsive for multiple platforms. The z-Index utility is for controlling the stack order of an element. It is the alternative to the CSS z-index property. This class is used to describe the z-index along the three-dimensional plane, as given in the below examples.
Tailwind CSS z-index classes:
z-0
z-10
z-20
z-30
z-40
z-50
z-auto
Note: In the above class, z-0 is equivalent to z-index:0 CSS property and so on.
z-0: It is used to give the z-index 0 to the element.
Syntax:
<element class="z-0">....</element>
Example:
HTML
<!DOCTYPE html><head> <link rel="stylesheet" href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class="flex-column"> <div class="relative z-0 w-full h-12 bg-green-400" style="top: 32px;">0</div> <div class="relative z-10 w-full h-12 bg-yellow-400">1</div> <div class="relative z-20 w-full h-12 bg-red-400">2</div> <div class="relative z-30 w-full h-12 bg-blue-400">3</div> <div class="relative z-40 w-full h-12 bg-green-300">4</div> <div class="relative z-50 w-full h-12 bg-orange-400">5</div> </div></body> </html>
Output:
z-10: It is used to give the z-index 10 to the element. The elements appear 10px upside along the z-axis.
Syntax:
<element class="z-10">....</element>
Example:
HTML
<!DOCTYPE html><head> <link rel="stylesheet" href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class="flex-column"> <div class="relative z-0 w-full h-12 bg-green-400">0</div> <div class="relative z-10 w-full h-12 bg-yellow-400" style="top: 32px;">1</div> <div class="relative z-20 w-full h-12 bg-red-400">2</div> <div class="relative z-30 w-full h-12 bg-blue-400">3</div> <div class="relative z-40 w-full h-12 bg-green-300">4</div> <div class="relative z-50 w-full h-12 bg-orange-400">5</div> </div></body> </html>
Output:
z-20: It is used to give the z-index 20 to the element. The elements appear 20px upside along the z-axis.
Syntax:
<element class="z-20">....</element>
Example:
HTML
<!DOCTYPE html><head> <link rel="stylesheet" href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class="flex-column"> <div class="relative z-0 w-full h-12 bg-green-400">0</div> <div class="relative z-10 w-full h-12 bg-yellow-400">1</div> <div class="relative z-20 w-full h-12 bg-red-400" style="top: 32px;">2</div> <div class="relative z-30 w-full h-12 bg-blue-400">3</div> <div class="relative z-40 w-full h-12 bg-green-300">4</div> <div class="relative z-50 w-full h-12 bg-orange-400">5</div> </div></body> </html>
Output:
z-30: It is used to give the z-index 30 to the element. The elements appear 30px upside along the z-axis.
Syntax:
<element class="z-30">....</element>
Example:
HTML
<!DOCTYPE html><head> <link rel="stylesheet" href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class="flex-column"> <div class="relative z-0 w-full h-12 bg-green-400">0</div> <div class="relative z-10 w-full h-12 bg-yellow-400">1</div> <div class="relative z-20 w-full h-12 bg-red-400">2</div> <div class="relative z-30 w-full h-12 bg-blue-400" style="top: 32px;">3</div> <div class="relative z-40 w-full h-12 bg-green-300">4</div> <div class="relative z-50 w-full h-12 bg-orange-400">5</div> </div></body> </html>
Output:
z-40: It is used to give the z-index 40 to the element. The elements appear 40px upside along the z-axis.
Syntax:
<element class="z-40">....</element>
Example:
HTML
<!DOCTYPE html><head> <link rel="stylesheet" href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class="flex-column"> <div class="relative z-0 w-full h-12 bg-green-400">0</div> <div class="relative z-10 w-full h-12 bg-yellow-400">1</div> <div class="relative z-20 w-full h-12 bg-red-400">2</div> <div class="relative z-30 w-full h-12 bg-blue-400">3</div> <div class="relative z-40 w-full h-12 bg-green-300" style="top: 32px;">4</div> <div class="relative z-50 w-full h-12 bg-orange-400">5</div> </div></body> </html>
Output:
z-50: It is used to give the z-index 50 to the element. The elements appear 50px upside along the z-axis.
Syntax:
<element class="z-50">....</element>
Example:
HTML
<!DOCTYPE html><head> <link rel="stylesheet" href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class="flex-column"> <div class="relative z-0 w-full h-12 bg-green-400">0</div> <div class="relative z-10 w-full h-12 bg-yellow-400">1</div> <div class="relative z-20 w-full h-12 bg-red-400">2</div> <div class="relative z-30 w-full h-12 bg-blue-400">3</div> <div class="relative z-40 w-full h-12 bg-green-300">4</div> <div class="relative z-50 w-full h-12 bg-orange-400" style="top: 32px;">5</div> </div></body> </html>
Output:
Picked
Tailwind CSS
Tailwind-Layout
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 37385,
"s": 37357,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 37817,
"s": 37385,
"text": "The tailwind CSS is a utility CSS framework that provides classes the manage our HTML content in the use of CSS. The tailwind CSS makes our designing part easier and responsive for multiple platforms. The z-Index utility is for controlling the stack order of an element. It is the alternative to the CSS z-index property. This class is used to describe the z-index along the three-dimensional plane, as given in the below examples."
},
{
"code": null,
"e": 37847,
"s": 37817,
"text": "Tailwind CSS z-index classes:"
},
{
"code": null,
"e": 37851,
"s": 37847,
"text": "z-0"
},
{
"code": null,
"e": 37856,
"s": 37851,
"text": "z-10"
},
{
"code": null,
"e": 37861,
"s": 37856,
"text": "z-20"
},
{
"code": null,
"e": 37866,
"s": 37861,
"text": "z-30"
},
{
"code": null,
"e": 37871,
"s": 37866,
"text": "z-40"
},
{
"code": null,
"e": 37876,
"s": 37871,
"text": "z-50"
},
{
"code": null,
"e": 37883,
"s": 37876,
"text": "z-auto"
},
{
"code": null,
"e": 37964,
"s": 37883,
"text": "Note: In the above class, z-0 is equivalent to z-index:0 CSS property and so on."
},
{
"code": null,
"e": 38019,
"s": 37964,
"text": "z-0: It is used to give the z-index 0 to the element. "
},
{
"code": null,
"e": 38027,
"s": 38019,
"text": "Syntax:"
},
{
"code": null,
"e": 38063,
"s": 38027,
"text": "<element class=\"z-0\">....</element>"
},
{
"code": null,
"e": 38072,
"s": 38063,
"text": "Example:"
},
{
"code": null,
"e": 38077,
"s": 38072,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><head> <link rel=\"stylesheet\" href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\"></head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class=\"flex-column\"> <div class=\"relative z-0 w-full h-12 bg-green-400\" style=\"top: 32px;\">0</div> <div class=\"relative z-10 w-full h-12 bg-yellow-400\">1</div> <div class=\"relative z-20 w-full h-12 bg-red-400\">2</div> <div class=\"relative z-30 w-full h-12 bg-blue-400\">3</div> <div class=\"relative z-40 w-full h-12 bg-green-300\">4</div> <div class=\"relative z-50 w-full h-12 bg-orange-400\">5</div> </div></body> </html>",
"e": 38957,
"s": 38077,
"text": null
},
{
"code": null,
"e": 38966,
"s": 38957,
"text": "Output: "
},
{
"code": null,
"e": 39073,
"s": 38966,
"text": " z-10: It is used to give the z-index 10 to the element. The elements appear 10px upside along the z-axis."
},
{
"code": null,
"e": 39081,
"s": 39073,
"text": "Syntax:"
},
{
"code": null,
"e": 39118,
"s": 39081,
"text": "<element class=\"z-10\">....</element>"
},
{
"code": null,
"e": 39127,
"s": 39118,
"text": "Example:"
},
{
"code": null,
"e": 39132,
"s": 39127,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><head> <link rel=\"stylesheet\" href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\"></head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class=\"flex-column\"> <div class=\"relative z-0 w-full h-12 bg-green-400\">0</div> <div class=\"relative z-10 w-full h-12 bg-yellow-400\" style=\"top: 32px;\">1</div> <div class=\"relative z-20 w-full h-12 bg-red-400\">2</div> <div class=\"relative z-30 w-full h-12 bg-blue-400\">3</div> <div class=\"relative z-40 w-full h-12 bg-green-300\">4</div> <div class=\"relative z-50 w-full h-12 bg-orange-400\">5</div> </div></body> </html>",
"e": 39898,
"s": 39132,
"text": null
},
{
"code": null,
"e": 39907,
"s": 39898,
"text": "Output: "
},
{
"code": null,
"e": 40013,
"s": 39907,
"text": "z-20: It is used to give the z-index 20 to the element. The elements appear 20px upside along the z-axis."
},
{
"code": null,
"e": 40021,
"s": 40013,
"text": "Syntax:"
},
{
"code": null,
"e": 40058,
"s": 40021,
"text": "<element class=\"z-20\">....</element>"
},
{
"code": null,
"e": 40067,
"s": 40058,
"text": "Example:"
},
{
"code": null,
"e": 40072,
"s": 40067,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><head> <link rel=\"stylesheet\" href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\"></head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class=\"flex-column\"> <div class=\"relative z-0 w-full h-12 bg-green-400\">0</div> <div class=\"relative z-10 w-full h-12 bg-yellow-400\">1</div> <div class=\"relative z-20 w-full h-12 bg-red-400\" style=\"top: 32px;\">2</div> <div class=\"relative z-30 w-full h-12 bg-blue-400\">3</div> <div class=\"relative z-40 w-full h-12 bg-green-300\">4</div> <div class=\"relative z-50 w-full h-12 bg-orange-400\">5</div> </div></body> </html>",
"e": 40860,
"s": 40072,
"text": null
},
{
"code": null,
"e": 40868,
"s": 40860,
"text": "Output:"
},
{
"code": null,
"e": 40974,
"s": 40868,
"text": "z-30: It is used to give the z-index 30 to the element. The elements appear 30px upside along the z-axis."
},
{
"code": null,
"e": 40982,
"s": 40974,
"text": "Syntax:"
},
{
"code": null,
"e": 41019,
"s": 40982,
"text": "<element class=\"z-30\">....</element>"
},
{
"code": null,
"e": 41028,
"s": 41019,
"text": "Example:"
},
{
"code": null,
"e": 41033,
"s": 41028,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><head> <link rel=\"stylesheet\" href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\"></head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class=\"flex-column\"> <div class=\"relative z-0 w-full h-12 bg-green-400\">0</div> <div class=\"relative z-10 w-full h-12 bg-yellow-400\">1</div> <div class=\"relative z-20 w-full h-12 bg-red-400\">2</div> <div class=\"relative z-30 w-full h-12 bg-blue-400\" style=\"top: 32px;\">3</div> <div class=\"relative z-40 w-full h-12 bg-green-300\">4</div> <div class=\"relative z-50 w-full h-12 bg-orange-400\">5</div> </div></body> </html>",
"e": 41806,
"s": 41033,
"text": null
},
{
"code": null,
"e": 41814,
"s": 41806,
"text": "Output:"
},
{
"code": null,
"e": 41921,
"s": 41814,
"text": " z-40: It is used to give the z-index 40 to the element. The elements appear 40px upside along the z-axis."
},
{
"code": null,
"e": 41929,
"s": 41921,
"text": "Syntax:"
},
{
"code": null,
"e": 41966,
"s": 41929,
"text": "<element class=\"z-40\">....</element>"
},
{
"code": null,
"e": 41975,
"s": 41966,
"text": "Example:"
},
{
"code": null,
"e": 41980,
"s": 41975,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><head> <link rel=\"stylesheet\" href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\"></head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class=\"flex-column\"> <div class=\"relative z-0 w-full h-12 bg-green-400\">0</div> <div class=\"relative z-10 w-full h-12 bg-yellow-400\">1</div> <div class=\"relative z-20 w-full h-12 bg-red-400\">2</div> <div class=\"relative z-30 w-full h-12 bg-blue-400\">3</div> <div class=\"relative z-40 w-full h-12 bg-green-300\" style=\"top: 32px;\">4</div> <div class=\"relative z-50 w-full h-12 bg-orange-400\">5</div> </div></body> </html>",
"e": 42767,
"s": 41980,
"text": null
},
{
"code": null,
"e": 42775,
"s": 42767,
"text": "Output:"
},
{
"code": null,
"e": 42882,
"s": 42775,
"text": " z-50: It is used to give the z-index 50 to the element. The elements appear 50px upside along the z-axis."
},
{
"code": null,
"e": 42890,
"s": 42882,
"text": "Syntax:"
},
{
"code": null,
"e": 42927,
"s": 42890,
"text": "<element class=\"z-50\">....</element>"
},
{
"code": null,
"e": 42936,
"s": 42927,
"text": "Example:"
},
{
"code": null,
"e": 42941,
"s": 42936,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><head> <link rel=\"stylesheet\" href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\"></head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Z-Index Class</b> <div class=\"flex-column\"> <div class=\"relative z-0 w-full h-12 bg-green-400\">0</div> <div class=\"relative z-10 w-full h-12 bg-yellow-400\">1</div> <div class=\"relative z-20 w-full h-12 bg-red-400\">2</div> <div class=\"relative z-30 w-full h-12 bg-blue-400\">3</div> <div class=\"relative z-40 w-full h-12 bg-green-300\">4</div> <div class=\"relative z-50 w-full h-12 bg-orange-400\" style=\"top: 32px;\">5</div> </div></body> </html>",
"e": 43729,
"s": 42941,
"text": null
},
{
"code": null,
"e": 43737,
"s": 43729,
"text": "Output:"
},
{
"code": null,
"e": 43744,
"s": 43737,
"text": "Picked"
},
{
"code": null,
"e": 43757,
"s": 43744,
"text": "Tailwind CSS"
},
{
"code": null,
"e": 43773,
"s": 43757,
"text": "Tailwind-Layout"
},
{
"code": null,
"e": 43777,
"s": 43773,
"text": "CSS"
},
{
"code": null,
"e": 43794,
"s": 43777,
"text": "Web Technologies"
},
{
"code": null,
"e": 43892,
"s": 43794,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43942,
"s": 43892,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 44004,
"s": 43942,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 44052,
"s": 44004,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 44110,
"s": 44052,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 44165,
"s": 44110,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 44205,
"s": 44165,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 44238,
"s": 44205,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 44283,
"s": 44238,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 44326,
"s": 44283,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Decode a string recursively encoded as count followed by substring | Set 2 (using Recursion) - GeeksforGeeks
|
05 Apr, 2022
An encoded string str is given. The pattern in which the string is encoded is as follows.
<count>[sub_str] ==> The substring ‘sub_str’ appears count times.
The task is to decode this string str.
Examples:
Input: str = “1[b]”Output: bExplanation: The substring ‘b’ is repeated 1 time.
Input: str = “2[ab]”Output: ababExplanation: The substring “ab” is repeated two times.
Input: str = “2[a2[b]]”Output: abbabbExplanation: The substring ‘b’ is repeated 2 times and added to ‘a’ which forms a substring “abb”. Now this substring is repeated two time. So the final string is “abbabb”.
Iterative Approach: The iterative approach is mentioned in the Set-1 of this problem.
Recursive Approach: In this article, the problem will be solved using Recursion and Stack. Follow the approach mentioned below to solve the problem
Declare a stack
Recursively traverse each character of the given string one by one. There can be 4 cases:Case 1: Current character is ‘[‘No need to do anything in this case. Just continue to next characterCase 2: Current character is ‘]’Pop the top string temp and top integer x from the stackRepeat the string temp, x timesIf the next top element in the stack is a string, append this repeated string to the top stringelse push the repeated string into the stackCase 3: Current character is a digitIf previous char of original string was also a digit, append this digit to the number on top of the stackIf previous char was something else, push this digit into the stackCase 4: Current character is an alphabetIf previous char of original string was also an alphabet, append this alphabet to the string on top of the stackIf previous char was something else, push this alphabet into the stack
Case 1: Current character is ‘[‘No need to do anything in this case. Just continue to next character
No need to do anything in this case. Just continue to next character
Case 2: Current character is ‘]’Pop the top string temp and top integer x from the stackRepeat the string temp, x timesIf the next top element in the stack is a string, append this repeated string to the top stringelse push the repeated string into the stack
Pop the top string temp and top integer x from the stack
Repeat the string temp, x times
If the next top element in the stack is a string, append this repeated string to the top string
else push the repeated string into the stack
Case 3: Current character is a digitIf previous char of original string was also a digit, append this digit to the number on top of the stackIf previous char was something else, push this digit into the stack
If previous char of original string was also a digit, append this digit to the number on top of the stack
If previous char was something else, push this digit into the stack
Case 4: Current character is an alphabetIf previous char of original string was also an alphabet, append this alphabet to the string on top of the stackIf previous char was something else, push this alphabet into the stack
If previous char of original string was also an alphabet, append this alphabet to the string on top of the stack
If previous char was something else, push this alphabet into the stack
At the end, return the string in the stack and print it
Below is the implementation of the above approach.
C++
Java
Python3
Javascript
// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Stack to store intermediate stringsstack<string> ans;string res = ""; // Recusrsive function to decode// the encoded stringvoid decode(string s, int i){ if (i == s.length()) { res = ans.top(); return; } // If the string character is '[' if (s[i] == '['); // If the string character is ']' else if (s[i] == ']') { string temp = ans.top(); ans.pop(); int x = stoi(ans.top()); ans.pop(); for (string j = temp; x > 1; x--) temp = temp + j; string temp1 = ans.empty() == false ? ans.top() : ""; if (!temp1.empty() && !(temp1[0] - '0' < 10)) { ans.pop(); temp1 = temp1 + temp; ans.push(temp1); } else { ans.push(temp); } } // If string character is a digit else if (s[i] - '0' < 10) { string temp = ans.empty() == false ? ans.top() : ""; if (!temp.empty() && temp[0] - '0' < 10 && s[i - 1] - '0' < 10) { ans.pop(); temp = temp + s[i]; ans.push(temp); } else { temp = s[i]; ans.push(temp); } } // If the string character is alphabet else if (s[i] - 'a' < 26) { string temp = ans.empty() == false ? ans.top() : ""; if (!temp.empty() && temp[0] - 'a' >= 0 && temp[0] - 'a' < 26) { ans.pop(); temp = temp + s[i]; ans.push(temp); } else { temp = s[i]; ans.push(temp); } } // Recursive call for next index decode(s, i + 1);} // Function to call the recursive functionstring decodeString(string s){ decode(s, 0); return res;} // Driver codeint main(){ string str = "2[a2[b]]"; cout << decodeString(str) << endl; return 0;}
// Java code to implement above approachimport java.util.*;class GFG{ // Stack to store intermediate Strings static Stack<String> ans = new Stack<String>(); static String res = ""; // Recusrsive function to decode // the encoded String static void decode(char[] s, int i) { if (i == s.length) { res = ans.peek(); return; } // If the String character is '[' if (s[i] == '['); // If the String character is ']' else if (s[i] == ']') { String temp = ans.peek(); ans.pop(); int x = Integer.valueOf(ans.peek()); ans.pop(); for (String j = temp; x > 1; x--) temp = temp + j; String temp1 = ans.isEmpty() == false ? ans.peek() : ""; if (!temp1.isEmpty() && !(temp1.charAt(0) - '0' < 10)) { ans.pop(); temp1 = temp1 + temp; ans.add(temp1); } else { ans.add(temp); } } // If String character is a digit else if (s[i] - '0' < 10) { String temp = ans.isEmpty() == false ? ans.peek() : ""; if (!temp.isEmpty() && temp.charAt(0) - '0' < 10 && s[i - 1] - '0' < 10) { ans.pop(); temp = temp + s[i]; ans.add(temp); } else { temp = String.valueOf(s[i]); ans.add(temp); } } // If the String character is alphabet else if (s[i] - 'a' < 26) { String temp = ans.isEmpty() == false ? ans.peek() : ""; if (!temp.isEmpty() && temp.charAt(0) - 'a' >= 0 && temp.charAt(0) - 'a' < 26) { ans.pop(); temp = temp + s[i]; ans.add(temp); } else { temp = String.valueOf(s[i]); ans.add(temp); } } // Recursive call for next index decode(s, i + 1); } // Function to call the recursive function static String decodeString(String s) { decode(s.toCharArray(), 0); return res; } // Driver code public static void main(String[] args) { String str = "2[a2[b]]"; System.out.print(decodeString(str) +"\n"); }} // This code is contributed by shikhasingrajput
# Python code to implement above approach # Stack to store intermediate stringsans = []res = "" # Recusrsive function to decode# the encoded stringdef decode(s, i): global res global ans if (i == len(s)): res = ans[len(ans) - 1] return # If the string character is '[' if (s[i] == '['): pass # If the string character is ']' elif (s[i] == ']'): temp = ans[len(ans) - 1] ans.pop() x = int(ans[len(ans) - 1]) ans.pop() j = temp while(x>1): temp = temp + j x -= 1 temp1 = ans[len(ans) - 1] if len(ans) != 0 else "" if len(temp1) != 0 and ~(ord(temp1[0]) - ord('0') < 10): ans.pop() temp1 = temp1 + temp ans.append(temp1) else: ans.append(temp) # If string character is a digit elif(ord(s[i]) - ord('0') < 10): temp = ans[len(ans) - 1] if len(ans) != 0 else "" if(len(temp) != 0 and ord(temp[0]) - ord('0') < 10 and ord(s[i - 1]) - ord('0') < 10): ans.pop() temp = temp + s[i] ans.append(temp) else: temp = s[i] ans.append(temp) # If the string character is alphabet elif (ord(s[i]) - ord('a') < 26): temp = ans[len(ans) - 1] if (len(ans) != 0) else "" if(temp != 0 and ord(temp[0]) - ord('a') >= 0 and ord(temp[0]) - ord('a') < 26): ans.pop() temp = temp + s[i] ans.append(temp) else: temp = s[i] ans.append(temp) # Recursive call for next index decode(s, i + 1) # Function to call the recursive functiondef decodeString(s): decode(s, 0) return res # Driver codestr = "2[a2[b]]"print(decodeString(str)) # This code is contributed by shinjanpatra
<script> // JavaScript code to implement above approach // Stack to store intermediate stringslet ans = [];let res = ""; // Recusrsive function to decode// the encoded stringfunction decode(s, i){ if (i == s.length) { res = ans[ans.length - 1]; return; } // If the string character is '[' if (s[i] == '['); // If the string character is ']' else if (s[i] == ']') { let temp = ans[ans.length - 1]; ans.pop(); let x = (ans[ans.length - 1]); ans.pop(); for(let j = temp; x > 1; x--) temp = temp + j; let temp1 = ans.length != 0 ? ans[ans.length - 1] : ""; if (!temp1.length == 0 && !(temp1[0].charCodeAt(0) - '0'.charCodeAt(0) < 10)) { ans.pop(); temp1 = temp1 + temp; ans.push(temp1); } else { ans.push(temp); } } // If string character is a digit else if (s[i].charCodeAt(0) - '0'.charCodeAt(0) < 10) { let temp = ans.length != 0 ? ans[ans.length - 1] : ""; if (!temp.length == 0 && temp[0].charCodeAt(0) - '0'.charCodeAt(0) < 10 && s[i - 1].charCodeAt(0) - '0'.charCodeAt(0) < 10) { ans.pop(); temp = temp + s[i]; ans.push(temp); } else { temp = s[i]; ans.push(temp); } } // If the string character is alphabet else if (s[i].charCodeAt(0) - 'a'.charCodeAt(0) < 26) { let temp = ans.length != 0 ? ans[ans.length - 1] : ""; if (!temp.length == 0 && temp[0].charCodeAt(0) - 'a'.charCodeAt(0) >= 0 && temp[0].charCodeAt(0) - 'a'.charCodeAt(0) < 26) { ans.pop(); temp = temp + s[i]; ans.push(temp); } else { temp = s[i]; ans.push(temp); } } // Recursive call for next index decode(s, i + 1);} // Function to call the recursive functionfunction decodeString(s){ decode(s, 0); return res;} // Driver codelet str = "2[a2[b]]";document.write(decodeString(str) + '<br>'); // This code is contributed by Potta Lokesh </script>
abbabb
Time Complexity: O(N) where N is the length of the decoded stringAuxiliary Space: O(N)
shikhasingrajput
lokeshpotta20
shinjanpatra
Algo-Geek 2021
substring
Algo Geek
Recursion
Strings
Strings
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if the given string is valid English word or not
Sort strings on the basis of their numeric part
Divide given number into two even parts
Smallest set of vertices to visit all nodes of the given Graph
Count of Palindrome Strings in given Array of strings
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
|
[
{
"code": null,
"e": 27509,
"s": 27481,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 27599,
"s": 27509,
"text": "An encoded string str is given. The pattern in which the string is encoded is as follows."
},
{
"code": null,
"e": 27665,
"s": 27599,
"text": "<count>[sub_str] ==> The substring ‘sub_str’ appears count times."
},
{
"code": null,
"e": 27704,
"s": 27665,
"text": "The task is to decode this string str."
},
{
"code": null,
"e": 27714,
"s": 27704,
"text": "Examples:"
},
{
"code": null,
"e": 27793,
"s": 27714,
"text": "Input: str = “1[b]”Output: bExplanation: The substring ‘b’ is repeated 1 time."
},
{
"code": null,
"e": 27880,
"s": 27793,
"text": "Input: str = “2[ab]”Output: ababExplanation: The substring “ab” is repeated two times."
},
{
"code": null,
"e": 28090,
"s": 27880,
"text": "Input: str = “2[a2[b]]”Output: abbabbExplanation: The substring ‘b’ is repeated 2 times and added to ‘a’ which forms a substring “abb”. Now this substring is repeated two time. So the final string is “abbabb”."
},
{
"code": null,
"e": 28177,
"s": 28090,
"text": "Iterative Approach: The iterative approach is mentioned in the Set-1 of this problem. "
},
{
"code": null,
"e": 28325,
"s": 28177,
"text": "Recursive Approach: In this article, the problem will be solved using Recursion and Stack. Follow the approach mentioned below to solve the problem"
},
{
"code": null,
"e": 28341,
"s": 28325,
"text": "Declare a stack"
},
{
"code": null,
"e": 29219,
"s": 28341,
"text": "Recursively traverse each character of the given string one by one. There can be 4 cases:Case 1: Current character is ‘[‘No need to do anything in this case. Just continue to next characterCase 2: Current character is ‘]’Pop the top string temp and top integer x from the stackRepeat the string temp, x timesIf the next top element in the stack is a string, append this repeated string to the top stringelse push the repeated string into the stackCase 3: Current character is a digitIf previous char of original string was also a digit, append this digit to the number on top of the stackIf previous char was something else, push this digit into the stackCase 4: Current character is an alphabetIf previous char of original string was also an alphabet, append this alphabet to the string on top of the stackIf previous char was something else, push this alphabet into the stack"
},
{
"code": null,
"e": 29320,
"s": 29219,
"text": "Case 1: Current character is ‘[‘No need to do anything in this case. Just continue to next character"
},
{
"code": null,
"e": 29389,
"s": 29320,
"text": "No need to do anything in this case. Just continue to next character"
},
{
"code": null,
"e": 29648,
"s": 29389,
"text": "Case 2: Current character is ‘]’Pop the top string temp and top integer x from the stackRepeat the string temp, x timesIf the next top element in the stack is a string, append this repeated string to the top stringelse push the repeated string into the stack"
},
{
"code": null,
"e": 29705,
"s": 29648,
"text": "Pop the top string temp and top integer x from the stack"
},
{
"code": null,
"e": 29737,
"s": 29705,
"text": "Repeat the string temp, x times"
},
{
"code": null,
"e": 29833,
"s": 29737,
"text": "If the next top element in the stack is a string, append this repeated string to the top string"
},
{
"code": null,
"e": 29878,
"s": 29833,
"text": "else push the repeated string into the stack"
},
{
"code": null,
"e": 30087,
"s": 29878,
"text": "Case 3: Current character is a digitIf previous char of original string was also a digit, append this digit to the number on top of the stackIf previous char was something else, push this digit into the stack"
},
{
"code": null,
"e": 30193,
"s": 30087,
"text": "If previous char of original string was also a digit, append this digit to the number on top of the stack"
},
{
"code": null,
"e": 30261,
"s": 30193,
"text": "If previous char was something else, push this digit into the stack"
},
{
"code": null,
"e": 30484,
"s": 30261,
"text": "Case 4: Current character is an alphabetIf previous char of original string was also an alphabet, append this alphabet to the string on top of the stackIf previous char was something else, push this alphabet into the stack"
},
{
"code": null,
"e": 30597,
"s": 30484,
"text": "If previous char of original string was also an alphabet, append this alphabet to the string on top of the stack"
},
{
"code": null,
"e": 30668,
"s": 30597,
"text": "If previous char was something else, push this alphabet into the stack"
},
{
"code": null,
"e": 30724,
"s": 30668,
"text": "At the end, return the string in the stack and print it"
},
{
"code": null,
"e": 30775,
"s": 30724,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 30779,
"s": 30775,
"text": "C++"
},
{
"code": null,
"e": 30784,
"s": 30779,
"text": "Java"
},
{
"code": null,
"e": 30792,
"s": 30784,
"text": "Python3"
},
{
"code": null,
"e": 30803,
"s": 30792,
"text": "Javascript"
},
{
"code": "// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Stack to store intermediate stringsstack<string> ans;string res = \"\"; // Recusrsive function to decode// the encoded stringvoid decode(string s, int i){ if (i == s.length()) { res = ans.top(); return; } // If the string character is '[' if (s[i] == '['); // If the string character is ']' else if (s[i] == ']') { string temp = ans.top(); ans.pop(); int x = stoi(ans.top()); ans.pop(); for (string j = temp; x > 1; x--) temp = temp + j; string temp1 = ans.empty() == false ? ans.top() : \"\"; if (!temp1.empty() && !(temp1[0] - '0' < 10)) { ans.pop(); temp1 = temp1 + temp; ans.push(temp1); } else { ans.push(temp); } } // If string character is a digit else if (s[i] - '0' < 10) { string temp = ans.empty() == false ? ans.top() : \"\"; if (!temp.empty() && temp[0] - '0' < 10 && s[i - 1] - '0' < 10) { ans.pop(); temp = temp + s[i]; ans.push(temp); } else { temp = s[i]; ans.push(temp); } } // If the string character is alphabet else if (s[i] - 'a' < 26) { string temp = ans.empty() == false ? ans.top() : \"\"; if (!temp.empty() && temp[0] - 'a' >= 0 && temp[0] - 'a' < 26) { ans.pop(); temp = temp + s[i]; ans.push(temp); } else { temp = s[i]; ans.push(temp); } } // Recursive call for next index decode(s, i + 1);} // Function to call the recursive functionstring decodeString(string s){ decode(s, 0); return res;} // Driver codeint main(){ string str = \"2[a2[b]]\"; cout << decodeString(str) << endl; return 0;}",
"e": 32866,
"s": 30803,
"text": null
},
{
"code": "// Java code to implement above approachimport java.util.*;class GFG{ // Stack to store intermediate Strings static Stack<String> ans = new Stack<String>(); static String res = \"\"; // Recusrsive function to decode // the encoded String static void decode(char[] s, int i) { if (i == s.length) { res = ans.peek(); return; } // If the String character is '[' if (s[i] == '['); // If the String character is ']' else if (s[i] == ']') { String temp = ans.peek(); ans.pop(); int x = Integer.valueOf(ans.peek()); ans.pop(); for (String j = temp; x > 1; x--) temp = temp + j; String temp1 = ans.isEmpty() == false ? ans.peek() : \"\"; if (!temp1.isEmpty() && !(temp1.charAt(0) - '0' < 10)) { ans.pop(); temp1 = temp1 + temp; ans.add(temp1); } else { ans.add(temp); } } // If String character is a digit else if (s[i] - '0' < 10) { String temp = ans.isEmpty() == false ? ans.peek() : \"\"; if (!temp.isEmpty() && temp.charAt(0) - '0' < 10 && s[i - 1] - '0' < 10) { ans.pop(); temp = temp + s[i]; ans.add(temp); } else { temp = String.valueOf(s[i]); ans.add(temp); } } // If the String character is alphabet else if (s[i] - 'a' < 26) { String temp = ans.isEmpty() == false ? ans.peek() : \"\"; if (!temp.isEmpty() && temp.charAt(0) - 'a' >= 0 && temp.charAt(0) - 'a' < 26) { ans.pop(); temp = temp + s[i]; ans.add(temp); } else { temp = String.valueOf(s[i]); ans.add(temp); } } // Recursive call for next index decode(s, i + 1); } // Function to call the recursive function static String decodeString(String s) { decode(s.toCharArray(), 0); return res; } // Driver code public static void main(String[] args) { String str = \"2[a2[b]]\"; System.out.print(decodeString(str) +\"\\n\"); }} // This code is contributed by shikhasingrajput",
"e": 34988,
"s": 32866,
"text": null
},
{
"code": "# Python code to implement above approach # Stack to store intermediate stringsans = []res = \"\" # Recusrsive function to decode# the encoded stringdef decode(s, i): global res global ans if (i == len(s)): res = ans[len(ans) - 1] return # If the string character is '[' if (s[i] == '['): pass # If the string character is ']' elif (s[i] == ']'): temp = ans[len(ans) - 1] ans.pop() x = int(ans[len(ans) - 1]) ans.pop() j = temp while(x>1): temp = temp + j x -= 1 temp1 = ans[len(ans) - 1] if len(ans) != 0 else \"\" if len(temp1) != 0 and ~(ord(temp1[0]) - ord('0') < 10): ans.pop() temp1 = temp1 + temp ans.append(temp1) else: ans.append(temp) # If string character is a digit elif(ord(s[i]) - ord('0') < 10): temp = ans[len(ans) - 1] if len(ans) != 0 else \"\" if(len(temp) != 0 and ord(temp[0]) - ord('0') < 10 and ord(s[i - 1]) - ord('0') < 10): ans.pop() temp = temp + s[i] ans.append(temp) else: temp = s[i] ans.append(temp) # If the string character is alphabet elif (ord(s[i]) - ord('a') < 26): temp = ans[len(ans) - 1] if (len(ans) != 0) else \"\" if(temp != 0 and ord(temp[0]) - ord('a') >= 0 and ord(temp[0]) - ord('a') < 26): ans.pop() temp = temp + s[i] ans.append(temp) else: temp = s[i] ans.append(temp) # Recursive call for next index decode(s, i + 1) # Function to call the recursive functiondef decodeString(s): decode(s, 0) return res # Driver codestr = \"2[a2[b]]\"print(decodeString(str)) # This code is contributed by shinjanpatra",
"e": 36809,
"s": 34988,
"text": null
},
{
"code": "<script> // JavaScript code to implement above approach // Stack to store intermediate stringslet ans = [];let res = \"\"; // Recusrsive function to decode// the encoded stringfunction decode(s, i){ if (i == s.length) { res = ans[ans.length - 1]; return; } // If the string character is '[' if (s[i] == '['); // If the string character is ']' else if (s[i] == ']') { let temp = ans[ans.length - 1]; ans.pop(); let x = (ans[ans.length - 1]); ans.pop(); for(let j = temp; x > 1; x--) temp = temp + j; let temp1 = ans.length != 0 ? ans[ans.length - 1] : \"\"; if (!temp1.length == 0 && !(temp1[0].charCodeAt(0) - '0'.charCodeAt(0) < 10)) { ans.pop(); temp1 = temp1 + temp; ans.push(temp1); } else { ans.push(temp); } } // If string character is a digit else if (s[i].charCodeAt(0) - '0'.charCodeAt(0) < 10) { let temp = ans.length != 0 ? ans[ans.length - 1] : \"\"; if (!temp.length == 0 && temp[0].charCodeAt(0) - '0'.charCodeAt(0) < 10 && s[i - 1].charCodeAt(0) - '0'.charCodeAt(0) < 10) { ans.pop(); temp = temp + s[i]; ans.push(temp); } else { temp = s[i]; ans.push(temp); } } // If the string character is alphabet else if (s[i].charCodeAt(0) - 'a'.charCodeAt(0) < 26) { let temp = ans.length != 0 ? ans[ans.length - 1] : \"\"; if (!temp.length == 0 && temp[0].charCodeAt(0) - 'a'.charCodeAt(0) >= 0 && temp[0].charCodeAt(0) - 'a'.charCodeAt(0) < 26) { ans.pop(); temp = temp + s[i]; ans.push(temp); } else { temp = s[i]; ans.push(temp); } } // Recursive call for next index decode(s, i + 1);} // Function to call the recursive functionfunction decodeString(s){ decode(s, 0); return res;} // Driver codelet str = \"2[a2[b]]\";document.write(decodeString(str) + '<br>'); // This code is contributed by Potta Lokesh </script>",
"e": 39128,
"s": 36809,
"text": null
},
{
"code": null,
"e": 39135,
"s": 39128,
"text": "abbabb"
},
{
"code": null,
"e": 39222,
"s": 39135,
"text": "Time Complexity: O(N) where N is the length of the decoded stringAuxiliary Space: O(N)"
},
{
"code": null,
"e": 39241,
"s": 39224,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 39255,
"s": 39241,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 39268,
"s": 39255,
"text": "shinjanpatra"
},
{
"code": null,
"e": 39283,
"s": 39268,
"text": "Algo-Geek 2021"
},
{
"code": null,
"e": 39293,
"s": 39283,
"text": "substring"
},
{
"code": null,
"e": 39303,
"s": 39293,
"text": "Algo Geek"
},
{
"code": null,
"e": 39313,
"s": 39303,
"text": "Recursion"
},
{
"code": null,
"e": 39321,
"s": 39313,
"text": "Strings"
},
{
"code": null,
"e": 39329,
"s": 39321,
"text": "Strings"
},
{
"code": null,
"e": 39339,
"s": 39329,
"text": "Recursion"
},
{
"code": null,
"e": 39437,
"s": 39339,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39492,
"s": 39437,
"text": "Check if the given string is valid English word or not"
},
{
"code": null,
"e": 39540,
"s": 39492,
"text": "Sort strings on the basis of their numeric part"
},
{
"code": null,
"e": 39580,
"s": 39540,
"text": "Divide given number into two even parts"
},
{
"code": null,
"e": 39643,
"s": 39580,
"text": "Smallest set of vertices to visit all nodes of the given Graph"
},
{
"code": null,
"e": 39697,
"s": 39643,
"text": "Count of Palindrome Strings in given Array of strings"
},
{
"code": null,
"e": 39757,
"s": 39697,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 39842,
"s": 39757,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 39852,
"s": 39842,
"text": "Recursion"
},
{
"code": null,
"e": 39879,
"s": 39852,
"text": "Program for Tower of Hanoi"
}
] |
K Centers Problem | Set 1 (Greedy Approximate Algorithm) - GeeksforGeeks
|
27 Oct, 2021
Given n cities and distances between every pair of cities, select k cities to place warehouses (or ATMs or Cloud Server) such that the maximum distance of a city to a warehouse (or ATM or Cloud Server) is minimized.
For example consider the following four cities, 0, 1, 2, and 3, and distances between them, how to do place 2 ATMs among these 4 cities so that the maximum distance of a city to an ATM is minimized.
There is no polynomial-time solution available for this problem as the problem is a known NP-Hard problem. There is a polynomial-time Greedy approximate algorithm, the greedy algorithm provides a solution that is never worse than twice the optimal solution. The greedy solution works only if the distances between cities follow Triangular Inequality (The distance between two points is always smaller than the sum of distances through a third point).
The 2-Approximate Greedy Algorithm: 1) Choose the first center arbitrarily. 2) Choose remaining k-1 centers using the following criteria. Let c1, c2, c3, ... ci be the already chosen centers. Choose (i+1)’th center by picking the city which is farthest from already selected centers, i.e, the point p which has following value as maximum Min[dist(p, c1), dist(p, c2), dist(p, c3), .... dist(p, ci)]
Example (k = 3 in the above-shown Graph) a) Let the first arbitrarily picked vertex be 0. b) The next vertex is 1 because 1 is the farthest vertex from 0. c) Remaining cities are 2 and 3. Calculate their distances from already selected centers (0 and 1). The greedy algorithm basically calculates the following values. Minimum of all distanced from 2 to already considered centers Min[dist(2, 0), dist(2, 1)] = Min[7, 8] = 7 Minimum of all distanced from 3 to already considered centers Min[dist(3, 0), dist(3, 1)] = Min[6, 5] = 5 After computing the above values, city 2 is picked as the value corresponding to 2 is maximum.
Note that the greedy algorithm doesn’t give the best solution for k = 2 as this is just an approximate algorithm with a bound as twice optimal.
Proof that the above greedy algorithm is 2 approximate. Let OPT be the maximum distance of a city from a center in the Optimal solution. We need to show that the maximum distance obtained from the Greedy algorithm is 2*OPT. The proof can be done using contradiction. a) Assume that the distance from the furthest point to all centers is > 2·OPT. b) This means that distances between all centers are also > 2·OPT. c) We have k + 1 points with distances > 2·OPT between every pair. d) Each point has a center of the optimal solution with distance <= OPT to it. e) There exists a pair of points with the same center X in the optimal solution (pigeonhole principle: k optimal centers, k+1 points) f) The distance between them is at most 2·OPT (triangle inequality) which is a contradiction.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; int maxindex(int* dist, int n){ int mi = 0; for (int i = 0; i < n; i++) { if (dist[i] > dist[mi]) mi = i; } return mi;} void selectKcities(int n, int weights[4][4], int k){ int* dist = new int[n]; vector<int> centers; for (int i = 0; i < n; i++) { dist[i] = INT_MAX; } // index of city having the // maximum distance to it's // closest center int max = 0; for (int i = 0; i < k; i++) { centers.push_back(max); for (int j = 0; j < n; j++) { // updating the distance // of the cities to their // closest centers dist[j] = min(dist[j], weights[max][j]); } // updating the index of the // city with the maximum // distance to it's closest center max = maxindex(dist, n); } // Printing the maximum distance // of a city to a center // that is our answer cout << endl << dist[max] << endl; // Printing the cities that // were chosen to be made // centers for (int i = 0; i < centers.size(); i++) { cout << centers[i] << " "; } cout << endl;} // Driver Codeint main(){ int n = 4; int weights[4][4] = { { 0, 4, 8, 5 }, { 4, 0, 10, 7 }, { 8, 10, 0, 9 }, { 5, 7, 9, 0 } }; int k = 2; // Function Call selectKcities(n, weights, k);}// Contributed by Balu Nagar
// Java program for the above approachimport java.util.*; class GFG{ static int maxindex(int[] dist, int n){ int mi = 0; for(int i = 0; i < n; i++) { if (dist[i] > dist[mi]) mi = i; } return mi;} static void selectKcities(int n, int weights[][], int k){ int[] dist = new int[n]; ArrayList<Integer> centers = new ArrayList<>(); for(int i = 0; i < n; i++) { dist[i] = Integer.MAX_VALUE; } // Index of city having the // maximum distance to it's // closest center int max = 0; for(int i = 0; i < k; i++) { centers.add(max); for(int j = 0; j < n; j++) { // Updating the distance // of the cities to their // closest centers dist[j] = Math.min(dist[j], weights[max][j]); } // Updating the index of the // city with the maximum // distance to it's closest center max = maxindex(dist, n); } // Printing the maximum distance // of a city to a center // that is our answer System.out.println(dist[max]); // Printing the cities that // were chosen to be made // centers for(int i = 0; i < centers.size(); i++) { System.out.print(centers.get(i) + " "); } System.out.print("\n");} // Driver Codepublic static void main(String[] args){ int n = 4; int[][] weights = new int[][]{ { 0, 4, 8, 5 }, { 4, 0, 10, 7 }, { 8, 10, 0, 9 }, { 5, 7, 9, 0 } }; int k = 2; // Function Call selectKcities(n, weights, k);}} // This code is contributed by nspatilme
# Python3 program for the above approachdef maxindex(dist, n): mi = 0 for i in range(n): if (dist[i] > dist[mi]): mi = i return mi def selectKcities(n, weights, k): dist = [0]*n centers = [] for i in range(n): dist[i] = 10**9 # index of city having the # maximum distance to it's # closest center max = 0 for i in range(k): centers.append(max) for j in range(n): # updating the distance # of the cities to their # closest centers dist[j] = min(dist[j], weights[max][j]) # updating the index of the # city with the maximum # distance to it's closest center max = maxindex(dist, n) # Printing the maximum distance # of a city to a center # that is our answer # print() print(dist[max]) # Printing the cities that # were chosen to be made # centers for i in centers: print(i, end = " ") # Driver Codeif __name__ == '__main__': n = 4 weights = [ [ 0, 4, 8, 5 ], [ 4, 0, 10, 7 ], [ 8, 10, 0, 9 ], [ 5, 7, 9, 0 ] ] k = 2 # Function Call selectKcities(n, weights, k) # This code is contributed by mohit kumar 29.
using System;using System.Collections.Generic; public class GFG{ static int maxindex(int[] dist, int n) { int mi = 0; for(int i = 0; i < n; i++) { if (dist[i] > dist[mi]) mi = i; } return mi; } static void selectKcities(int n, int[,] weights, int k) { int[] dist = new int[n]; List<int> centers = new List<int>(); for(int i = 0; i < n; i++) { dist[i] = Int32.MaxValue; } // Index of city having the // maximum distance to it's // closest center int max = 0; for(int i = 0; i < k; i++) { centers.Add(max); for(int j = 0; j < n; j++) { // Updating the distance // of the cities to their // closest centers dist[j] = Math.Min(dist[j], weights[max,j]); } // Updating the index of the // city with the maximum // distance to it's closest center max = maxindex(dist, n); } // Printing the maximum distance // of a city to a center // that is our answer Console.WriteLine(dist[max]); // Printing the cities that // were chosen to be made // centers for(int i = 0; i < centers.Count; i++) { Console.Write(centers[i] + " "); } Console.Write("\n"); } // Driver Code static public void Main (){ int n = 4; int[,] weights = new int[,]{ { 0, 4, 8, 5 }, { 4, 0, 10, 7 }, { 8, 10, 0, 9 }, { 5, 7, 9, 0 } }; int k = 2; // Function Call selectKcities(n, weights, k); }} // This code is contributed by avanitrachhadiya2155.
<script>// Javascript program for the above approach function maxindex(dist,n) { let mi = 0; for(let i = 0; i < n; i++) { if (dist[i] > dist[mi]) mi = i; } return mi; } function selectKcities(n,weights,k) { let dist = new Array(n); let centers = []; for(let i = 0; i < n; i++) { dist[i] = Number.MAX_VALUE; } // Index of city having the // maximum distance to it's // closest center let max = 0; for(let i = 0; i < k; i++) { centers.push(max); for(let j = 0; j < n; j++) { // Updating the distance // of the cities to their // closest centers dist[j] = Math.min(dist[j], weights[max][j]); } // Updating the index of the // city with the maximum // distance to it's closest center max = maxindex(dist, n); } // Printing the maximum distance // of a city to a center // that is our answer document.write(dist[max]+"<br>"); // Printing the cities that // were chosen to be made // centers for(let i = 0; i < centers.length; i++) { document.write(centers[i] + " "); } document.write("<br>"); } // Driver Code let n = 4; let weights = [ [ 0, 4, 8, 5 ], [ 4, 0, 10, 7 ], [ 8, 10, 0, 9 ], [ 5, 7, 9, 0 ] ] let k = 2 selectKcities(n, weights, k) // This code is contributed by unknown2108</script>
5
0 2
Source: http://algo2.iti.kit.edu/vanstee/courses/kcenter.pdf This article is contributed by Harshit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
balunagar
mohit kumar 29
nspatilme
unknown2108
avanitrachhadiya2155
reenadevi98412200
Graph
Greedy
Greedy
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Ford-Fulkerson Algorithm for Maximum Flow Problem
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Traveling Salesman Problem (TSP) Implementation
Strongly Connected Components
Program for array rotation
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
|
[
{
"code": null,
"e": 26083,
"s": 26055,
"text": "\n27 Oct, 2021"
},
{
"code": null,
"e": 26300,
"s": 26083,
"text": "Given n cities and distances between every pair of cities, select k cities to place warehouses (or ATMs or Cloud Server) such that the maximum distance of a city to a warehouse (or ATM or Cloud Server) is minimized. "
},
{
"code": null,
"e": 26501,
"s": 26300,
"text": "For example consider the following four cities, 0, 1, 2, and 3, and distances between them, how to do place 2 ATMs among these 4 cities so that the maximum distance of a city to an ATM is minimized. "
},
{
"code": null,
"e": 26953,
"s": 26501,
"text": "There is no polynomial-time solution available for this problem as the problem is a known NP-Hard problem. There is a polynomial-time Greedy approximate algorithm, the greedy algorithm provides a solution that is never worse than twice the optimal solution. The greedy solution works only if the distances between cities follow Triangular Inequality (The distance between two points is always smaller than the sum of distances through a third point). "
},
{
"code": null,
"e": 27392,
"s": 26953,
"text": "The 2-Approximate Greedy Algorithm: 1) Choose the first center arbitrarily. 2) Choose remaining k-1 centers using the following criteria. Let c1, c2, c3, ... ci be the already chosen centers. Choose (i+1)’th center by picking the city which is farthest from already selected centers, i.e, the point p which has following value as maximum Min[dist(p, c1), dist(p, c2), dist(p, c3), .... dist(p, ci)] "
},
{
"code": null,
"e": 28059,
"s": 27392,
"text": "Example (k = 3 in the above-shown Graph) a) Let the first arbitrarily picked vertex be 0. b) The next vertex is 1 because 1 is the farthest vertex from 0. c) Remaining cities are 2 and 3. Calculate their distances from already selected centers (0 and 1). The greedy algorithm basically calculates the following values. Minimum of all distanced from 2 to already considered centers Min[dist(2, 0), dist(2, 1)] = Min[7, 8] = 7 Minimum of all distanced from 3 to already considered centers Min[dist(3, 0), dist(3, 1)] = Min[6, 5] = 5 After computing the above values, city 2 is picked as the value corresponding to 2 is maximum. "
},
{
"code": null,
"e": 28204,
"s": 28059,
"text": "Note that the greedy algorithm doesn’t give the best solution for k = 2 as this is just an approximate algorithm with a bound as twice optimal. "
},
{
"code": null,
"e": 28992,
"s": 28204,
"text": "Proof that the above greedy algorithm is 2 approximate. Let OPT be the maximum distance of a city from a center in the Optimal solution. We need to show that the maximum distance obtained from the Greedy algorithm is 2*OPT. The proof can be done using contradiction. a) Assume that the distance from the furthest point to all centers is > 2·OPT. b) This means that distances between all centers are also > 2·OPT. c) We have k + 1 points with distances > 2·OPT between every pair. d) Each point has a center of the optimal solution with distance <= OPT to it. e) There exists a pair of points with the same center X in the optimal solution (pigeonhole principle: k optimal centers, k+1 points) f) The distance between them is at most 2·OPT (triangle inequality) which is a contradiction. "
},
{
"code": null,
"e": 28996,
"s": 28992,
"text": "C++"
},
{
"code": null,
"e": 29001,
"s": 28996,
"text": "Java"
},
{
"code": null,
"e": 29009,
"s": 29001,
"text": "Python3"
},
{
"code": null,
"e": 29012,
"s": 29009,
"text": "C#"
},
{
"code": null,
"e": 29023,
"s": 29012,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; int maxindex(int* dist, int n){ int mi = 0; for (int i = 0; i < n; i++) { if (dist[i] > dist[mi]) mi = i; } return mi;} void selectKcities(int n, int weights[4][4], int k){ int* dist = new int[n]; vector<int> centers; for (int i = 0; i < n; i++) { dist[i] = INT_MAX; } // index of city having the // maximum distance to it's // closest center int max = 0; for (int i = 0; i < k; i++) { centers.push_back(max); for (int j = 0; j < n; j++) { // updating the distance // of the cities to their // closest centers dist[j] = min(dist[j], weights[max][j]); } // updating the index of the // city with the maximum // distance to it's closest center max = maxindex(dist, n); } // Printing the maximum distance // of a city to a center // that is our answer cout << endl << dist[max] << endl; // Printing the cities that // were chosen to be made // centers for (int i = 0; i < centers.size(); i++) { cout << centers[i] << \" \"; } cout << endl;} // Driver Codeint main(){ int n = 4; int weights[4][4] = { { 0, 4, 8, 5 }, { 4, 0, 10, 7 }, { 8, 10, 0, 9 }, { 5, 7, 9, 0 } }; int k = 2; // Function Call selectKcities(n, weights, k);}// Contributed by Balu Nagar",
"e": 30548,
"s": 29023,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ static int maxindex(int[] dist, int n){ int mi = 0; for(int i = 0; i < n; i++) { if (dist[i] > dist[mi]) mi = i; } return mi;} static void selectKcities(int n, int weights[][], int k){ int[] dist = new int[n]; ArrayList<Integer> centers = new ArrayList<>(); for(int i = 0; i < n; i++) { dist[i] = Integer.MAX_VALUE; } // Index of city having the // maximum distance to it's // closest center int max = 0; for(int i = 0; i < k; i++) { centers.add(max); for(int j = 0; j < n; j++) { // Updating the distance // of the cities to their // closest centers dist[j] = Math.min(dist[j], weights[max][j]); } // Updating the index of the // city with the maximum // distance to it's closest center max = maxindex(dist, n); } // Printing the maximum distance // of a city to a center // that is our answer System.out.println(dist[max]); // Printing the cities that // were chosen to be made // centers for(int i = 0; i < centers.size(); i++) { System.out.print(centers.get(i) + \" \"); } System.out.print(\"\\n\");} // Driver Codepublic static void main(String[] args){ int n = 4; int[][] weights = new int[][]{ { 0, 4, 8, 5 }, { 4, 0, 10, 7 }, { 8, 10, 0, 9 }, { 5, 7, 9, 0 } }; int k = 2; // Function Call selectKcities(n, weights, k);}} // This code is contributed by nspatilme",
"e": 32288,
"s": 30548,
"text": null
},
{
"code": "# Python3 program for the above approachdef maxindex(dist, n): mi = 0 for i in range(n): if (dist[i] > dist[mi]): mi = i return mi def selectKcities(n, weights, k): dist = [0]*n centers = [] for i in range(n): dist[i] = 10**9 # index of city having the # maximum distance to it's # closest center max = 0 for i in range(k): centers.append(max) for j in range(n): # updating the distance # of the cities to their # closest centers dist[j] = min(dist[j], weights[max][j]) # updating the index of the # city with the maximum # distance to it's closest center max = maxindex(dist, n) # Printing the maximum distance # of a city to a center # that is our answer # print() print(dist[max]) # Printing the cities that # were chosen to be made # centers for i in centers: print(i, end = \" \") # Driver Codeif __name__ == '__main__': n = 4 weights = [ [ 0, 4, 8, 5 ], [ 4, 0, 10, 7 ], [ 8, 10, 0, 9 ], [ 5, 7, 9, 0 ] ] k = 2 # Function Call selectKcities(n, weights, k) # This code is contributed by mohit kumar 29.",
"e": 33541,
"s": 32288,
"text": null
},
{
"code": "using System;using System.Collections.Generic; public class GFG{ static int maxindex(int[] dist, int n) { int mi = 0; for(int i = 0; i < n; i++) { if (dist[i] > dist[mi]) mi = i; } return mi; } static void selectKcities(int n, int[,] weights, int k) { int[] dist = new int[n]; List<int> centers = new List<int>(); for(int i = 0; i < n; i++) { dist[i] = Int32.MaxValue; } // Index of city having the // maximum distance to it's // closest center int max = 0; for(int i = 0; i < k; i++) { centers.Add(max); for(int j = 0; j < n; j++) { // Updating the distance // of the cities to their // closest centers dist[j] = Math.Min(dist[j], weights[max,j]); } // Updating the index of the // city with the maximum // distance to it's closest center max = maxindex(dist, n); } // Printing the maximum distance // of a city to a center // that is our answer Console.WriteLine(dist[max]); // Printing the cities that // were chosen to be made // centers for(int i = 0; i < centers.Count; i++) { Console.Write(centers[i] + \" \"); } Console.Write(\"\\n\"); } // Driver Code static public void Main (){ int n = 4; int[,] weights = new int[,]{ { 0, 4, 8, 5 }, { 4, 0, 10, 7 }, { 8, 10, 0, 9 }, { 5, 7, 9, 0 } }; int k = 2; // Function Call selectKcities(n, weights, k); }} // This code is contributed by avanitrachhadiya2155.",
"e": 35529,
"s": 33541,
"text": null
},
{
"code": "<script>// Javascript program for the above approach function maxindex(dist,n) { let mi = 0; for(let i = 0; i < n; i++) { if (dist[i] > dist[mi]) mi = i; } return mi; } function selectKcities(n,weights,k) { let dist = new Array(n); let centers = []; for(let i = 0; i < n; i++) { dist[i] = Number.MAX_VALUE; } // Index of city having the // maximum distance to it's // closest center let max = 0; for(let i = 0; i < k; i++) { centers.push(max); for(let j = 0; j < n; j++) { // Updating the distance // of the cities to their // closest centers dist[j] = Math.min(dist[j], weights[max][j]); } // Updating the index of the // city with the maximum // distance to it's closest center max = maxindex(dist, n); } // Printing the maximum distance // of a city to a center // that is our answer document.write(dist[max]+\"<br>\"); // Printing the cities that // were chosen to be made // centers for(let i = 0; i < centers.length; i++) { document.write(centers[i] + \" \"); } document.write(\"<br>\"); } // Driver Code let n = 4; let weights = [ [ 0, 4, 8, 5 ], [ 4, 0, 10, 7 ], [ 8, 10, 0, 9 ], [ 5, 7, 9, 0 ] ] let k = 2 selectKcities(n, weights, k) // This code is contributed by unknown2108</script>",
"e": 37090,
"s": 35529,
"text": null
},
{
"code": null,
"e": 37097,
"s": 37090,
"text": "5\n0 2 "
},
{
"code": null,
"e": 37323,
"s": 37097,
"text": "Source: http://algo2.iti.kit.edu/vanstee/courses/kcenter.pdf This article is contributed by Harshit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 37333,
"s": 37323,
"text": "balunagar"
},
{
"code": null,
"e": 37348,
"s": 37333,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37358,
"s": 37348,
"text": "nspatilme"
},
{
"code": null,
"e": 37370,
"s": 37358,
"text": "unknown2108"
},
{
"code": null,
"e": 37391,
"s": 37370,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 37409,
"s": 37391,
"text": "reenadevi98412200"
},
{
"code": null,
"e": 37415,
"s": 37409,
"text": "Graph"
},
{
"code": null,
"e": 37422,
"s": 37415,
"text": "Greedy"
},
{
"code": null,
"e": 37429,
"s": 37422,
"text": "Greedy"
},
{
"code": null,
"e": 37435,
"s": 37429,
"text": "Graph"
},
{
"code": null,
"e": 37533,
"s": 37435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37601,
"s": 37533,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 37651,
"s": 37601,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 37726,
"s": 37651,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 37774,
"s": 37726,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 37804,
"s": 37774,
"text": "Strongly Connected Components"
},
{
"code": null,
"e": 37831,
"s": 37804,
"text": "Program for array rotation"
},
{
"code": null,
"e": 37891,
"s": 37831,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37922,
"s": 37891,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 37965,
"s": 37922,
"text": "Activity Selection Problem | Greedy Algo-1"
}
] |
matplotlib.axes.Axes.vlines() in Python - GeeksforGeeks
|
13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.vlines() function in axes module of matplotlib library is used to Plot vertical lines at each x from ymin to ymax.
Syntax: Axes.vlines(self, x, ymin, ymax, colors=’k’, linestyles=’solid’, label=”, *, data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
x: This parameter is the sequence of x-indexes where to plot the lines.
ymin, ymax: These parameter contains an array.And they represents the beginning and end of each line.
colors: This parameter is an optional parameter. And it is the color of the lines with default value k.
linetsyle: This parameter is also an optional parameter. And it is used to represent the linestyle{‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}.
label: This parameter is also an optional parameter.It is the label of the plot.
Returns: This returns the LineCollection.
Below examples illustrate the matplotlib.axes.Axes.vlines() function in matplotlib.axes:
Example #1:
# Implementation of matplotlib function import numpy as npfrom matplotlib import patchesimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.vlines([1, 2, 3, 4], 0, 1, color ="green", transform = ax.get_xaxis_transform()) ax.set_title('matplotlib.axes.Axes.vlines Example') plt.show()
Output:
Example #2:
# Implementation of matplotlib function import numpy as npfrom matplotlib import patchesimport matplotlib.pyplot as plt t = np.arange(0.0, 5.0, 0.1)s = np.exp(-t) + np.cos(3 * np.pi * t) + np.sin(np.pi * t)nse = np.random.normal(0.0, 0.8, t.shape) * s fig, ax = plt.subplots() ax.vlines(t, [0], s)ax.vlines([1, 2], 0, 1, color ="lightgreen", transform = ax.get_xaxis_transform()) ax.set_xlabel('time (s)')ax.set_title('matplotlib.axes.Axes.vlines Example') plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26099,
"s": 26071,
"text": "\n13 Apr, 2020"
},
{
"code": null,
"e": 26399,
"s": 26099,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 26523,
"s": 26399,
"text": "The Axes.vlines() function in axes module of matplotlib library is used to Plot vertical lines at each x from ymin to ymax."
},
{
"code": null,
"e": 26629,
"s": 26523,
"text": "Syntax: Axes.vlines(self, x, ymin, ymax, colors=’k’, linestyles=’solid’, label=”, *, data=None, **kwargs)"
},
{
"code": null,
"e": 26711,
"s": 26629,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 26783,
"s": 26711,
"text": "x: This parameter is the sequence of x-indexes where to plot the lines."
},
{
"code": null,
"e": 26885,
"s": 26783,
"text": "ymin, ymax: These parameter contains an array.And they represents the beginning and end of each line."
},
{
"code": null,
"e": 26989,
"s": 26885,
"text": "colors: This parameter is an optional parameter. And it is the color of the lines with default value k."
},
{
"code": null,
"e": 27129,
"s": 26989,
"text": "linetsyle: This parameter is also an optional parameter. And it is used to represent the linestyle{‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}."
},
{
"code": null,
"e": 27210,
"s": 27129,
"text": "label: This parameter is also an optional parameter.It is the label of the plot."
},
{
"code": null,
"e": 27252,
"s": 27210,
"text": "Returns: This returns the LineCollection."
},
{
"code": null,
"e": 27341,
"s": 27252,
"text": "Below examples illustrate the matplotlib.axes.Axes.vlines() function in matplotlib.axes:"
},
{
"code": null,
"e": 27353,
"s": 27341,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib function import numpy as npfrom matplotlib import patchesimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.vlines([1, 2, 3, 4], 0, 1, color =\"green\", transform = ax.get_xaxis_transform()) ax.set_title('matplotlib.axes.Axes.vlines Example') plt.show()",
"e": 27672,
"s": 27353,
"text": null
},
{
"code": null,
"e": 27680,
"s": 27672,
"text": "Output:"
},
{
"code": null,
"e": 27692,
"s": 27680,
"text": "Example #2:"
},
{
"code": "# Implementation of matplotlib function import numpy as npfrom matplotlib import patchesimport matplotlib.pyplot as plt t = np.arange(0.0, 5.0, 0.1)s = np.exp(-t) + np.cos(3 * np.pi * t) + np.sin(np.pi * t)nse = np.random.normal(0.0, 0.8, t.shape) * s fig, ax = plt.subplots() ax.vlines(t, [0], s)ax.vlines([1, 2], 0, 1, color =\"lightgreen\", transform = ax.get_xaxis_transform()) ax.set_xlabel('time (s)')ax.set_title('matplotlib.axes.Axes.vlines Example') plt.show()",
"e": 28182,
"s": 27692,
"text": null
},
{
"code": null,
"e": 28190,
"s": 28182,
"text": "Output:"
},
{
"code": null,
"e": 28208,
"s": 28190,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28215,
"s": 28208,
"text": "Python"
},
{
"code": null,
"e": 28313,
"s": 28215,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28331,
"s": 28313,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28366,
"s": 28331,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28398,
"s": 28366,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28420,
"s": 28398,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28462,
"s": 28420,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28492,
"s": 28462,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28518,
"s": 28492,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28547,
"s": 28518,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28591,
"s": 28547,
"text": "Reading and Writing to text files in Python"
}
] |
numpy.log2() in Python - GeeksforGeeks
|
29 Nov, 2018
numpy.log2(arr, out = None, *, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None, ufunc ‘log1p’) :This mathematical function helps user to calculate Base-2 logarithm of x where x belongs to all the input array elements.
Parameters :
array : [array_like]Input array or object.
out : [ndarray, optional]Output array with same dimensions as Input array,
placed with result.
**kwargs : Allows you to pass keyword variable length of argument to a function.
It is used when we want to handle named argument in a function.
where : [array_like, optional]True value means to calculate the universal
functions(ufunc) at that position, False value means to leave the
value in the output alone.
Return :
An array with Base-2 logarithmic value of x;
where x belongs to all elements of input array.
Code 1 : Working
# Python program explaining# log2() functionimport numpy as np in_array = [1, 3, 5, 2**8]print ("Input array : ", in_array) out_array = np.log2(in_array)print ("Output array : ", out_array) print("\nnp.log2(4**4) : ", np.log2(4**4))print("np.log2(2**8) : ", np.log2(2**8))
Output :
Input array : [1, 3, 5, 256]
Output array : [ 0. 1.5849625 2.32192809 8. ]
np.log2(4**4) : 8.0
np.log2(2**8) : 8.0
Code 2 : Graphical representation
# Python program showing# Graphical representation of # log2() functionimport numpy as npimport matplotlib.pyplot as plt in_array = [1, 1.2, 1.4, 1.6, 1.8, 2]out_array = np.log2(in_array) print ("out_array : ", out_array) plt.plot(in_array, in_array, color = 'blue', marker = "*") # red for numpy.log2()plt.plot(out_array, in_array, color = 'red', marker = "o")plt.title("numpy.log2()")plt.xlabel("out_array")plt.ylabel("in_array")plt.show()
Output :
out_array : [ 0. 0.26303441 0.48542683 0.67807191 0.84799691 1. ]
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.exp.html.
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
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25335,
"s": 25307,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 25568,
"s": 25335,
"text": "numpy.log2(arr, out = None, *, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None, ufunc ‘log1p’) :This mathematical function helps user to calculate Base-2 logarithm of x where x belongs to all the input array elements."
},
{
"code": null,
"e": 25581,
"s": 25568,
"text": "Parameters :"
},
{
"code": null,
"e": 26091,
"s": 25581,
"text": "array : [array_like]Input array or object.\nout : [ndarray, optional]Output array with same dimensions as Input array, \n placed with result.\n**kwargs : Allows you to pass keyword variable length of argument to a function. \n It is used when we want to handle named argument in a function.\nwhere : [array_like, optional]True value means to calculate the universal \n functions(ufunc) at that position, False value means to leave the \n value in the output alone.\n"
},
{
"code": null,
"e": 26100,
"s": 26091,
"text": "Return :"
},
{
"code": null,
"e": 26196,
"s": 26100,
"text": "An array with Base-2 logarithmic value of x; \nwhere x belongs to all elements of input array. \n"
},
{
"code": null,
"e": 26213,
"s": 26196,
"text": "Code 1 : Working"
},
{
"code": "# Python program explaining# log2() functionimport numpy as np in_array = [1, 3, 5, 2**8]print (\"Input array : \", in_array) out_array = np.log2(in_array)print (\"Output array : \", out_array) print(\"\\nnp.log2(4**4) : \", np.log2(4**4))print(\"np.log2(2**8) : \", np.log2(2**8))",
"e": 26491,
"s": 26213,
"text": null
},
{
"code": null,
"e": 26500,
"s": 26491,
"text": "Output :"
},
{
"code": null,
"e": 26640,
"s": 26500,
"text": "Input array : [1, 3, 5, 256]\nOutput array : [ 0. 1.5849625 2.32192809 8. ]\n\nnp.log2(4**4) : 8.0\nnp.log2(2**8) : 8.0\n"
},
{
"code": null,
"e": 26675,
"s": 26640,
"text": " Code 2 : Graphical representation"
},
{
"code": "# Python program showing# Graphical representation of # log2() functionimport numpy as npimport matplotlib.pyplot as plt in_array = [1, 1.2, 1.4, 1.6, 1.8, 2]out_array = np.log2(in_array) print (\"out_array : \", out_array) plt.plot(in_array, in_array, color = 'blue', marker = \"*\") # red for numpy.log2()plt.plot(out_array, in_array, color = 'red', marker = \"o\")plt.title(\"numpy.log2()\")plt.xlabel(\"out_array\")plt.ylabel(\"in_array\")plt.show() ",
"e": 27123,
"s": 26675,
"text": null
},
{
"code": null,
"e": 27132,
"s": 27123,
"text": "Output :"
},
{
"code": null,
"e": 27219,
"s": 27132,
"text": "out_array : [ 0. 0.26303441 0.48542683 0.67807191 0.84799691 1. ]"
},
{
"code": null,
"e": 27307,
"s": 27219,
"text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.exp.html."
},
{
"code": null,
"e": 27336,
"s": 27307,
"text": "Python numpy-Logic Functions"
},
{
"code": null,
"e": 27349,
"s": 27336,
"text": "Python-numpy"
},
{
"code": null,
"e": 27356,
"s": 27349,
"text": "Python"
},
{
"code": null,
"e": 27454,
"s": 27356,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27472,
"s": 27454,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27507,
"s": 27472,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27539,
"s": 27507,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27561,
"s": 27539,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27603,
"s": 27561,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27633,
"s": 27603,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27659,
"s": 27633,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27688,
"s": 27659,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27732,
"s": 27688,
"text": "Reading and Writing to text files in Python"
}
] |
Python - Cumulative product of dictionary value lists - GeeksforGeeks
|
25 Aug, 2021
Sometimes, while working with Python dictionaries, we can have it’s values as lists. In this can we can have a problem that we just require the product of elements in those list as a whole. This can be a problem in Data Science in which we need to get total records in observations. Let’s discuss certain ways in which this task can be performedMethod #1 : Using loop + list comprehension This task can be performed using explicit product function which can be used to get the product and internal list comprehension can provide a mechanism to iterate this logic to all the keys of dictionary.
Python3
# Python3 code to demonstrate working of# Cumulative product of dictionary value lists# using loop + list comprehension def prod(val) : res = 1 for ele in val: res *= ele return res # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Cumulative product of dictionary value lists# using loop + list comprehensionres = sum(prod(sub) for sub in test_dict.values()) # printing resultprint("Product of dictionary list values are : " + str(res))
The original dictionary is : {'best': [19, 31, 22], 'gfg': [5, 6, 7], 'is': [10, 11]}
Product of dictionary list values are : 13278
Method #2 : Using loop + map() This task can also be performed using map function in place of list comprehension to extend the logic of finding the product, rest all the functionality remaining same as the above method.
Python3
# Python3 code to demonstrate working of# Cumulative product of dictionary value lists# using loop + map() def prod(val) : res = 1 for ele in val: res *= ele return res # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Cumulative product of dictionary value lists# using loop + map()res = sum(map(prod, test_dict.values())) # printing resultprint("Product of dictionary list values are : " + str(res))
The original dictionary is : {'best': [19, 31, 22], 'gfg': [5, 6, 7], 'is': [10, 11]}
Product of dictionary list values are : 13278
gabaa406
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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 dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 26132,
"s": 25537,
"text": "Sometimes, while working with Python dictionaries, we can have it’s values as lists. In this can we can have a problem that we just require the product of elements in those list as a whole. This can be a problem in Data Science in which we need to get total records in observations. Let’s discuss certain ways in which this task can be performedMethod #1 : Using loop + list comprehension This task can be performed using explicit product function which can be used to get the product and internal list comprehension can provide a mechanism to iterate this logic to all the keys of dictionary. "
},
{
"code": null,
"e": 26140,
"s": 26132,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Cumulative product of dictionary value lists# using loop + list comprehension def prod(val) : res = 1 for ele in val: res *= ele return res # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Cumulative product of dictionary value lists# using loop + list comprehensionres = sum(prod(sub) for sub in test_dict.values()) # printing resultprint(\"Product of dictionary list values are : \" + str(res))",
"e": 26755,
"s": 26140,
"text": null
},
{
"code": null,
"e": 26887,
"s": 26755,
"text": "The original dictionary is : {'best': [19, 31, 22], 'gfg': [5, 6, 7], 'is': [10, 11]}\nProduct of dictionary list values are : 13278"
},
{
"code": null,
"e": 27111,
"s": 26889,
"text": " Method #2 : Using loop + map() This task can also be performed using map function in place of list comprehension to extend the logic of finding the product, rest all the functionality remaining same as the above method. "
},
{
"code": null,
"e": 27119,
"s": 27111,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Cumulative product of dictionary value lists# using loop + map() def prod(val) : res = 1 for ele in val: res *= ele return res # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Cumulative product of dictionary value lists# using loop + map()res = sum(map(prod, test_dict.values())) # printing resultprint(\"Product of dictionary list values are : \" + str(res))",
"e": 27698,
"s": 27119,
"text": null
},
{
"code": null,
"e": 27830,
"s": 27698,
"text": "The original dictionary is : {'best': [19, 31, 22], 'gfg': [5, 6, 7], 'is': [10, 11]}\nProduct of dictionary list values are : 13278"
},
{
"code": null,
"e": 27841,
"s": 27832,
"text": "gabaa406"
},
{
"code": null,
"e": 27862,
"s": 27841,
"text": "Python list-programs"
},
{
"code": null,
"e": 27869,
"s": 27862,
"text": "Python"
},
{
"code": null,
"e": 27885,
"s": 27869,
"text": "Python Programs"
},
{
"code": null,
"e": 27983,
"s": 27885,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28015,
"s": 27983,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28057,
"s": 28015,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28099,
"s": 28057,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28126,
"s": 28099,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28182,
"s": 28126,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28204,
"s": 28182,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28243,
"s": 28204,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28289,
"s": 28243,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28327,
"s": 28289,
"text": "Python | Convert a list to dictionary"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.