title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Parbegin/Parend Concurrent Statement | 26 Feb, 2021
Prerequisite – Introduction of Process Synchronization PARBEGIN/PAREND statement is a higher-level language construct for specifying concurrency. All statements can be executed concurrently those are enclosed between PARBEGIN and PAREND. It is used in modelling precedence graph. It is used as an alternative for the FORK/JOIN statement.
Note – PARBEGIN/PAREND is also called COBEGIN/COEND.
Consider the following program:
S0;
PARBEGIN;
S1;
S2;
...
Sn-1;
PAREND;
Sn;
The above program is equivalent to the following precedence graph.
Example – Construct the precedence graph for the following parbegin/parend program.
begin
S1;
parbegin
S3;
begin
S2;
parbegin
S4;
S5;
parend;
S6;
end;
parend;
S7;
end;
Explanation :
We can also Parbegin two process –
Void P( ) Void Q( )
{ {
A; D;
B; E;
C; }
}
The relative order among the statements of P & Q is always maintained
Advantages of Parbegin/Parend –
It is a high-level language block-structure.
It has the advantage of structured control statements.
Semaphores mechanism is also one of the advantages.
Disadvantages of Parbegin/Parend –
It is not powerful enough to model all possible precedence graph.
It is less powerful than the FORK/JOIN construct in modelling precedence graph.
pawanchoure
Process Synchronization
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Feb, 2021"
},
{
"code": null,
"e": 391,
"s": 52,
"text": "Prerequisite – Introduction of Process Synchronization PARBEGIN/PAREND statement is a higher-level language construct for specifying concurrency. All statements can be executed concurrently those are enclosed between PARBEGIN and PAREND. It is used in modelling precedence graph. It is used as an alternative for the FORK/JOIN statement. "
},
{
"code": null,
"e": 445,
"s": 391,
"text": "Note – PARBEGIN/PAREND is also called COBEGIN/COEND. "
},
{
"code": null,
"e": 479,
"s": 445,
"text": "Consider the following program: "
},
{
"code": null,
"e": 535,
"s": 479,
"text": "S0;\nPARBEGIN;\n S1;\n S2;\n ...\n Sn-1;\nPAREND;\nSn;"
},
{
"code": null,
"e": 603,
"s": 535,
"text": "The above program is equivalent to the following precedence graph. "
},
{
"code": null,
"e": 691,
"s": 605,
"text": "Example – Construct the precedence graph for the following parbegin/parend program. "
},
{
"code": null,
"e": 871,
"s": 691,
"text": "begin\nS1;\n parbegin\n S3;\n begin\n S2;\n parbegin\n S4;\n S5;\n parend;\n S6;\n end;\n parend;\nS7;\nend;"
},
{
"code": null,
"e": 886,
"s": 871,
"text": "Explanation : "
},
{
"code": null,
"e": 923,
"s": 888,
"text": "We can also Parbegin two process –"
},
{
"code": null,
"e": 963,
"s": 923,
"text": "Void P( ) Void Q( )"
},
{
"code": null,
"e": 996,
"s": 963,
"text": "{ {"
},
{
"code": null,
"e": 1036,
"s": 996,
"text": "A; D;"
},
{
"code": null,
"e": 1077,
"s": 1036,
"text": "B; E;"
},
{
"code": null,
"e": 1108,
"s": 1077,
"text": "C; }"
},
{
"code": null,
"e": 1110,
"s": 1108,
"text": "}"
},
{
"code": null,
"e": 1180,
"s": 1110,
"text": "The relative order among the statements of P & Q is always maintained"
},
{
"code": null,
"e": 1213,
"s": 1180,
"text": "Advantages of Parbegin/Parend – "
},
{
"code": null,
"e": 1258,
"s": 1213,
"text": "It is a high-level language block-structure."
},
{
"code": null,
"e": 1313,
"s": 1258,
"text": "It has the advantage of structured control statements."
},
{
"code": null,
"e": 1365,
"s": 1313,
"text": "Semaphores mechanism is also one of the advantages."
},
{
"code": null,
"e": 1401,
"s": 1365,
"text": "Disadvantages of Parbegin/Parend – "
},
{
"code": null,
"e": 1467,
"s": 1401,
"text": "It is not powerful enough to model all possible precedence graph."
},
{
"code": null,
"e": 1547,
"s": 1467,
"text": "It is less powerful than the FORK/JOIN construct in modelling precedence graph."
},
{
"code": null,
"e": 1559,
"s": 1547,
"text": "pawanchoure"
},
{
"code": null,
"e": 1583,
"s": 1559,
"text": "Process Synchronization"
},
{
"code": null,
"e": 1601,
"s": 1583,
"text": "Operating Systems"
},
{
"code": null,
"e": 1619,
"s": 1601,
"text": "Operating Systems"
}
] |
ar command in Linux with examples - GeeksforGeeks | 04 Apr, 2019
ar command is used to create, modify and extract the files from the archives. An archive is a collection of other files having a particular structure from which the individual files can be extracted. Individual files are termed as the members of the archive.
Syntax:
ar [OPTIONS] archive_name member_files
Options:
r: This is used to create archive, insert files in archive. This is different from q as it deletes any previously existing members. If any member filename does not exist it throws an error. By default, it adds a new member at end of the file.Example: Assume there is a file named star1 and you want to create archive named “super” without modifier then you can use the following command:ar r super.a *star1This will create an archive with member star1. With modifier it looks like as:ar rv super.a *star1.txtNote: The modifier v gives a line or output with letter a or r indicating if the file is appended or not.
Example: Assume there is a file named star1 and you want to create archive named “super” without modifier then you can use the following command:
ar r super.a *star1
This will create an archive with member star1. With modifier it looks like as:
ar rv super.a *star1.txt
Note: The modifier v gives a line or output with letter a or r indicating if the file is appended or not.
d: Deletes modules from archive. Specify names of the modules as member...; When you add modifier v, ar lists each module as it is deleted.ar d super.a star1.txtIn our previous case, we used star1.txt in archive super.a, now we will delete that file from thereIn that we had super.a archive storing star1.txt, after using d without modifier it just deleted the filenow lets see the same example with modifier var dv super.a star1.txtWith using modifier v it listed module as they are deleted.
ar d super.a star1.txt
In our previous case, we used star1.txt in archive super.a, now we will delete that file from there
In that we had super.a archive storing star1.txt, after using d without modifier it just deleted the filenow lets see the same example with modifier v
ar dv super.a star1.txt
With using modifier v it listed module as they are deleted.
p: This option is used to print the specified members of a archive in a standard output file if you do not use modifier it will print member as it is an output file whereas if you use modifier v then it will show member name before it is copied to output file.ar p super.aHere it gave the output which was written in our files stat1.txt and star2.txt, now let us check what happens when we use modifier v in it.ar pv super.aWith the use of the modifier, first get the file name and then content written inside it.
ar p super.a
Here it gave the output which was written in our files stat1.txt and star2.txt, now let us check what happens when we use modifier v in it.
ar pv super.a
With the use of the modifier, first get the file name and then content written inside it.
t: It displays the contents of the archive in a listed manner, usually, it shows the contents of the archive but if we use modifier O then it also shows the corresponding offset of each member.ar t super.a (taking our old files and examples)Here t displayed the members of the archive, now lets see what it shows when we use modifier.ar tO super.aThis time with the use of modifier we get the corresponding offset of each member.
ar t super.a (taking our old files and examples)
Here t displayed the members of the archive, now lets see what it shows when we use modifier.
ar tO super.a
This time with the use of modifier we get the corresponding offset of each member.
x: It extracts each named member from the archive if you do not name the member to be extracted it extracts the whole archive. We can use v modifier to list name of each member which is extracted.The modifier v displays each file which is extracted and also we did not specify a name so it extracted the whole archive if we specify names of the member it extracts only that member.This command does not extract thin files as in our case, it just displays that it has extracted the archive.The above image shows extraction based on specified member name, and v modifier lists file is extract.
The modifier v displays each file which is extracted and also we did not specify a name so it extracted the whole archive if we specify names of the member it extracts only that member.
This command does not extract thin files as in our case, it just displays that it has extracted the archive.
The above image shows extraction based on specified member name, and v modifier lists file is extract.
linux-command
Linux-file-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
ZIP command in Linux with examples
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
'crontab' in Linux with Examples
Tail command in Linux with examples
UDP Server-Client implementation in C
diff command in Linux with examples
Cat command in Linux with examples | [
{
"code": null,
"e": 25975,
"s": 25947,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 26234,
"s": 25975,
"text": "ar command is used to create, modify and extract the files from the archives. An archive is a collection of other files having a particular structure from which the individual files can be extracted. Individual files are termed as the members of the archive."
},
{
"code": null,
"e": 26242,
"s": 26234,
"text": "Syntax:"
},
{
"code": null,
"e": 26281,
"s": 26242,
"text": "ar [OPTIONS] archive_name member_files"
},
{
"code": null,
"e": 26290,
"s": 26281,
"text": "Options:"
},
{
"code": null,
"e": 26904,
"s": 26290,
"text": "r: This is used to create archive, insert files in archive. This is different from q as it deletes any previously existing members. If any member filename does not exist it throws an error. By default, it adds a new member at end of the file.Example: Assume there is a file named star1 and you want to create archive named “super” without modifier then you can use the following command:ar r super.a *star1This will create an archive with member star1. With modifier it looks like as:ar rv super.a *star1.txtNote: The modifier v gives a line or output with letter a or r indicating if the file is appended or not."
},
{
"code": null,
"e": 27050,
"s": 26904,
"text": "Example: Assume there is a file named star1 and you want to create archive named “super” without modifier then you can use the following command:"
},
{
"code": null,
"e": 27070,
"s": 27050,
"text": "ar r super.a *star1"
},
{
"code": null,
"e": 27149,
"s": 27070,
"text": "This will create an archive with member star1. With modifier it looks like as:"
},
{
"code": null,
"e": 27174,
"s": 27149,
"text": "ar rv super.a *star1.txt"
},
{
"code": null,
"e": 27280,
"s": 27174,
"text": "Note: The modifier v gives a line or output with letter a or r indicating if the file is appended or not."
},
{
"code": null,
"e": 27773,
"s": 27280,
"text": "d: Deletes modules from archive. Specify names of the modules as member...; When you add modifier v, ar lists each module as it is deleted.ar d super.a star1.txtIn our previous case, we used star1.txt in archive super.a, now we will delete that file from thereIn that we had super.a archive storing star1.txt, after using d without modifier it just deleted the filenow lets see the same example with modifier var dv super.a star1.txtWith using modifier v it listed module as they are deleted."
},
{
"code": null,
"e": 27796,
"s": 27773,
"text": "ar d super.a star1.txt"
},
{
"code": null,
"e": 27896,
"s": 27796,
"text": "In our previous case, we used star1.txt in archive super.a, now we will delete that file from there"
},
{
"code": null,
"e": 28047,
"s": 27896,
"text": "In that we had super.a archive storing star1.txt, after using d without modifier it just deleted the filenow lets see the same example with modifier v"
},
{
"code": null,
"e": 28071,
"s": 28047,
"text": "ar dv super.a star1.txt"
},
{
"code": null,
"e": 28131,
"s": 28071,
"text": "With using modifier v it listed module as they are deleted."
},
{
"code": null,
"e": 28645,
"s": 28131,
"text": "p: This option is used to print the specified members of a archive in a standard output file if you do not use modifier it will print member as it is an output file whereas if you use modifier v then it will show member name before it is copied to output file.ar p super.aHere it gave the output which was written in our files stat1.txt and star2.txt, now let us check what happens when we use modifier v in it.ar pv super.aWith the use of the modifier, first get the file name and then content written inside it."
},
{
"code": null,
"e": 28658,
"s": 28645,
"text": "ar p super.a"
},
{
"code": null,
"e": 28798,
"s": 28658,
"text": "Here it gave the output which was written in our files stat1.txt and star2.txt, now let us check what happens when we use modifier v in it."
},
{
"code": null,
"e": 28812,
"s": 28798,
"text": "ar pv super.a"
},
{
"code": null,
"e": 28902,
"s": 28812,
"text": "With the use of the modifier, first get the file name and then content written inside it."
},
{
"code": null,
"e": 29332,
"s": 28902,
"text": "t: It displays the contents of the archive in a listed manner, usually, it shows the contents of the archive but if we use modifier O then it also shows the corresponding offset of each member.ar t super.a (taking our old files and examples)Here t displayed the members of the archive, now lets see what it shows when we use modifier.ar tO super.aThis time with the use of modifier we get the corresponding offset of each member."
},
{
"code": null,
"e": 29381,
"s": 29332,
"text": "ar t super.a (taking our old files and examples)"
},
{
"code": null,
"e": 29475,
"s": 29381,
"text": "Here t displayed the members of the archive, now lets see what it shows when we use modifier."
},
{
"code": null,
"e": 29489,
"s": 29475,
"text": "ar tO super.a"
},
{
"code": null,
"e": 29572,
"s": 29489,
"text": "This time with the use of modifier we get the corresponding offset of each member."
},
{
"code": null,
"e": 30164,
"s": 29572,
"text": "x: It extracts each named member from the archive if you do not name the member to be extracted it extracts the whole archive. We can use v modifier to list name of each member which is extracted.The modifier v displays each file which is extracted and also we did not specify a name so it extracted the whole archive if we specify names of the member it extracts only that member.This command does not extract thin files as in our case, it just displays that it has extracted the archive.The above image shows extraction based on specified member name, and v modifier lists file is extract."
},
{
"code": null,
"e": 30350,
"s": 30164,
"text": "The modifier v displays each file which is extracted and also we did not specify a name so it extracted the whole archive if we specify names of the member it extracts only that member."
},
{
"code": null,
"e": 30459,
"s": 30350,
"text": "This command does not extract thin files as in our case, it just displays that it has extracted the archive."
},
{
"code": null,
"e": 30562,
"s": 30459,
"text": "The above image shows extraction based on specified member name, and v modifier lists file is extract."
},
{
"code": null,
"e": 30576,
"s": 30562,
"text": "linux-command"
},
{
"code": null,
"e": 30596,
"s": 30576,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 30603,
"s": 30596,
"text": "Picked"
},
{
"code": null,
"e": 30614,
"s": 30603,
"text": "Linux-Unix"
},
{
"code": null,
"e": 30712,
"s": 30614,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30750,
"s": 30712,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 30785,
"s": 30750,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 30826,
"s": 30785,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 30861,
"s": 30826,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 30897,
"s": 30861,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 30930,
"s": 30897,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 30966,
"s": 30930,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 31004,
"s": 30966,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 31040,
"s": 31004,
"text": "diff command in Linux with examples"
}
] |
C Programming Interview Questions | Dear readers, these C Programming Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of C Programming. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −
What is a pointer on pointer?
It’s a pointer variable which can hold the address of another pointer variable. It de-refers twice to point to the data held by the designated pointer variable.
Eg: int x = 5, *p=&x, **q=&p;
Therefore ‘x’ can be accessed by **q.
It’s a pointer variable which can hold the address of another pointer variable. It de-refers twice to point to the data held by the designated pointer variable.
Eg: int x = 5, *p=&x, **q=&p;
Therefore ‘x’ can be accessed by **q.
Distinguish between malloc() & calloc() memory allocation.
Both allocates memory from heap area/dynamic memory. By default calloc fills the allocated memory with 0’s.
Both allocates memory from heap area/dynamic memory. By default calloc fills the allocated memory with 0’s.
What is keyword auto for?
By default every local variable of the function is automatic (auto). In the below function both the variables ‘i’ and ‘j’ are automatic variables.
void f() {
int i;
auto int j;
}
NOTE − A global variable can’t be an automatic variable.
By default every local variable of the function is automatic (auto). In the below function both the variables ‘i’ and ‘j’ are automatic variables.
void f() {
int i;
auto int j;
}
NOTE − A global variable can’t be an automatic variable.
What are the valid places for the keyword break to appear.
Break can appear only with in the looping control and switch statement. The purpose of the break is to bring the control out from the said blocks.
Break can appear only with in the looping control and switch statement. The purpose of the break is to bring the control out from the said blocks.
Explain the syntax for for loop.
for(expression-1;expression-2;expression-3) {
//set of statements
}
When control reaches for expression-1 is executed first. Then following expression-2, and if expression-2 evaluates to non-zero ‘set of statements’ and expression-3 is executed, follows expression-2.
for(expression-1;expression-2;expression-3) {
//set of statements
}
When control reaches for expression-1 is executed first. Then following expression-2, and if expression-2 evaluates to non-zero ‘set of statements’ and expression-3 is executed, follows expression-2.
What is difference between including the header file with-in angular braces < > and double quotes “ “
If a header file is included with in < > then the compiler searches for the particular header file only with in the built in include path. If a header file is included with in “ “, then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path.
If a header file is included with in < > then the compiler searches for the particular header file only with in the built in include path. If a header file is included with in “ “, then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path.
How a negative integer is stored.
Get the two’s compliment of the same positive integer. Eg: 1011 (-5)
Step-1 − One’s compliment of 5 : 1010
Step-2 − Add 1 to above, giving 1011, which is -5
Get the two’s compliment of the same positive integer. Eg: 1011 (-5)
Step-1 − One’s compliment of 5 : 1010
Step-2 − Add 1 to above, giving 1011, which is -5
What is a static variable?
A static local variables retains its value between the function call and the default value is 0. The following function will print 1 2 3 if called thrice.
void f() {
static int i;
++i;
printf(“%d “,i);
}
If a global variable is static then its visibility is limited to the same source code.
A static local variables retains its value between the function call and the default value is 0. The following function will print 1 2 3 if called thrice.
void f() {
static int i;
++i;
printf(“%d “,i);
}
If a global variable is static then its visibility is limited to the same source code.
What is a NULL pointer?
A pointer pointing to nothing is called so. Eg: char *p=NULL;
A pointer pointing to nothing is called so. Eg: char *p=NULL;
What is the purpose of extern storage specifier?
Used to resolve the scope of global symbol.
Eg:
main() {
extern int i;
Printf(“%d”,i);
}
int i = 20;
Used to resolve the scope of global symbol.
Eg:
main() {
extern int i;
Printf(“%d”,i);
}
int i = 20;
Explain the purpose of the function sprintf().
Prints the formatted output onto the character array.
Prints the formatted output onto the character array.
What is the meaning of base address of the array?
The starting address of the array is called as the base address of the array.
The starting address of the array is called as the base address of the array.
When should we use the register storage specifier?
If a variable is used most frequently then it should be declared using register storage specifier, then possibly the compiler gives CPU register for its storage to speed up the look up of the variable.
If a variable is used most frequently then it should be declared using register storage specifier, then possibly the compiler gives CPU register for its storage to speed up the look up of the variable.
S++ or S = S+1, which can be recommended to increment the value by 1 and why?
S++, as it is single machine instruction (INC) internally.
S++, as it is single machine instruction (INC) internally.
What is a dangling pointer?
A pointer initially holding valid address, but later the held address is released or freed. Then such a pointer is called as dangling pointer.
A pointer initially holding valid address, but later the held address is released or freed. Then such a pointer is called as dangling pointer.
What is the purpose of the keyword typedef?
It is used to alias the existing type. Also used to simplify the complex declaration of the type.
It is used to alias the existing type. Also used to simplify the complex declaration of the type.
What is lvalue and rvalue?
The expression appearing on right side of the assignment operator is called as rvalue. Rvalue is assigned to lvalue, which appears on left side of the assignment operator. The lvalue should designate to a variable not a constant.
The expression appearing on right side of the assignment operator is called as rvalue. Rvalue is assigned to lvalue, which appears on left side of the assignment operator. The lvalue should designate to a variable not a constant.
What is the difference between actual and formal parameters?
The parameters sent to the function at calling end are called as actual parameters while at the receiving of the function definition called as formal parameters.
The parameters sent to the function at calling end are called as actual parameters while at the receiving of the function definition called as formal parameters.
Can a program be compiled without main() function?
Yes, it can be but cannot be executed, as the execution requires main() function definition.
Yes, it can be but cannot be executed, as the execution requires main() function definition.
What is the advantage of declaring void pointers?
When we do not know what type of the memory address the pointer variable is going to hold, then we declare a void pointer for such.
When we do not know what type of the memory address the pointer variable is going to hold, then we declare a void pointer for such.
Where an automatic variable is stored?
Every local variable by default being an auto variable is stored in stack memory.
Every local variable by default being an auto variable is stored in stack memory.
What is a nested structure?
A structure containing an element of another structure as its member is referred so.
A structure containing an element of another structure as its member is referred so.
What is the difference between variable declaration and variable definition?
Declaration associates type to the variable whereas definition gives the value to the variable.
Declaration associates type to the variable whereas definition gives the value to the variable.
What is a self-referential structure?
A structure containing the same structure pointer variable as its element is called as self-referential structure.
A structure containing the same structure pointer variable as its element is called as self-referential structure.
Does a built-in header file contains built-in function definition?
No, the header file only declares function. The definition is in library which is linked by the linker.
No, the header file only declares function. The definition is in library which is linked by the linker.
Explain modular programming.
Dividing the program in to sub programs (modules/function) to achieve the given task is modular approach. More generic functions definition gives the ability to re-use the functions, such as built-in library functions.
Dividing the program in to sub programs (modules/function) to achieve the given task is modular approach. More generic functions definition gives the ability to re-use the functions, such as built-in library functions.
What is a token?
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol.
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol.
What is a preprocessor?
Preprocessor is a directive to the compiler to perform certain things before the actual compilation process begins.
Preprocessor is a directive to the compiler to perform certain things before the actual compilation process begins.
Explain the use of %i format specifier w.r.t scanf().
Can be used to input integer in all the supported format.
Can be used to input integer in all the supported format.
How can you print a \ (backslash) using any of the printf() family of functions.
Escape it using \ (backslash).
Escape it using \ (backslash).
Does a break is required by default case in switch statement?
Yes, if it is not appearing as the last case and if we do not want the control to flow to the following case after default if any.
Yes, if it is not appearing as the last case and if we do not want the control to flow to the following case after default if any.
When to user -> (arrow) operator.
If the structure/union variable is a pointer variable, to access structure/union elements the arrow operator is used.
If the structure/union variable is a pointer variable, to access structure/union elements the arrow operator is used.
What are bit fields?
We can create integer structure members of differing size apart from non-standard size using bit fields. Such structure size is automatically adjusted with the multiple of integer size of the machine.
We can create integer structure members of differing size apart from non-standard size using bit fields. Such structure size is automatically adjusted with the multiple of integer size of the machine.
What are command line arguments?
The arguments which we pass to the main() function while executing the program are called as command line arguments. The parameters are always strings held in the second argument (below in args) of the function which is array of character pointers. First argument represents the count of arguments (below in count) and updated automatically by operating system.
main( int count, char *args[]) {
}
The arguments which we pass to the main() function while executing the program are called as command line arguments. The parameters are always strings held in the second argument (below in args) of the function which is array of character pointers. First argument represents the count of arguments (below in count) and updated automatically by operating system.
main( int count, char *args[]) {
}
What are the different ways of passing parameters to the functions? Which to use when?
Call by value − We send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used.
Call by reference − We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters.
Call by value − We send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used.
Call by value − We send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used.
Call by reference − We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters.
Call by reference − We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters.
What is the purpose of built-in stricmp() function.
It compares two strings by ignoring the case.
It compares two strings by ignoring the case.
Describe the file opening mode “w+”.
Opens a file both for reading and writing. If a file is not existing it creates one, else if the file is existing it will be over written.
Opens a file both for reading and writing. If a file is not existing it creates one, else if the file is existing it will be over written.
Where the address of operator (&) cannot be used?
It cannot be used on constants.
It cannot be used on variable which are declared using register storage class.
It cannot be used on constants.
It cannot be used on variable which are declared using register storage class.
Is FILE a built-in data type?
No, it is a structure defined in stdio.h.
What is reminder for 5.0 % 2?
Error, It is invalid that either of the operands for the modulus operator (%) is a real number.
Error, It is invalid that either of the operands for the modulus operator (%) is a real number.
How many operators are there under the category of ternary operators?
There is only one operator and is conditional operator (? : ).
There is only one operator and is conditional operator (? : ).
Which key word is used to perform unconditional branching?
goto
goto
What is a pointer to a function? Give the general syntax for the same.
A pointer holding the reference of the function is called pointer to a function. In general it is declared as follows.
T (*fun_ptr) (T1,T2...); Where T is any date type.
Once fun_ptr refers a function the same can be invoked using the pointer as follows.
fun_ptr();
[Or]
(*fun_ptr)();
A pointer holding the reference of the function is called pointer to a function. In general it is declared as follows.
T (*fun_ptr) (T1,T2...); Where T is any date type.
Once fun_ptr refers a function the same can be invoked using the pointer as follows.
fun_ptr();
[Or]
(*fun_ptr)();
Explain the use of comma operator (,).
Comma operator can be used to separate two or more expressions.
Eg: printf(“hi”) , printf(“Hello”);
Comma operator can be used to separate two or more expressions.
Eg: printf(“hi”) , printf(“Hello”);
What is a NULL statement?
A null statement is no executable statements such as ; (semicolon).
Eg: int count = 0;
while( ++count<=10 ) ;
Above does nothing 10 times.
A null statement is no executable statements such as ; (semicolon).
Eg: int count = 0;
while( ++count<=10 ) ;
Above does nothing 10 times.
What is a static function?
A function’s definition prefixed with static keyword is called as a static function. You would make a function static if it should be called only within the same source code.
A function’s definition prefixed with static keyword is called as a static function. You would make a function static if it should be called only within the same source code.
Which compiler switch to be used for compiling the programs using math library with gcc compiler?
Opiton –lm to be used as > gcc –lm <file.c>
Opiton –lm to be used as > gcc –lm <file.c>
Which operator is used to continue the definition of macro in the next line?
Backward slash (\) is used.
E.g. #define MESSAGE "Hi, \
Welcome to C"
Backward slash (\) is used.
E.g. #define MESSAGE "Hi, \
Welcome to C"
Which operator is used to receive the variable number of arguments for a function?
Ellipses (...) is used for the same. A general function definition looks as follows
void f(int k,...) {
}
Ellipses (...) is used for the same. A general function definition looks as follows
void f(int k,...) {
}
What is the problem with the following coding snippet?
char *s1 = "hello",*s2 = "welcome";
strcat(s1,s2);
s1 points to a string constant and cannot be altered.
char *s1 = "hello",*s2 = "welcome";
strcat(s1,s2);
s1 points to a string constant and cannot be altered.
Which built-in library function can be used to re-size the allocated dynamic memory?
realloc().
realloc().
Define an array.
Array is collection of similar data items under a common name.
Array is collection of similar data items under a common name.
What are enumerations?
Enumerations are list of integer constants with name. Enumerators are defined with the keyword enum.
Enumerations are list of integer constants with name. Enumerators are defined with the keyword enum.
Which built-in function can be used to move the file pointer internally?
fseek()
fseek()
What is a variable?
A variable is the name storage.
A variable is the name storage.
Who designed C programming language?
Dennis M Ritchie.
Dennis M Ritchie.
C is successor of which programming language?
B
B
What is the full form of ANSI?
American National Standards Institute.
American National Standards Institute.
Which operator can be used to determine the size of a data type or variable?
sizeof
sizeof
Can we assign a float variable to a long integer variable?
Yes, with loss of fractional part.
Yes, with loss of fractional part.
Is 068 a valid octal number?
No, it contains invalid octal digits.
No, it contains invalid octal digits.
What it the return value of a relational operator if it returns any?
Return a value 1 if the relation between the expressions is true, else 0.
Return a value 1 if the relation between the expressions is true, else 0.
How does bitwise operator XOR works.
If both the corresponding bits are same it gives 0 else 1.
If both the corresponding bits are same it gives 0 else 1.
What is an infinite loop?
A loop executing repeatedly as the loop-expression always evaluates to true such as
while(0 == 0) {
}
A loop executing repeatedly as the loop-expression always evaluates to true such as
while(0 == 0) {
}
Can variables belonging to different scope have same name? If so show an example.
Variables belonging to different scope can have same name as in the following code snippet.
int var;
void f() {
int var;
}
main() {
int var;
}
Variables belonging to different scope can have same name as in the following code snippet.
int var;
void f() {
int var;
}
main() {
int var;
}
What is the default value of local and global variables?
Local variables get garbage value and global variables get a value 0 by default.
Local variables get garbage value and global variables get a value 0 by default.
Can a pointer access the array?
Pointer by holding array’s base address can access the array.
Pointer by holding array’s base address can access the array.
What are valid operations on pointers?
The only two permitted operations on pointers are
Comparision ii) Addition/Substraction (excluding void pointers)
The only two permitted operations on pointers are
Comparision ii) Addition/Substraction (excluding void pointers)
What is a string length?
It is the count of character excluding the ‘\0’ character.
It is the count of character excluding the ‘\0’ character.
What is the built-in function to append one string to another?
strcat() form the header string.h
strcat() form the header string.h
Which operator can be used to access union elements if union variable is a pointer variable?
Arrow (->) operator.
Arrow (->) operator.
Explain about ‘stdin’.
stdin in a pointer variable which is by default opened for standard input device.
stdin in a pointer variable which is by default opened for standard input device.
Name a function which can be used to close the file stream.
fclose().
fclose().
What is the purpose of #undef preprocessor?
It be used to undefine an existing macro definition.
It be used to undefine an existing macro definition.
Define a structure.
A structure can be defined of collection of heterogeneous data items.
A structure can be defined of collection of heterogeneous data items.
Name the predefined macro which be used to determine whether your compiler is ANSI standard or not?
__STDC__
__STDC__
What is typecasting?
Typecasting is a way to convert a variable/constant from one type to another type.
Typecasting is a way to convert a variable/constant from one type to another type.
What is recursion?
Function calling itself is called as recursion.
Function calling itself is called as recursion.
Which function can be used to release the dynamic allocated memory?
free().
free().
What is the first string in the argument vector w.r.t command line arguments?
Program name.
Program name.
How can we determine whether a file is successfully opened or not using fopen() function?
On failure fopen() returns NULL, otherwise opened successfully.
On failure fopen() returns NULL, otherwise opened successfully.
What is the output file generated by the linker.
Linker generates the executable file.
Linker generates the executable file.
What is the maximum length of an identifier?
Ideally it is 32 characters and also implementation dependent.
Ideally it is 32 characters and also implementation dependent.
What is the default function call method?
By default the functions are called by value.
By default the functions are called by value.
Functions must and should be declared. Comment on this.
Function declaration is optional if the same is invoked after its definition.
Function declaration is optional if the same is invoked after its definition.
When the macros gets expanded?
At the time of preprocessing.
At the time of preprocessing.
Can a function return multiple values to the caller using return reserved word?
No, only one value can be returned to the caller.
No, only one value can be returned to the caller.
What is a constant pointer?
A pointer which is not allowed to be altered to hold another address after it is holding one.
A pointer which is not allowed to be altered to hold another address after it is holding one.
To make pointer generic for which date type it need to be declared?
Void
Void
Can the structure variable be initialized as soon as it is declared?
Yes, w.r.t the order of structure elements only.
Yes, w.r.t the order of structure elements only.
Is there a way to compare two structure variables?
There is no such. We need to compare element by element of the structure variables.
There is no such. We need to compare element by element of the structure variables.
Which built-in library function can be used to match a patter from the string?
Strstr()
Strstr()
What is difference between far and near pointers?
In first place they are non-standard keywords. A near pointer can access only 2^15 memory space and far pointer can access 2^32 memory space. Both the keywords are implementation specific and are non-standard.
In first place they are non-standard keywords. A near pointer can access only 2^15 memory space and far pointer can access 2^32 memory space. Both the keywords are implementation specific and are non-standard.
Can we nest comments in a C code?
No, we cannot.
No, we cannot.
Which control loop is recommended if you have to execute set of statements for fixed number of times?
for – Loop.
for – Loop.
What is a constant?
A value which cannot be modified is called so. Such variables are qualified with the keyword const.
A value which cannot be modified is called so. Such variables are qualified with the keyword const.
Can we use just the tag name of structures to declare the variables for the same?
No, we need to use both the keyword ‘struct’ and the tag name.
No, we need to use both the keyword ‘struct’ and the tag name.
Can the main() function left empty?
Yes, possibly the program doing nothing.
Yes, possibly the program doing nothing.
Can one function call another?
Yes, any user defined function can call any function.
Yes, any user defined function can call any function.
Apart from Dennis Ritchie who the other person who contributed in design of C language.
Brain Kernighan
Brain Kernighan
Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2535,
"s": 2084,
"text": "Dear readers, these C Programming Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of C Programming. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −"
},
{
"code": null,
"e": 2799,
"s": 2535,
"text": "\n\nWhat is a pointer on pointer?\n\nIt’s a pointer variable which can hold the address of another pointer variable. It de-refers twice to point to the data held by the designated pointer variable.\nEg: int x = 5, *p=&x, **q=&p;\nTherefore ‘x’ can be accessed by **q.\n\n"
},
{
"code": null,
"e": 2960,
"s": 2799,
"text": "It’s a pointer variable which can hold the address of another pointer variable. It de-refers twice to point to the data held by the designated pointer variable."
},
{
"code": null,
"e": 2990,
"s": 2960,
"text": "Eg: int x = 5, *p=&x, **q=&p;"
},
{
"code": null,
"e": 3028,
"s": 2990,
"text": "Therefore ‘x’ can be accessed by **q."
},
{
"code": null,
"e": 3200,
"s": 3028,
"text": "\n\nDistinguish between malloc() & calloc() memory allocation.\n\nBoth allocates memory from heap area/dynamic memory. By default calloc fills the allocated memory with 0’s.\n\n"
},
{
"code": null,
"e": 3308,
"s": 3200,
"text": "Both allocates memory from heap area/dynamic memory. By default calloc fills the allocated memory with 0’s."
},
{
"code": null,
"e": 3579,
"s": 3308,
"text": "\n\nWhat is keyword auto for?\nBy default every local variable of the function is automatic (auto). In the below function both the variables ‘i’ and ‘j’ are automatic variables.\nvoid f() {\n int i;\n auto int j;\n}\nNOTE − A global variable can’t be an automatic variable.\n"
},
{
"code": null,
"e": 3726,
"s": 3579,
"text": "By default every local variable of the function is automatic (auto). In the below function both the variables ‘i’ and ‘j’ are automatic variables."
},
{
"code": null,
"e": 3764,
"s": 3726,
"text": "void f() {\n int i;\n auto int j;\n}"
},
{
"code": null,
"e": 3821,
"s": 3764,
"text": "NOTE − A global variable can’t be an automatic variable."
},
{
"code": null,
"e": 4030,
"s": 3821,
"text": "\n\nWhat are the valid places for the keyword break to appear.\nBreak can appear only with in the looping control and switch statement. The purpose of the break is to bring the control out from the said blocks.\n"
},
{
"code": null,
"e": 4177,
"s": 4030,
"text": "Break can appear only with in the looping control and switch statement. The purpose of the break is to bring the control out from the said blocks."
},
{
"code": null,
"e": 4484,
"s": 4177,
"text": "\n\nExplain the syntax for for loop.\nfor(expression-1;expression-2;expression-3) {\n //set of statements\n}\nWhen control reaches for expression-1 is executed first. Then following expression-2, and if expression-2 evaluates to non-zero ‘set of statements’ and expression-3 is executed, follows expression-2.\n"
},
{
"code": null,
"e": 4555,
"s": 4484,
"text": "for(expression-1;expression-2;expression-3) {\n //set of statements\n}"
},
{
"code": null,
"e": 4755,
"s": 4555,
"text": "When control reaches for expression-1 is executed first. Then following expression-2, and if expression-2 evaluates to non-zero ‘set of statements’ and expression-3 is executed, follows expression-2."
},
{
"code": null,
"e": 5187,
"s": 4755,
"text": "\n\nWhat is difference between including the header file with-in angular braces < > and double quotes “ “\nIf a header file is included with in < > then the compiler searches for the particular header file only with in the built in include path. If a header file is included with in “ “, then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path.\n"
},
{
"code": null,
"e": 5514,
"s": 5187,
"text": "If a header file is included with in < > then the compiler searches for the particular header file only with in the built in include path. If a header file is included with in “ “, then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path."
},
{
"code": null,
"e": 5708,
"s": 5514,
"text": "\n\nHow a negative integer is stored.\nGet the two’s compliment of the same positive integer. Eg: 1011 (-5)\nStep-1 − One’s compliment of 5 : 1010\nStep-2 − Add 1 to above, giving 1011, which is -5\n"
},
{
"code": null,
"e": 5777,
"s": 5708,
"text": "Get the two’s compliment of the same positive integer. Eg: 1011 (-5)"
},
{
"code": null,
"e": 5815,
"s": 5777,
"text": "Step-1 − One’s compliment of 5 : 1010"
},
{
"code": null,
"e": 5865,
"s": 5815,
"text": "Step-2 − Add 1 to above, giving 1011, which is -5"
},
{
"code": null,
"e": 6199,
"s": 5865,
"text": "\n\nWhat is a static variable?\nA static local variables retains its value between the function call and the default value is 0. The following function will print 1 2 3 if called thrice.\nvoid f() { \n static int i; \n ++i; \n printf(“%d “,i); \n}\nIf a global variable is static then its visibility is limited to the same source code.\n"
},
{
"code": null,
"e": 6354,
"s": 6199,
"text": "A static local variables retains its value between the function call and the default value is 0. The following function will print 1 2 3 if called thrice."
},
{
"code": null,
"e": 6416,
"s": 6354,
"text": "void f() { \n static int i; \n ++i; \n printf(“%d “,i); \n}"
},
{
"code": null,
"e": 6503,
"s": 6416,
"text": "If a global variable is static then its visibility is limited to the same source code."
},
{
"code": null,
"e": 6592,
"s": 6503,
"text": "\n\nWhat is a NULL pointer?\nA pointer pointing to nothing is called so. Eg: char *p=NULL;\n"
},
{
"code": null,
"e": 6654,
"s": 6592,
"text": "A pointer pointing to nothing is called so. Eg: char *p=NULL;"
},
{
"code": null,
"e": 6816,
"s": 6654,
"text": "\n\nWhat is the purpose of extern storage specifier?\nUsed to resolve the scope of global symbol.\nEg: \nmain() {\n extern int i;\n Printf(“%d”,i);\n}\n\nint i = 20;\n"
},
{
"code": null,
"e": 6860,
"s": 6816,
"text": "Used to resolve the scope of global symbol."
},
{
"code": null,
"e": 6926,
"s": 6860,
"text": "Eg: \nmain() {\n extern int i;\n Printf(“%d”,i);\n}\n\nint i = 20;"
},
{
"code": null,
"e": 7030,
"s": 6926,
"text": "\n\nExplain the purpose of the function sprintf().\nPrints the formatted output onto the character array.\n"
},
{
"code": null,
"e": 7084,
"s": 7030,
"text": "Prints the formatted output onto the character array."
},
{
"code": null,
"e": 7215,
"s": 7084,
"text": "\n\nWhat is the meaning of base address of the array?\nThe starting address of the array is called as the base address of the array.\n"
},
{
"code": null,
"e": 7293,
"s": 7215,
"text": "The starting address of the array is called as the base address of the array."
},
{
"code": null,
"e": 7549,
"s": 7293,
"text": "\n\nWhen should we use the register storage specifier?\nIf a variable is used most frequently then it should be declared using register storage specifier, then possibly the compiler gives CPU register for its storage to speed up the look up of the variable.\n"
},
{
"code": null,
"e": 7751,
"s": 7549,
"text": "If a variable is used most frequently then it should be declared using register storage specifier, then possibly the compiler gives CPU register for its storage to speed up the look up of the variable."
},
{
"code": null,
"e": 7891,
"s": 7751,
"text": "\n\nS++ or S = S+1, which can be recommended to increment the value by 1 and why?\nS++, as it is single machine instruction (INC) internally.\n"
},
{
"code": null,
"e": 7950,
"s": 7891,
"text": "S++, as it is single machine instruction (INC) internally."
},
{
"code": null,
"e": 8124,
"s": 7950,
"text": "\n\nWhat is a dangling pointer?\nA pointer initially holding valid address, but later the held address is released or freed. Then such a pointer is called as dangling pointer.\n"
},
{
"code": null,
"e": 8267,
"s": 8124,
"text": "A pointer initially holding valid address, but later the held address is released or freed. Then such a pointer is called as dangling pointer."
},
{
"code": null,
"e": 8412,
"s": 8267,
"text": "\n\nWhat is the purpose of the keyword typedef?\nIt is used to alias the existing type. Also used to simplify the complex declaration of the type.\n"
},
{
"code": null,
"e": 8510,
"s": 8412,
"text": "It is used to alias the existing type. Also used to simplify the complex declaration of the type."
},
{
"code": null,
"e": 8770,
"s": 8510,
"text": "\n\nWhat is lvalue and rvalue?\nThe expression appearing on right side of the assignment operator is called as rvalue. Rvalue is assigned to lvalue, which appears on left side of the assignment operator. The lvalue should designate to a variable not a constant.\n"
},
{
"code": null,
"e": 9000,
"s": 8770,
"text": "The expression appearing on right side of the assignment operator is called as rvalue. Rvalue is assigned to lvalue, which appears on left side of the assignment operator. The lvalue should designate to a variable not a constant."
},
{
"code": null,
"e": 9226,
"s": 9000,
"text": "\n\nWhat is the difference between actual and formal parameters?\nThe parameters sent to the function at calling end are called as actual parameters while at the receiving of the function definition called as formal parameters.\n"
},
{
"code": null,
"e": 9388,
"s": 9226,
"text": "The parameters sent to the function at calling end are called as actual parameters while at the receiving of the function definition called as formal parameters."
},
{
"code": null,
"e": 9535,
"s": 9388,
"text": "\n\nCan a program be compiled without main() function?\nYes, it can be but cannot be executed, as the execution requires main() function definition.\n"
},
{
"code": null,
"e": 9628,
"s": 9535,
"text": "Yes, it can be but cannot be executed, as the execution requires main() function definition."
},
{
"code": null,
"e": 9813,
"s": 9628,
"text": "\n\nWhat is the advantage of declaring void pointers?\nWhen we do not know what type of the memory address the pointer variable is going to hold, then we declare a void pointer for such.\n"
},
{
"code": null,
"e": 9945,
"s": 9813,
"text": "When we do not know what type of the memory address the pointer variable is going to hold, then we declare a void pointer for such."
},
{
"code": null,
"e": 10069,
"s": 9945,
"text": "\n\nWhere an automatic variable is stored?\nEvery local variable by default being an auto variable is stored in stack memory.\n"
},
{
"code": null,
"e": 10151,
"s": 10069,
"text": "Every local variable by default being an auto variable is stored in stack memory."
},
{
"code": null,
"e": 10267,
"s": 10151,
"text": "\n\nWhat is a nested structure?\nA structure containing an element of another structure as its member is referred so.\n"
},
{
"code": null,
"e": 10352,
"s": 10267,
"text": "A structure containing an element of another structure as its member is referred so."
},
{
"code": null,
"e": 10528,
"s": 10352,
"text": "\n\nWhat is the difference between variable declaration and variable definition?\nDeclaration associates type to the variable whereas definition gives the value to the variable.\n"
},
{
"code": null,
"e": 10624,
"s": 10528,
"text": "Declaration associates type to the variable whereas definition gives the value to the variable."
},
{
"code": null,
"e": 10780,
"s": 10624,
"text": "\n\nWhat is a self-referential structure?\nA structure containing the same structure pointer variable as its element is called as self-referential structure.\n"
},
{
"code": null,
"e": 10895,
"s": 10780,
"text": "A structure containing the same structure pointer variable as its element is called as self-referential structure."
},
{
"code": null,
"e": 11069,
"s": 10895,
"text": "\n\nDoes a built-in header file contains built-in function definition?\nNo, the header file only declares function. The definition is in library which is linked by the linker.\n"
},
{
"code": null,
"e": 11173,
"s": 11069,
"text": "No, the header file only declares function. The definition is in library which is linked by the linker."
},
{
"code": null,
"e": 11424,
"s": 11173,
"text": "\n\nExplain modular programming.\nDividing the program in to sub programs (modules/function) to achieve the given task is modular approach. More generic functions definition gives the ability to re-use the functions, such as built-in library functions.\n"
},
{
"code": null,
"e": 11643,
"s": 11424,
"text": "Dividing the program in to sub programs (modules/function) to achieve the given task is modular approach. More generic functions definition gives the ability to re-use the functions, such as built-in library functions."
},
{
"code": null,
"e": 11793,
"s": 11643,
"text": "\n\nWhat is a token?\nA C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol.\n"
},
{
"code": null,
"e": 11923,
"s": 11793,
"text": "A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol."
},
{
"code": null,
"e": 12066,
"s": 11923,
"text": "\n\nWhat is a preprocessor?\nPreprocessor is a directive to the compiler to perform certain things before the actual compilation process begins.\n"
},
{
"code": null,
"e": 12182,
"s": 12066,
"text": "Preprocessor is a directive to the compiler to perform certain things before the actual compilation process begins."
},
{
"code": null,
"e": 12297,
"s": 12182,
"text": "\n\nExplain the use of %i format specifier w.r.t scanf().\nCan be used to input integer in all the supported format.\n"
},
{
"code": null,
"e": 12355,
"s": 12297,
"text": "Can be used to input integer in all the supported format."
},
{
"code": null,
"e": 12470,
"s": 12355,
"text": "\n\nHow can you print a \\ (backslash) using any of the printf() family of functions.\nEscape it using \\ (backslash).\n"
},
{
"code": null,
"e": 12501,
"s": 12470,
"text": "Escape it using \\ (backslash)."
},
{
"code": null,
"e": 12697,
"s": 12501,
"text": "\n\nDoes a break is required by default case in switch statement?\nYes, if it is not appearing as the last case and if we do not want the control to flow to the following case after default if any.\n"
},
{
"code": null,
"e": 12828,
"s": 12697,
"text": "Yes, if it is not appearing as the last case and if we do not want the control to flow to the following case after default if any."
},
{
"code": null,
"e": 12983,
"s": 12828,
"text": "\n\nWhen to user -> (arrow) operator.\nIf the structure/union variable is a pointer variable, to access structure/union elements the arrow operator is used.\n"
},
{
"code": null,
"e": 13101,
"s": 12983,
"text": "If the structure/union variable is a pointer variable, to access structure/union elements the arrow operator is used."
},
{
"code": null,
"e": 13326,
"s": 13101,
"text": "\n\nWhat are bit fields?\nWe can create integer structure members of differing size apart from non-standard size using bit fields. Such structure size is automatically adjusted with the multiple of integer size of the machine.\n"
},
{
"code": null,
"e": 13527,
"s": 13326,
"text": "We can create integer structure members of differing size apart from non-standard size using bit fields. Such structure size is automatically adjusted with the multiple of integer size of the machine."
},
{
"code": null,
"e": 13961,
"s": 13527,
"text": "\n\nWhat are command line arguments?\nThe arguments which we pass to the main() function while executing the program are called as command line arguments. The parameters are always strings held in the second argument (below in args) of the function which is array of character pointers. First argument represents the count of arguments (below in count) and updated automatically by operating system.\nmain( int count, char *args[]) {\n}\n\n"
},
{
"code": null,
"e": 14323,
"s": 13961,
"text": "The arguments which we pass to the main() function while executing the program are called as command line arguments. The parameters are always strings held in the second argument (below in args) of the function which is array of character pointers. First argument represents the count of arguments (below in count) and updated automatically by operating system."
},
{
"code": null,
"e": 14358,
"s": 14323,
"text": "main( int count, char *args[]) {\n}"
},
{
"code": null,
"e": 14797,
"s": 14358,
"text": "\n\nWhat are the different ways of passing parameters to the functions? Which to use when?\n\n\nCall by value − We send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used.\nCall by reference − We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters.\n\n\n"
},
{
"code": null,
"e": 14972,
"s": 14797,
"text": "Call by value − We send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used."
},
{
"code": null,
"e": 15147,
"s": 14972,
"text": "Call by value − We send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used."
},
{
"code": null,
"e": 15317,
"s": 15147,
"text": "Call by reference − We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters."
},
{
"code": null,
"e": 15487,
"s": 15317,
"text": "Call by reference − We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters."
},
{
"code": null,
"e": 15588,
"s": 15487,
"text": "\n\nWhat is the purpose of built-in stricmp() function.\nIt compares two strings by ignoring the case.\n"
},
{
"code": null,
"e": 15634,
"s": 15588,
"text": "It compares two strings by ignoring the case."
},
{
"code": null,
"e": 15813,
"s": 15634,
"text": "\n\nDescribe the file opening mode “w+”.\nOpens a file both for reading and writing. If a file is not existing it creates one, else if the file is existing it will be over written.\n"
},
{
"code": null,
"e": 15952,
"s": 15813,
"text": "Opens a file both for reading and writing. If a file is not existing it creates one, else if the file is existing it will be over written."
},
{
"code": null,
"e": 16116,
"s": 15952,
"text": "\n\nWhere the address of operator (&) cannot be used?\nIt cannot be used on constants.\nIt cannot be used on variable which are declared using register storage class.\n"
},
{
"code": null,
"e": 16148,
"s": 16116,
"text": "It cannot be used on constants."
},
{
"code": null,
"e": 16227,
"s": 16148,
"text": "It cannot be used on variable which are declared using register storage class."
},
{
"code": null,
"e": 16302,
"s": 16227,
"text": "\n\nIs FILE a built-in data type?\nNo, it is a structure defined in stdio.h.\n"
},
{
"code": null,
"e": 16431,
"s": 16302,
"text": "\n\nWhat is reminder for 5.0 % 2?\nError, It is invalid that either of the operands for the modulus operator (%) is a real number.\n"
},
{
"code": null,
"e": 16527,
"s": 16431,
"text": "Error, It is invalid that either of the operands for the modulus operator (%) is a real number."
},
{
"code": null,
"e": 16663,
"s": 16527,
"text": "\n\nHow many operators are there under the category of ternary operators?\nThere is only one operator and is conditional operator (? : ).\n"
},
{
"code": null,
"e": 16726,
"s": 16663,
"text": "There is only one operator and is conditional operator (? : )."
},
{
"code": null,
"e": 16793,
"s": 16726,
"text": "\n\nWhich key word is used to perform unconditional branching?\ngoto\n"
},
{
"code": null,
"e": 16798,
"s": 16793,
"text": "goto"
},
{
"code": null,
"e": 17158,
"s": 16798,
"text": "\n\nWhat is a pointer to a function? Give the general syntax for the same.\nA pointer holding the reference of the function is called pointer to a function. In general it is declared as follows.\nT (*fun_ptr) (T1,T2...); Where T is any date type.\n\nOnce fun_ptr refers a function the same can be invoked using the pointer as follows.\nfun_ptr();\n[Or]\n(*fun_ptr)();\n"
},
{
"code": null,
"e": 17277,
"s": 17158,
"text": "A pointer holding the reference of the function is called pointer to a function. In general it is declared as follows."
},
{
"code": null,
"e": 17329,
"s": 17277,
"text": "T (*fun_ptr) (T1,T2...); Where T is any date type.\n"
},
{
"code": null,
"e": 17414,
"s": 17329,
"text": "Once fun_ptr refers a function the same can be invoked using the pointer as follows."
},
{
"code": null,
"e": 17444,
"s": 17414,
"text": "fun_ptr();\n[Or]\n(*fun_ptr)();"
},
{
"code": null,
"e": 17586,
"s": 17444,
"text": "\n\nExplain the use of comma operator (,).\nComma operator can be used to separate two or more expressions.\nEg: printf(“hi”) , printf(“Hello”);\n"
},
{
"code": null,
"e": 17650,
"s": 17586,
"text": "Comma operator can be used to separate two or more expressions."
},
{
"code": null,
"e": 17686,
"s": 17650,
"text": "Eg: printf(“hi”) , printf(“Hello”);"
},
{
"code": null,
"e": 17855,
"s": 17686,
"text": "\n\nWhat is a NULL statement?\nA null statement is no executable statements such as ; (semicolon).\nEg: int count = 0; \nwhile( ++count<=10 ) ;\nAbove does nothing 10 times.\n"
},
{
"code": null,
"e": 17923,
"s": 17855,
"text": "A null statement is no executable statements such as ; (semicolon)."
},
{
"code": null,
"e": 17966,
"s": 17923,
"text": "Eg: int count = 0; \nwhile( ++count<=10 ) ;"
},
{
"code": null,
"e": 17995,
"s": 17966,
"text": "Above does nothing 10 times."
},
{
"code": null,
"e": 18200,
"s": 17995,
"text": "\n\nWhat is a static function?\nA function’s definition prefixed with static keyword is called as a static function. You would make a function static if it should be called only within the same source code.\n"
},
{
"code": null,
"e": 18375,
"s": 18200,
"text": "A function’s definition prefixed with static keyword is called as a static function. You would make a function static if it should be called only within the same source code."
},
{
"code": null,
"e": 18521,
"s": 18375,
"text": "\n\nWhich compiler switch to be used for compiling the programs using math library with gcc compiler?\nOpiton –lm to be used as > gcc –lm <file.c>\n"
},
{
"code": null,
"e": 18566,
"s": 18521,
"text": "Opiton –lm to be used as > gcc –lm <file.c>"
},
{
"code": null,
"e": 18721,
"s": 18566,
"text": "\n\nWhich operator is used to continue the definition of macro in the next line?\nBackward slash (\\) is used.\nE.g. #define MESSAGE \"Hi, \\\n \nWelcome to C\"\n\n"
},
{
"code": null,
"e": 18749,
"s": 18721,
"text": "Backward slash (\\) is used."
},
{
"code": null,
"e": 18796,
"s": 18749,
"text": "E.g. #define MESSAGE \"Hi, \\\n \nWelcome to C\"\n"
},
{
"code": null,
"e": 18989,
"s": 18796,
"text": "\n\nWhich operator is used to receive the variable number of arguments for a function?\nEllipses (...) is used for the same. A general function definition looks as follows\nvoid f(int k,...) {\n}\n"
},
{
"code": null,
"e": 19073,
"s": 18989,
"text": "Ellipses (...) is used for the same. A general function definition looks as follows"
},
{
"code": null,
"e": 19096,
"s": 19073,
"text": "void f(int k,...) {\n}"
},
{
"code": null,
"e": 19263,
"s": 19096,
"text": "\n\nWhat is the problem with the following coding snippet?\nchar *s1 = \"hello\",*s2 = \"welcome\";\n \nstrcat(s1,s2);\ns1 points to a string constant and cannot be altered.\n"
},
{
"code": null,
"e": 19318,
"s": 19263,
"text": "char *s1 = \"hello\",*s2 = \"welcome\";\n \nstrcat(s1,s2);"
},
{
"code": null,
"e": 19372,
"s": 19318,
"text": "s1 points to a string constant and cannot be altered."
},
{
"code": null,
"e": 19471,
"s": 19372,
"text": "\n\nWhich built-in library function can be used to re-size the allocated dynamic memory?\nrealloc().\n"
},
{
"code": null,
"e": 19482,
"s": 19471,
"text": "realloc()."
},
{
"code": null,
"e": 19565,
"s": 19482,
"text": "\n\nDefine an array.\nArray is collection of similar data items under a common name.\n"
},
{
"code": null,
"e": 19628,
"s": 19565,
"text": "Array is collection of similar data items under a common name."
},
{
"code": null,
"e": 19755,
"s": 19628,
"text": "\n\nWhat are enumerations?\nEnumerations are list of integer constants with name. Enumerators are defined with the keyword enum.\n"
},
{
"code": null,
"e": 19856,
"s": 19755,
"text": "Enumerations are list of integer constants with name. Enumerators are defined with the keyword enum."
},
{
"code": null,
"e": 19940,
"s": 19856,
"text": "\n\nWhich built-in function can be used to move the file pointer internally?\nfseek()\n"
},
{
"code": null,
"e": 19948,
"s": 19940,
"text": "fseek()"
},
{
"code": null,
"e": 20003,
"s": 19948,
"text": "\n\nWhat is a variable?\nA variable is the name storage.\n"
},
{
"code": null,
"e": 20035,
"s": 20003,
"text": "A variable is the name storage."
},
{
"code": null,
"e": 20093,
"s": 20035,
"text": "\n\nWho designed C programming language?\nDennis M Ritchie.\n"
},
{
"code": null,
"e": 20111,
"s": 20093,
"text": "Dennis M Ritchie."
},
{
"code": null,
"e": 20162,
"s": 20111,
"text": "\n\nC is successor of which programming language?\nB\n"
},
{
"code": null,
"e": 20164,
"s": 20162,
"text": "B"
},
{
"code": null,
"e": 20237,
"s": 20164,
"text": "\n\nWhat is the full form of ANSI?\nAmerican National Standards Institute.\n"
},
{
"code": null,
"e": 20276,
"s": 20237,
"text": "American National Standards Institute."
},
{
"code": null,
"e": 20363,
"s": 20276,
"text": "\n\nWhich operator can be used to determine the size of a data type or variable?\nsizeof\n"
},
{
"code": null,
"e": 20370,
"s": 20363,
"text": "sizeof"
},
{
"code": null,
"e": 20467,
"s": 20370,
"text": "\n\nCan we assign a float variable to a long integer variable?\nYes, with loss of fractional part.\n"
},
{
"code": null,
"e": 20502,
"s": 20467,
"text": "Yes, with loss of fractional part."
},
{
"code": null,
"e": 20572,
"s": 20502,
"text": "\n\nIs 068 a valid octal number?\nNo, it contains invalid octal digits.\n"
},
{
"code": null,
"e": 20610,
"s": 20572,
"text": "No, it contains invalid octal digits."
},
{
"code": null,
"e": 20756,
"s": 20610,
"text": "\n\nWhat it the return value of a relational operator if it returns any?\nReturn a value 1 if the relation between the expressions is true, else 0.\n"
},
{
"code": null,
"e": 20830,
"s": 20756,
"text": "Return a value 1 if the relation between the expressions is true, else 0."
},
{
"code": null,
"e": 20929,
"s": 20830,
"text": "\n\nHow does bitwise operator XOR works.\nIf both the corresponding bits are same it gives 0 else 1.\n"
},
{
"code": null,
"e": 20988,
"s": 20929,
"text": "If both the corresponding bits are same it gives 0 else 1."
},
{
"code": null,
"e": 21119,
"s": 20988,
"text": "\n\nWhat is an infinite loop?\nA loop executing repeatedly as the loop-expression always evaluates to true such as\nwhile(0 == 0) {\n}\n"
},
{
"code": null,
"e": 21203,
"s": 21119,
"text": "A loop executing repeatedly as the loop-expression always evaluates to true such as"
},
{
"code": null,
"e": 21221,
"s": 21203,
"text": "while(0 == 0) {\n}"
},
{
"code": null,
"e": 21462,
"s": 21221,
"text": "\n\nCan variables belonging to different scope have same name? If so show an example.\nVariables belonging to different scope can have same name as in the following code snippet.\nint var;\n\nvoid f() { \n int var; \n}\n\nmain() { \n int var; \n}\n\n"
},
{
"code": null,
"e": 21554,
"s": 21462,
"text": "Variables belonging to different scope can have same name as in the following code snippet."
},
{
"code": null,
"e": 21617,
"s": 21554,
"text": "int var;\n\nvoid f() { \n int var; \n}\n\nmain() { \n int var; \n}"
},
{
"code": null,
"e": 21758,
"s": 21617,
"text": "\n\nWhat is the default value of local and global variables?\nLocal variables get garbage value and global variables get a value 0 by default.\n"
},
{
"code": null,
"e": 21839,
"s": 21758,
"text": "Local variables get garbage value and global variables get a value 0 by default."
},
{
"code": null,
"e": 21936,
"s": 21839,
"text": "\n\nCan a pointer access the array?\nPointer by holding array’s base address can access the array.\n"
},
{
"code": null,
"e": 21998,
"s": 21936,
"text": "Pointer by holding array’s base address can access the array."
},
{
"code": null,
"e": 22157,
"s": 21998,
"text": "\n\nWhat are valid operations on pointers?\nThe only two permitted operations on pointers are\n\nComparision ii) Addition/Substraction (excluding void pointers)\n\n\n"
},
{
"code": null,
"e": 22207,
"s": 22157,
"text": "The only two permitted operations on pointers are"
},
{
"code": null,
"e": 22271,
"s": 22207,
"text": "Comparision ii) Addition/Substraction (excluding void pointers)"
},
{
"code": null,
"e": 22358,
"s": 22271,
"text": "\n\nWhat is a string length?\nIt is the count of character excluding the ‘\\0’ character.\n"
},
{
"code": null,
"e": 22417,
"s": 22358,
"text": "It is the count of character excluding the ‘\\0’ character."
},
{
"code": null,
"e": 22517,
"s": 22417,
"text": "\n\nWhat is the built-in function to append one string to another?\nstrcat() form the header string.h\n"
},
{
"code": null,
"e": 22551,
"s": 22517,
"text": "strcat() form the header string.h"
},
{
"code": null,
"e": 22668,
"s": 22551,
"text": "\n\nWhich operator can be used to access union elements if union variable is a pointer variable?\nArrow (->) operator.\n"
},
{
"code": null,
"e": 22689,
"s": 22668,
"text": "Arrow (->) operator."
},
{
"code": null,
"e": 22797,
"s": 22689,
"text": "\n\nExplain about ‘stdin’.\nstdin in a pointer variable which is by default opened for standard input device.\n"
},
{
"code": null,
"e": 22879,
"s": 22797,
"text": "stdin in a pointer variable which is by default opened for standard input device."
},
{
"code": null,
"e": 22952,
"s": 22879,
"text": "\n\nName a function which can be used to close the file stream.\nfclose().\n"
},
{
"code": null,
"e": 22962,
"s": 22952,
"text": "fclose()."
},
{
"code": null,
"e": 23062,
"s": 22962,
"text": "\n\nWhat is the purpose of #undef preprocessor?\nIt be used to undefine an existing macro definition.\n"
},
{
"code": null,
"e": 23115,
"s": 23062,
"text": "It be used to undefine an existing macro definition."
},
{
"code": null,
"e": 23208,
"s": 23115,
"text": "\n\nDefine a structure.\nA structure can be defined of collection of heterogeneous data items.\n"
},
{
"code": null,
"e": 23278,
"s": 23208,
"text": "A structure can be defined of collection of heterogeneous data items."
},
{
"code": null,
"e": 23392,
"s": 23278,
"text": "\n\nName the predefined macro which be used to determine whether your compiler is ANSI standard or not?\n__STDC__ \n"
},
{
"code": null,
"e": 23403,
"s": 23392,
"text": "__STDC__ "
},
{
"code": null,
"e": 23510,
"s": 23403,
"text": "\n\nWhat is typecasting?\nTypecasting is a way to convert a variable/constant from one type to another type.\n"
},
{
"code": null,
"e": 23593,
"s": 23510,
"text": "Typecasting is a way to convert a variable/constant from one type to another type."
},
{
"code": null,
"e": 23663,
"s": 23593,
"text": "\n\nWhat is recursion?\nFunction calling itself is called as recursion.\n"
},
{
"code": null,
"e": 23711,
"s": 23663,
"text": "Function calling itself is called as recursion."
},
{
"code": null,
"e": 23790,
"s": 23711,
"text": "\n\nWhich function can be used to release the dynamic allocated memory?\nfree().\n"
},
{
"code": null,
"e": 23798,
"s": 23790,
"text": "free()."
},
{
"code": null,
"e": 23893,
"s": 23798,
"text": "\n\nWhat is the first string in the argument vector w.r.t command line arguments?\nProgram name.\n"
},
{
"code": null,
"e": 23907,
"s": 23893,
"text": "Program name."
},
{
"code": null,
"e": 24064,
"s": 23907,
"text": "\n\nHow can we determine whether a file is successfully opened or not using fopen() function?\nOn failure fopen() returns NULL, otherwise opened successfully.\n"
},
{
"code": null,
"e": 24128,
"s": 24064,
"text": "On failure fopen() returns NULL, otherwise opened successfully."
},
{
"code": null,
"e": 24218,
"s": 24128,
"text": "\n\nWhat is the output file generated by the linker.\nLinker generates the executable file.\n"
},
{
"code": null,
"e": 24256,
"s": 24218,
"text": "Linker generates the executable file."
},
{
"code": null,
"e": 24367,
"s": 24256,
"text": "\n\nWhat is the maximum length of an identifier?\nIdeally it is 32 characters and also implementation dependent.\n"
},
{
"code": null,
"e": 24430,
"s": 24367,
"text": "Ideally it is 32 characters and also implementation dependent."
},
{
"code": null,
"e": 24521,
"s": 24430,
"text": "\n\nWhat is the default function call method?\nBy default the functions are called by value.\n"
},
{
"code": null,
"e": 24567,
"s": 24521,
"text": "By default the functions are called by value."
},
{
"code": null,
"e": 24704,
"s": 24567,
"text": "\n\nFunctions must and should be declared. Comment on this.\nFunction declaration is optional if the same is invoked after its definition.\n"
},
{
"code": null,
"e": 24782,
"s": 24704,
"text": "Function declaration is optional if the same is invoked after its definition."
},
{
"code": null,
"e": 24846,
"s": 24782,
"text": "\n\nWhen the macros gets expanded?\nAt the time of preprocessing.\n"
},
{
"code": null,
"e": 24876,
"s": 24846,
"text": "At the time of preprocessing."
},
{
"code": null,
"e": 25009,
"s": 24876,
"text": "\n\nCan a function return multiple values to the caller using return reserved word?\nNo, only one value can be returned to the caller.\n"
},
{
"code": null,
"e": 25059,
"s": 25009,
"text": "No, only one value can be returned to the caller."
},
{
"code": null,
"e": 25184,
"s": 25059,
"text": "\n\nWhat is a constant pointer?\nA pointer which is not allowed to be altered to hold another address after it is holding one.\n"
},
{
"code": null,
"e": 25278,
"s": 25184,
"text": "A pointer which is not allowed to be altered to hold another address after it is holding one."
},
{
"code": null,
"e": 25354,
"s": 25278,
"text": "\n\nTo make pointer generic for which date type it need to be declared?\nVoid\n"
},
{
"code": null,
"e": 25359,
"s": 25354,
"text": "Void"
},
{
"code": null,
"e": 25480,
"s": 25359,
"text": "\n\nCan the structure variable be initialized as soon as it is declared?\nYes, w.r.t the order of structure elements only.\n"
},
{
"code": null,
"e": 25529,
"s": 25480,
"text": "Yes, w.r.t the order of structure elements only."
},
{
"code": null,
"e": 25667,
"s": 25529,
"text": "\n\nIs there a way to compare two structure variables?\nThere is no such. We need to compare element by element of the structure variables.\n"
},
{
"code": null,
"e": 25751,
"s": 25667,
"text": "There is no such. We need to compare element by element of the structure variables."
},
{
"code": null,
"e": 25842,
"s": 25751,
"text": "\n\nWhich built-in library function can be used to match a patter from the string?\nStrstr()\n"
},
{
"code": null,
"e": 25851,
"s": 25842,
"text": "Strstr()"
},
{
"code": null,
"e": 26114,
"s": 25851,
"text": "\n\nWhat is difference between far and near pointers?\nIn first place they are non-standard keywords. A near pointer can access only 2^15 memory space and far pointer can access 2^32 memory space. Both the keywords are implementation specific and are non-standard.\n"
},
{
"code": null,
"e": 26324,
"s": 26114,
"text": "In first place they are non-standard keywords. A near pointer can access only 2^15 memory space and far pointer can access 2^32 memory space. Both the keywords are implementation specific and are non-standard."
},
{
"code": null,
"e": 26376,
"s": 26324,
"text": "\n\nCan we nest comments in a C code?\nNo, we cannot.\n"
},
{
"code": null,
"e": 26391,
"s": 26376,
"text": "No, we cannot."
},
{
"code": null,
"e": 26508,
"s": 26391,
"text": "\n\nWhich control loop is recommended if you have to execute set of statements for fixed number of times?\nfor – Loop.\n"
},
{
"code": null,
"e": 26520,
"s": 26508,
"text": "for – Loop."
},
{
"code": null,
"e": 26643,
"s": 26520,
"text": "\n\nWhat is a constant?\nA value which cannot be modified is called so. Such variables are qualified with the keyword const.\n"
},
{
"code": null,
"e": 26743,
"s": 26643,
"text": "A value which cannot be modified is called so. Such variables are qualified with the keyword const."
},
{
"code": null,
"e": 26891,
"s": 26743,
"text": "\n\nCan we use just the tag name of structures to declare the variables for the same?\nNo, we need to use both the keyword ‘struct’ and the tag name.\n"
},
{
"code": null,
"e": 26954,
"s": 26891,
"text": "No, we need to use both the keyword ‘struct’ and the tag name."
},
{
"code": null,
"e": 27034,
"s": 26954,
"text": "\n\nCan the main() function left empty?\nYes, possibly the program doing nothing.\n"
},
{
"code": null,
"e": 27075,
"s": 27034,
"text": "Yes, possibly the program doing nothing."
},
{
"code": null,
"e": 27163,
"s": 27075,
"text": "\n\nCan one function call another?\nYes, any user defined function can call any function.\n"
},
{
"code": null,
"e": 27217,
"s": 27163,
"text": "Yes, any user defined function can call any function."
},
{
"code": null,
"e": 27324,
"s": 27217,
"text": "\n\nApart from Dennis Ritchie who the other person who contributed in design of C language.\nBrain Kernighan\n"
},
{
"code": null,
"e": 27340,
"s": 27324,
"text": "Brain Kernighan"
},
{
"code": null,
"e": 27627,
"s": 27340,
"text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong."
},
{
"code": null,
"e": 27957,
"s": 27627,
"text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)"
},
{
"code": null,
"e": 27964,
"s": 27957,
"text": " Print"
},
{
"code": null,
"e": 27975,
"s": 27964,
"text": " Add Notes"
}
] |
LRU Cache | Practice | GeeksforGeeks | Design a data structure that works like a LRU Cache. Here cap denotes the capacity of the cache and Q denotes the number of queries. Query can be of two types:
SET x y : sets the value of the key x with value y
GET x : gets the key of x if present else returns -1.
SET x y : sets the value of the key x with value y
GET x : gets the key of x if present else returns -1.
The LRUCache class has two methods get() and set() which are defined as follows.
get(key) : returns the value of the key if it already exists in the cache otherwise returns -1.
set(key, value) : if the key is already present, update its value. If not present, add the key-value pair to the cache. If the cache reaches its capacity it should invalidate the least recently used item before inserting the new item.
In the constructor of the class the capacity of the cache should be intitialized.
get(key) : returns the value of the key if it already exists in the cache otherwise returns -1.
set(key, value) : if the key is already present, update its value. If not present, add the key-value pair to the cache. If the cache reaches its capacity it should invalidate the least recently used item before inserting the new item.
In the constructor of the class the capacity of the cache should be intitialized.
Example 1:
Input:
cap = 2
Q = 2
Queries = SET 1 2 GET 1
Output: 2
Explanation:
Cache Size = 2
SET 1 2 GET 1
SET 1 2 : 1 -> 2
GET 1 : Print the value corresponding
to Key 1, ie 2.
Example 2:
Input:
cap = 2
Q = 8
Queries = SET 1 2 SET 2 3 SET 1 5
SET 4 5 SET 6 7 GET 4 SET 1 2 GET 3
Output: 5 -1
Explanation:
Cache Size = 2
SET 1 2 : 1 -> 2
SET 2 3 : 1 -> 2, 2 -> 3 (the most recently
used one is kept at the rightmost position)
SET 1 5 : 2 -> 3, 1 -> 5
SET 4 5 : 1 -> 5, 4 -> 5 (Cache size is 2, hence
we delete the least recently used key-value pair)
SET 6 7 : 4 -> 5, 6 -> 7
GET 4 : Prints 5 (The cache now looks like
6 -> 7, 4->5)
SET 1 2 : 4 -> 5, 1 -> 2
(Cache size is 2, hence we delete the least
recently used key-value pair)
GET 3 : No key value pair having
key = 3. Hence, -1 is printed.
Your Task:
You don't need to read input or print anything . Complete the constructor and get(), set() methods of the class LRUcache.
Expected Time Complexity: O(1) for both get() and set().
Expected Auxiliary Space: O(1) for both get() and set().
(Although, you may use extra space for cache storage and implementation purposes).
Constraints:
1 <= cap <= 1000
1 <= Q <= 100000
1 <= x, y <= 1000
0
bhardwajji2 days ago
easy c++ using 2 map and list
unordered_map<int,int>m;
unordered_map<int,list<int>::iterator>pata;
list<int>l;
int currsize; // overall capacity
int size;
LRUCache(int cap)
{
currsize = cap;
size=0;
}
int get(int key)
{
if(m.find(key)==m.end())
return -1;
list<int>::iterator add = pata[key];
l.erase(add);
l.push_front(key);
pata[key] = l.begin();
return m[key];
}
void set(int key, int value)
{
if(m.find(key)!=m.end()){
m[key] = value;
list<int>::iterator add = pata[key];
l.erase(add);
l.push_front(key);
pata[key]=l.begin();
}
else{
m[key]=value;
l.push_front(key);
pata[key]=l.begin();
size++;
if(size>currsize){
int k=l.back();
l.pop_back();
m.erase(k);
pata.erase(k);
}
}
}
0
aman hamid5 days ago
Solution using two maps:
One map for storing the current elements
Second map for keeping track of least recently used element
class LRUCache{private:
public: //Constructor for initializing the cache capacity with the given value. int size = 0; int c = 0; int priority = 0; int lp = 0; unordered_map<int,pair<int,int>> m; unordered_map<int,int> p; LRUCache(int cap) { // code here c = cap; } //Function to return value corresponding to the key. int get(int key) { // your code here auto it = m.find(key); if(it==m.end()) { return -1; } pair<int,int> vp = {(it->second).first,priority}; auto itr = p.find((it->second).second); if(itr!=p.end()) { p.erase(itr->first); } m[key] = vp; p[priority] = key; priority++; return (it->second).first; } //Function for storing key-value pair. void set(int key, int value) { // your code here pair<int,int> vp; auto it = m.find(key); if(it!=m.end()) { int r = (it->second).second; p.erase(r); vp = {value,priority}; m[key] = vp; p[priority] = key; priority = priority+1; } else { if(size==c) { while(p.find(lp)==p.end()) { lp++; } int rem = p[lp]; p.erase(lp); m.erase(rem); vp = {value,priority}; m[key] = vp; p[priority] = key; priority++; } else { vp = {value,priority}; m[key] = vp; p[priority] = key; priority = priority+1; size++; } } }};
0
danish_nitdgp5 days ago
Easy and simple C++ solution.
O(1) Time for Both Get and set.
Using dounly Linked List and HashMap.
class LRUCache {
public:
class node {
public:
int key;
int val;
node* next;
node* prev;
node(int newkey, int newval){
key = newkey;
val = newval;
}
};
node* head = new node(-1,-1);
node* tail = new node(-1,-1);
int cap;
unordered_map<int,node*> m;
LRUCache(int capacity) {
cap = capacity;
head->next = tail;
tail->prev = head;
}
void addnode(node* newnode){
node *temp = head->next;
newnode->next = temp;
newnode->prev = head;
head->next = newnode;
temp->prev = newnode;
}
void deletenode(node* delnode){
node *delprev = delnode->prev;
node *delnext = delnode->next;
delnext->prev = delprev;
delprev->next = delnext;
}
int get(int key) {
if(m.find(key)!=m.end()){
node *resnode = m[key];
int res = resnode->val;
m.erase(key);
deletenode(resnode);
addnode(resnode);
m[key] = head->next;
return res;
} else return -1;
}
void set(int key, int value) {
if(m.find(key)!=m.end()){
node *existingnode = m[key];
m.erase(key);
deletenode(existingnode);
}
if(m.size()==cap){
m.erase(tail->prev->key);
deletenode(tail->prev);
}
addnode(new node(key,value));
m[key] = head->next;
}
};
0
roadslestraveled2 weeks ago
I get a wrong answer when using static variables but on removing static keyword my solution passes. Can someone pls explain this why is it happening???
class LRUCache
{
//Constructor for initializing the cache capacity with the given value.
static Node head = new Node(0,0);
static Node tail = new Node(0,0);
static HashMap<Integer,Node> map = new HashMap<>();
static int capacity=0 ;
LRUCache(int cap)
{
//code here
this.capacity = cap;
head.next = tail;
tail.prev = head;
}
//Function to return value corresponding to the key.
public static int get(int key)
{
// your code here
if(map.get(key) != null){
Node node = map.get(key);
remove(node);
insert(node);
return node.val;
}
else{
return -1;
}
}
//Function for storing key-value pair.
public static void set(int key, int value)
{
// your code here
if(map.get(key) != null){
remove(map.get(key));
}
if(map.size() == capacity){
remove(tail.prev);
}
insert(new Node(key,value));
}
private static void remove(Node node){
map.remove(node.key);
node.prev.next = node.next;
node.next.prev = node.prev;
}
private static void insert(Node node){
map.put(node.key,node);
node.next = head.next;
node.next.prev = node;
head.next = node;
node.prev = head;
}
}
class Node{
Node next;
Node prev;
int key,val;
Node(int key,int val){
this.key = key;
this.val = val;
}
}
+1
gaurabhkumarjha271020012 weeks ago
// in c++
list<pair<int,int>>l;
unordered_map<int,list<pair<int, int>>::iterator> m;
int size;
LRUCache(int cap)
{
// code here
size=cap;
}
int get(int key)
{
// your code here
if (m.find(key) == m.end()) return -1;
l.splice(l.begin(), l, m[key]);
return m[key]->second;
}
//Function for storing key-value pair.
void set(int key, int value)
{
// your code here
if (m.find(key) != m.end()){
l.splice(l.begin(), l, m[key]);
m[key]->second= value;
return;
}
if (l.size() == size){
auto dkey= l.back().first;
l.pop_back();
m.erase(dkey);
}
l.push_front({key, value});
m[key]= l.begin();
}
0
joyrockok3 weeks ago
class LRUCache{ static class Node{ int key; int value; Node pre; Node next; public Node(int key, int value) { this.key = key; this.value = value; }}static int N=0; // cached size// static Queue<Integer> cache;static HashMap<Integer, Node> map;static Node head, tail;
//Constructor for initializing the cache capacity with the given value.public LRUCache(int cap) //LRUCache(int cap) { //code here N = cap; map = new HashMap<Integer, Node>(); head = new Node(0, 0); tail = new Node(0, 0); head.next = tail; tail.pre = head; head.pre = null; tail.next = null; }
public static void delNode(Node node) { node.pre.next = node.next; node.next.pre = node.pre;}public static void addNode(Node node) { node.next = head.next; node.next.pre = node; node.pre = head; head.next = node;} //Function to return value corresponding to the key. public static int get(int key) { // your code here if(map.get(key) != null) { Node node = map.get(key); delNode(node); // node를 삭제 후 addNode(node); // 제일 끝에 넣는다. 즉 head에 넣는다. return node.value; } else { return -1; } }
//Function for storing key-value pair. public static void set(int key, int value) { // your code here if(map.get(key) != null) { Node node = map.get(key); node.value = value; delNode(node); addNode(node); } else { Node node = new Node(key, value); if(map.size()>= N) { map.remove(tail.pre.key); map.put(key, node); delNode(tail.pre); addNode(node); } else { addNode(node); map.put(key, node); } } }}
0
kundankumardec163 weeks ago
Java implementation (using LinkedHashMap):
class LRUCache
{
//Constructor for initializing the cache capacity with the given value.
private static LinkedHashMap<Integer, Integer> map;
private static int size;
LRUCache(int cap) {
//code here
size = 0;
map = new LinkedHashMap<>() {
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > cap;
}
};
}
//Function to return value corresponding to the key.
public static int get(int key)
{
// your code here
int ans = map.getOrDefault(key, -1);
if (ans != -1) {
map.remove(key);
set(key, ans);
}
return ans;
}
//Function for storing key-value pair.
public static void set(int key, int value)
{
// your code here
if (map.containsKey(key)) {
map.remove(key);
}
map.put(key, value);
}
}
0
swatisingh727774 weeks ago
class LRUCache
{
private:
public:
struct Node{
int key;
int val;
Node* prev;
Node* next;
Node(int Key1 , int Val1){
key = Key1;
val = Val1;
}
};
Node * head = new Node(-1,-1);
Node * tail = new Node(-1,-1);
int size;
unordered_map<int , Node*>mp;
LRUCache(int cap)
{
size = cap;
head->next = tail;
tail->prev = head;
}
void DelNode( Node* tempNode){
Node* prev = tempNode->prev;
Node* forward = tempNode->next;
prev->next = forward;
forward->prev = prev;
}
void InsNode(Node* tempNode){
Node* temp = head->next;
tempNode->next = temp;
tempNode->prev = head;
head->next = tempNode;
temp->prev = tempNode;
}
int get(int key)
{
if(mp.find(key)!=mp.end()){
Node* dummy = mp[key];
int val = dummy->val;
mp.erase(key);
DelNode(dummy);
InsNode(dummy);
mp[key] = head->next;
return val;
}
return -1;
}
void set(int key, int value)
{
if(mp.find(key)!=mp.end()){
Node* dummy = mp[key];
mp.erase(key);
DelNode(dummy);
}
if(mp.size()==size){
mp.erase(tail->prev->key);
DelNode(tail->prev);
}
InsNode(new Node(key , value));
mp[key] = head->next;
}
// O(1) time complexity
+1
akbhobhiya4 weeks ago
// Just Wanted to know where they have used the stack and queue in this question. I have done this with the help of doubly linked list and unordered_map. bellow is the clean code of the implementation
class LRUCache
{
private:
public:
//Constructor for initializing the cache capacity with the given value.
class Node{
public:
int key;
int data;
Node *next,*prev;
Node(int _key, int _data){
key = _key;
data= _data;
}
};
Node *head = new Node(-1,-1);
Node *tail = new Node(-1,-1);
int cap;
unordered_map<int,Node*>mp;
LRUCache(int capacity){
cap = capacity;
head->next = tail;
tail->prev = head;
}
void add(Node *node){
Node *temp = head->next;
head->next = node;
node->prev = head;
node->next = temp;
temp->prev = node;
}
void remove(Node *node){
Node *temp1 = node->prev;
Node *temp2 = node->next;
temp1->next=temp2;
temp2->prev=temp1;
}
//Function to return value corresponding to the key.
int get(int key){
if(mp.find(key)==mp.end())return -1;
Node *node = mp[key];
int data = node->data;
remove(node);
mp.erase(key);
add(node);
mp[key]=node;
return data;
}
//Function for storing key-value pair.
void set(int key, int value){
if(mp.find(key)!=mp.end()){
Node *node = mp[key];
mp.erase(key);
remove(node);
}
if(mp.size()==cap){
mp.erase(tail->prev->key);
remove(tail->prev);
}
Node *newnode = new Node(key,value);
add(newnode);
mp[key]=newnode;
}
};
0
abhishekshrivastav19201 month ago
I have used dummy head and tail pointer so that i need not to put extra condition.
private:
struct Node{
int key;
int value;
Node *prev;
Node *next;
Node(int key,int value){
this->key = key;
this->value = value;
}
};
Node *head = new Node(-1,-1);
Node *tail = new Node(-1,-1);
unordered_map<int,Node *> map;
int capacity;
public:
//Constructor for initializing the cache capacity with the given value.
LRUCache(int cap)
{
// code here
capacity = cap;
head->next = tail;
tail->prev = head;
}
void removeNode(Node *node){
Node *left = node->prev;
Node *right = node->next;
left->next = right;
right->prev = left;
}
void addFirst(Node *node){
Node *right = head->next;
node->next = right;
right->prev = node;
head->next = node;
node->prev = head;
}
//Function to return value corresponding to the key.
int get(int key)
{
if(map.find(key) == map.end()){
return -1;
}
Node *n = map[key];
int ans = n->value;
map.erase(key);
removeNode(n);
addFirst(n);
map[key] = n;
return ans;
}
//Function for storing key-value pair.
void set(int key, int value)
{
if(map.find(key) != map.end()){
removeNode(map[key]);
map.erase(key);
}
if(map.size() == capacity){
// remove last node
Node *last = tail->prev;
removeNode(last);
map.erase(last->key);
}
Node *newNode = new Node(key,value);
map[key] = newNode;
addFirst(newNode);
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 398,
"s": 238,
"text": "Design a data structure that works like a LRU Cache. Here cap denotes the capacity of the cache and Q denotes the number of queries. Query can be of two types:"
},
{
"code": null,
"e": 506,
"s": 398,
"text": "\nSET x y : sets the value of the key x with value y \nGET x : gets the key of x if present else returns -1.\n"
},
{
"code": null,
"e": 558,
"s": 506,
"text": "SET x y : sets the value of the key x with value y "
},
{
"code": null,
"e": 612,
"s": 558,
"text": "GET x : gets the key of x if present else returns -1."
},
{
"code": null,
"e": 694,
"s": 612,
"text": "\nThe LRUCache class has two methods get() and set() which are defined as follows."
},
{
"code": null,
"e": 1111,
"s": 694,
"text": "\nget(key) : returns the value of the key if it already exists in the cache otherwise returns -1.\nset(key, value) : if the key is already present, update its value. If not present, add the key-value pair to the cache. If the cache reaches its capacity it should invalidate the least recently used item before inserting the new item.\nIn the constructor of the class the capacity of the cache should be intitialized.\n"
},
{
"code": null,
"e": 1209,
"s": 1111,
"text": "get(key) : returns the value of the key if it already exists in the cache otherwise returns -1."
},
{
"code": null,
"e": 1444,
"s": 1209,
"text": "set(key, value) : if the key is already present, update its value. If not present, add the key-value pair to the cache. If the cache reaches its capacity it should invalidate the least recently used item before inserting the new item."
},
{
"code": null,
"e": 1526,
"s": 1444,
"text": "In the constructor of the class the capacity of the cache should be intitialized."
},
{
"code": null,
"e": 1539,
"s": 1528,
"text": "Example 1:"
},
{
"code": null,
"e": 1711,
"s": 1539,
"text": "Input:\ncap = 2\nQ = 2\nQueries = SET 1 2 GET 1\nOutput: 2\nExplanation: \nCache Size = 2\n\nSET 1 2 GET 1\nSET 1 2 : 1 -> 2\n\nGET 1 : Print the value corresponding\nto Key 1, ie 2.\n"
},
{
"code": null,
"e": 1723,
"s": 1711,
"text": "\nExample 2:"
},
{
"code": null,
"e": 2346,
"s": 1723,
"text": "Input:\ncap = 2\nQ = 8\nQueries = SET 1 2 SET 2 3 SET 1 5\nSET 4 5 SET 6 7 GET 4 SET 1 2 GET 3\nOutput: 5 -1\nExplanation: \nCache Size = 2\nSET 1 2 : 1 -> 2\n\nSET 2 3 : 1 -> 2, 2 -> 3 (the most recently \nused one is kept at the rightmost position) \n\nSET 1 5 : 2 -> 3, 1 -> 5\n\nSET 4 5 : 1 -> 5, 4 -> 5 (Cache size is 2, hence \nwe delete the least recently used key-value pair)\n\nSET 6 7 : 4 -> 5, 6 -> 7 \n\nGET 4 : Prints 5 (The cache now looks like\n6 -> 7, 4->5)\n\nSET 1 2 : 4 -> 5, 1 -> 2 \n(Cache size is 2, hence we delete the least \nrecently used key-value pair)\n\nGET 3 : No key value pair having \nkey = 3. Hence, -1 is printed.\n\n"
},
{
"code": null,
"e": 2480,
"s": 2346,
"text": "Your Task:\nYou don't need to read input or print anything . Complete the constructor and get(), set() methods of the class LRUcache. "
},
{
"code": null,
"e": 2679,
"s": 2480,
"text": "\nExpected Time Complexity: O(1) for both get() and set().\nExpected Auxiliary Space: O(1) for both get() and set(). \n(Although, you may use extra space for cache storage and implementation purposes)."
},
{
"code": null,
"e": 2745,
"s": 2679,
"text": "\nConstraints:\n1 <= cap <= 1000\n1 <= Q <= 100000\n1 <= x, y <= 1000"
},
{
"code": null,
"e": 2747,
"s": 2745,
"text": "0"
},
{
"code": null,
"e": 2768,
"s": 2747,
"text": "bhardwajji2 days ago"
},
{
"code": null,
"e": 2798,
"s": 2768,
"text": "easy c++ using 2 map and list"
},
{
"code": null,
"e": 3842,
"s": 2800,
"text": "unordered_map<int,int>m;\n unordered_map<int,list<int>::iterator>pata;\n list<int>l;\n int currsize; // overall capacity\n int size;\n \n LRUCache(int cap)\n {\n currsize = cap;\n size=0;\n }\n \n int get(int key)\n {\n if(m.find(key)==m.end())\n return -1;\n list<int>::iterator add = pata[key];\n l.erase(add);\n l.push_front(key);\n pata[key] = l.begin();\n \n return m[key];\n }\n \n void set(int key, int value)\n {\n if(m.find(key)!=m.end()){\n m[key] = value;\n list<int>::iterator add = pata[key];\n l.erase(add);\n l.push_front(key);\n pata[key]=l.begin();\n }\n else{\n m[key]=value;\n l.push_front(key);\n pata[key]=l.begin();\n size++;\n \n if(size>currsize){\n int k=l.back();\n l.pop_back();\n m.erase(k);\n pata.erase(k);\n }\n }\n }"
},
{
"code": null,
"e": 3844,
"s": 3842,
"text": "0"
},
{
"code": null,
"e": 3865,
"s": 3844,
"text": "aman hamid5 days ago"
},
{
"code": null,
"e": 3890,
"s": 3865,
"text": "Solution using two maps:"
},
{
"code": null,
"e": 3931,
"s": 3890,
"text": "One map for storing the current elements"
},
{
"code": null,
"e": 3991,
"s": 3931,
"text": "Second map for keeping track of least recently used element"
},
{
"code": null,
"e": 4017,
"s": 3993,
"text": "class LRUCache{private:"
},
{
"code": null,
"e": 5639,
"s": 4017,
"text": " public: //Constructor for initializing the cache capacity with the given value. int size = 0; int c = 0; int priority = 0; int lp = 0; unordered_map<int,pair<int,int>> m; unordered_map<int,int> p; LRUCache(int cap) { // code here c = cap; } //Function to return value corresponding to the key. int get(int key) { // your code here auto it = m.find(key); if(it==m.end()) { return -1; } pair<int,int> vp = {(it->second).first,priority}; auto itr = p.find((it->second).second); if(itr!=p.end()) { p.erase(itr->first); } m[key] = vp; p[priority] = key; priority++; return (it->second).first; } //Function for storing key-value pair. void set(int key, int value) { // your code here pair<int,int> vp; auto it = m.find(key); if(it!=m.end()) { int r = (it->second).second; p.erase(r); vp = {value,priority}; m[key] = vp; p[priority] = key; priority = priority+1; } else { if(size==c) { while(p.find(lp)==p.end()) { lp++; } int rem = p[lp]; p.erase(lp); m.erase(rem); vp = {value,priority}; m[key] = vp; p[priority] = key; priority++; } else { vp = {value,priority}; m[key] = vp; p[priority] = key; priority = priority+1; size++; } } }};"
},
{
"code": null,
"e": 5641,
"s": 5639,
"text": "0"
},
{
"code": null,
"e": 5665,
"s": 5641,
"text": "danish_nitdgp5 days ago"
},
{
"code": null,
"e": 5695,
"s": 5665,
"text": "Easy and simple C++ solution."
},
{
"code": null,
"e": 5727,
"s": 5695,
"text": "O(1) Time for Both Get and set."
},
{
"code": null,
"e": 5765,
"s": 5727,
"text": "Using dounly Linked List and HashMap."
},
{
"code": null,
"e": 7387,
"s": 5767,
"text": "class LRUCache {\npublic:\n class node {\n public:\n int key;\n int val;\n node* next;\n node* prev;\n node(int newkey, int newval){\n key = newkey;\n val = newval;\n }\n };\n \n node* head = new node(-1,-1);\n node* tail = new node(-1,-1);\n int cap;\n unordered_map<int,node*> m;\n \n LRUCache(int capacity) {\n cap = capacity;\n head->next = tail;\n tail->prev = head; \n }\n \n void addnode(node* newnode){\n node *temp = head->next;\n newnode->next = temp;\n newnode->prev = head;\n head->next = newnode;\n temp->prev = newnode;\n }\n \n void deletenode(node* delnode){\n node *delprev = delnode->prev;\n node *delnext = delnode->next;\n delnext->prev = delprev;\n delprev->next = delnext; \n }\n \n int get(int key) {\n if(m.find(key)!=m.end()){\n node *resnode = m[key];\n int res = resnode->val;\n m.erase(key);\n deletenode(resnode);\n addnode(resnode);\n m[key] = head->next;\n return res;\n } else return -1;\n \n }\n \n void set(int key, int value) {\n if(m.find(key)!=m.end()){\n node *existingnode = m[key];\n m.erase(key);\n deletenode(existingnode);\n }\n if(m.size()==cap){\n m.erase(tail->prev->key);\n deletenode(tail->prev);\n } \n addnode(new node(key,value));\n m[key] = head->next;\n }\n};"
},
{
"code": null,
"e": 7393,
"s": 7391,
"text": "0"
},
{
"code": null,
"e": 7421,
"s": 7393,
"text": "roadslestraveled2 weeks ago"
},
{
"code": null,
"e": 7573,
"s": 7421,
"text": "I get a wrong answer when using static variables but on removing static keyword my solution passes. Can someone pls explain this why is it happening???"
},
{
"code": null,
"e": 9122,
"s": 7573,
"text": "class LRUCache\n{\n //Constructor for initializing the cache capacity with the given value.\n \n static Node head = new Node(0,0);\n static Node tail = new Node(0,0);\n static HashMap<Integer,Node> map = new HashMap<>();\n static int capacity=0 ;\n LRUCache(int cap)\n {\n //code here\n this.capacity = cap;\n head.next = tail;\n tail.prev = head;\n \n \n }\n //Function to return value corresponding to the key.\n public static int get(int key)\n {\n // your code here\n if(map.get(key) != null){\n Node node = map.get(key);\n remove(node);\n insert(node);\n return node.val;\n }\n else{\n return -1;\n }\n \n }\n //Function for storing key-value pair.\n public static void set(int key, int value)\n {\n // your code here\n if(map.get(key) != null){\n remove(map.get(key));\n }\n if(map.size() == capacity){\n remove(tail.prev);\n }\n insert(new Node(key,value));\n }\n private static void remove(Node node){\n map.remove(node.key);\n node.prev.next = node.next;\n node.next.prev = node.prev;\n }\n \n private static void insert(Node node){\n \n map.put(node.key,node);\n node.next = head.next;\n node.next.prev = node;\n head.next = node;\n node.prev = head;\n \n }\n \n \n}\nclass Node{\n Node next;\n Node prev;\n int key,val;\n \n Node(int key,int val){\n this.key = key;\n this.val = val;\n }\n \n}"
},
{
"code": null,
"e": 9127,
"s": 9124,
"text": "+1"
},
{
"code": null,
"e": 9162,
"s": 9127,
"text": "gaurabhkumarjha271020012 weeks ago"
},
{
"code": null,
"e": 10034,
"s": 9162,
"text": "// in c++\nlist<pair<int,int>>l;\nunordered_map<int,list<pair<int, int>>::iterator> m;\n int size;\n LRUCache(int cap)\n {\n // code here\n size=cap;\n }\n int get(int key)\n {\n // your code here\n if (m.find(key) == m.end()) return -1;\n \n l.splice(l.begin(), l, m[key]);\n return m[key]->second;\n }\n \n //Function for storing key-value pair.\n void set(int key, int value)\n {\n // your code here \n if (m.find(key) != m.end()){\n l.splice(l.begin(), l, m[key]);\n m[key]->second= value;\n return; \n }\n \n if (l.size() == size){\n \n auto dkey= l.back().first;\n l.pop_back();\n m.erase(dkey);\n }\n \n l.push_front({key, value});\n m[key]= l.begin();\n }"
},
{
"code": null,
"e": 10036,
"s": 10034,
"text": "0"
},
{
"code": null,
"e": 10057,
"s": 10036,
"text": "joyrockok3 weeks ago"
},
{
"code": null,
"e": 10328,
"s": 10057,
"text": "class LRUCache{ static class Node{ int key; int value; Node pre; Node next; public Node(int key, int value) { this.key = key; this.value = value; }}static int N=0; // cached size// static Queue<Integer> cache;static HashMap<Integer, Node> map;static Node head, tail;"
},
{
"code": null,
"e": 10663,
"s": 10328,
"text": " //Constructor for initializing the cache capacity with the given value.public LRUCache(int cap) //LRUCache(int cap) { //code here N = cap; map = new HashMap<Integer, Node>(); head = new Node(0, 0); tail = new Node(0, 0); head.next = tail; tail.pre = head; head.pre = null; tail.next = null; }"
},
{
"code": null,
"e": 11217,
"s": 10663,
"text": "public static void delNode(Node node) { node.pre.next = node.next; node.next.pre = node.pre;}public static void addNode(Node node) { node.next = head.next; node.next.pre = node; node.pre = head; head.next = node;} //Function to return value corresponding to the key. public static int get(int key) { // your code here if(map.get(key) != null) { Node node = map.get(key); delNode(node); // node를 삭제 후 addNode(node); // 제일 끝에 넣는다. 즉 head에 넣는다. return node.value; } else { return -1; } }"
},
{
"code": null,
"e": 11708,
"s": 11217,
"text": " //Function for storing key-value pair. public static void set(int key, int value) { // your code here if(map.get(key) != null) { Node node = map.get(key); node.value = value; delNode(node); addNode(node); } else { Node node = new Node(key, value); if(map.size()>= N) { map.remove(tail.pre.key); map.put(key, node); delNode(tail.pre); addNode(node); } else { addNode(node); map.put(key, node); } } }}"
},
{
"code": null,
"e": 11710,
"s": 11708,
"text": "0"
},
{
"code": null,
"e": 11738,
"s": 11710,
"text": "kundankumardec163 weeks ago"
},
{
"code": null,
"e": 11781,
"s": 11738,
"text": "Java implementation (using LinkedHashMap):"
},
{
"code": null,
"e": 12740,
"s": 11781,
"text": "class LRUCache\n{\n //Constructor for initializing the cache capacity with the given value.\n private static LinkedHashMap<Integer, Integer> map;\n private static int size;\n \n LRUCache(int cap) {\n //code here\n size = 0;\n map = new LinkedHashMap<>() {\n protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {\n return size() > cap;\n }\n };\n }\n\n //Function to return value corresponding to the key.\n public static int get(int key)\n {\n // your code here\n int ans = map.getOrDefault(key, -1);\n if (ans != -1) {\n map.remove(key);\n set(key, ans);\n }\n return ans;\n }\n\n //Function for storing key-value pair.\n public static void set(int key, int value)\n {\n // your code here\n if (map.containsKey(key)) {\n map.remove(key);\n }\n map.put(key, value);\n }\n}"
},
{
"code": null,
"e": 12742,
"s": 12740,
"text": "0"
},
{
"code": null,
"e": 12769,
"s": 12742,
"text": "swatisingh727774 weeks ago"
},
{
"code": null,
"e": 14337,
"s": 12769,
"text": "class LRUCache\n{ \n private:\n\n public:\n struct Node{\n int key;\n int val;\n Node* prev;\n Node* next;\n \n Node(int Key1 , int Val1){\n key = Key1;\n val = Val1;\n }\n };\n Node * head = new Node(-1,-1);\n Node * tail = new Node(-1,-1);\n int size;\n unordered_map<int , Node*>mp;\n \n \n LRUCache(int cap)\n {\n size = cap;\n head->next = tail;\n tail->prev = head;\n }\n void DelNode( Node* tempNode){\n Node* prev = tempNode->prev;\n Node* forward = tempNode->next;\n \n prev->next = forward;\n forward->prev = prev;\n }\n \n void InsNode(Node* tempNode){\n Node* temp = head->next;\n tempNode->next = temp;\n tempNode->prev = head;\n head->next = tempNode;\n temp->prev = tempNode;\n }\n int get(int key)\n {\n if(mp.find(key)!=mp.end()){\n Node* dummy = mp[key];\n int val = dummy->val;\n mp.erase(key);\n DelNode(dummy);\n InsNode(dummy);\n mp[key] = head->next;\n return val;\n }\n return -1;\n }\n \n \n void set(int key, int value)\n {\n if(mp.find(key)!=mp.end()){\n Node* dummy = mp[key];\n mp.erase(key);\n DelNode(dummy);\n \n } \n if(mp.size()==size){\n mp.erase(tail->prev->key);\n DelNode(tail->prev);\n }\n InsNode(new Node(key , value));\n mp[key] = head->next;\n }"
},
{
"code": null,
"e": 14361,
"s": 14337,
"text": "// O(1) time complexity"
},
{
"code": null,
"e": 14364,
"s": 14361,
"text": "+1"
},
{
"code": null,
"e": 14386,
"s": 14364,
"text": "akbhobhiya4 weeks ago"
},
{
"code": null,
"e": 16203,
"s": 14386,
"text": "// Just Wanted to know where they have used the stack and queue in this question. I have done this with the help of doubly linked list and unordered_map. bellow is the clean code of the implementation\n\nclass LRUCache\n{\n private:\n\n public:\n //Constructor for initializing the cache capacity with the given value.\n class Node{\n public:\n int key;\n int data;\n Node *next,*prev;\n Node(int _key, int _data){\n key = _key;\n data= _data;\n }\n };\n Node *head = new Node(-1,-1);\n Node *tail = new Node(-1,-1);\n int cap;\n unordered_map<int,Node*>mp;\n LRUCache(int capacity){\n cap = capacity;\n head->next = tail;\n tail->prev = head;\n }\n void add(Node *node){\n Node *temp = head->next;\n head->next = node;\n node->prev = head;\n node->next = temp;\n temp->prev = node;\n }\n void remove(Node *node){\n Node *temp1 = node->prev;\n Node *temp2 = node->next;\n temp1->next=temp2;\n temp2->prev=temp1;\n }\n //Function to return value corresponding to the key.\n int get(int key){\n if(mp.find(key)==mp.end())return -1;\n Node *node = mp[key];\n int data = node->data;\n remove(node);\n mp.erase(key);\n add(node);\n mp[key]=node;\n return data;\n }\n //Function for storing key-value pair.\n void set(int key, int value){\n if(mp.find(key)!=mp.end()){\n Node *node = mp[key];\n mp.erase(key);\n remove(node);\n }\n if(mp.size()==cap){\n mp.erase(tail->prev->key);\n remove(tail->prev);\n }\n Node *newnode = new Node(key,value);\n add(newnode);\n mp[key]=newnode;\n }\n};"
},
{
"code": null,
"e": 16205,
"s": 16203,
"text": "0"
},
{
"code": null,
"e": 16239,
"s": 16205,
"text": "abhishekshrivastav19201 month ago"
},
{
"code": null,
"e": 16322,
"s": 16239,
"text": "I have used dummy head and tail pointer so that i need not to put extra condition."
},
{
"code": null,
"e": 18318,
"s": 16322,
"text": " private:\n struct Node{\n int key;\n int value;\n Node *prev;\n Node *next;\n \n Node(int key,int value){\n this->key = key;\n this->value = value;\n \n }\n };\n \n Node *head = new Node(-1,-1);\n Node *tail = new Node(-1,-1);\n unordered_map<int,Node *> map;\n int capacity;\n \n public:\n //Constructor for initializing the cache capacity with the given value.\n LRUCache(int cap)\n {\n // code here\n capacity = cap;\n head->next = tail;\n tail->prev = head;\n }\n \n void removeNode(Node *node){\n \n Node *left = node->prev;\n Node *right = node->next;\n \n left->next = right;\n right->prev = left;\n }\n \n void addFirst(Node *node){\n Node *right = head->next;\n \n \n node->next = right;\n right->prev = node;\n \n head->next = node;\n node->prev = head;\n \n }\n //Function to return value corresponding to the key.\n int get(int key)\n {\n if(map.find(key) == map.end()){\n return -1;\n }\n \n \n Node *n = map[key];\n int ans = n->value;\n \n \n map.erase(key);\n \n removeNode(n);\n addFirst(n);\n \n map[key] = n;\n \n return ans;\n }\n \n //Function for storing key-value pair.\n void set(int key, int value)\n {\n if(map.find(key) != map.end()){\n removeNode(map[key]);\n map.erase(key);\n \n }\n \n if(map.size() == capacity){\n \n // remove last node\n Node *last = tail->prev;\n removeNode(last);\n map.erase(last->key);\n }\n \n \n Node *newNode = new Node(key,value);\n map[key] = newNode;\n addFirst(newNode);\n }"
},
{
"code": null,
"e": 18464,
"s": 18318,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 18500,
"s": 18464,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 18510,
"s": 18500,
"text": "\nProblem\n"
},
{
"code": null,
"e": 18520,
"s": 18510,
"text": "\nContest\n"
},
{
"code": null,
"e": 18583,
"s": 18520,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 18731,
"s": 18583,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 18939,
"s": 18731,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 19045,
"s": 18939,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to insert records with double quotes in MySQL? | To insert records with double quotes, use the backslash (\) as in the below syntax −
insert into yourTableName values('\"yourValue\"');
Let us first create a table −
mysql> create table DemoTable
-> (
-> Name varchar(20)
-> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('\"John\"');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('\"Chris\"');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('\"Adam Smith\"');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('\"Carol\"');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output. The double quotes around the records can be easily seen −
+--------------+
| Name |
+--------------+
| "John" |
| "Chris" |
| "Adam Smith" |
| "Carol" |
+--------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "To insert records with double quotes, use the backslash (\\) as in the below syntax −"
},
{
"code": null,
"e": 1198,
"s": 1147,
"text": "insert into yourTableName values('\\\"yourValue\\\"');"
},
{
"code": null,
"e": 1228,
"s": 1198,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1335,
"s": 1228,
"text": "mysql> create table DemoTable\n -> (\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1391,
"s": 1335,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1739,
"s": 1391,
"text": "mysql> insert into DemoTable values('\\\"John\\\"');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values('\\\"Chris\\\"');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('\\\"Adam Smith\\\"');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('\\\"Carol\\\"');\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 1799,
"s": 1739,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1830,
"s": 1799,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1928,
"s": 1830,
"text": "This will produce the following output. The double quotes around the records can be easily seen −"
},
{
"code": null,
"e": 2089,
"s": 1928,
"text": "+--------------+\n| Name |\n+--------------+\n| \"John\" |\n| \"Chris\" |\n| \"Adam Smith\" |\n| \"Carol\" |\n+--------------+\n4 rows in set (0.00 sec)"
}
] |
JSON - Overview | JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc.
JSON stands for JavaScript Object Notation.
JSON stands for JavaScript Object Notation.
The format was specified by Douglas Crockford.
The format was specified by Douglas Crockford.
It was designed for human-readable data interchange.
It was designed for human-readable data interchange.
It has been extended from the JavaScript scripting language.
It has been extended from the JavaScript scripting language.
The filename extension is .json.
The filename extension is .json.
JSON Internet Media type is application/json.
JSON Internet Media type is application/json.
The Uniform Type Identifier is public.json.
The Uniform Type Identifier is public.json.
It is used while writing JavaScript based applications that includes browser extensions and websites.
It is used while writing JavaScript based applications that includes browser extensions and websites.
JSON format is used for serializing and transmitting structured data over network connection.
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.
It is primarily used to transmit data between a server and web applications.
Web services and APIs use JSON format to provide public data.
Web services and APIs use JSON format to provide public data.
It can be used with modern programming languages.
It can be used with modern programming languages.
JSON is easy to read and write.
It is a lightweight text-based interchange format.
JSON is language independent.
The following example shows how to use JSON to store information related to books based on their topic and edition.
{
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
After understanding the above program, we will try another example. Let's save the below code as json.htm −
<html>
<head>
<title>JSON example</title>
<script language = "javascript" >
var object1 = { "language" : "Java", "author" : "herbert schildt" };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Language = " + object1.language+"</h3>");
document.write("<h3>Author = " + object1.author+"</h3>");
var object2 = { "language" : "C++", "author" : "E-Balagurusamy" };
document.write("<br>");
document.write("<h3>Language = " + object2.language+"</h3>");
document.write("<h3>Author = " + object2.author+"</h3>");
document.write("<hr />");
document.write(object2.language + " programming language can be studied " + "from book written by " + object2.author);
document.write("<hr />");
</script>
</head>
<body>
</body>
</html>
Now let's try to open json.htm using IE or any other javascript enabled browser that produces the following result −
You can refer to JSON Objects chapter for more information on JSON objects.
20 Lectures
1 hours
Laurence Svekis
16 Lectures
1 hours
Laurence Svekis
10 Lectures
1 hours
Laurence Svekis
23 Lectures
2.5 hours
Laurence Svekis
9 Lectures
48 mins
Nilay Mehta
18 Lectures
2.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2001,
"s": 1780,
"text": "JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc."
},
{
"code": null,
"e": 2045,
"s": 2001,
"text": "JSON stands for JavaScript Object Notation."
},
{
"code": null,
"e": 2089,
"s": 2045,
"text": "JSON stands for JavaScript Object Notation."
},
{
"code": null,
"e": 2136,
"s": 2089,
"text": "The format was specified by Douglas Crockford."
},
{
"code": null,
"e": 2183,
"s": 2136,
"text": "The format was specified by Douglas Crockford."
},
{
"code": null,
"e": 2236,
"s": 2183,
"text": "It was designed for human-readable data interchange."
},
{
"code": null,
"e": 2289,
"s": 2236,
"text": "It was designed for human-readable data interchange."
},
{
"code": null,
"e": 2350,
"s": 2289,
"text": "It has been extended from the JavaScript scripting language."
},
{
"code": null,
"e": 2411,
"s": 2350,
"text": "It has been extended from the JavaScript scripting language."
},
{
"code": null,
"e": 2444,
"s": 2411,
"text": "The filename extension is .json."
},
{
"code": null,
"e": 2477,
"s": 2444,
"text": "The filename extension is .json."
},
{
"code": null,
"e": 2523,
"s": 2477,
"text": "JSON Internet Media type is application/json."
},
{
"code": null,
"e": 2569,
"s": 2523,
"text": "JSON Internet Media type is application/json."
},
{
"code": null,
"e": 2613,
"s": 2569,
"text": "The Uniform Type Identifier is public.json."
},
{
"code": null,
"e": 2657,
"s": 2613,
"text": "The Uniform Type Identifier is public.json."
},
{
"code": null,
"e": 2759,
"s": 2657,
"text": "It is used while writing JavaScript based applications that includes browser extensions and websites."
},
{
"code": null,
"e": 2861,
"s": 2759,
"text": "It is used while writing JavaScript based applications that includes browser extensions and websites."
},
{
"code": null,
"e": 2955,
"s": 2861,
"text": "JSON format is used for serializing and transmitting structured data over network connection."
},
{
"code": null,
"e": 3049,
"s": 2955,
"text": "JSON format is used for serializing and transmitting structured data over network connection."
},
{
"code": null,
"e": 3126,
"s": 3049,
"text": "It is primarily used to transmit data between a server and web applications."
},
{
"code": null,
"e": 3203,
"s": 3126,
"text": "It is primarily used to transmit data between a server and web applications."
},
{
"code": null,
"e": 3265,
"s": 3203,
"text": "Web services and APIs use JSON format to provide public data."
},
{
"code": null,
"e": 3327,
"s": 3265,
"text": "Web services and APIs use JSON format to provide public data."
},
{
"code": null,
"e": 3377,
"s": 3327,
"text": "It can be used with modern programming languages."
},
{
"code": null,
"e": 3427,
"s": 3377,
"text": "It can be used with modern programming languages."
},
{
"code": null,
"e": 3459,
"s": 3427,
"text": "JSON is easy to read and write."
},
{
"code": null,
"e": 3510,
"s": 3459,
"text": "It is a lightweight text-based interchange format."
},
{
"code": null,
"e": 3540,
"s": 3510,
"text": "JSON is language independent."
},
{
"code": null,
"e": 3656,
"s": 3540,
"text": "The following example shows how to use JSON to store information related to books based on their topic and edition."
},
{
"code": null,
"e": 3944,
"s": 3656,
"text": "{\n \"book\": [\n\t\n {\n \"id\":\"01\",\n \"language\": \"Java\",\n \"edition\": \"third\",\n \"author\": \"Herbert Schildt\"\n },\n\t\n {\n \"id\":\"07\",\n \"language\": \"C++\",\n \"edition\": \"second\",\n \"author\": \"E.Balagurusamy\"\n }\n ]\n}"
},
{
"code": null,
"e": 4052,
"s": 3944,
"text": "After understanding the above program, we will try another example. Let's save the below code as json.htm −"
},
{
"code": null,
"e": 4979,
"s": 4052,
"text": "<html>\n <head>\n <title>JSON example</title>\n <script language = \"javascript\" >\n var object1 = { \"language\" : \"Java\", \"author\" : \"herbert schildt\" };\n document.write(\"<h1>JSON with JavaScript example</h1>\");\n document.write(\"<br>\");\n document.write(\"<h3>Language = \" + object1.language+\"</h3>\"); \n document.write(\"<h3>Author = \" + object1.author+\"</h3>\"); \n\n var object2 = { \"language\" : \"C++\", \"author\" : \"E-Balagurusamy\" };\n document.write(\"<br>\");\n document.write(\"<h3>Language = \" + object2.language+\"</h3>\"); \n document.write(\"<h3>Author = \" + object2.author+\"</h3>\"); \n \n document.write(\"<hr />\");\n document.write(object2.language + \" programming language can be studied \" + \"from book written by \" + object2.author);\n document.write(\"<hr />\");\n </script>\n </head>\n \n <body>\n </body>\n</html>"
},
{
"code": null,
"e": 5096,
"s": 4979,
"text": "Now let's try to open json.htm using IE or any other javascript enabled browser that produces the following result −"
},
{
"code": null,
"e": 5172,
"s": 5096,
"text": "You can refer to JSON Objects chapter for more information on JSON objects."
},
{
"code": null,
"e": 5205,
"s": 5172,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5222,
"s": 5205,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5255,
"s": 5222,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5272,
"s": 5255,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5305,
"s": 5272,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5322,
"s": 5305,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5357,
"s": 5322,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5374,
"s": 5357,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5405,
"s": 5374,
"text": "\n 9 Lectures \n 48 mins\n"
},
{
"code": null,
"e": 5418,
"s": 5405,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5453,
"s": 5418,
"text": "\n 18 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5476,
"s": 5453,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5483,
"s": 5476,
"text": " Print"
},
{
"code": null,
"e": 5494,
"s": 5483,
"text": " Add Notes"
}
] |
Python Pandas Dataframe to Google Sheets for Tableau Public LIVE | by Eklavya Saxena | Towards Data Science | This blog is a part of Automated ETL for LIVE Tableau Public Visualizations and is sub-divided into three parts, namely:
Enable Google Sheets API and Create CredentialsConnect Python to Google Sheets and Export the DataframeEnable Tableau Public LIVE using Google Sheets
Enable Google Sheets API and Create Credentials
Connect Python to Google Sheets and Export the Dataframe
Enable Tableau Public LIVE using Google Sheets
Accessing your Google API Console is the first step to connect python scripts with google sheets. Step wise follow along to enable google sheets API and create required credentials.
On the top left corner, click on the drop-down ‘Select a project’, which will open a pop-up windowOn the top right corner of this pop-up, click on ‘NEW PROJECT’, which will take you to a new windowGive your project a suitable name (for e.g: covid-viz-data). You may leave the ‘Location *’ field as it is and click on ‘CREATE’
On the top left corner, click on the drop-down ‘Select a project’, which will open a pop-up window
On the top right corner of this pop-up, click on ‘NEW PROJECT’, which will take you to a new window
Give your project a suitable name (for e.g: covid-viz-data). You may leave the ‘Location *’ field as it is and click on ‘CREATE’
Select ‘Library’ (under ‘Dashboard’) from the left pane, which will re-direct you to ‘API Library’ window an option to search for APIs and servicesType in the field ‘Google Sheets API’ and select it from the result, which will re-direct you the Google Sheets API windowClick on ‘ENABLE’ to enable it for your project created in the previous step
Select ‘Library’ (under ‘Dashboard’) from the left pane, which will re-direct you to ‘API Library’ window an option to search for APIs and services
Type in the field ‘Google Sheets API’ and select it from the result, which will re-direct you the Google Sheets API window
Click on ‘ENABLE’ to enable it for your project created in the previous step
Similarly, enable Google Drive API as python library imported later may use the functionalities of both the above APIs.
You may select ‘CREATE CREDENTIALS’ on the right side of the Google Sheets API window or alternatively if you are on dashboard — start with Step 1.
Select ‘Credentials’ (under ‘Library’) from the left pane. This will display you the ‘Credentials’ pane on the rightClick on the ‘CREATE CREDENTIALS’ option on the top, which will display a drop-down menuClick on ‘Help me choose’ option from the drop-down menu, which will redirect you to a pane with heading ‘Add credentials to your project’On this ‘Add credentials to your project’ pane follow along:Step 1: ‘Find out what kind of credentials you need’Which API are you using? — Google Sheets APIWhere will you be calling the API from? — Web serverWhat data will you be accessing? — Application dataAre you planning to use this API with App Engine or Compute Engine? — No, I’m not using themNow, click on ‘What credentials do I need?’ for suggestion as per our inputStep 2: ‘Create a service account’Service account name — (for e.g: covid-data-update)Role — Editor (From drop-down select ‘Project’ and then ‘Editor’)Service account ID — auto-createdKey type — JSONNow, click on ‘Continue’.This will ask you to save credentials .json file which allows access to your cloud resources — so store it securely.
Select ‘Credentials’ (under ‘Library’) from the left pane. This will display you the ‘Credentials’ pane on the right
Click on the ‘CREATE CREDENTIALS’ option on the top, which will display a drop-down menu
Click on ‘Help me choose’ option from the drop-down menu, which will redirect you to a pane with heading ‘Add credentials to your project’
On this ‘Add credentials to your project’ pane follow along:Step 1: ‘Find out what kind of credentials you need’Which API are you using? — Google Sheets APIWhere will you be calling the API from? — Web serverWhat data will you be accessing? — Application dataAre you planning to use this API with App Engine or Compute Engine? — No, I’m not using themNow, click on ‘What credentials do I need?’ for suggestion as per our inputStep 2: ‘Create a service account’Service account name — (for e.g: covid-data-update)Role — Editor (From drop-down select ‘Project’ and then ‘Editor’)Service account ID — auto-createdKey type — JSONNow, click on ‘Continue’.This will ask you to save credentials .json file which allows access to your cloud resources — so store it securely.
Now that we have our secret credentials to access the API (saved in .json format), we need to make sure that the target google sheet is shared with the client email generated in that .json file.
Copy the email address value from ‘client_email’ key in the .json fileCreate a new google sheet, where you want to export your dataOnce the sheet is opened, click ‘Share’ on the top right cornerPaste the copied email address and give it ‘Can edit’ access
Copy the email address value from ‘client_email’ key in the .json file
Create a new google sheet, where you want to export your data
Once the sheet is opened, click ‘Share’ on the top right corner
Paste the copied email address and give it ‘Can edit’ access
Congratulations! we have successfully enabled Google Sheets API from Google API Console and created credentials to access this API via python script. Now, let’s move onto to the second part.
While Google created the Google Sheets API, they, of course, did not stay behind to beautifully create a guide for Python QuickStart. I would highly recommend to referring it as the additional documentation/guide enables vast possibilities to play around with Google Sheets.
Why this blog then?The quick-start asks you to install 3 libraries, namely google-api-python-client, google-auth-httplib2, google-auth-oauthlib.But, as evident from the widespread plethora of python libraries — here we have:
pygsheets — A simple, intuitive python library to access google spreadsheets through the Google Sheets API v4
This part will utilize pyghseets to export Dataframe to Google Sheets.Let’s get started:
import sys!{sys.executable} -m pip install pygsheets
Why I did not use !pip install pyghseets ?In Jupyter, the above code makes sure that you are running the pip version associated with the current Python kernel. Also, FYI the shell environment and the Python executable are disconnected. Click here for more information.
import pygsheetsclient = pygsheets.authorize(service_file='/Users/eklav/credentials.json')print("-----------------Authorized--------------------")
After installation, the next step is to of course import the library. Then, create a variable client using authorize functionality to authenticate python script (or an application) with a google account.
sheet = client.open('COVID-19')print("-----------------Sheet Opened------------------")
Now, use open functionality to return the spreadsheet (created in the previous part) by title (e.g: ‘COVID-19’) and assign it to the variable sheet .
wks = sheet[0]print("-----------------First Sheet Accessed----------")
To access the first sheet, worksheet on ‘0th’ index of sheet is assigned to the variable wks .
wks.set_dataframe(df_COVID,(1,1))print("-----------------Data Updated------------------")
Now, use .set_dataframe functionality of worksheet wks to assign values ‘df_COVID’* and ‘(1,1)’ to ‘df’ and ‘start’ parameters respectively.The value ‘(1,1)’ refers to the A1 cell of the spreadsheet.
To know how dataframe ‘df_COVID’ was curated, please refer to the first part — ‘Data Extraction from GitHub and Auto-run or Schedule Python Script’ of the blog Automated ETL for LIVE Tableau Public Visualizations.
This brings us to the end of this part. We have enabled APIs and credentials using which we connected Python to Google Sheets — your free cloud storage.
As mentioned in the parent blog, finally it is time to bust the myth that Tableau Public cannot have LIVE data. By now, we have a Python script being run automatically by Windows Task Scheduler, which in turns updates the Google Sheets. And this sheet will be our source of data for dashboard or visualizations published over Tableau Public.
I will refrain from elaborating on a very well-known step — to select a data source from the Tableau Start Page. If required, please follow the GIF below:
Well, now you may go ahead and create visualizations as required with data sourced LIVE from your Google Sheets
While you have a LIVE connection with Google Sheet, it must be straight forward to publish the workbook. Just connect to https://public.tableau.com server by logging in and share.
But, here is the catch! The following error will pop-up:
“The Tableau server you are publishing to requires extracts to be enabled for data sources. Use the Data menu to enable the extracts for the following data sources:
Data Extract Required”
Now the question is — Data Extract???
The whole point of sourcing data from Google Sheets was to have a LIVE connection. And, this is where we believe that Tableau Public just works with extracts.
But, Tableau has more to serve — without a blink of an eye just go ahead and make your connection to ‘Extract’. Now when you share, tick the checkbox which displays the following and save:
“Keep my data in sync with Google Sheets and embed my Google credentials”
Once ‘Save’ button is clicked, you will be re-directed to Tableau Public, with your dashboard published. Scroll down and notice the ‘Request Update’ button. This button is to force update the dashboard accessing the latest data from the Google Sheets. Else otherwise, what I have experienced Tableau refreshes the dashboard automatically every day.
Bingo!
Introduction to the Google Sheets API
Reading and Writing to Google Spreadsheets using Python by Erik Rood
Documentation on pygsheets Python Library
Thank you for reading! I hope this blog revealed an interesting aspect of Tableau Public. Go ahead and make your visualizations LIVE. If this article was helpful, share it.
Let me know in a comment:
If you felt like this did or didn’t help, orIf you would like to know ‘how to’ of different features used in Tableau visualizations
If you felt like this did or didn’t help, or
If you would like to know ‘how to’ of different features used in Tableau visualizations | [
{
"code": null,
"e": 168,
"s": 47,
"text": "This blog is a part of Automated ETL for LIVE Tableau Public Visualizations and is sub-divided into three parts, namely:"
},
{
"code": null,
"e": 318,
"s": 168,
"text": "Enable Google Sheets API and Create CredentialsConnect Python to Google Sheets and Export the DataframeEnable Tableau Public LIVE using Google Sheets"
},
{
"code": null,
"e": 366,
"s": 318,
"text": "Enable Google Sheets API and Create Credentials"
},
{
"code": null,
"e": 423,
"s": 366,
"text": "Connect Python to Google Sheets and Export the Dataframe"
},
{
"code": null,
"e": 470,
"s": 423,
"text": "Enable Tableau Public LIVE using Google Sheets"
},
{
"code": null,
"e": 652,
"s": 470,
"text": "Accessing your Google API Console is the first step to connect python scripts with google sheets. Step wise follow along to enable google sheets API and create required credentials."
},
{
"code": null,
"e": 978,
"s": 652,
"text": "On the top left corner, click on the drop-down ‘Select a project’, which will open a pop-up windowOn the top right corner of this pop-up, click on ‘NEW PROJECT’, which will take you to a new windowGive your project a suitable name (for e.g: covid-viz-data). You may leave the ‘Location *’ field as it is and click on ‘CREATE’"
},
{
"code": null,
"e": 1077,
"s": 978,
"text": "On the top left corner, click on the drop-down ‘Select a project’, which will open a pop-up window"
},
{
"code": null,
"e": 1177,
"s": 1077,
"text": "On the top right corner of this pop-up, click on ‘NEW PROJECT’, which will take you to a new window"
},
{
"code": null,
"e": 1306,
"s": 1177,
"text": "Give your project a suitable name (for e.g: covid-viz-data). You may leave the ‘Location *’ field as it is and click on ‘CREATE’"
},
{
"code": null,
"e": 1652,
"s": 1306,
"text": "Select ‘Library’ (under ‘Dashboard’) from the left pane, which will re-direct you to ‘API Library’ window an option to search for APIs and servicesType in the field ‘Google Sheets API’ and select it from the result, which will re-direct you the Google Sheets API windowClick on ‘ENABLE’ to enable it for your project created in the previous step"
},
{
"code": null,
"e": 1800,
"s": 1652,
"text": "Select ‘Library’ (under ‘Dashboard’) from the left pane, which will re-direct you to ‘API Library’ window an option to search for APIs and services"
},
{
"code": null,
"e": 1923,
"s": 1800,
"text": "Type in the field ‘Google Sheets API’ and select it from the result, which will re-direct you the Google Sheets API window"
},
{
"code": null,
"e": 2000,
"s": 1923,
"text": "Click on ‘ENABLE’ to enable it for your project created in the previous step"
},
{
"code": null,
"e": 2120,
"s": 2000,
"text": "Similarly, enable Google Drive API as python library imported later may use the functionalities of both the above APIs."
},
{
"code": null,
"e": 2268,
"s": 2120,
"text": "You may select ‘CREATE CREDENTIALS’ on the right side of the Google Sheets API window or alternatively if you are on dashboard — start with Step 1."
},
{
"code": null,
"e": 3376,
"s": 2268,
"text": "Select ‘Credentials’ (under ‘Library’) from the left pane. This will display you the ‘Credentials’ pane on the rightClick on the ‘CREATE CREDENTIALS’ option on the top, which will display a drop-down menuClick on ‘Help me choose’ option from the drop-down menu, which will redirect you to a pane with heading ‘Add credentials to your project’On this ‘Add credentials to your project’ pane follow along:Step 1: ‘Find out what kind of credentials you need’Which API are you using? — Google Sheets APIWhere will you be calling the API from? — Web serverWhat data will you be accessing? — Application dataAre you planning to use this API with App Engine or Compute Engine? — No, I’m not using themNow, click on ‘What credentials do I need?’ for suggestion as per our inputStep 2: ‘Create a service account’Service account name — (for e.g: covid-data-update)Role — Editor (From drop-down select ‘Project’ and then ‘Editor’)Service account ID — auto-createdKey type — JSONNow, click on ‘Continue’.This will ask you to save credentials .json file which allows access to your cloud resources — so store it securely."
},
{
"code": null,
"e": 3493,
"s": 3376,
"text": "Select ‘Credentials’ (under ‘Library’) from the left pane. This will display you the ‘Credentials’ pane on the right"
},
{
"code": null,
"e": 3582,
"s": 3493,
"text": "Click on the ‘CREATE CREDENTIALS’ option on the top, which will display a drop-down menu"
},
{
"code": null,
"e": 3721,
"s": 3582,
"text": "Click on ‘Help me choose’ option from the drop-down menu, which will redirect you to a pane with heading ‘Add credentials to your project’"
},
{
"code": null,
"e": 4487,
"s": 3721,
"text": "On this ‘Add credentials to your project’ pane follow along:Step 1: ‘Find out what kind of credentials you need’Which API are you using? — Google Sheets APIWhere will you be calling the API from? — Web serverWhat data will you be accessing? — Application dataAre you planning to use this API with App Engine or Compute Engine? — No, I’m not using themNow, click on ‘What credentials do I need?’ for suggestion as per our inputStep 2: ‘Create a service account’Service account name — (for e.g: covid-data-update)Role — Editor (From drop-down select ‘Project’ and then ‘Editor’)Service account ID — auto-createdKey type — JSONNow, click on ‘Continue’.This will ask you to save credentials .json file which allows access to your cloud resources — so store it securely."
},
{
"code": null,
"e": 4682,
"s": 4487,
"text": "Now that we have our secret credentials to access the API (saved in .json format), we need to make sure that the target google sheet is shared with the client email generated in that .json file."
},
{
"code": null,
"e": 4937,
"s": 4682,
"text": "Copy the email address value from ‘client_email’ key in the .json fileCreate a new google sheet, where you want to export your dataOnce the sheet is opened, click ‘Share’ on the top right cornerPaste the copied email address and give it ‘Can edit’ access"
},
{
"code": null,
"e": 5008,
"s": 4937,
"text": "Copy the email address value from ‘client_email’ key in the .json file"
},
{
"code": null,
"e": 5070,
"s": 5008,
"text": "Create a new google sheet, where you want to export your data"
},
{
"code": null,
"e": 5134,
"s": 5070,
"text": "Once the sheet is opened, click ‘Share’ on the top right corner"
},
{
"code": null,
"e": 5195,
"s": 5134,
"text": "Paste the copied email address and give it ‘Can edit’ access"
},
{
"code": null,
"e": 5386,
"s": 5195,
"text": "Congratulations! we have successfully enabled Google Sheets API from Google API Console and created credentials to access this API via python script. Now, let’s move onto to the second part."
},
{
"code": null,
"e": 5661,
"s": 5386,
"text": "While Google created the Google Sheets API, they, of course, did not stay behind to beautifully create a guide for Python QuickStart. I would highly recommend to referring it as the additional documentation/guide enables vast possibilities to play around with Google Sheets."
},
{
"code": null,
"e": 5886,
"s": 5661,
"text": "Why this blog then?The quick-start asks you to install 3 libraries, namely google-api-python-client, google-auth-httplib2, google-auth-oauthlib.But, as evident from the widespread plethora of python libraries — here we have:"
},
{
"code": null,
"e": 5996,
"s": 5886,
"text": "pygsheets — A simple, intuitive python library to access google spreadsheets through the Google Sheets API v4"
},
{
"code": null,
"e": 6085,
"s": 5996,
"text": "This part will utilize pyghseets to export Dataframe to Google Sheets.Let’s get started:"
},
{
"code": null,
"e": 6138,
"s": 6085,
"text": "import sys!{sys.executable} -m pip install pygsheets"
},
{
"code": null,
"e": 6407,
"s": 6138,
"text": "Why I did not use !pip install pyghseets ?In Jupyter, the above code makes sure that you are running the pip version associated with the current Python kernel. Also, FYI the shell environment and the Python executable are disconnected. Click here for more information."
},
{
"code": null,
"e": 6554,
"s": 6407,
"text": "import pygsheetsclient = pygsheets.authorize(service_file='/Users/eklav/credentials.json')print(\"-----------------Authorized--------------------\")"
},
{
"code": null,
"e": 6758,
"s": 6554,
"text": "After installation, the next step is to of course import the library. Then, create a variable client using authorize functionality to authenticate python script (or an application) with a google account."
},
{
"code": null,
"e": 6846,
"s": 6758,
"text": "sheet = client.open('COVID-19')print(\"-----------------Sheet Opened------------------\")"
},
{
"code": null,
"e": 6996,
"s": 6846,
"text": "Now, use open functionality to return the spreadsheet (created in the previous part) by title (e.g: ‘COVID-19’) and assign it to the variable sheet ."
},
{
"code": null,
"e": 7067,
"s": 6996,
"text": "wks = sheet[0]print(\"-----------------First Sheet Accessed----------\")"
},
{
"code": null,
"e": 7162,
"s": 7067,
"text": "To access the first sheet, worksheet on ‘0th’ index of sheet is assigned to the variable wks ."
},
{
"code": null,
"e": 7252,
"s": 7162,
"text": "wks.set_dataframe(df_COVID,(1,1))print(\"-----------------Data Updated------------------\")"
},
{
"code": null,
"e": 7452,
"s": 7252,
"text": "Now, use .set_dataframe functionality of worksheet wks to assign values ‘df_COVID’* and ‘(1,1)’ to ‘df’ and ‘start’ parameters respectively.The value ‘(1,1)’ refers to the A1 cell of the spreadsheet."
},
{
"code": null,
"e": 7666,
"s": 7452,
"text": "To know how dataframe ‘df_COVID’ was curated, please refer to the first part — ‘Data Extraction from GitHub and Auto-run or Schedule Python Script’ of the blog Automated ETL for LIVE Tableau Public Visualizations."
},
{
"code": null,
"e": 7819,
"s": 7666,
"text": "This brings us to the end of this part. We have enabled APIs and credentials using which we connected Python to Google Sheets — your free cloud storage."
},
{
"code": null,
"e": 8161,
"s": 7819,
"text": "As mentioned in the parent blog, finally it is time to bust the myth that Tableau Public cannot have LIVE data. By now, we have a Python script being run automatically by Windows Task Scheduler, which in turns updates the Google Sheets. And this sheet will be our source of data for dashboard or visualizations published over Tableau Public."
},
{
"code": null,
"e": 8316,
"s": 8161,
"text": "I will refrain from elaborating on a very well-known step — to select a data source from the Tableau Start Page. If required, please follow the GIF below:"
},
{
"code": null,
"e": 8428,
"s": 8316,
"text": "Well, now you may go ahead and create visualizations as required with data sourced LIVE from your Google Sheets"
},
{
"code": null,
"e": 8608,
"s": 8428,
"text": "While you have a LIVE connection with Google Sheet, it must be straight forward to publish the workbook. Just connect to https://public.tableau.com server by logging in and share."
},
{
"code": null,
"e": 8665,
"s": 8608,
"text": "But, here is the catch! The following error will pop-up:"
},
{
"code": null,
"e": 8830,
"s": 8665,
"text": "“The Tableau server you are publishing to requires extracts to be enabled for data sources. Use the Data menu to enable the extracts for the following data sources:"
},
{
"code": null,
"e": 8853,
"s": 8830,
"text": "Data Extract Required”"
},
{
"code": null,
"e": 8891,
"s": 8853,
"text": "Now the question is — Data Extract???"
},
{
"code": null,
"e": 9050,
"s": 8891,
"text": "The whole point of sourcing data from Google Sheets was to have a LIVE connection. And, this is where we believe that Tableau Public just works with extracts."
},
{
"code": null,
"e": 9239,
"s": 9050,
"text": "But, Tableau has more to serve — without a blink of an eye just go ahead and make your connection to ‘Extract’. Now when you share, tick the checkbox which displays the following and save:"
},
{
"code": null,
"e": 9313,
"s": 9239,
"text": "“Keep my data in sync with Google Sheets and embed my Google credentials”"
},
{
"code": null,
"e": 9662,
"s": 9313,
"text": "Once ‘Save’ button is clicked, you will be re-directed to Tableau Public, with your dashboard published. Scroll down and notice the ‘Request Update’ button. This button is to force update the dashboard accessing the latest data from the Google Sheets. Else otherwise, what I have experienced Tableau refreshes the dashboard automatically every day."
},
{
"code": null,
"e": 9669,
"s": 9662,
"text": "Bingo!"
},
{
"code": null,
"e": 9707,
"s": 9669,
"text": "Introduction to the Google Sheets API"
},
{
"code": null,
"e": 9776,
"s": 9707,
"text": "Reading and Writing to Google Spreadsheets using Python by Erik Rood"
},
{
"code": null,
"e": 9818,
"s": 9776,
"text": "Documentation on pygsheets Python Library"
},
{
"code": null,
"e": 9991,
"s": 9818,
"text": "Thank you for reading! I hope this blog revealed an interesting aspect of Tableau Public. Go ahead and make your visualizations LIVE. If this article was helpful, share it."
},
{
"code": null,
"e": 10017,
"s": 9991,
"text": "Let me know in a comment:"
},
{
"code": null,
"e": 10149,
"s": 10017,
"text": "If you felt like this did or didn’t help, orIf you would like to know ‘how to’ of different features used in Tableau visualizations"
},
{
"code": null,
"e": 10194,
"s": 10149,
"text": "If you felt like this did or didn’t help, or"
}
] |
Ridge and Lasso Regression: L1 and L2 Regularization | by Saptashwa Bhattacharyya | Towards Data Science | Moving on from a very important unsupervised learning technique that I have discussed last week, today we will dig deep in to supervised learning through linear regression, specifically two special linear regression model — Lasso and Ridge regression.
As I’m using the term linear, first let’s clarify that linear models are one of the simplest way to predict output using a linear function of input features.
In the equation (1.1) above, we have shown the linear model based on the n number of features. Considering only a single feature as you probably already have understood that w[0] will be slope and b will represent intercept. Linear regression looks for optimizing w and b such that it minimizes the cost function. The cost function can be written as
In the equation above I have assumed the data-set has M instances and p features. Once we use linear regression on a data-set divided in to training and test set, calculating the scores on training and test set can give us a rough idea about whether the model is suffering from over-fitting or under-fitting. The chosen linear model can be just right also, if you’re lucky enough! If we have very few features on a data-set and the score is poor for both training and test set then it’s a problem of under-fitting. On the other hand if we have large number of features and test score is relatively poor than the training score then it’s the problem of over-generalization or over-fitting. Ridge and Lasso regression are some of the simple techniques to reduce model complexity and prevent over-fitting which may result from simple linear regression.
Ridge Regression : In ridge regression, the cost function is altered by adding a penalty equivalent to square of the magnitude of the coefficients.
This is equivalent to saying minimizing the cost function in equation 1.2 under the condition as below
So ridge regression puts constraint on the coefficients (w). The penalty term (lambda) regularizes the coefficients such that if the coefficients take large values the optimization function is penalized. So, ridge regression shrinks the coefficients and it helps to reduce the model complexity and multi-collinearity. Going back to eq. 1.3 one can see that when λ → 0 , the cost function becomes similar to the linear regression cost function (eq. 1.2). So lower the constraint (low λ) on the features, the model will resemble linear regression model. Let’s see an example using Boston house data and below is the code I used to depict linear regression as a limiting case of Ridge regression-
import matplotlib.pyplot as pltimport numpy as np import pandas as pdimport matplotlibmatplotlib.rcParams.update({'font.size': 12})from sklearn.datasets import load_bostonfrom sklearn.cross_validation import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.linear_model import Ridgeboston=load_boston()boston_df=pd.DataFrame(boston.data,columns=boston.feature_names)#print boston_df.info()# add another column that contains the house prices which in scikit learn datasets are considered as targetboston_df['Price']=boston.target#print boston_df.head(3)newX=boston_df.drop('Price',axis=1)print newX[0:3] # check newY=boston_df['Price']#print type(newY)# pandas core frameX_train,X_test,y_train,y_test=train_test_split(newX,newY,test_size=0.3,random_state=3)print len(X_test), len(y_test)lr = LinearRegression()lr.fit(X_train, y_train)rr = Ridge(alpha=0.01) # higher the alpha value, more restriction on the coefficients; low alpha > more generalization,# in this case linear and ridge regression resemblesrr.fit(X_train, y_train)rr100 = Ridge(alpha=100) # comparison with alpha valuerr100.fit(X_train, y_train)train_score=lr.score(X_train, y_train)test_score=lr.score(X_test, y_test)Ridge_train_score = rr.score(X_train,y_train)Ridge_test_score = rr.score(X_test, y_test)Ridge_train_score100 = rr100.score(X_train,y_train)Ridge_test_score100 = rr100.score(X_test, y_test)plt.plot(rr.coef_,alpha=0.7,linestyle='none',marker='*',markersize=5,color='red',label=r'Ridge; $\alpha = 0.01$',zorder=7) plt.plot(rr100.coef_,alpha=0.5,linestyle='none',marker='d',markersize=6,color='blue',label=r'Ridge; $\alpha = 100$') plt.plot(lr.coef_,alpha=0.4,linestyle='none',marker='o',markersize=7,color='green',label='Linear Regression')plt.xlabel('Coefficient Index',fontsize=16)plt.ylabel('Coefficient Magnitude',fontsize=16)plt.legend(fontsize=13,loc=4)plt.show()
Let’s understand the figure above. In X axis we plot the coefficient index and, for Boston data there are 13 features (for Python 0th index refers to 1st feature). For low value of α (0.01), when the coefficients are less restricted, the magnitudes of the coefficients are almost same as of linear regression. For higher value of α (100), we see that for coefficient indices 3,4,5 the magnitudes are considerably less compared to linear regression case. This is an example of shrinking coefficient magnitude using Ridge regression.
Lasso Regression : The cost function for Lasso (least absolute shrinkage and selection operator) regression can be written as
Just like Ridge regression cost function, for lambda =0, the equation above reduces to equation 1.2. The only difference is instead of taking the square of the coefficients, magnitudes are taken into account. This type of regularization (L1) can lead to zero coefficients i.e. some of the features are completely neglected for the evaluation of output. So Lasso regression not only helps in reducing over-fitting but it can help us in feature selection. Just like Ridge regression the regularization parameter (lambda) can be controlled and we will see the effect below using cancer data set in sklearn. Reason I am using cancer data instead of Boston house data, that I have used before, is, cancer data-set have 30 features compared to only 13 features of Boston house data. So feature selection using Lasso regression can be depicted well by changing the regularization parameter.
The code I used to make these plots is as below
import math import matplotlib.pyplot as plt import pandas as pdimport numpy as np# difference of lasso and ridge regression is that some of the coefficients can be zero i.e. some of the features are # completely neglectedfrom sklearn.linear_model import Lassofrom sklearn.linear_model import LinearRegressionfrom sklearn.datasets import load_breast_cancerfrom sklearn.cross_validation import train_test_splitcancer = load_breast_cancer()#print cancer.keys()cancer_df = pd.DataFrame(cancer.data, columns=cancer.feature_names)#print cancer_df.head(3)X = cancer.dataY = cancer.targetX_train,X_test,y_train,y_test=train_test_split(X,Y, test_size=0.3, random_state=31)lasso = Lasso()lasso.fit(X_train,y_train)train_score=lasso.score(X_train,y_train)test_score=lasso.score(X_test,y_test)coeff_used = np.sum(lasso.coef_!=0)print "training score:", train_score print "test score: ", test_scoreprint "number of features used: ", coeff_usedlasso001 = Lasso(alpha=0.01, max_iter=10e5)lasso001.fit(X_train,y_train)train_score001=lasso001.score(X_train,y_train)test_score001=lasso001.score(X_test,y_test)coeff_used001 = np.sum(lasso001.coef_!=0)print "training score for alpha=0.01:", train_score001 print "test score for alpha =0.01: ", test_score001print "number of features used: for alpha =0.01:", coeff_used001lasso00001 = Lasso(alpha=0.0001, max_iter=10e5)lasso00001.fit(X_train,y_train)train_score00001=lasso00001.score(X_train,y_train)test_score00001=lasso00001.score(X_test,y_test)coeff_used00001 = np.sum(lasso00001.coef_!=0)print "training score for alpha=0.0001:", train_score00001 print "test score for alpha =0.0001: ", test_score00001print "number of features used: for alpha =0.0001:", coeff_used00001lr = LinearRegression()lr.fit(X_train,y_train)lr_train_score=lr.score(X_train,y_train)lr_test_score=lr.score(X_test,y_test)print "LR training score:", lr_train_score print "LR test score: ", lr_test_scoreplt.subplot(1,2,1)plt.plot(lasso.coef_,alpha=0.7,linestyle='none',marker='*',markersize=5,color='red',label=r'Lasso; $\alpha = 1$',zorder=7) # alpha here is for transparencyplt.plot(lasso001.coef_,alpha=0.5,linestyle='none',marker='d',markersize=6,color='blue',label=r'Lasso; $\alpha = 0.01$') # alpha here is for transparencyplt.xlabel('Coefficient Index',fontsize=16)plt.ylabel('Coefficient Magnitude',fontsize=16)plt.legend(fontsize=13,loc=4)plt.subplot(1,2,2)plt.plot(lasso.coef_,alpha=0.7,linestyle='none',marker='*',markersize=5,color='red',label=r'Lasso; $\alpha = 1$',zorder=7) # alpha here is for transparencyplt.plot(lasso001.coef_,alpha=0.5,linestyle='none',marker='d',markersize=6,color='blue',label=r'Lasso; $\alpha = 0.01$') # alpha here is for transparencyplt.plot(lasso00001.coef_,alpha=0.8,linestyle='none',marker='v',markersize=6,color='black',label=r'Lasso; $\alpha = 0.00001$') # alpha here is for transparencyplt.plot(lr.coef_,alpha=0.7,linestyle='none',marker='o',markersize=5,color='green',label='Linear Regression',zorder=2)plt.xlabel('Coefficient Index',fontsize=16)plt.ylabel('Coefficient Magnitude',fontsize=16)plt.legend(fontsize=13,loc=4)plt.tight_layout()plt.show()#output training score: 0.5600974529893081test score: 0.5832244618818156number of features used: 4training score for alpha=0.01: 0.7037865778498829test score for alpha =0.01: 0.664183157772623number of features used: for alpha =0.01: 10training score for alpha=0.0001: 0.7754092006936697test score for alpha =0.0001: 0.7318608210757904number of features used: for alpha =0.0001: 22LR training score: 0.7842206194055068LR test score: 0.7329325010888681
Let’s understand the plot and the code in a short summary.
The default value of regularization parameter in Lasso regression (given by α) is 1.
With this, out of 30 features in cancer data-set, only 4 features are used (non zero value of the coefficient).
Both training and test score (with only 4 features) are low; conclude that the model is under-fitting the cancer data-set.
Reduce this under-fitting by reducing alpha and increasing number of iterations. Now α = 0.01, non-zero features =10, training and test score increases.
Comparison of coefficient magnitude for two different values of alpha are shown in the left panel of figure 2. For alpha =1, we can see most of the coefficients are zero or nearly zero, which is not the case for alpha=0.01.
Further reduce α =0.0001, non-zero features = 22. Training and test scores are similar to basic linear regression case.
In the right panel of figure, for α = 0.0001, coefficients for Lasso regression and linear regression show close resemblance.
So far we have gone through the basics of Ridge and Lasso regression and seen some examples to understand the applications. Now, I will try to explain why the Lasso regression can result in feature selection and Ridge regression only reduces the coefficients close to zero, but not zero. An illustrative figure below will help us to understand better, where we will assume a hypothetical data-set with only two features. Using the constrain for the coefficients of Ridge and Lasso regression (as shown above in the supplements 1 and 2), we can plot the figure below
For a two dimensional feature space, the constraint regions (see supplement 1 and 2) are plotted for Lasso and Ridge regression with cyan and green colours. The elliptical contours are the cost function of linear regression (eq. 1.2). Now if we have relaxed conditions on the coefficients, then the constrained regions can get bigger and eventually they will hit the centre of the ellipse. This is the case when Ridge and Lasso regression resembles linear regression results. Otherwise, both methods determine coefficients by finding the first point where the elliptical contours hit the region of constraints. The diamond (Lasso) has corners on the axes, unlike the disk, and whenever the elliptical region hits such point, one of the features completely vanishes! For higher dimensional feature space there can be many solutions on the axis with Lasso regression and thus we get only the important features selected.
Finally to end this meditation, let’s summarize what we have learnt so far
Cost function of Ridge and Lasso regression and importance of regularization term.Went through some examples using simple data-sets to understand Linear regression as a limiting case for both Lasso and Ridge regression.Understood why Lasso regression can lead to feature selection whereas Ridge can only shrink coefficients close to zero.
Cost function of Ridge and Lasso regression and importance of regularization term.
Went through some examples using simple data-sets to understand Linear regression as a limiting case for both Lasso and Ridge regression.
Understood why Lasso regression can lead to feature selection whereas Ridge can only shrink coefficients close to zero.
For further reading I suggest “The element of statistical learning”; J. Friedman et.al., Springer, pages- 79-91, 2008. Examples shown here to demonstrate regularization using L1 and L2 are influenced from the fantastic Machine Learning with Python book by Andreas Muller.
Hope you have enjoyed the post and stay happy ! Cheers !
P.S: Please see the comment made by Akanksha Rawat for a critical view on standardizing the variables before applying Ridge regression algorithm. | [
{
"code": null,
"e": 424,
"s": 172,
"text": "Moving on from a very important unsupervised learning technique that I have discussed last week, today we will dig deep in to supervised learning through linear regression, specifically two special linear regression model — Lasso and Ridge regression."
},
{
"code": null,
"e": 582,
"s": 424,
"text": "As I’m using the term linear, first let’s clarify that linear models are one of the simplest way to predict output using a linear function of input features."
},
{
"code": null,
"e": 932,
"s": 582,
"text": "In the equation (1.1) above, we have shown the linear model based on the n number of features. Considering only a single feature as you probably already have understood that w[0] will be slope and b will represent intercept. Linear regression looks for optimizing w and b such that it minimizes the cost function. The cost function can be written as"
},
{
"code": null,
"e": 1782,
"s": 932,
"text": "In the equation above I have assumed the data-set has M instances and p features. Once we use linear regression on a data-set divided in to training and test set, calculating the scores on training and test set can give us a rough idea about whether the model is suffering from over-fitting or under-fitting. The chosen linear model can be just right also, if you’re lucky enough! If we have very few features on a data-set and the score is poor for both training and test set then it’s a problem of under-fitting. On the other hand if we have large number of features and test score is relatively poor than the training score then it’s the problem of over-generalization or over-fitting. Ridge and Lasso regression are some of the simple techniques to reduce model complexity and prevent over-fitting which may result from simple linear regression."
},
{
"code": null,
"e": 1930,
"s": 1782,
"text": "Ridge Regression : In ridge regression, the cost function is altered by adding a penalty equivalent to square of the magnitude of the coefficients."
},
{
"code": null,
"e": 2033,
"s": 1930,
"text": "This is equivalent to saying minimizing the cost function in equation 1.2 under the condition as below"
},
{
"code": null,
"e": 2727,
"s": 2033,
"text": "So ridge regression puts constraint on the coefficients (w). The penalty term (lambda) regularizes the coefficients such that if the coefficients take large values the optimization function is penalized. So, ridge regression shrinks the coefficients and it helps to reduce the model complexity and multi-collinearity. Going back to eq. 1.3 one can see that when λ → 0 , the cost function becomes similar to the linear regression cost function (eq. 1.2). So lower the constraint (low λ) on the features, the model will resemble linear regression model. Let’s see an example using Boston house data and below is the code I used to depict linear regression as a limiting case of Ridge regression-"
},
{
"code": null,
"e": 4606,
"s": 2727,
"text": "import matplotlib.pyplot as pltimport numpy as np import pandas as pdimport matplotlibmatplotlib.rcParams.update({'font.size': 12})from sklearn.datasets import load_bostonfrom sklearn.cross_validation import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.linear_model import Ridgeboston=load_boston()boston_df=pd.DataFrame(boston.data,columns=boston.feature_names)#print boston_df.info()# add another column that contains the house prices which in scikit learn datasets are considered as targetboston_df['Price']=boston.target#print boston_df.head(3)newX=boston_df.drop('Price',axis=1)print newX[0:3] # check newY=boston_df['Price']#print type(newY)# pandas core frameX_train,X_test,y_train,y_test=train_test_split(newX,newY,test_size=0.3,random_state=3)print len(X_test), len(y_test)lr = LinearRegression()lr.fit(X_train, y_train)rr = Ridge(alpha=0.01) # higher the alpha value, more restriction on the coefficients; low alpha > more generalization,# in this case linear and ridge regression resemblesrr.fit(X_train, y_train)rr100 = Ridge(alpha=100) # comparison with alpha valuerr100.fit(X_train, y_train)train_score=lr.score(X_train, y_train)test_score=lr.score(X_test, y_test)Ridge_train_score = rr.score(X_train,y_train)Ridge_test_score = rr.score(X_test, y_test)Ridge_train_score100 = rr100.score(X_train,y_train)Ridge_test_score100 = rr100.score(X_test, y_test)plt.plot(rr.coef_,alpha=0.7,linestyle='none',marker='*',markersize=5,color='red',label=r'Ridge; $\\alpha = 0.01$',zorder=7) plt.plot(rr100.coef_,alpha=0.5,linestyle='none',marker='d',markersize=6,color='blue',label=r'Ridge; $\\alpha = 100$') plt.plot(lr.coef_,alpha=0.4,linestyle='none',marker='o',markersize=7,color='green',label='Linear Regression')plt.xlabel('Coefficient Index',fontsize=16)plt.ylabel('Coefficient Magnitude',fontsize=16)plt.legend(fontsize=13,loc=4)plt.show()"
},
{
"code": null,
"e": 5138,
"s": 4606,
"text": "Let’s understand the figure above. In X axis we plot the coefficient index and, for Boston data there are 13 features (for Python 0th index refers to 1st feature). For low value of α (0.01), when the coefficients are less restricted, the magnitudes of the coefficients are almost same as of linear regression. For higher value of α (100), we see that for coefficient indices 3,4,5 the magnitudes are considerably less compared to linear regression case. This is an example of shrinking coefficient magnitude using Ridge regression."
},
{
"code": null,
"e": 5264,
"s": 5138,
"text": "Lasso Regression : The cost function for Lasso (least absolute shrinkage and selection operator) regression can be written as"
},
{
"code": null,
"e": 6148,
"s": 5264,
"text": "Just like Ridge regression cost function, for lambda =0, the equation above reduces to equation 1.2. The only difference is instead of taking the square of the coefficients, magnitudes are taken into account. This type of regularization (L1) can lead to zero coefficients i.e. some of the features are completely neglected for the evaluation of output. So Lasso regression not only helps in reducing over-fitting but it can help us in feature selection. Just like Ridge regression the regularization parameter (lambda) can be controlled and we will see the effect below using cancer data set in sklearn. Reason I am using cancer data instead of Boston house data, that I have used before, is, cancer data-set have 30 features compared to only 13 features of Boston house data. So feature selection using Lasso regression can be depicted well by changing the regularization parameter."
},
{
"code": null,
"e": 6196,
"s": 6148,
"text": "The code I used to make these plots is as below"
},
{
"code": null,
"e": 9756,
"s": 6196,
"text": "import math import matplotlib.pyplot as plt import pandas as pdimport numpy as np# difference of lasso and ridge regression is that some of the coefficients can be zero i.e. some of the features are # completely neglectedfrom sklearn.linear_model import Lassofrom sklearn.linear_model import LinearRegressionfrom sklearn.datasets import load_breast_cancerfrom sklearn.cross_validation import train_test_splitcancer = load_breast_cancer()#print cancer.keys()cancer_df = pd.DataFrame(cancer.data, columns=cancer.feature_names)#print cancer_df.head(3)X = cancer.dataY = cancer.targetX_train,X_test,y_train,y_test=train_test_split(X,Y, test_size=0.3, random_state=31)lasso = Lasso()lasso.fit(X_train,y_train)train_score=lasso.score(X_train,y_train)test_score=lasso.score(X_test,y_test)coeff_used = np.sum(lasso.coef_!=0)print \"training score:\", train_score print \"test score: \", test_scoreprint \"number of features used: \", coeff_usedlasso001 = Lasso(alpha=0.01, max_iter=10e5)lasso001.fit(X_train,y_train)train_score001=lasso001.score(X_train,y_train)test_score001=lasso001.score(X_test,y_test)coeff_used001 = np.sum(lasso001.coef_!=0)print \"training score for alpha=0.01:\", train_score001 print \"test score for alpha =0.01: \", test_score001print \"number of features used: for alpha =0.01:\", coeff_used001lasso00001 = Lasso(alpha=0.0001, max_iter=10e5)lasso00001.fit(X_train,y_train)train_score00001=lasso00001.score(X_train,y_train)test_score00001=lasso00001.score(X_test,y_test)coeff_used00001 = np.sum(lasso00001.coef_!=0)print \"training score for alpha=0.0001:\", train_score00001 print \"test score for alpha =0.0001: \", test_score00001print \"number of features used: for alpha =0.0001:\", coeff_used00001lr = LinearRegression()lr.fit(X_train,y_train)lr_train_score=lr.score(X_train,y_train)lr_test_score=lr.score(X_test,y_test)print \"LR training score:\", lr_train_score print \"LR test score: \", lr_test_scoreplt.subplot(1,2,1)plt.plot(lasso.coef_,alpha=0.7,linestyle='none',marker='*',markersize=5,color='red',label=r'Lasso; $\\alpha = 1$',zorder=7) # alpha here is for transparencyplt.plot(lasso001.coef_,alpha=0.5,linestyle='none',marker='d',markersize=6,color='blue',label=r'Lasso; $\\alpha = 0.01$') # alpha here is for transparencyplt.xlabel('Coefficient Index',fontsize=16)plt.ylabel('Coefficient Magnitude',fontsize=16)plt.legend(fontsize=13,loc=4)plt.subplot(1,2,2)plt.plot(lasso.coef_,alpha=0.7,linestyle='none',marker='*',markersize=5,color='red',label=r'Lasso; $\\alpha = 1$',zorder=7) # alpha here is for transparencyplt.plot(lasso001.coef_,alpha=0.5,linestyle='none',marker='d',markersize=6,color='blue',label=r'Lasso; $\\alpha = 0.01$') # alpha here is for transparencyplt.plot(lasso00001.coef_,alpha=0.8,linestyle='none',marker='v',markersize=6,color='black',label=r'Lasso; $\\alpha = 0.00001$') # alpha here is for transparencyplt.plot(lr.coef_,alpha=0.7,linestyle='none',marker='o',markersize=5,color='green',label='Linear Regression',zorder=2)plt.xlabel('Coefficient Index',fontsize=16)plt.ylabel('Coefficient Magnitude',fontsize=16)plt.legend(fontsize=13,loc=4)plt.tight_layout()plt.show()#output training score: 0.5600974529893081test score: 0.5832244618818156number of features used: 4training score for alpha=0.01: 0.7037865778498829test score for alpha =0.01: 0.664183157772623number of features used: for alpha =0.01: 10training score for alpha=0.0001: 0.7754092006936697test score for alpha =0.0001: 0.7318608210757904number of features used: for alpha =0.0001: 22LR training score: 0.7842206194055068LR test score: 0.7329325010888681"
},
{
"code": null,
"e": 9815,
"s": 9756,
"text": "Let’s understand the plot and the code in a short summary."
},
{
"code": null,
"e": 9900,
"s": 9815,
"text": "The default value of regularization parameter in Lasso regression (given by α) is 1."
},
{
"code": null,
"e": 10012,
"s": 9900,
"text": "With this, out of 30 features in cancer data-set, only 4 features are used (non zero value of the coefficient)."
},
{
"code": null,
"e": 10135,
"s": 10012,
"text": "Both training and test score (with only 4 features) are low; conclude that the model is under-fitting the cancer data-set."
},
{
"code": null,
"e": 10288,
"s": 10135,
"text": "Reduce this under-fitting by reducing alpha and increasing number of iterations. Now α = 0.01, non-zero features =10, training and test score increases."
},
{
"code": null,
"e": 10512,
"s": 10288,
"text": "Comparison of coefficient magnitude for two different values of alpha are shown in the left panel of figure 2. For alpha =1, we can see most of the coefficients are zero or nearly zero, which is not the case for alpha=0.01."
},
{
"code": null,
"e": 10632,
"s": 10512,
"text": "Further reduce α =0.0001, non-zero features = 22. Training and test scores are similar to basic linear regression case."
},
{
"code": null,
"e": 10758,
"s": 10632,
"text": "In the right panel of figure, for α = 0.0001, coefficients for Lasso regression and linear regression show close resemblance."
},
{
"code": null,
"e": 11324,
"s": 10758,
"text": "So far we have gone through the basics of Ridge and Lasso regression and seen some examples to understand the applications. Now, I will try to explain why the Lasso regression can result in feature selection and Ridge regression only reduces the coefficients close to zero, but not zero. An illustrative figure below will help us to understand better, where we will assume a hypothetical data-set with only two features. Using the constrain for the coefficients of Ridge and Lasso regression (as shown above in the supplements 1 and 2), we can plot the figure below"
},
{
"code": null,
"e": 12243,
"s": 11324,
"text": "For a two dimensional feature space, the constraint regions (see supplement 1 and 2) are plotted for Lasso and Ridge regression with cyan and green colours. The elliptical contours are the cost function of linear regression (eq. 1.2). Now if we have relaxed conditions on the coefficients, then the constrained regions can get bigger and eventually they will hit the centre of the ellipse. This is the case when Ridge and Lasso regression resembles linear regression results. Otherwise, both methods determine coefficients by finding the first point where the elliptical contours hit the region of constraints. The diamond (Lasso) has corners on the axes, unlike the disk, and whenever the elliptical region hits such point, one of the features completely vanishes! For higher dimensional feature space there can be many solutions on the axis with Lasso regression and thus we get only the important features selected."
},
{
"code": null,
"e": 12318,
"s": 12243,
"text": "Finally to end this meditation, let’s summarize what we have learnt so far"
},
{
"code": null,
"e": 12657,
"s": 12318,
"text": "Cost function of Ridge and Lasso regression and importance of regularization term.Went through some examples using simple data-sets to understand Linear regression as a limiting case for both Lasso and Ridge regression.Understood why Lasso regression can lead to feature selection whereas Ridge can only shrink coefficients close to zero."
},
{
"code": null,
"e": 12740,
"s": 12657,
"text": "Cost function of Ridge and Lasso regression and importance of regularization term."
},
{
"code": null,
"e": 12878,
"s": 12740,
"text": "Went through some examples using simple data-sets to understand Linear regression as a limiting case for both Lasso and Ridge regression."
},
{
"code": null,
"e": 12998,
"s": 12878,
"text": "Understood why Lasso regression can lead to feature selection whereas Ridge can only shrink coefficients close to zero."
},
{
"code": null,
"e": 13270,
"s": 12998,
"text": "For further reading I suggest “The element of statistical learning”; J. Friedman et.al., Springer, pages- 79-91, 2008. Examples shown here to demonstrate regularization using L1 and L2 are influenced from the fantastic Machine Learning with Python book by Andreas Muller."
},
{
"code": null,
"e": 13327,
"s": 13270,
"text": "Hope you have enjoyed the post and stay happy ! Cheers !"
}
] |
Selenium Webdriver - Explicit and Implicit Wait | Let us understand what an explicit wait in the Selenium Webdriver is.
An explicit wait is applied to instruct the webdriver to wait for a specific condition before moving to the other steps in the automation script.
Explicit wait is implemented using the WebDriverWait class along with expected_conditions. The expected_conditions class has a group of pre-built conditions to be used along with the WebDriverWait class.
The pre-built conditions which are to be used along with the WebDriverWait class are given below −
alert_is_present
alert_is_present
element_selection_state_to_be
element_selection_state_to_be
presence_of_all_elements_located
presence_of_all_elements_located
element_located_to_be_selected
element_located_to_be_selected
text_to_be_present_in_element
text_to_be_present_in_element
text_to_be_present_in_element_value
text_to_be_present_in_element_value
frame_to_be_available_and_switch_to_it
frame_to_be_available_and_switch_to_it
element_located_to_be_selected
element_located_to_be_selected
visibility_of_element_located
visibility_of_element_located
presence_of_element_located
presence_of_element_located
title_is
title_is
title_contains
title_contains
visibility_of
visibility_of
staleness_of
staleness_of
element_to_be_clickable
element_to_be_clickable
invisibility_of_element_located
invisibility_of_element_located
element_to_be_selected
element_to_be_selected
Let us wait for the text - Team @ Tutorials Point which becomes available on clicking the link - Team on the page.
On clicking the Team link, the text Team @ Tutorials Point appears.
The code implementation for the explicit wait is as follows −
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#url launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify element
l = driver.find_element_by_link_text('Team')
l.click()
#expected condition for explicit wait
w = WebDriverWait(driver, 5)
w.until(EC.presence_of_element_located((By.TAG_NAME, 'h1')))
s = driver.find_element_by_tag_name('h1')
#obtain text
t = s.text
print('Text is: ' + t)
#driver quit
driver.quit()
The output is mentioned below −
The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the text (obtained from the text method) - Team @ Tutorials Point gets printed in the console.
An implicit wait is applied to instruct the webdriver for polling the DOM (Document Object Model) for a specific amount of time while making an attempt to identify an element which is currently unavailable.
The default value of the implicit wait time is 0. Once a wait time is set, it remains applicable through the entire life of the webdriver object. If an implicit wait is not set and an element is still not present in DOM, an exception is thrown.
The syntax for the implicit wait is as follows −
driver.implicitly_wait(5)
Here, a wait time of five seconds is applied to the webdriver object.
The code implementation for the implicit wait is as follows −
from selenium import webdriver
#set path of chromedriver.exe
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait of 0.5s
driver.implicitly_wait(0.5)
#url launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify link with link text
l = driver.find_element_by_link_text('FAQ')
#perform click
l.click()
print('Page navigated after click: ' + driver.title)
#driver quit
driver.quit()
The output is mentioned below −
The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. On clicking on the FAQ link, the webdriver waits for 0.5 seconds and then moves to the next step. Also, the title of the next page(obtained from the driver.title method) - Frequently Asked Questions - Tutorialspoint gets printed in the console.
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2273,
"s": 2203,
"text": "Let us understand what an explicit wait in the Selenium Webdriver is."
},
{
"code": null,
"e": 2419,
"s": 2273,
"text": "An explicit wait is applied to instruct the webdriver to wait for a specific condition before moving to the other steps in the automation script."
},
{
"code": null,
"e": 2623,
"s": 2419,
"text": "Explicit wait is implemented using the WebDriverWait class along with expected_conditions. The expected_conditions class has a group of pre-built conditions to be used along with the WebDriverWait class."
},
{
"code": null,
"e": 2722,
"s": 2623,
"text": "The pre-built conditions which are to be used along with the WebDriverWait class are given below −"
},
{
"code": null,
"e": 2739,
"s": 2722,
"text": "alert_is_present"
},
{
"code": null,
"e": 2756,
"s": 2739,
"text": "alert_is_present"
},
{
"code": null,
"e": 2786,
"s": 2756,
"text": "element_selection_state_to_be"
},
{
"code": null,
"e": 2816,
"s": 2786,
"text": "element_selection_state_to_be"
},
{
"code": null,
"e": 2849,
"s": 2816,
"text": "presence_of_all_elements_located"
},
{
"code": null,
"e": 2882,
"s": 2849,
"text": "presence_of_all_elements_located"
},
{
"code": null,
"e": 2913,
"s": 2882,
"text": "element_located_to_be_selected"
},
{
"code": null,
"e": 2944,
"s": 2913,
"text": "element_located_to_be_selected"
},
{
"code": null,
"e": 2974,
"s": 2944,
"text": "text_to_be_present_in_element"
},
{
"code": null,
"e": 3004,
"s": 2974,
"text": "text_to_be_present_in_element"
},
{
"code": null,
"e": 3040,
"s": 3004,
"text": "text_to_be_present_in_element_value"
},
{
"code": null,
"e": 3076,
"s": 3040,
"text": "text_to_be_present_in_element_value"
},
{
"code": null,
"e": 3115,
"s": 3076,
"text": "frame_to_be_available_and_switch_to_it"
},
{
"code": null,
"e": 3154,
"s": 3115,
"text": "frame_to_be_available_and_switch_to_it"
},
{
"code": null,
"e": 3185,
"s": 3154,
"text": "element_located_to_be_selected"
},
{
"code": null,
"e": 3216,
"s": 3185,
"text": "element_located_to_be_selected"
},
{
"code": null,
"e": 3246,
"s": 3216,
"text": "visibility_of_element_located"
},
{
"code": null,
"e": 3276,
"s": 3246,
"text": "visibility_of_element_located"
},
{
"code": null,
"e": 3304,
"s": 3276,
"text": "presence_of_element_located"
},
{
"code": null,
"e": 3332,
"s": 3304,
"text": "presence_of_element_located"
},
{
"code": null,
"e": 3341,
"s": 3332,
"text": "title_is"
},
{
"code": null,
"e": 3350,
"s": 3341,
"text": "title_is"
},
{
"code": null,
"e": 3365,
"s": 3350,
"text": "title_contains"
},
{
"code": null,
"e": 3380,
"s": 3365,
"text": "title_contains"
},
{
"code": null,
"e": 3394,
"s": 3380,
"text": "visibility_of"
},
{
"code": null,
"e": 3408,
"s": 3394,
"text": "visibility_of"
},
{
"code": null,
"e": 3421,
"s": 3408,
"text": "staleness_of"
},
{
"code": null,
"e": 3434,
"s": 3421,
"text": "staleness_of"
},
{
"code": null,
"e": 3458,
"s": 3434,
"text": "element_to_be_clickable"
},
{
"code": null,
"e": 3482,
"s": 3458,
"text": "element_to_be_clickable"
},
{
"code": null,
"e": 3514,
"s": 3482,
"text": "invisibility_of_element_located"
},
{
"code": null,
"e": 3546,
"s": 3514,
"text": "invisibility_of_element_located"
},
{
"code": null,
"e": 3569,
"s": 3546,
"text": "element_to_be_selected"
},
{
"code": null,
"e": 3592,
"s": 3569,
"text": "element_to_be_selected"
},
{
"code": null,
"e": 3707,
"s": 3592,
"text": "Let us wait for the text - Team @ Tutorials Point which becomes available on clicking the link - Team on the page."
},
{
"code": null,
"e": 3775,
"s": 3707,
"text": "On clicking the Team link, the text Team @ Tutorials Point appears."
},
{
"code": null,
"e": 3837,
"s": 3775,
"text": "The code implementation for the explicit wait is as follows −"
},
{
"code": null,
"e": 4502,
"s": 3837,
"text": "from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify element\nl = driver.find_element_by_link_text('Team')\nl.click()\n#expected condition for explicit wait\nw = WebDriverWait(driver, 5)\nw.until(EC.presence_of_element_located((By.TAG_NAME, 'h1')))\ns = driver.find_element_by_tag_name('h1')\n#obtain text\nt = s.text\nprint('Text is: ' + t)\n#driver quit\ndriver.quit()"
},
{
"code": null,
"e": 4534,
"s": 4502,
"text": "The output is mentioned below −"
},
{
"code": null,
"e": 4749,
"s": 4534,
"text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the text (obtained from the text method) - Team @ Tutorials Point gets printed in the console."
},
{
"code": null,
"e": 4956,
"s": 4749,
"text": "An implicit wait is applied to instruct the webdriver for polling the DOM (Document Object Model) for a specific amount of time while making an attempt to identify an element which is currently unavailable."
},
{
"code": null,
"e": 5201,
"s": 4956,
"text": "The default value of the implicit wait time is 0. Once a wait time is set, it remains applicable through the entire life of the webdriver object. If an implicit wait is not set and an element is still not present in DOM, an exception is thrown."
},
{
"code": null,
"e": 5250,
"s": 5201,
"text": "The syntax for the implicit wait is as follows −"
},
{
"code": null,
"e": 5277,
"s": 5250,
"text": "driver.implicitly_wait(5)\n"
},
{
"code": null,
"e": 5347,
"s": 5277,
"text": "Here, a wait time of five seconds is applied to the webdriver object."
},
{
"code": null,
"e": 5409,
"s": 5347,
"text": "The code implementation for the implicit wait is as follows −"
},
{
"code": null,
"e": 5850,
"s": 5409,
"text": "from selenium import webdriver\n#set path of chromedriver.exe\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait of 0.5s\ndriver.implicitly_wait(0.5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify link with link text\nl = driver.find_element_by_link_text('FAQ')\n#perform click\nl.click()\nprint('Page navigated after click: ' + driver.title)\n#driver quit\ndriver.quit()"
},
{
"code": null,
"e": 5882,
"s": 5850,
"text": "The output is mentioned below −"
},
{
"code": null,
"e": 6241,
"s": 5882,
"text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. On clicking on the FAQ link, the webdriver waits for 0.5 seconds and then moves to the next step. Also, the title of the next page(obtained from the driver.title method) - Frequently Asked Questions - Tutorialspoint gets printed in the console."
},
{
"code": null,
"e": 6276,
"s": 6241,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6288,
"s": 6276,
"text": " Aditya Dua"
},
{
"code": null,
"e": 6324,
"s": 6288,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 6338,
"s": 6324,
"text": " Arun Motoori"
},
{
"code": null,
"e": 6375,
"s": 6338,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 6397,
"s": 6375,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6430,
"s": 6397,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6444,
"s": 6430,
"text": " Arun Motoori"
},
{
"code": null,
"e": 6479,
"s": 6444,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 6493,
"s": 6479,
"text": " Arun Motoori"
},
{
"code": null,
"e": 6530,
"s": 6493,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 6544,
"s": 6530,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6551,
"s": 6544,
"text": " Print"
},
{
"code": null,
"e": 6562,
"s": 6551,
"text": " Add Notes"
}
] |
C++ Program that will fill whole memory - GeeksforGeeks | 15 Aug, 2017
NOTE:We strongly recommend to try this code in virtual machine because it may hang your computer within 5 second
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer. Dynamically allocated memory is allocated on Heap and non-static and local variables get memory allocated on Stack
new KeywordThe new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
Syntax to use new operator: To allocate memory of any data type, the syntax is
pointer-variable = new data-type;
delete Keyworddelete that perform the task of allocating and freeing the memory in a better and easier way.
Syntax to use delete operator: To allocate memory of any data type, the syntax is
delete pointer-variable;
Following is C++ Program that will fill whole memory
#include<bits/stdc++.h> int main(){ while (true) int *a = new int; // allocating }
Output & ExplanationIt hung my computer while the task manager was open and showed that it took 890 Mb of memory in 1 second then it also hung. It keeps on giving memory to a variable.To explore more of this code, added a statement delete a and every thing was fine while testing (no hanging) So, I think that the chunk of memory is given (due to new int) and then taken back (due to delete a) to the free space in the new code below.
Mitigated Code
#include<bits/stdc++.h>int main(){ while (true) { int *a = new int; // allocating delete a; // deallocating }}
Referenceshttps://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-memory
This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Bitwise Operators in C/C++
Operator Overloading in C++
Constructors in C++
Socket Programming in C/C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
Copy Constructor in C++ | [
{
"code": null,
"e": 24419,
"s": 24391,
"text": "\n15 Aug, 2017"
},
{
"code": null,
"e": 24532,
"s": 24419,
"text": "NOTE:We strongly recommend to try this code in virtual machine because it may hang your computer within 5 second"
},
{
"code": null,
"e": 24745,
"s": 24532,
"text": "Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer. Dynamically allocated memory is allocated on Heap and non-static and local variables get memory allocated on Stack"
},
{
"code": null,
"e": 24992,
"s": 24745,
"text": "new KeywordThe new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable."
},
{
"code": null,
"e": 25071,
"s": 24992,
"text": "Syntax to use new operator: To allocate memory of any data type, the syntax is"
},
{
"code": null,
"e": 25106,
"s": 25071,
"text": "pointer-variable = new data-type;\n"
},
{
"code": null,
"e": 25214,
"s": 25106,
"text": "delete Keyworddelete that perform the task of allocating and freeing the memory in a better and easier way."
},
{
"code": null,
"e": 25296,
"s": 25214,
"text": "Syntax to use delete operator: To allocate memory of any data type, the syntax is"
},
{
"code": null,
"e": 25323,
"s": 25296,
"text": "delete pointer-variable; \n"
},
{
"code": null,
"e": 25376,
"s": 25323,
"text": "Following is C++ Program that will fill whole memory"
},
{
"code": "#include<bits/stdc++.h> int main(){ while (true) int *a = new int; // allocating } ",
"e": 25471,
"s": 25376,
"text": null
},
{
"code": null,
"e": 25906,
"s": 25471,
"text": "Output & ExplanationIt hung my computer while the task manager was open and showed that it took 890 Mb of memory in 1 second then it also hung. It keeps on giving memory to a variable.To explore more of this code, added a statement delete a and every thing was fine while testing (no hanging) So, I think that the chunk of memory is given (due to new int) and then taken back (due to delete a) to the free space in the new code below."
},
{
"code": null,
"e": 25921,
"s": 25906,
"text": "Mitigated Code"
},
{
"code": "#include<bits/stdc++.h>int main(){ while (true) { int *a = new int; // allocating delete a; // deallocating }} ",
"e": 26071,
"s": 25921,
"text": null
},
{
"code": null,
"e": 26162,
"s": 26071,
"text": "Referenceshttps://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-memory"
},
{
"code": null,
"e": 26462,
"s": 26162,
"text": "This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 26587,
"s": 26462,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26591,
"s": 26587,
"text": "C++"
},
{
"code": null,
"e": 26595,
"s": 26591,
"text": "CPP"
},
{
"code": null,
"e": 26693,
"s": 26595,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26712,
"s": 26693,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 26755,
"s": 26712,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26779,
"s": 26755,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26806,
"s": 26779,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 26834,
"s": 26806,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26854,
"s": 26834,
"text": "Constructors in C++"
},
{
"code": null,
"e": 26882,
"s": 26854,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26917,
"s": 26882,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26948,
"s": 26917,
"text": "Templates in C++ with Examples"
}
] |
Ruby | Matrix inverse() function - GeeksforGeeks | 07 Jan, 2020
The inverse() is an inbuilt method in Ruby returns the inverse of the given matrix.
Syntax: mat1.inverse()
Parameters: The function does not takes any parameter.
Return Value: It returns the inverse of a matrix.
Example 1:
#Ruby program for inverse() method in Matrix #Include matrixrequire "matrix" #Initialize a matrix mat1 = Matrix[[ Complex(1, 2), 21 ], [ 31, Complex(9, 12) ]] #prints the inverse matrix puts mat1.inverse()
Output:
Matrix[[-313/24692-459/24692i, 777/24692+35/24692i], [1147/24692+155/74076i, -101/74076-227/74076i]]
Example 2:
#Ruby program for inverse() method in Matrix #Include matrixrequire "matrix" #Initialize a matrix mat1 = Matrix[[ 1, -8 ], [ -2, -8 ]] #prints the inverse matrix puts mat1.inverse()
Output:
Matrix[[1/3, -1/3], [-1/12, -1/24]]
Ruby Matrix-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Include v/s Extend in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement
Ruby | Numeric round() function | [
{
"code": null,
"e": 23209,
"s": 23181,
"text": "\n07 Jan, 2020"
},
{
"code": null,
"e": 23293,
"s": 23209,
"text": "The inverse() is an inbuilt method in Ruby returns the inverse of the given matrix."
},
{
"code": null,
"e": 23316,
"s": 23293,
"text": "Syntax: mat1.inverse()"
},
{
"code": null,
"e": 23371,
"s": 23316,
"text": "Parameters: The function does not takes any parameter."
},
{
"code": null,
"e": 23421,
"s": 23371,
"text": "Return Value: It returns the inverse of a matrix."
},
{
"code": null,
"e": 23432,
"s": 23421,
"text": "Example 1:"
},
{
"code": "#Ruby program for inverse() method in Matrix #Include matrixrequire \"matrix\" #Initialize a matrix mat1 = Matrix[[ Complex(1, 2), 21 ], [ 31, Complex(9, 12) ]] #prints the inverse matrix puts mat1.inverse()",
"e": 23652,
"s": 23432,
"text": null
},
{
"code": null,
"e": 23660,
"s": 23652,
"text": "Output:"
},
{
"code": null,
"e": 23762,
"s": 23660,
"text": "Matrix[[-313/24692-459/24692i, 777/24692+35/24692i], [1147/24692+155/74076i, -101/74076-227/74076i]]\n"
},
{
"code": null,
"e": 23773,
"s": 23762,
"text": "Example 2:"
},
{
"code": "#Ruby program for inverse() method in Matrix #Include matrixrequire \"matrix\" #Initialize a matrix mat1 = Matrix[[ 1, -8 ], [ -2, -8 ]] #prints the inverse matrix puts mat1.inverse()",
"e": 23969,
"s": 23773,
"text": null
},
{
"code": null,
"e": 23977,
"s": 23969,
"text": "Output:"
},
{
"code": null,
"e": 24013,
"s": 23977,
"text": "Matrix[[1/3, -1/3], [-1/12, -1/24]]"
},
{
"code": null,
"e": 24031,
"s": 24013,
"text": "Ruby Matrix-class"
},
{
"code": null,
"e": 24044,
"s": 24031,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 24049,
"s": 24044,
"text": "Ruby"
},
{
"code": null,
"e": 24147,
"s": 24049,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24156,
"s": 24147,
"text": "Comments"
},
{
"code": null,
"e": 24169,
"s": 24156,
"text": "Old Comments"
},
{
"code": null,
"e": 24196,
"s": 24169,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 24239,
"s": 24196,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 24270,
"s": 24239,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 24294,
"s": 24270,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 24324,
"s": 24294,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 24351,
"s": 24324,
"text": "Ruby | String gsub! Method"
},
{
"code": null,
"e": 24385,
"s": 24351,
"text": "Ruby | String capitalize() Method"
},
{
"code": null,
"e": 24431,
"s": 24385,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 24453,
"s": 24431,
"text": "Ruby | Case Statement"
}
] |
Express.js app.locals Property - GeeksforGeeks | 09 Jul, 2020
The app.locals object has properties that are local variables within the application. These variables are local to the application and are very useful.
Syntax:
app.locals
Parameter: No parameters.
Return Value: Object
Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install express module. You can install this package by using this command.npm install express
npm install express
After installing the express module, you can check your express version in command prompt using the command.npm version express
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Example 1: Filename: index.js
var express = require('express');var app = express(); // Setting single locals variableapp.locals.email = '[email protected]' console.log(app.locals.email);
Steps to run the program:
The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:[email protected]
The project structure will look like this:
Make sure you have installed express module using the following command:npm install express
npm install express
Run index.js file using below command:node index.jsOutput:[email protected]
node index.js
Output:
[email protected]
Example 2: Filename: index.js
var express = require('express');var app = express(); // Setting multiple locals variableapp.locals.domain = 'www.sample.com' app.locals.age = '24' app.locals.company = 'ABC Ltd' console.log(app.locals);
Run index.js file using below command:
node index.js
Output:
[Object: null prototype] {
settings: {
'x-powered-by': true,
etag: 'weak',
'etag fn': [Function: generateETag],
env: 'development',
'query parser': 'extended',
'query parser fn': [Function: parseExtendedQueryString],
'subdomain offset': 2,
'trust proxy': false,
'trust proxy fn': [Function: trustNone],
view: [Function: View],
views: 'C:\\Users\\Lenovo\\Downloads\\GFG
Reviewer Internship\\Program\\views',
'jsonp callback name': 'callback'
},
domain: 'www.sample.com',
age: '24',
company: 'ABC Ltd'
}
Reference: https://expressjs.com/en/4x/api.html#app.locals
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
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": 29199,
"s": 29171,
"text": "\n09 Jul, 2020"
},
{
"code": null,
"e": 29351,
"s": 29199,
"text": "The app.locals object has properties that are local variables within the application. These variables are local to the application and are very useful."
},
{
"code": null,
"e": 29359,
"s": 29351,
"text": "Syntax:"
},
{
"code": null,
"e": 29370,
"s": 29359,
"text": "app.locals"
},
{
"code": null,
"e": 29396,
"s": 29370,
"text": "Parameter: No parameters."
},
{
"code": null,
"e": 29417,
"s": 29396,
"text": "Return Value: Object"
},
{
"code": null,
"e": 29449,
"s": 29417,
"text": "Installation of express module:"
},
{
"code": null,
"e": 29844,
"s": 29449,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 29965,
"s": 29844,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install express"
},
{
"code": null,
"e": 29985,
"s": 29965,
"text": "npm install express"
},
{
"code": null,
"e": 30113,
"s": 29985,
"text": "After installing the express module, you can check your express version in command prompt using the command.npm version express"
},
{
"code": null,
"e": 30133,
"s": 30113,
"text": "npm version express"
},
{
"code": null,
"e": 30281,
"s": 30133,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 30295,
"s": 30281,
"text": "node index.js"
},
{
"code": null,
"e": 30325,
"s": 30295,
"text": "Example 1: Filename: index.js"
},
{
"code": "var express = require('express');var app = express(); // Setting single locals variableapp.locals.email = '[email protected]' console.log(app.locals.email);",
"e": 30482,
"s": 30325,
"text": null
},
{
"code": null,
"e": 30508,
"s": 30482,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 30715,
"s": 30508,
"text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:[email protected]\n"
},
{
"code": null,
"e": 30758,
"s": 30715,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 30850,
"s": 30758,
"text": "Make sure you have installed express module using the following command:npm install express"
},
{
"code": null,
"e": 30870,
"s": 30850,
"text": "npm install express"
},
{
"code": null,
"e": 30944,
"s": 30870,
"text": "Run index.js file using below command:node index.jsOutput:[email protected]\n"
},
{
"code": null,
"e": 30958,
"s": 30944,
"text": "node index.js"
},
{
"code": null,
"e": 30966,
"s": 30958,
"text": "Output:"
},
{
"code": null,
"e": 30982,
"s": 30966,
"text": "[email protected]\n"
},
{
"code": null,
"e": 31012,
"s": 30982,
"text": "Example 2: Filename: index.js"
},
{
"code": "var express = require('express');var app = express(); // Setting multiple locals variableapp.locals.domain = 'www.sample.com' app.locals.age = '24' app.locals.company = 'ABC Ltd' console.log(app.locals);",
"e": 31219,
"s": 31012,
"text": null
},
{
"code": null,
"e": 31258,
"s": 31219,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 31272,
"s": 31258,
"text": "node index.js"
},
{
"code": null,
"e": 31280,
"s": 31272,
"text": "Output:"
},
{
"code": null,
"e": 31849,
"s": 31280,
"text": "[Object: null prototype] {\n settings: {\n 'x-powered-by': true, \n etag: 'weak',\n 'etag fn': [Function: generateETag],\n env: 'development',\n 'query parser': 'extended',\n 'query parser fn': [Function: parseExtendedQueryString],\n 'subdomain offset': 2,\n 'trust proxy': false,\n 'trust proxy fn': [Function: trustNone],\n view: [Function: View],\n views: 'C:\\\\Users\\\\Lenovo\\\\Downloads\\\\GFG \n Reviewer Internship\\\\Program\\\\views',\n 'jsonp callback name': 'callback'\n },\n domain: 'www.sample.com',\n age: '24',\n company: 'ABC Ltd'\n}\n"
},
{
"code": null,
"e": 31908,
"s": 31849,
"text": "Reference: https://expressjs.com/en/4x/api.html#app.locals"
},
{
"code": null,
"e": 31919,
"s": 31908,
"text": "Express.js"
},
{
"code": null,
"e": 31927,
"s": 31919,
"text": "Node.js"
},
{
"code": null,
"e": 31944,
"s": 31927,
"text": "Web Technologies"
},
{
"code": null,
"e": 32042,
"s": 31944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32051,
"s": 32042,
"text": "Comments"
},
{
"code": null,
"e": 32064,
"s": 32051,
"text": "Old Comments"
},
{
"code": null,
"e": 32097,
"s": 32064,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32145,
"s": 32097,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 32178,
"s": 32145,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 32207,
"s": 32178,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 32227,
"s": 32207,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 32283,
"s": 32227,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 32316,
"s": 32283,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32378,
"s": 32316,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32421,
"s": 32378,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
C++ Vector Library - end() Function | The C++ function std::vector::end() returns an iterator which points to past-the-end element in the vector container.
The past-the-end element is the theoretical element that would follow the last element in the vector.
Following is the declaration for std::vector::end() function form std::vector header.
iterator end();
const_iterator end() const;
iterator end() noexcept;
const_iterator end() const noexcept;
None
Returns an iterator which points to past-the-end element in the vector.
If vector object is constant qualified method returns constant random access iterator otherwise non-constatnt random access iterator.
This member function never throws an exception.
Constant i.e. O(1)
The following example shows the usage of std::vector::end() function.
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> v = {1, 2, 3, 4, 5};
for (auto it = v.begin(); it != v.end(); ++it)
cout << *it << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
1
2
3
4
5
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2721,
"s": 2603,
"text": "The C++ function std::vector::end() returns an iterator which points to past-the-end element in the vector container."
},
{
"code": null,
"e": 2823,
"s": 2721,
"text": "The past-the-end element is the theoretical element that would follow the last element in the vector."
},
{
"code": null,
"e": 2909,
"s": 2823,
"text": "Following is the declaration for std::vector::end() function form std::vector header."
},
{
"code": null,
"e": 2954,
"s": 2909,
"text": "iterator end();\nconst_iterator end() const;\n"
},
{
"code": null,
"e": 3017,
"s": 2954,
"text": "iterator end() noexcept;\nconst_iterator end() const noexcept;\n"
},
{
"code": null,
"e": 3022,
"s": 3017,
"text": "None"
},
{
"code": null,
"e": 3094,
"s": 3022,
"text": "Returns an iterator which points to past-the-end element in the vector."
},
{
"code": null,
"e": 3228,
"s": 3094,
"text": "If vector object is constant qualified method returns constant random access iterator otherwise non-constatnt random access iterator."
},
{
"code": null,
"e": 3276,
"s": 3228,
"text": "This member function never throws an exception."
},
{
"code": null,
"e": 3295,
"s": 3276,
"text": "Constant i.e. O(1)"
},
{
"code": null,
"e": 3365,
"s": 3295,
"text": "The following example shows the usage of std::vector::end() function."
},
{
"code": null,
"e": 3573,
"s": 3365,
"text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v = {1, 2, 3, 4, 5};\n\n for (auto it = v.begin(); it != v.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 3656,
"s": 3573,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3667,
"s": 3656,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 3674,
"s": 3667,
"text": " Print"
},
{
"code": null,
"e": 3685,
"s": 3674,
"text": " Add Notes"
}
] |
MongoDB - Regular Expression | Regular Expressions are frequently used in all languages to search for a pattern or word in any string. MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language.
Unlike text search, we do not need to do any configuration or command to use regular expressions.
Assume we have inserted a document in a database named posts as shown below −
> db.posts.insert(
{
"post_text": "enjoy the mongodb articles on tutorialspoint",
"tags": [
"mongodb",
"tutorialspoint"
]
}
WriteResult({ "nInserted" : 1 })
The following regex query searches for all the posts containing string tutorialspoint in it −
> db.posts.find({post_text:{$regex:"tutorialspoint"}}).pretty()
{
"_id" : ObjectId("5dd7ce28f1dd4583e7103fe0"),
"post_text" : "enjoy the mongodb articles on tutorialspoint",
"tags" : [
"mongodb",
"tutorialspoint"
]
}
{
"_id" : ObjectId("5dd7d111f1dd4583e7103fe2"),
"post_text" : "enjoy the mongodb articles on tutorialspoint",
"tags" : [
"mongodb",
"tutorialspoint"
]
}
>
The same query can also be written as −
>db.posts.find({post_text:/tutorialspoint/})
To make the search case insensitive, we use the $options parameter with value $i. The following command will look for strings having the word tutorialspoint, irrespective of smaller or capital case −
>db.posts.find({post_text:{$regex:"tutorialspoint",$options:"$i"}})
One of the results returned from this query is the following document which contains the word tutorialspoint in different cases −
{
"_id" : ObjectId("53493d37d852429c10000004"),
"post_text" : "hey! this is my post on TutorialsPoint",
"tags" : [ "tutorialspoint" ]
}
We can also use the concept of regex on array field. This is particularly very important when we implement the functionality of tags. So, if you want to search for all the posts having tags beginning from the word tutorial (either tutorial or tutorials or tutorialpoint or tutorialphp), you can use the following code −
>db.posts.find({tags:{$regex:"tutorial"}})
If the document fields are indexed, the query will use make use of indexed values to match the regular expression. This makes the search very fast as compared to the regular expression scanning the whole collection.
If the document fields are indexed, the query will use make use of indexed values to match the regular expression. This makes the search very fast as compared to the regular expression scanning the whole collection.
If the regular expression is a prefix expression, all the matches are meant to start with a certain string characters. For e.g., if the regex expression is ^tut, then the query has to search for only those strings that begin with tut.
If the regular expression is a prefix expression, all the matches are meant to start with a certain string characters. For e.g., if the regex expression is ^tut, then the query has to search for only those strings that begin with tut.
44 Lectures
3 hours
Arnab Chakraborty
54 Lectures
5.5 hours
Eduonix Learning Solutions
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
40 Lectures
2.5 hours
University Code
26 Lectures
8 hours
Bassir Jafarzadeh
70 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2857,
"s": 2553,
"text": "Regular Expressions are frequently used in all languages to search for a pattern or word in any string. MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language."
},
{
"code": null,
"e": 2955,
"s": 2857,
"text": "Unlike text search, we do not need to do any configuration or command to use regular expressions."
},
{
"code": null,
"e": 3033,
"s": 2955,
"text": "Assume we have inserted a document in a database named posts as shown below −"
},
{
"code": null,
"e": 3211,
"s": 3033,
"text": "> db.posts.insert(\n{\n \"post_text\": \"enjoy the mongodb articles on tutorialspoint\",\n \"tags\": [\n \"mongodb\",\n \"tutorialspoint\"\n ]\n}\nWriteResult({ \"nInserted\" : 1 })"
},
{
"code": null,
"e": 3305,
"s": 3211,
"text": "The following regex query searches for all the posts containing string tutorialspoint in it −"
},
{
"code": null,
"e": 3693,
"s": 3305,
"text": "> db.posts.find({post_text:{$regex:\"tutorialspoint\"}}).pretty()\n{\n\t\"_id\" : ObjectId(\"5dd7ce28f1dd4583e7103fe0\"),\n\t\"post_text\" : \"enjoy the mongodb articles on tutorialspoint\",\n\t\"tags\" : [\n\t\t\"mongodb\",\n\t\t\"tutorialspoint\"\n\t]\n}\n{\n\t\"_id\" : ObjectId(\"5dd7d111f1dd4583e7103fe2\"),\n\t\"post_text\" : \"enjoy the mongodb articles on tutorialspoint\",\n\t\"tags\" : [\n\t\t\"mongodb\",\n\t\t\"tutorialspoint\"\n\t]\n}\n>"
},
{
"code": null,
"e": 3733,
"s": 3693,
"text": "The same query can also be written as −"
},
{
"code": null,
"e": 3778,
"s": 3733,
"text": ">db.posts.find({post_text:/tutorialspoint/})"
},
{
"code": null,
"e": 3978,
"s": 3778,
"text": "To make the search case insensitive, we use the $options parameter with value $i. The following command will look for strings having the word tutorialspoint, irrespective of smaller or capital case −"
},
{
"code": null,
"e": 4046,
"s": 3978,
"text": ">db.posts.find({post_text:{$regex:\"tutorialspoint\",$options:\"$i\"}})"
},
{
"code": null,
"e": 4176,
"s": 4046,
"text": "One of the results returned from this query is the following document which contains the word tutorialspoint in different cases −"
},
{
"code": null,
"e": 4325,
"s": 4176,
"text": "{\n \"_id\" : ObjectId(\"53493d37d852429c10000004\"),\n \"post_text\" : \"hey! this is my post on TutorialsPoint\", \n \"tags\" : [ \"tutorialspoint\" ]\n} \n "
},
{
"code": null,
"e": 4645,
"s": 4325,
"text": "We can also use the concept of regex on array field. This is particularly very important when we implement the functionality of tags. So, if you want to search for all the posts having tags beginning from the word tutorial (either tutorial or tutorials or tutorialpoint or tutorialphp), you can use the following code −"
},
{
"code": null,
"e": 4688,
"s": 4645,
"text": ">db.posts.find({tags:{$regex:\"tutorial\"}})"
},
{
"code": null,
"e": 4904,
"s": 4688,
"text": "If the document fields are indexed, the query will use make use of indexed values to match the regular expression. This makes the search very fast as compared to the regular expression scanning the whole collection."
},
{
"code": null,
"e": 5120,
"s": 4904,
"text": "If the document fields are indexed, the query will use make use of indexed values to match the regular expression. This makes the search very fast as compared to the regular expression scanning the whole collection."
},
{
"code": null,
"e": 5355,
"s": 5120,
"text": "If the regular expression is a prefix expression, all the matches are meant to start with a certain string characters. For e.g., if the regex expression is ^tut, then the query has to search for only those strings that begin with tut."
},
{
"code": null,
"e": 5590,
"s": 5355,
"text": "If the regular expression is a prefix expression, all the matches are meant to start with a certain string characters. For e.g., if the regex expression is ^tut, then the query has to search for only those strings that begin with tut."
},
{
"code": null,
"e": 5623,
"s": 5590,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5642,
"s": 5623,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5677,
"s": 5642,
"text": "\n 54 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5705,
"s": 5677,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5740,
"s": 5705,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5763,
"s": 5740,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 5798,
"s": 5763,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5815,
"s": 5798,
"text": " University Code"
},
{
"code": null,
"e": 5848,
"s": 5815,
"text": "\n 26 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5867,
"s": 5848,
"text": " Bassir Jafarzadeh"
},
{
"code": null,
"e": 5902,
"s": 5867,
"text": "\n 70 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5922,
"s": 5902,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5929,
"s": 5922,
"text": " Print"
},
{
"code": null,
"e": 5940,
"s": 5929,
"text": " Add Notes"
}
] |
Interthread Communication | If you are aware of interprocess communication then it will be easy for you to understand interthread communication. Interthread communication is important when you develop an application where two or more threads exchange some information.
There are three simple methods and a little trick which makes thread communication possible. All the three methods are listed below −
public void wait()
Causes the current thread to wait until another thread invokes the notify().
public void notify()
Wakes up a single thread that is waiting on this object's monitor.
public void notifyAll()
Wakes up all the threads that called wait( ) on the same object.
These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context.
This examples shows how two threads can communicate using wait() and notify() method. You can create a complex system using the same concept.
class Chat {
boolean flag = false;
public synchronized void Question(String msg) {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(msg);
flag = true;
notify();
}
public synchronized void Answer(String msg) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(msg);
flag = false;
notify();
}
}
class T1 implements Runnable {
Chat m;
String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };
public T1(Chat m1) {
this.m = m1;
new Thread(this, "Question").start();
}
public void run() {
for (int i = 0; i < s1.length; i++) {
m.Question(s1[i]);
}
}
}
class T2 implements Runnable {
Chat m;
String[] s2 = { "Hi", "I am good, what about you?", "Great!" };
public T2(Chat m2) {
this.m = m2;
new Thread(this, "Answer").start();
}
public void run() {
for (int i = 0; i < s2.length; i++) {
m.Answer(s2[i]);
}
}
}
public class TestThread {
public static void main(String[] args) {
Chat m = new Chat();
new T1(m);
new T2(m);
}
}
When the above program is complied and executed, it produces the following result −
Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!
Above example has been taken and then modified from [https://stackoverflow.com/questions/2170520/inter-thread-communication-in-java]
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2898,
"s": 2657,
"text": "If you are aware of interprocess communication then it will be easy for you to understand interthread communication. Interthread communication is important when you develop an application where two or more threads exchange some information."
},
{
"code": null,
"e": 3032,
"s": 2898,
"text": "There are three simple methods and a little trick which makes thread communication possible. All the three methods are listed below −"
},
{
"code": null,
"e": 3051,
"s": 3032,
"text": "public void wait()"
},
{
"code": null,
"e": 3128,
"s": 3051,
"text": "Causes the current thread to wait until another thread invokes the notify()."
},
{
"code": null,
"e": 3149,
"s": 3128,
"text": "public void notify()"
},
{
"code": null,
"e": 3216,
"s": 3149,
"text": "Wakes up a single thread that is waiting on this object's monitor."
},
{
"code": null,
"e": 3240,
"s": 3216,
"text": "public void notifyAll()"
},
{
"code": null,
"e": 3305,
"s": 3240,
"text": "Wakes up all the threads that called wait( ) on the same object."
},
{
"code": null,
"e": 3484,
"s": 3305,
"text": "These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context."
},
{
"code": null,
"e": 3626,
"s": 3484,
"text": "This examples shows how two threads can communicate using wait() and notify() method. You can create a complex system using the same concept."
},
{
"code": null,
"e": 5003,
"s": 3626,
"text": "class Chat {\n boolean flag = false;\n\n public synchronized void Question(String msg) {\n\n if (flag) {\n \n try {\n wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n System.out.println(msg);\n flag = true;\n notify();\n }\n\n public synchronized void Answer(String msg) {\n\n if (!flag) {\n \n try {\n wait();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n System.out.println(msg);\n flag = false;\n notify();\n }\n}\n\nclass T1 implements Runnable {\n Chat m;\n String[] s1 = { \"Hi\", \"How are you ?\", \"I am also doing fine!\" };\n\n public T1(Chat m1) {\n this.m = m1;\n new Thread(this, \"Question\").start();\n }\n\n public void run() {\n \n for (int i = 0; i < s1.length; i++) {\n m.Question(s1[i]);\n }\n }\n}\n\nclass T2 implements Runnable {\n Chat m;\n String[] s2 = { \"Hi\", \"I am good, what about you?\", \"Great!\" };\n\n public T2(Chat m2) {\n this.m = m2;\n new Thread(this, \"Answer\").start();\n }\n\n public void run() {\n\n for (int i = 0; i < s2.length; i++) {\n m.Answer(s2[i]);\n }\n }\n}\n\npublic class TestThread {\n\n public static void main(String[] args) {\n Chat m = new Chat();\n new T1(m);\n new T2(m);\n }\n}"
},
{
"code": null,
"e": 5087,
"s": 5003,
"text": "When the above program is complied and executed, it produces the following result −"
},
{
"code": null,
"e": 5164,
"s": 5087,
"text": "Hi\nHi\nHow are you ?\nI am good, what about you?\nI am also doing fine!\nGreat!\n"
},
{
"code": null,
"e": 5297,
"s": 5164,
"text": "Above example has been taken and then modified from [https://stackoverflow.com/questions/2170520/inter-thread-communication-in-java]"
},
{
"code": null,
"e": 5330,
"s": 5297,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5346,
"s": 5330,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5379,
"s": 5346,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5395,
"s": 5379,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5430,
"s": 5395,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5444,
"s": 5430,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5478,
"s": 5444,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5492,
"s": 5478,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5529,
"s": 5492,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5544,
"s": 5529,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5577,
"s": 5544,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5596,
"s": 5577,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5603,
"s": 5596,
"text": " Print"
},
{
"code": null,
"e": 5614,
"s": 5603,
"text": " Add Notes"
}
] |
How to easily 'create table from view' syntax in MySQL? | You can create a table from view using create table select syntax. The syntax is as follows −
CREATE TABLE yourTableName AS SELECT
yourColumnName1,yourColumnName2,yourColumnName3,........N from yourViewName;
To run the above query, first you need to create a table and after that you need to create a view on that table. After that run the query.
First, you need to create a table. The query to create a table is as follow −
mysql> create table StuedntInformation
-> (
-> Id int,
-> Name varchar(100)
-> );
Query OK, 0 rows affected (0.54 sec)
Above, we have created a table. After that you need to create a view. The query to create a view is as follows −
mysql> CREATE VIEW view_Student AS SELECT Id,Name from StuedntInformation;
Query OK, 0 rows affected (0.11 sec)
Now I have created a view with the name ‘view_Student’. Check the view using show command.
The query is as follows −
mysql> SHOW CREATE VIEW view_Student;
+--------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
| View | Create View | character_set_client | collation_connection |
+--------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
| view_student | CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `view_student` AS select `stuedntinformation`.`Id` AS `Id`,`stuedntinformation`.`Name` AS `Name` from `stuedntinformation` | utf8 | utf8_general_ci |
+--------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
1 row in set (0.00 sec)
We will use the above view name ‘view_Student’ to create a table. The following is the query to create a table using view −
mysql> CREATE TABLE CreatingTableUsingViewStudent AS
-> select Id,Name from view_Student;
Query OK, 0 rows affected (0.50 sec)
Records: 0 Duplicates: 0 Warnings: 0
Now you can check the DDL of a table using show command. The query is as follows −
mysql> show create table CreatingTableUsingViewStudent;
+-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| CreatingTableUsingViewStudent | CREATE TABLE `creatingtableusingviewstudent` ( `Id` int(11) DEFAULT NULL, `Name` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "You can create a table from view using create table select syntax. The syntax is as follows −"
},
{
"code": null,
"e": 1270,
"s": 1156,
"text": "CREATE TABLE yourTableName AS SELECT\nyourColumnName1,yourColumnName2,yourColumnName3,........N from yourViewName;"
},
{
"code": null,
"e": 1409,
"s": 1270,
"text": "To run the above query, first you need to create a table and after that you need to create a view on that table. After that run the query."
},
{
"code": null,
"e": 1487,
"s": 1409,
"text": "First, you need to create a table. The query to create a table is as follow −"
},
{
"code": null,
"e": 1618,
"s": 1487,
"text": "mysql> create table StuedntInformation\n -> (\n -> Id int,\n -> Name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.54 sec)"
},
{
"code": null,
"e": 1731,
"s": 1618,
"text": "Above, we have created a table. After that you need to create a view. The query to create a view is as follows −"
},
{
"code": null,
"e": 1843,
"s": 1731,
"text": "mysql> CREATE VIEW view_Student AS SELECT Id,Name from StuedntInformation;\nQuery OK, 0 rows affected (0.11 sec)"
},
{
"code": null,
"e": 1934,
"s": 1843,
"text": "Now I have created a view with the name ‘view_Student’. Check the view using show command."
},
{
"code": null,
"e": 1960,
"s": 1934,
"text": "The query is as follows −"
},
{
"code": null,
"e": 1998,
"s": 1960,
"text": "mysql> SHOW CREATE VIEW view_Student;"
},
{
"code": null,
"e": 3301,
"s": 1998,
"text": "+--------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n| View | Create View | character_set_client | collation_connection |\n+--------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n| view_student | CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `view_student` AS select `stuedntinformation`.`Id` AS `Id`,`stuedntinformation`.`Name` AS `Name` from `stuedntinformation` | utf8 | utf8_general_ci |\n+--------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 3425,
"s": 3301,
"text": "We will use the above view name ‘view_Student’ to create a table. The following is the query to create a table using view −"
},
{
"code": null,
"e": 3593,
"s": 3425,
"text": "mysql> CREATE TABLE CreatingTableUsingViewStudent AS\n -> select Id,Name from view_Student;\n\nQuery OK, 0 rows affected (0.50 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 3676,
"s": 3593,
"text": "Now you can check the DDL of a table using show command. The query is as follows −"
},
{
"code": null,
"e": 3732,
"s": 3676,
"text": "mysql> show create table CreatingTableUsingViewStudent;"
},
{
"code": null,
"e": 4820,
"s": 3732,
"text": "+-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Table | Create Table |\n+-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| CreatingTableUsingViewStudent | CREATE TABLE `creatingtableusingviewstudent` ( `Id` int(11) DEFAULT NULL, `Name` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |\n+-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)"
}
] |
Send data from one Fragment to another using Kotlin? | This example demonstrates how to send data from one Fragment to another using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="8dp">
</RelativeLayout>
Step 3 − Create two FragmentActivity and add the codes which are given below.
fragmentOne.xml −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="8dp">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:hint="Enter your message"
android:textColorHint="@android:color/background_dark"
android:textSize="16sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_dark"
android:padding="10dp"
android:text="Send Message"
android:textColor="@android:color/white"
android:textStyle="bold" />
</LinearLayout>
FirstFragment.kt −
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_one.view.*
class FirstFragment : Fragment() {
private lateinit var communicator: Communicator
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_one, container, false) as ViewGroup
communicator = activity as Communicator
rootView.btnSend.setOnClickListener {
communicator.passData(rootView.editText.text.toString())
}
return rootView
}
}
fragmentTwo.xml −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/outPutTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
FragmentTwo.kt −
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_two.view.*
class FragmentTwo : Fragment() {
var inputText: String? = ""
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_two, container, false)
inputText = arguments?.getString("inputText")
rootView.outPutTextView.text = inputText
return rootView
}
}
Step 4 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentTransaction
class MainActivity : AppCompatActivity(), Communicator {
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val firstFragment = FirstFragment()
supportFragmentManager.beginTransaction().replace(R.id.relativeLayout, firstFragment)
.commit()
}
override fun passData(editTextInput: String) {
val bundle = Bundle()
bundle.putString("inputText", editTextInput)
val transaction = this.supportFragmentManager.beginTransaction()
val fragmentTwo = FragmentTwo()
fragmentTwo.arguments = bundle
transaction.replace(R.id.relativeLayout, fragmentTwo)
transaction.addToBackStack(null)
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
transaction.commit()
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.kotlipapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" /&g;
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter&g;
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "This example demonstrates how to send data from one Fragment to another using Kotlin."
},
{
"code": null,
"e": 1277,
"s": 1148,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1342,
"s": 1277,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1649,
"s": 1342,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/relativeLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"8dp\">\n</RelativeLayout>"
},
{
"code": null,
"e": 1727,
"s": 1649,
"text": "Step 3 − Create two FragmentActivity and add the codes which are given below."
},
{
"code": null,
"e": 1745,
"s": 1727,
"text": "fragmentOne.xml −"
},
{
"code": null,
"e": 2703,
"s": 1745,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n android:padding=\"8dp\">\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"50dp\"\n android:hint=\"Enter your message\"\n android:textColorHint=\"@android:color/background_dark\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/btnSend\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:background=\"@android:color/holo_blue_dark\"\n android:padding=\"10dp\"\n android:text=\"Send Message\"\n android:textColor=\"@android:color/white\"\n android:textStyle=\"bold\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2722,
"s": 2703,
"text": "FirstFragment.kt −"
},
{
"code": null,
"e": 3443,
"s": 2722,
"text": "import android.os.Bundle\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport androidx.fragment.app.Fragment\nimport kotlinx.android.synthetic.main.fragment_one.view.*\nclass FirstFragment : Fragment() {\n private lateinit var communicator: Communicator\n override fun onCreateView(\n inflater: LayoutInflater,\n container: ViewGroup?,\n savedInstanceState: Bundle?\n ): View? {\n val rootView = inflater.inflate(R.layout.fragment_one, container, false) as ViewGroup\n communicator = activity as Communicator\n rootView.btnSend.setOnClickListener {\n communicator.passData(rootView.editText.text.toString())\n }\n return rootView\n }\n}"
},
{
"code": null,
"e": 3461,
"s": 3443,
"text": "fragmentTwo.xml −"
},
{
"code": null,
"e": 4020,
"s": 3461,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/outPutTextView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:gravity=\"center\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</LinearLayout>"
},
{
"code": null,
"e": 4037,
"s": 4020,
"text": "FragmentTwo.kt −"
},
{
"code": null,
"e": 4658,
"s": 4037,
"text": "import android.os.Bundle\nimport androidx.fragment.app.Fragment\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport kotlinx.android.synthetic.main.fragment_two.view.*\nclass FragmentTwo : Fragment() {\n var inputText: String? = \"\"\n override fun onCreateView(\n inflater: LayoutInflater,\n container: ViewGroup?,\n savedInstanceState: Bundle?\n ): View? {\n val rootView = inflater.inflate(R.layout.fragment_two, container, false)\n inputText = arguments?.getString(\"inputText\")\n rootView.outPutTextView.text = inputText\n return rootView\n }\n}"
},
{
"code": null,
"e": 4713,
"s": 4658,
"text": "Step 4 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 5679,
"s": 4713,
"text": "import android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.fragment.app.FragmentTransaction\nclass MainActivity : AppCompatActivity(), Communicator {\n public override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n val firstFragment = FirstFragment()\n supportFragmentManager.beginTransaction().replace(R.id.relativeLayout, firstFragment)\n .commit()\n }\n override fun passData(editTextInput: String) {\n val bundle = Bundle()\n bundle.putString(\"inputText\", editTextInput)\n val transaction = this.supportFragmentManager.beginTransaction()\n val fragmentTwo = FragmentTwo()\n fragmentTwo.arguments = bundle\n transaction.replace(R.id.relativeLayout, fragmentTwo)\n transaction.addToBackStack(null)\n transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)\n transaction.commit()\n }\n}"
},
{
"code": null,
"e": 5734,
"s": 5679,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 6414,
"s": 5734,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlipapp\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" /&g;\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter&g;\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6765,
"s": 6414,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 6806,
"s": 6765,
"text": "Click here to download the project code."
}
] |
Panel data regression: a powerful time series modeling technique | by Mahbubul Alam | Towards Data Science | In a previous piece, I briefly mentioned about panel data models; and in this post, I am getting a bit deeper into it with some technical details. As I said in that post, econometrics has some of the most important tools for data scientists’ toolbox. It has numerous use cases — from measuring impacts of temperature variability on agriculture to time series data modeling and forecasting.
So what exactly is panel data? First, let’s take a look at the following definition:
A panel data is a multi-dimensional data of an observation that is measured repeatedly over time.
This is a one-liner definition, but a lot to unpack from. This definition implicitly describes three key properties of a panel dataset:
property 1: the same objects/individuals are observed repeatedly
property 2: multiple variables are measured of those same individuals/objects
property 3: the observations take place at multiple points in time
To illustrate these properties the following is a hypothetical (I made it up on the fly) dataset with 4 columns and 4 rows.
The dataset contains 4 observations of two (imaginary) US counties— Crow County and Bull county (property 1).
For each county, 2 variables were measured — the number of speed cameras installed and the number of traffic violations (property 2).
And finally, measurements took place in 2 different discrete time points — 2018 and 2019 (property 3).
How cool!
I’ll now move along to describe how panel data modeling techniques can answer specific questions. Let’s say using the above 4 x 4 dataset we want to answer the following question:
Does number of installed speed cameras impact number of traffic violation cases?
If we run a simple linear OLS regression we should be able to quickly check the association — if there is any — between the two variables:
traffic_violation = f(speed_camera)
However, remember that this is no ordinary dataset, it’s a panel data. Which means we can use it far effectively than running a simple OLS regression.
How?
First, we shouldn’t forget that the independent variable has two other properties — county and year. Meaning that there is a variation along individual and time dimensions, which we can capture in more advanced models that we are calling panel data regression.
There are three main types of panel data models (i.e. estimators) and briefly described below are their formulation.
a) Pooled OLS model
Pooled OLS (Ordinary Least Square) model treats a dataset like any other cross-sectional data and ignores that the data has a time and individual dimensions. That is why the assumptions are similar to that of ordinary linear regression.
b) Fixed effects model
While speed camera installation might have an impact on traffic violations, it is also possible that each individual county is different in terms of traffic violation because of reasons other than speed camera (e.g. higher rate of highway patrol?). However, this is not reflected in the above OLS model. Fixed effects models go a step further by taking into account the differences between individual entities (counties in our case):
c) Random effects model
In fixed effects model we have controlled for differences between individual counties. But what about variables that are constant across individuals but change over time? A random effects model takes into consideration these individual variations as well as time dependent variations. The model eliminates biases from variables that are unobserved and change over time.
It is really just a few lines of codes (assuming that you have done the other 80% work of data wrangling!). plm is the best R library in town that implements your model in just 3 easy steps: (1) it takes in input the data; (2) converts data into a panel data frame; (3) implements the model as you specify.
# import packagelibrary(plm)# import data df = read.table("../data.csv")# convert the data frame to a data format recognizable by `plm` pdf = pdata.frame(df, index = c("county", "year"))# specify and run the modelmodel = plm(traffic_violation~speed_camera, data = pdf, model = "random")summary(model)
Data science is an evolving discipline and is being enriched with diverse tools and techniques coming from many disciplines. Econometrics offers tools which are traditionally used in social and economic research but are also adding value in data science. For those interested, two open access books can get you started in econometrics and advanced social science research:
Introduction to Econometrics with R and
Principles of Econometrics with R.
These two books describe complex techniques in an accessible way along with applications and implementation in R programming language. | [
{
"code": null,
"e": 562,
"s": 172,
"text": "In a previous piece, I briefly mentioned about panel data models; and in this post, I am getting a bit deeper into it with some technical details. As I said in that post, econometrics has some of the most important tools for data scientists’ toolbox. It has numerous use cases — from measuring impacts of temperature variability on agriculture to time series data modeling and forecasting."
},
{
"code": null,
"e": 647,
"s": 562,
"text": "So what exactly is panel data? First, let’s take a look at the following definition:"
},
{
"code": null,
"e": 745,
"s": 647,
"text": "A panel data is a multi-dimensional data of an observation that is measured repeatedly over time."
},
{
"code": null,
"e": 881,
"s": 745,
"text": "This is a one-liner definition, but a lot to unpack from. This definition implicitly describes three key properties of a panel dataset:"
},
{
"code": null,
"e": 946,
"s": 881,
"text": "property 1: the same objects/individuals are observed repeatedly"
},
{
"code": null,
"e": 1024,
"s": 946,
"text": "property 2: multiple variables are measured of those same individuals/objects"
},
{
"code": null,
"e": 1091,
"s": 1024,
"text": "property 3: the observations take place at multiple points in time"
},
{
"code": null,
"e": 1215,
"s": 1091,
"text": "To illustrate these properties the following is a hypothetical (I made it up on the fly) dataset with 4 columns and 4 rows."
},
{
"code": null,
"e": 1325,
"s": 1215,
"text": "The dataset contains 4 observations of two (imaginary) US counties— Crow County and Bull county (property 1)."
},
{
"code": null,
"e": 1459,
"s": 1325,
"text": "For each county, 2 variables were measured — the number of speed cameras installed and the number of traffic violations (property 2)."
},
{
"code": null,
"e": 1562,
"s": 1459,
"text": "And finally, measurements took place in 2 different discrete time points — 2018 and 2019 (property 3)."
},
{
"code": null,
"e": 1572,
"s": 1562,
"text": "How cool!"
},
{
"code": null,
"e": 1752,
"s": 1572,
"text": "I’ll now move along to describe how panel data modeling techniques can answer specific questions. Let’s say using the above 4 x 4 dataset we want to answer the following question:"
},
{
"code": null,
"e": 1833,
"s": 1752,
"text": "Does number of installed speed cameras impact number of traffic violation cases?"
},
{
"code": null,
"e": 1972,
"s": 1833,
"text": "If we run a simple linear OLS regression we should be able to quickly check the association — if there is any — between the two variables:"
},
{
"code": null,
"e": 2008,
"s": 1972,
"text": "traffic_violation = f(speed_camera)"
},
{
"code": null,
"e": 2159,
"s": 2008,
"text": "However, remember that this is no ordinary dataset, it’s a panel data. Which means we can use it far effectively than running a simple OLS regression."
},
{
"code": null,
"e": 2164,
"s": 2159,
"text": "How?"
},
{
"code": null,
"e": 2425,
"s": 2164,
"text": "First, we shouldn’t forget that the independent variable has two other properties — county and year. Meaning that there is a variation along individual and time dimensions, which we can capture in more advanced models that we are calling panel data regression."
},
{
"code": null,
"e": 2542,
"s": 2425,
"text": "There are three main types of panel data models (i.e. estimators) and briefly described below are their formulation."
},
{
"code": null,
"e": 2562,
"s": 2542,
"text": "a) Pooled OLS model"
},
{
"code": null,
"e": 2799,
"s": 2562,
"text": "Pooled OLS (Ordinary Least Square) model treats a dataset like any other cross-sectional data and ignores that the data has a time and individual dimensions. That is why the assumptions are similar to that of ordinary linear regression."
},
{
"code": null,
"e": 2822,
"s": 2799,
"text": "b) Fixed effects model"
},
{
"code": null,
"e": 3256,
"s": 2822,
"text": "While speed camera installation might have an impact on traffic violations, it is also possible that each individual county is different in terms of traffic violation because of reasons other than speed camera (e.g. higher rate of highway patrol?). However, this is not reflected in the above OLS model. Fixed effects models go a step further by taking into account the differences between individual entities (counties in our case):"
},
{
"code": null,
"e": 3280,
"s": 3256,
"text": "c) Random effects model"
},
{
"code": null,
"e": 3650,
"s": 3280,
"text": "In fixed effects model we have controlled for differences between individual counties. But what about variables that are constant across individuals but change over time? A random effects model takes into consideration these individual variations as well as time dependent variations. The model eliminates biases from variables that are unobserved and change over time."
},
{
"code": null,
"e": 3957,
"s": 3650,
"text": "It is really just a few lines of codes (assuming that you have done the other 80% work of data wrangling!). plm is the best R library in town that implements your model in just 3 easy steps: (1) it takes in input the data; (2) converts data into a panel data frame; (3) implements the model as you specify."
},
{
"code": null,
"e": 4260,
"s": 3957,
"text": "# import packagelibrary(plm)# import data df = read.table(\"../data.csv\")# convert the data frame to a data format recognizable by `plm` pdf = pdata.frame(df, index = c(\"county\", \"year\"))# specify and run the modelmodel = plm(traffic_violation~speed_camera, data = pdf, model = \"random\")summary(model)"
},
{
"code": null,
"e": 4633,
"s": 4260,
"text": "Data science is an evolving discipline and is being enriched with diverse tools and techniques coming from many disciplines. Econometrics offers tools which are traditionally used in social and economic research but are also adding value in data science. For those interested, two open access books can get you started in econometrics and advanced social science research:"
},
{
"code": null,
"e": 4673,
"s": 4633,
"text": "Introduction to Econometrics with R and"
},
{
"code": null,
"e": 4708,
"s": 4673,
"text": "Principles of Econometrics with R."
}
] |
Check if Object is of the Character Data type in R Programming - is.character() Function - GeeksforGeeks | 03 Jun, 2020
is.character() Function in R Language is used to check if the object is of the form of a string/character or not. It will return true if any element of the object is of the character data type.
Syntax: is.character(Object)
Parameter:Object: It could be an array, list, vector, etc.
Example 1:
# R Program to illustrate # the use of is.character function # Creating a vector of mixed datatypex1 <- c("Hello", "Geeks", 100) # Creating a vector of Numeric datatypex2 <- c(10, 20, 30) # Calling is.character() functionis.character(x1)is.character(x2)
Output:
[1] TRUE
[1] FALSE
Example 2:
# R Program to illustrate # the use of is.character function # Create the vectors with different length vector1 <- c(1, 2, 3) vector2 <- c("GFG", "Geeks", "Hello") # taking this vector as input result <- array(c(vector1, vector2), dim = c(3, 3, 2)) # Calling is.character() functionis.character(result)
Output:
[1] TRUE
R Data-types
R String-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
Remove rows with NA in one column of R DataFrame
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? | [
{
"code": null,
"e": 24992,
"s": 24964,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 25186,
"s": 24992,
"text": "is.character() Function in R Language is used to check if the object is of the form of a string/character or not. It will return true if any element of the object is of the character data type."
},
{
"code": null,
"e": 25215,
"s": 25186,
"text": "Syntax: is.character(Object)"
},
{
"code": null,
"e": 25274,
"s": 25215,
"text": "Parameter:Object: It could be an array, list, vector, etc."
},
{
"code": null,
"e": 25285,
"s": 25274,
"text": "Example 1:"
},
{
"code": "# R Program to illustrate # the use of is.character function # Creating a vector of mixed datatypex1 <- c(\"Hello\", \"Geeks\", 100) # Creating a vector of Numeric datatypex2 <- c(10, 20, 30) # Calling is.character() functionis.character(x1)is.character(x2)",
"e": 25542,
"s": 25285,
"text": null
},
{
"code": null,
"e": 25550,
"s": 25542,
"text": "Output:"
},
{
"code": null,
"e": 25570,
"s": 25550,
"text": "[1] TRUE\n[1] FALSE\n"
},
{
"code": null,
"e": 25581,
"s": 25570,
"text": "Example 2:"
},
{
"code": "# R Program to illustrate # the use of is.character function # Create the vectors with different length vector1 <- c(1, 2, 3) vector2 <- c(\"GFG\", \"Geeks\", \"Hello\") # taking this vector as input result <- array(c(vector1, vector2), dim = c(3, 3, 2)) # Calling is.character() functionis.character(result)",
"e": 25891,
"s": 25581,
"text": null
},
{
"code": null,
"e": 25899,
"s": 25891,
"text": "Output:"
},
{
"code": null,
"e": 25909,
"s": 25899,
"text": "[1] TRUE\n"
},
{
"code": null,
"e": 25922,
"s": 25909,
"text": "R Data-types"
},
{
"code": null,
"e": 25941,
"s": 25922,
"text": "R String-Functions"
},
{
"code": null,
"e": 25952,
"s": 25941,
"text": "R Language"
},
{
"code": null,
"e": 26050,
"s": 25952,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26059,
"s": 26050,
"text": "Comments"
},
{
"code": null,
"e": 26072,
"s": 26059,
"text": "Old Comments"
},
{
"code": null,
"e": 26130,
"s": 26072,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 26182,
"s": 26130,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 26214,
"s": 26182,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 26266,
"s": 26214,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26310,
"s": 26266,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 26342,
"s": 26310,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 26391,
"s": 26342,
"text": "Remove rows with NA in one column of R DataFrame"
},
{
"code": null,
"e": 26429,
"s": 26391,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26464,
"s": 26429,
"text": "Group by function in R using Dplyr"
}
] |
Ruby - Command Line Options | Ruby is generally run from the command line in the following way −
$ ruby [ options ] [.] [ programfile ] [ arguments ... ]
The interpreter can be invoked with any of the following options to control the environment and behavior of the interpreter.
-a
Used with -n or -p to split each line. Check -n and -p options.
-c
Checks syntax only, without executing program.
-C dir
Changes directory before executing (equivalent to -X).
-d
Enables debug mode (equivalent to -debug).
-F pat
Specifies pat as the default separator pattern ($;) used by split.
-e prog
Specifies prog as the program from the command line. Specify multiple -e options for multiline programs.
-h
Displays an overview of command-line options.
-i [ ext]
Overwrites the file contents with program output. The original file is saved with the extension ext. If ext isn't specified, the original file is deleted.
-I dir
Adds dir as the directory for loading libraries.
-K [ kcode]
Specifies the multibyte character set code (e or E for EUC (extended Unix code); s or S for SJIS (Shift-JIS); u or U for UTF8; and a, A, n, or N for ASCII).
-l
Enables automatic line-end processing. Chops a newline from input lines and appends a newline to output lines.
-n
Places code within an input loop (as in while gets; ... end).
-0[ octal]
Sets default record separator ($/) as an octal. Defaults to \0 if octal not specified.
-p
Places code within an input loop. Writes $_ for each iteration.
-r lib
Uses require to load lib as a library before executing.
-s
Interprets any arguments between the program name and filename arguments fitting the pattern -xxx as a switch and defines the corresponding variable.
-T [level]
Sets the level for tainting checks (1 if level not specified).
-v
Displays version and enables verbose mode.
-w
Enables verbose mode. If program file not specified, reads from STDIN.
-x [dir]
Strips text before #!ruby line. Changes directory to dir before executing if dir is specified.
-X dir
Changes directory before executing (equivalent to -C).
-y
Enables parser debug mode.
--copyright
Displays copyright notice.
--debug
Enables debug mode (equivalent to -d).
--help
Displays an overview of command-line options (equivalent to h).
--version
Displays version.
--verbose
Enables verbose mode (equivalent to -v). Sets $VERBOSE to true.
--yydebug
Enables parser debug mode (equivalent to -y).
Single character command-line options can be combined. The following two lines express the same meaning −
$ruby -ne 'print if /Ruby/' /usr/share/bin
$ruby -n -e 'print if /Ruby/' /usr/share/bin
46 Lectures
9.5 hours
Eduonix Learning Solutions
97 Lectures
7.5 hours
Skillbakerystudios
227 Lectures
40 hours
YouAccel
19 Lectures
10 hours
Programming Line
51 Lectures
5 hours
Stone River ELearning
39 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2361,
"s": 2294,
"text": "Ruby is generally run from the command line in the following way −"
},
{
"code": null,
"e": 2419,
"s": 2361,
"text": "$ ruby [ options ] [.] [ programfile ] [ arguments ... ]\n"
},
{
"code": null,
"e": 2544,
"s": 2419,
"text": "The interpreter can be invoked with any of the following options to control the environment and behavior of the interpreter."
},
{
"code": null,
"e": 2547,
"s": 2544,
"text": "-a"
},
{
"code": null,
"e": 2611,
"s": 2547,
"text": "Used with -n or -p to split each line. Check -n and -p options."
},
{
"code": null,
"e": 2614,
"s": 2611,
"text": "-c"
},
{
"code": null,
"e": 2661,
"s": 2614,
"text": "Checks syntax only, without executing program."
},
{
"code": null,
"e": 2668,
"s": 2661,
"text": "-C dir"
},
{
"code": null,
"e": 2723,
"s": 2668,
"text": "Changes directory before executing (equivalent to -X)."
},
{
"code": null,
"e": 2726,
"s": 2723,
"text": "-d"
},
{
"code": null,
"e": 2769,
"s": 2726,
"text": "Enables debug mode (equivalent to -debug)."
},
{
"code": null,
"e": 2776,
"s": 2769,
"text": "-F pat"
},
{
"code": null,
"e": 2843,
"s": 2776,
"text": "Specifies pat as the default separator pattern ($;) used by split."
},
{
"code": null,
"e": 2851,
"s": 2843,
"text": "-e prog"
},
{
"code": null,
"e": 2956,
"s": 2851,
"text": "Specifies prog as the program from the command line. Specify multiple -e options for multiline programs."
},
{
"code": null,
"e": 2959,
"s": 2956,
"text": "-h"
},
{
"code": null,
"e": 3005,
"s": 2959,
"text": "Displays an overview of command-line options."
},
{
"code": null,
"e": 3015,
"s": 3005,
"text": "-i [ ext]"
},
{
"code": null,
"e": 3170,
"s": 3015,
"text": "Overwrites the file contents with program output. The original file is saved with the extension ext. If ext isn't specified, the original file is deleted."
},
{
"code": null,
"e": 3177,
"s": 3170,
"text": "-I dir"
},
{
"code": null,
"e": 3226,
"s": 3177,
"text": "Adds dir as the directory for loading libraries."
},
{
"code": null,
"e": 3238,
"s": 3226,
"text": "-K [ kcode]"
},
{
"code": null,
"e": 3395,
"s": 3238,
"text": "Specifies the multibyte character set code (e or E for EUC (extended Unix code); s or S for SJIS (Shift-JIS); u or U for UTF8; and a, A, n, or N for ASCII)."
},
{
"code": null,
"e": 3398,
"s": 3395,
"text": "-l"
},
{
"code": null,
"e": 3509,
"s": 3398,
"text": "Enables automatic line-end processing. Chops a newline from input lines and appends a newline to output lines."
},
{
"code": null,
"e": 3512,
"s": 3509,
"text": "-n"
},
{
"code": null,
"e": 3574,
"s": 3512,
"text": "Places code within an input loop (as in while gets; ... end)."
},
{
"code": null,
"e": 3585,
"s": 3574,
"text": "-0[ octal]"
},
{
"code": null,
"e": 3672,
"s": 3585,
"text": "Sets default record separator ($/) as an octal. Defaults to \\0 if octal not specified."
},
{
"code": null,
"e": 3675,
"s": 3672,
"text": "-p"
},
{
"code": null,
"e": 3739,
"s": 3675,
"text": "Places code within an input loop. Writes $_ for each iteration."
},
{
"code": null,
"e": 3746,
"s": 3739,
"text": "-r lib"
},
{
"code": null,
"e": 3802,
"s": 3746,
"text": "Uses require to load lib as a library before executing."
},
{
"code": null,
"e": 3805,
"s": 3802,
"text": "-s"
},
{
"code": null,
"e": 3955,
"s": 3805,
"text": "Interprets any arguments between the program name and filename arguments fitting the pattern -xxx as a switch and defines the corresponding variable."
},
{
"code": null,
"e": 3966,
"s": 3955,
"text": "-T [level]"
},
{
"code": null,
"e": 4029,
"s": 3966,
"text": "Sets the level for tainting checks (1 if level not specified)."
},
{
"code": null,
"e": 4032,
"s": 4029,
"text": "-v"
},
{
"code": null,
"e": 4075,
"s": 4032,
"text": "Displays version and enables verbose mode."
},
{
"code": null,
"e": 4078,
"s": 4075,
"text": "-w"
},
{
"code": null,
"e": 4149,
"s": 4078,
"text": "Enables verbose mode. If program file not specified, reads from STDIN."
},
{
"code": null,
"e": 4158,
"s": 4149,
"text": "-x [dir]"
},
{
"code": null,
"e": 4253,
"s": 4158,
"text": "Strips text before #!ruby line. Changes directory to dir before executing if dir is specified."
},
{
"code": null,
"e": 4260,
"s": 4253,
"text": "-X dir"
},
{
"code": null,
"e": 4315,
"s": 4260,
"text": "Changes directory before executing (equivalent to -C)."
},
{
"code": null,
"e": 4318,
"s": 4315,
"text": "-y"
},
{
"code": null,
"e": 4345,
"s": 4318,
"text": "Enables parser debug mode."
},
{
"code": null,
"e": 4357,
"s": 4345,
"text": "--copyright"
},
{
"code": null,
"e": 4384,
"s": 4357,
"text": "Displays copyright notice."
},
{
"code": null,
"e": 4392,
"s": 4384,
"text": "--debug"
},
{
"code": null,
"e": 4431,
"s": 4392,
"text": "Enables debug mode (equivalent to -d)."
},
{
"code": null,
"e": 4438,
"s": 4431,
"text": "--help"
},
{
"code": null,
"e": 4502,
"s": 4438,
"text": "Displays an overview of command-line options (equivalent to h)."
},
{
"code": null,
"e": 4512,
"s": 4502,
"text": "--version"
},
{
"code": null,
"e": 4530,
"s": 4512,
"text": "Displays version."
},
{
"code": null,
"e": 4540,
"s": 4530,
"text": "--verbose"
},
{
"code": null,
"e": 4604,
"s": 4540,
"text": "Enables verbose mode (equivalent to -v). Sets $VERBOSE to true."
},
{
"code": null,
"e": 4614,
"s": 4604,
"text": "--yydebug"
},
{
"code": null,
"e": 4660,
"s": 4614,
"text": "Enables parser debug mode (equivalent to -y)."
},
{
"code": null,
"e": 4766,
"s": 4660,
"text": "Single character command-line options can be combined. The following two lines express the same meaning −"
},
{
"code": null,
"e": 4859,
"s": 4766,
"text": "$ruby -ne 'print if /Ruby/' /usr/share/bin\n \n$ruby -n -e 'print if /Ruby/' /usr/share/bin\n"
},
{
"code": null,
"e": 4894,
"s": 4859,
"text": "\n 46 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 4922,
"s": 4894,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4957,
"s": 4922,
"text": "\n 97 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4977,
"s": 4957,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5012,
"s": 4977,
"text": "\n 227 Lectures \n 40 hours \n"
},
{
"code": null,
"e": 5022,
"s": 5012,
"text": " YouAccel"
},
{
"code": null,
"e": 5056,
"s": 5022,
"text": "\n 19 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 5074,
"s": 5056,
"text": " Programming Line"
},
{
"code": null,
"e": 5107,
"s": 5074,
"text": "\n 51 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5130,
"s": 5107,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5165,
"s": 5130,
"text": "\n 39 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5188,
"s": 5165,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5195,
"s": 5188,
"text": " Print"
},
{
"code": null,
"e": 5206,
"s": 5195,
"text": " Add Notes"
}
] |
Java String endsWith() Method | ❮ String Methods
Find out if the string ends with the specified characters:
String myStr = "Hello";
System.out.println(myStr.endsWith("Hel")); // false
System.out.println(myStr.endsWith("llo")); // true
System.out.println(myStr.endsWith("o")); // true
Try it Yourself »
The endsWith() method checks whether a
string ends with the specified character(s).
Tip: Use the startsWith() method to check whether a string
starts with the specified character(s).
public boolean endsWith(String chars)
true - if the string ends with the specified character(s)
false - if the string does not end with the specified character(s)
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 19,
"s": 0,
"text": "\n❮ String Methods\n"
},
{
"code": null,
"e": 78,
"s": 19,
"text": "Find out if the string ends with the specified characters:"
},
{
"code": null,
"e": 262,
"s": 78,
"text": "String myStr = \"Hello\";\nSystem.out.println(myStr.endsWith(\"Hel\")); // false\nSystem.out.println(myStr.endsWith(\"llo\")); // true\nSystem.out.println(myStr.endsWith(\"o\")); // true"
},
{
"code": null,
"e": 282,
"s": 262,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 367,
"s": 282,
"text": "The endsWith() method checks whether a \nstring ends with the specified character(s)."
},
{
"code": null,
"e": 467,
"s": 367,
"text": "Tip: Use the startsWith() method to check whether a string \nstarts with the specified character(s)."
},
{
"code": null,
"e": 506,
"s": 467,
"text": "public boolean endsWith(String chars)\n"
},
{
"code": null,
"e": 564,
"s": 506,
"text": "true - if the string ends with the specified character(s)"
},
{
"code": null,
"e": 631,
"s": 564,
"text": "false - if the string does not end with the specified character(s)"
},
{
"code": null,
"e": 664,
"s": 631,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 706,
"s": 664,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 813,
"s": 706,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 832,
"s": 813,
"text": "[email protected]"
}
] |
How to scan through a directory recursively in Python?
| You can use the os.walk function to walk through the directory tree in python.
import os
for dirpath, dirs, files in os.walk("./my_directory/"):
for filename in files:
fname = os.path.join(dirpath,filename)
with open(fname) as myfile:
print(myfile.read())
The above program recursively moves through the my_directory tree and prints contents of each file in the tree to the console output. | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "You can use the os.walk function to walk through the directory tree in python."
},
{
"code": null,
"e": 1416,
"s": 1141,
"text": "import os\nfor dirpath, dirs, files in os.walk(\"./my_directory/\"): \n for filename in files:\n fname = os.path.join(dirpath,filename)\n with open(fname) as myfile:\n print(myfile.read())"
},
{
"code": null,
"e": 1550,
"s": 1416,
"text": "The above program recursively moves through the my_directory tree and prints contents of each file in the tree to the console output."
}
] |
Python time localtime() Method | Pythom time method localtime() is similar to gmtime() but it converts number of seconds to local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time.
Following is the syntax for localtime() method −
time.localtime([ sec ])
sec − These are the number of seconds to be converted into structure struct_time representation.
sec − These are the number of seconds to be converted into structure struct_time representation.
This method does not return any value.
The following example shows the usage of localtime() method.
#!/usr/bin/python
import time
print "time.localtime() : %s" % time.localtime()
When we run above program, it produces following result −
time.localtime() : (2009, 2, 17, 17, 3, 38, 1, 48, 0)
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": 2489,
"s": 2244,
"text": "Pythom time method localtime() is similar to gmtime() but it converts number of seconds to local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time."
},
{
"code": null,
"e": 2538,
"s": 2489,
"text": "Following is the syntax for localtime() method −"
},
{
"code": null,
"e": 2563,
"s": 2538,
"text": "time.localtime([ sec ])\n"
},
{
"code": null,
"e": 2661,
"s": 2563,
"text": "sec − These are the number of seconds to be converted into structure struct_time representation. "
},
{
"code": null,
"e": 2759,
"s": 2661,
"text": "sec − These are the number of seconds to be converted into structure struct_time representation. "
},
{
"code": null,
"e": 2798,
"s": 2759,
"text": "This method does not return any value."
},
{
"code": null,
"e": 2859,
"s": 2798,
"text": "The following example shows the usage of localtime() method."
},
{
"code": null,
"e": 2939,
"s": 2859,
"text": "#!/usr/bin/python\nimport time\n\nprint \"time.localtime() : %s\" % time.localtime()"
},
{
"code": null,
"e": 2997,
"s": 2939,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3052,
"s": 2997,
"text": "time.localtime() : (2009, 2, 17, 17, 3, 38, 1, 48, 0)\n"
},
{
"code": null,
"e": 3089,
"s": 3052,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3105,
"s": 3089,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3138,
"s": 3105,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3157,
"s": 3138,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3192,
"s": 3157,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3214,
"s": 3192,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3248,
"s": 3214,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3276,
"s": 3248,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3311,
"s": 3276,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3325,
"s": 3311,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3358,
"s": 3325,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3375,
"s": 3358,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3382,
"s": 3375,
"text": " Print"
},
{
"code": null,
"e": 3393,
"s": 3382,
"text": " Add Notes"
}
] |
Arduino - switch case statement | Similar to the if statements, switch...case controls the flow of programs by allowing the programmers to specify different codes that should be executed in various conditions. In particular, a switch statement compares the value of a variable to the values specified in the case statements. When a case statement is found whose value matches that of the variable, the code in that case statement is run.
The break keyword makes the switch statement exit, and is typically used at the end of each case. Without a break statement, the switch statement will continue executing the following expressions ("falling-through") until a break, or the end of the switch statement is reached.
switch (variable) {
case label:
// statements
break;
}
case label: {
// statements
break;
}
default: {
// statements
break;
}
Here is a simple example with switch. Suppose we have a variable phase with only 3 different states (0, 1, or 2) and a corresponding function (event) for each of these states. This is how we could switch the code to the appropriate routine −
switch (phase) {
case 0: Lo(); break;
case 1: Mid(); break;
case 2: Hi(); break;
default: Message("Invalid state!");
}
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3274,
"s": 2870,
"text": "Similar to the if statements, switch...case controls the flow of programs by allowing the programmers to specify different codes that should be executed in various conditions. In particular, a switch statement compares the value of a variable to the values specified in the case statements. When a case statement is found whose value matches that of the variable, the code in that case statement is run."
},
{
"code": null,
"e": 3552,
"s": 3274,
"text": "The break keyword makes the switch statement exit, and is typically used at the end of each case. Without a break statement, the switch statement will continue executing the following expressions (\"falling-through\") until a break, or the end of the switch statement is reached."
},
{
"code": null,
"e": 3705,
"s": 3552,
"text": "switch (variable) { \n case label:\n // statements\n break;\n}\n\ncase label: { \n // statements\n break;\n}\n\ndefault: { \n // statements\n break;\n}\n"
},
{
"code": null,
"e": 3947,
"s": 3705,
"text": "Here is a simple example with switch. Suppose we have a variable phase with only 3 different states (0, 1, or 2) and a corresponding function (event) for each of these states. This is how we could switch the code to the appropriate routine −"
},
{
"code": null,
"e": 4078,
"s": 3947,
"text": "switch (phase) {\n case 0: Lo(); break;\n case 1: Mid(); break;\n case 2: Hi(); break;\n default: Message(\"Invalid state!\");\n}"
},
{
"code": null,
"e": 4113,
"s": 4078,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4124,
"s": 4113,
"text": " Amit Rana"
},
{
"code": null,
"e": 4157,
"s": 4124,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4168,
"s": 4157,
"text": " Amit Rana"
},
{
"code": null,
"e": 4201,
"s": 4168,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4214,
"s": 4201,
"text": " Ashraf Said"
},
{
"code": null,
"e": 4249,
"s": 4214,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4262,
"s": 4249,
"text": " Ashraf Said"
},
{
"code": null,
"e": 4294,
"s": 4262,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 4307,
"s": 4294,
"text": " Ashraf Said"
},
{
"code": null,
"e": 4338,
"s": 4307,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 4351,
"s": 4338,
"text": " Ashraf Said"
},
{
"code": null,
"e": 4358,
"s": 4351,
"text": " Print"
},
{
"code": null,
"e": 4369,
"s": 4358,
"text": " Add Notes"
}
] |
How can I pop-up a print dialog box using JavaScript? | To pop-up a print dialog box using JavaScript, use the print() method. With the dialog box, you can easily set the printing options like which printer to select for printing.
This is the dialog box −
You can try to run the following code to learn how to print a page −
Live Demo
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">Click to Print</button>
<script>
function display() {
window.print();
}
</script>
</body>
</html> | [
{
"code": null,
"e": 1237,
"s": 1062,
"text": "To pop-up a print dialog box using JavaScript, use the print() method. With the dialog box, you can easily set the printing options like which printer to select for printing."
},
{
"code": null,
"e": 1262,
"s": 1237,
"text": "This is the dialog box −"
},
{
"code": null,
"e": 1331,
"s": 1262,
"text": "You can try to run the following code to learn how to print a page −"
},
{
"code": null,
"e": 1341,
"s": 1331,
"text": "Live Demo"
},
{
"code": null,
"e": 1551,
"s": 1341,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <button onclick=\"display()\">Click to Print</button>\n <script>\n function display() {\n window.print();\n }\n </script>\n </body>\n</html>"
}
] |
GATE | GATE CS 2020 | Question 52 - GeeksforGeeks | 26 May, 2021
The number of permutations of the characters in LILAC so that no character appears in its original position, if the two L’s are indistinguishable, is ________ .
Note – This question was Numerical Type.(A) 12(B) 10(C) 8(D) 15Answer: (A)Explanation: There are 3 choices for the first slot, and then 2 for the third slot. That leaves one letter out of I,A,C unchosen and there are 2 slots that one might occupy. After that, the L′s must go in the 2 unfilled slots.
Hence the answer is,
3×2×1×2 = 12
Option (A) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2015 (Set 1) | Question 42 | [
{
"code": null,
"e": 24073,
"s": 24045,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 24234,
"s": 24073,
"text": "The number of permutations of the characters in LILAC so that no character appears in its original position, if the two L’s are indistinguishable, is ________ ."
},
{
"code": null,
"e": 24535,
"s": 24234,
"text": "Note – This question was Numerical Type.(A) 12(B) 10(C) 8(D) 15Answer: (A)Explanation: There are 3 choices for the first slot, and then 2 for the third slot. That leaves one letter out of I,A,C unchosen and there are 2 slots that one might occupy. After that, the L′s must go in the 2 unfilled slots."
},
{
"code": null,
"e": 24556,
"s": 24535,
"text": "Hence the answer is,"
},
{
"code": null,
"e": 24570,
"s": 24556,
"text": "3×2×1×2 = 12 "
},
{
"code": null,
"e": 24614,
"s": 24570,
"text": "Option (A) is correct.Quiz of this Question"
},
{
"code": null,
"e": 24619,
"s": 24614,
"text": "GATE"
},
{
"code": null,
"e": 24717,
"s": 24619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24726,
"s": 24717,
"text": "Comments"
},
{
"code": null,
"e": 24739,
"s": 24726,
"text": "Old Comments"
},
{
"code": null,
"e": 24781,
"s": 24739,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 24823,
"s": 24781,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 24857,
"s": 24823,
"text": "GATE | GATE-CS-2001 | Question 23"
},
{
"code": null,
"e": 24899,
"s": 24857,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 24933,
"s": 24899,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 24975,
"s": 24933,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25008,
"s": 24975,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25050,
"s": 25008,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 25104,
"s": 25050,
"text": "C++ Program to count Vowels in a string using Pointer"
}
] |
How to draw an ellipse in HTML5 SVG? | SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG.
To draw an ellipse in HTML SVG, use the SVG <ellipse> element.
You can try to run the following code to learn how to draw an ellipse in HTML5 SVG −
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 10%;
-webkit-transform: translateX(-20%);
-ms-transform: translateX(-20%);
transform: translateX(-20%);
}
</style>
<title>HTML5 SVG Ellipse</title>
</head>
<body>
<h2>HTML5 SVG Ellipse</h2>
<svg id = "svgelem" width = "300" height = "200" xmlns = "http://www.w3.org/2000/svg">
<ellipse cx = "120" cy = "50" rx = "100" ry = "50" fill = "blue" />
</svg>
</body>
</html> | [
{
"code": null,
"e": 1315,
"s": 1062,
"text": "SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG."
},
{
"code": null,
"e": 1378,
"s": 1315,
"text": "To draw an ellipse in HTML SVG, use the SVG <ellipse> element."
},
{
"code": null,
"e": 1463,
"s": 1378,
"text": "You can try to run the following code to learn how to draw an ellipse in HTML5 SVG −"
},
{
"code": null,
"e": 1922,
"s": 1463,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n#svgelem {\n position: relative;\n left: 10%;\n -webkit-transform: translateX(-20%);\n -ms-transform: translateX(-20%);\n transform: translateX(-20%);\n}\n</style>\n<title>HTML5 SVG Ellipse</title>\n</head>\n\n<body>\n<h2>HTML5 SVG Ellipse</h2>\n<svg id = \"svgelem\" width = \"300\" height = \"200\" xmlns = \"http://www.w3.org/2000/svg\">\n<ellipse cx = \"120\" cy = \"50\" rx = \"100\" ry = \"50\" fill = \"blue\" />\n</svg>\n</body>\n</html>"
}
] |
Smallest number with sum of digits as N and divisible by 10^N | 25 Mar, 2021
Find the smallest number such that the sum of its digits is N and it is divisible by .Examples :
Input : N = 5
Output : 500000
500000 is the smallest number divisible
by 10^5 and sum of digits as 5.
Input : N = 20
Output : 29900000000000000000000
ExplanationTo make a number divisible by we need at least N zeros at the end of the number. To make the number smallest, we append exactly N zeros to the end of the number. Now, we need to ensure the sum of the digits is N. For this, we will try to make the length of the number as small as possible to get the answer. Thus we keep on inserting 9 into the number till the sum doesn’t exceed N. If we have any remainder left, then we keep it as the first digit (most significant one) so that the resulting number is minimized.The approach works well for all subtasks but there are 2 corner cases:1. The first is that the final number may not fit into the data types present in C++/Java. Since we only need to output the number, we can use strings to store the answer. 2. The only corner case where the answer is 0 is N = 0. 3. There are no cases where the answer doesn’t exist.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find smallest// number to find smallest number// with N as sum of digits and// divisible by 10^N.#include <bits/stdc++.h>using namespace std; void digitsNum(int N){ // If N = 0 the string will be 0 if (N == 0) cout << "0\n"; // If n is not perfectly divisible // by 9 output the remainder if (N % 9 != 0) cout << (N % 9); // Print 9 N/9 times for (int i = 1; i <= (N / 9); ++i) cout << "9"; // Append N zero's to the number so // as to make it divisible by 10^N for (int i = 1; i <= N; ++i) cout << "0"; cout << "\n";} // Driver Codeint main(){ int N = 5; cout << "The number is : "; digitsNum(N); return 0;}
// Java program to find smallest// number to find smallest number// with N as sum of digits and// divisible by 10^N.import java.io.*; class GFG{ static void digitsNum(int N){ // If N = 0 the string will be 0 if (N == 0) System.out.println("0"); // If n is not perfectly divisible // by 9 output the remainder if (N % 9 != 0) System.out.print((N % 9)); // Print 9 N/9 times for (int i = 1; i <= (N / 9); ++i) System.out.print("9"); // Append N zero's to the number so // as to make it divisible by 10^N for (int i = 1; i <= N; ++i) System.out.print("0"); System.out.print("" ); } // Driver Code public static void main (String[] args) { int N = 5; System.out.print("The number is : "); digitsNum(N); }} // This code is contributed by vt_m
# Python program to find smallest# number to find smallest number# with N as sum of digits and# divisible by 10^N. import mathdef digitsNum(N): # If N = 0 the string will be 0 if (N == 0) : print("0", end = "") # If n is not perfectly divisible # by 9 output the remainder if (N % 9 != 0): print (N % 9, end ="") # Print 9 N/9 times for i in range( 1, int(N / 9) + 1) : print("9", end = "") # Append N zero's to the number so # as to make it divisible by 10^N for i in range(1, N + 1) : print("0", end = "") print() # Driver CodeN = 5print("The number is : ",end="")digitsNum(N) # This code is contributed by Gitanjali.
// C# program to find smallest// number to find smallest number// with N as sum of digits and// divisible by 10^N.using System; class GFG{ static void digitsNum(int N){ // If N = 0 the string will be 0 if (N == 0)Console.Write("0"); // If n is not perfectly divisible // by 9 output the remainder if (N % 9 != 0) Console.Write((N % 9)); // Print 9 N/9 times for (int i = 1; i <= (N / 9); ++i) Console.Write("9"); // Append N zero's to the number so // as to make it divisible by 10^N ) for (int i = 1; i <= N; ++i) Console.Write("0"); Console.WriteLine("" ); } // Driver Code public static void Main () { int N = 5; Console.Write("The number is : "); digitsNum(N); }} // This code is contributed by vt_m
<?php// PHP program to find smallest// number to find smallest number// with N as sum of digits and// divisible by 10^N. function digitsNum($N){ // If N = 0 the string will be 0 if ($N == 0) echo "0\n"; // If n is not perfectly divisible // by 9 output the remainder if ($N % 9 != 0) echo ($N % 9); // Print 9 N/9 times for ( $i = 1; $i <= ($N / 9); ++$i) echo "9"; // Append N zero's to the number so // as to make it divisible by 10^N for ($i = 1; $i <= $N; ++$i) echo "0"; echo "\n";} // Driver Code$N = 5;echo "The number is : ";digitsNum($N); // This code is contributed by ajit.?>
<script> // JavaScript program to find smallest // number to find smallest number // with N as sum of digits and // divisible by 10^N. function digitsNum(N) { // If N = 0 the string will be 0 if (N == 0) document.write("0\n"); // If n is not perfectly divisible // by 9 output the remainder if (N % 9 != 0) document.write(N % 9); // Print 9 N/9 times for (var i = 1; i <= N / 9; ++i) document.write("9"); // Append N zero's to the number so // as to make it divisible by 10^N for (var i = 1; i <= N; ++i) document.write("0"); document.write("\n"); } // Driver Code var N = 5; document.write("The number is : "); digitsNum(N); // This code is contributed by rrrtnx. </script>
Output :
The number is : 500000
Time Complexity : O(N)
jit_t
rdtank
number-digits
Numbers
Competitive Programming
Greedy
Mathematical
Strings
Strings
Greedy
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Mar, 2021"
},
{
"code": null,
"e": 151,
"s": 52,
"text": "Find the smallest number such that the sum of its digits is N and it is divisible by .Examples : "
},
{
"code": null,
"e": 302,
"s": 151,
"text": "Input : N = 5\nOutput : 500000\n500000 is the smallest number divisible\nby 10^5 and sum of digits as 5.\n\nInput : N = 20\nOutput : 29900000000000000000000"
},
{
"code": null,
"e": 1184,
"s": 306,
"text": "ExplanationTo make a number divisible by we need at least N zeros at the end of the number. To make the number smallest, we append exactly N zeros to the end of the number. Now, we need to ensure the sum of the digits is N. For this, we will try to make the length of the number as small as possible to get the answer. Thus we keep on inserting 9 into the number till the sum doesn’t exceed N. If we have any remainder left, then we keep it as the first digit (most significant one) so that the resulting number is minimized.The approach works well for all subtasks but there are 2 corner cases:1. The first is that the final number may not fit into the data types present in C++/Java. Since we only need to output the number, we can use strings to store the answer. 2. The only corner case where the answer is 0 is N = 0. 3. There are no cases where the answer doesn’t exist. "
},
{
"code": null,
"e": 1190,
"s": 1186,
"text": "C++"
},
{
"code": null,
"e": 1195,
"s": 1190,
"text": "Java"
},
{
"code": null,
"e": 1203,
"s": 1195,
"text": "Python3"
},
{
"code": null,
"e": 1206,
"s": 1203,
"text": "C#"
},
{
"code": null,
"e": 1210,
"s": 1206,
"text": "PHP"
},
{
"code": null,
"e": 1221,
"s": 1210,
"text": "Javascript"
},
{
"code": "// CPP program to find smallest// number to find smallest number// with N as sum of digits and// divisible by 10^N.#include <bits/stdc++.h>using namespace std; void digitsNum(int N){ // If N = 0 the string will be 0 if (N == 0) cout << \"0\\n\"; // If n is not perfectly divisible // by 9 output the remainder if (N % 9 != 0) cout << (N % 9); // Print 9 N/9 times for (int i = 1; i <= (N / 9); ++i) cout << \"9\"; // Append N zero's to the number so // as to make it divisible by 10^N for (int i = 1; i <= N; ++i) cout << \"0\"; cout << \"\\n\";} // Driver Codeint main(){ int N = 5; cout << \"The number is : \"; digitsNum(N); return 0;}",
"e": 1941,
"s": 1221,
"text": null
},
{
"code": "// Java program to find smallest// number to find smallest number// with N as sum of digits and// divisible by 10^N.import java.io.*; class GFG{ static void digitsNum(int N){ // If N = 0 the string will be 0 if (N == 0) System.out.println(\"0\"); // If n is not perfectly divisible // by 9 output the remainder if (N % 9 != 0) System.out.print((N % 9)); // Print 9 N/9 times for (int i = 1; i <= (N / 9); ++i) System.out.print(\"9\"); // Append N zero's to the number so // as to make it divisible by 10^N for (int i = 1; i <= N; ++i) System.out.print(\"0\"); System.out.print(\"\" ); } // Driver Code public static void main (String[] args) { int N = 5; System.out.print(\"The number is : \"); digitsNum(N); }} // This code is contributed by vt_m",
"e": 2804,
"s": 1941,
"text": null
},
{
"code": "# Python program to find smallest# number to find smallest number# with N as sum of digits and# divisible by 10^N. import mathdef digitsNum(N): # If N = 0 the string will be 0 if (N == 0) : print(\"0\", end = \"\") # If n is not perfectly divisible # by 9 output the remainder if (N % 9 != 0): print (N % 9, end =\"\") # Print 9 N/9 times for i in range( 1, int(N / 9) + 1) : print(\"9\", end = \"\") # Append N zero's to the number so # as to make it divisible by 10^N for i in range(1, N + 1) : print(\"0\", end = \"\") print() # Driver CodeN = 5print(\"The number is : \",end=\"\")digitsNum(N) # This code is contributed by Gitanjali.",
"e": 3507,
"s": 2804,
"text": null
},
{
"code": "// C# program to find smallest// number to find smallest number// with N as sum of digits and// divisible by 10^N.using System; class GFG{ static void digitsNum(int N){ // If N = 0 the string will be 0 if (N == 0)Console.Write(\"0\"); // If n is not perfectly divisible // by 9 output the remainder if (N % 9 != 0) Console.Write((N % 9)); // Print 9 N/9 times for (int i = 1; i <= (N / 9); ++i) Console.Write(\"9\"); // Append N zero's to the number so // as to make it divisible by 10^N ) for (int i = 1; i <= N; ++i) Console.Write(\"0\"); Console.WriteLine(\"\" ); } // Driver Code public static void Main () { int N = 5; Console.Write(\"The number is : \"); digitsNum(N); }} // This code is contributed by vt_m",
"e": 4333,
"s": 3507,
"text": null
},
{
"code": "<?php// PHP program to find smallest// number to find smallest number// with N as sum of digits and// divisible by 10^N. function digitsNum($N){ // If N = 0 the string will be 0 if ($N == 0) echo \"0\\n\"; // If n is not perfectly divisible // by 9 output the remainder if ($N % 9 != 0) echo ($N % 9); // Print 9 N/9 times for ( $i = 1; $i <= ($N / 9); ++$i) echo \"9\"; // Append N zero's to the number so // as to make it divisible by 10^N for ($i = 1; $i <= $N; ++$i) echo \"0\"; echo \"\\n\";} // Driver Code$N = 5;echo \"The number is : \";digitsNum($N); // This code is contributed by ajit.?>",
"e": 5001,
"s": 4333,
"text": null
},
{
"code": "<script> // JavaScript program to find smallest // number to find smallest number // with N as sum of digits and // divisible by 10^N. function digitsNum(N) { // If N = 0 the string will be 0 if (N == 0) document.write(\"0\\n\"); // If n is not perfectly divisible // by 9 output the remainder if (N % 9 != 0) document.write(N % 9); // Print 9 N/9 times for (var i = 1; i <= N / 9; ++i) document.write(\"9\"); // Append N zero's to the number so // as to make it divisible by 10^N for (var i = 1; i <= N; ++i) document.write(\"0\"); document.write(\"\\n\"); } // Driver Code var N = 5; document.write(\"The number is : \"); digitsNum(N); // This code is contributed by rrrtnx. </script>",
"e": 5836,
"s": 5001,
"text": null
},
{
"code": null,
"e": 5847,
"s": 5836,
"text": "Output : "
},
{
"code": null,
"e": 5870,
"s": 5847,
"text": "The number is : 500000"
},
{
"code": null,
"e": 5895,
"s": 5872,
"text": "Time Complexity : O(N)"
},
{
"code": null,
"e": 5903,
"s": 5897,
"text": "jit_t"
},
{
"code": null,
"e": 5910,
"s": 5903,
"text": "rdtank"
},
{
"code": null,
"e": 5924,
"s": 5910,
"text": "number-digits"
},
{
"code": null,
"e": 5932,
"s": 5924,
"text": "Numbers"
},
{
"code": null,
"e": 5956,
"s": 5932,
"text": "Competitive Programming"
},
{
"code": null,
"e": 5963,
"s": 5956,
"text": "Greedy"
},
{
"code": null,
"e": 5976,
"s": 5963,
"text": "Mathematical"
},
{
"code": null,
"e": 5984,
"s": 5976,
"text": "Strings"
},
{
"code": null,
"e": 5992,
"s": 5984,
"text": "Strings"
},
{
"code": null,
"e": 5999,
"s": 5992,
"text": "Greedy"
},
{
"code": null,
"e": 6012,
"s": 5999,
"text": "Mathematical"
},
{
"code": null,
"e": 6020,
"s": 6012,
"text": "Numbers"
}
] |
JavaFX | Slider Class | 26 Jan, 2022
A Slider is a Control in JavaFX which is used to display a continuous or discrete range of valid numeric choices and allows the user to interact with the control. A slider is rendered as a vertical or horizontal bar with a knob that the user can slide to indicate the desired value. A slider can also have tick marks and labels to indicate the intervals along the bar. The three fundamental variables of the slider are min, max, and value. The value should always be a number within the range defined by min and max. min should always be less than to max. min defaults to 0, whereas max defaults to 100.Constructors of the class:
Slider(): Creates a default Slider instance.
Slider(double min, double max, double value): Constructs a Slider control with the specified slider min, max and current value values.
Commonly Used Methods:
Below programs illustrate the use of Slider class:
Simple Java program to implement the Slider Class: In this program we will create a group and Scene. Add Scene to the frame. Then, create a Slider and add it to the frame. Now launch the application.
Java
// Java program to implement the Slider Classimport javafx.application.Application;import javafx.scene.Group;import javafx.scene.Scene;import javafx.scene.control.Slider;import javafx.stage.Stage; public class SliderExample extends Application { public void start(Stage stage) { // creating group Group root = new Group(); Scene scene = new Scene(root, 600, 400); // set Scene to the stage stage.setScene(scene); // set title for the frame stage.setTitle("Slider Sample"); // create slider Slider slider = new Slider(); // add slider to the frame root.getChildren().add(slider); stage.show(); } // Main Method public static void main(String[] args) { // launch the application launch(args); }}
Output:
Java program to implement Slider class by using TickMarks and TickLabels: In this program we will create a Group and scene. Add the scene to the frame. Create a slider with specified min, max and value. Enable the Marks and Labels. Set MajorTickUnit with the specified value. Add the Slider to the frame and display it.
Java
// Java program to implement Slider class// by using TickMarks and TickLabelsimport javafx.application.Application;import javafx.scene.Group;import javafx.scene.Scene;import javafx.scene.control.Slider;import javafx.stage.Stage; public class SliderExample extends Application { public void start(Stage stage) { Group root = new Group(); // create a Scene Scene scene = new Scene(root, 600, 400); // add Scene to the frame stage.setScene(scene); // set title of the frame stage.setTitle("Slider Sample"); // Creates a slider Slider slider = new Slider(0, 1, 0.5); // enable the marks slider.setShowTickMarks(true); // enable the Labels slider.setShowTickLabels(true); // set Major tick unit slider.setMajorTickUnit(0.25f); // sets the value of the property // blockIncrement slider.setBlockIncrement(0.1f); root.getChildren().add(slider); // display stage.show(); } // Main Method public static void main(String[] args) { // Launch the application launch(args); }}
Output :
Java program to implement Slider Class using ChangeListener: In this program, we will create a Label and set the color for the text. Create a slider and set its min, max and value. Enable TickLabels and TickMarks. Set the value of the property blockIncrement. setBlockIncrement() method defines the distance that the thumb moves when a user clicks on the track. Add ChangeListener, on moving the slider the value of the brightness changes which will show in the label. Create a VBox and add to the frame. Create Scene and to the frame. Finally, launch the application.
Java
// Java program to implement Slider Class// using ChangeListenerimport javafx.application.Application;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.geometry.Insets;import javafx.scene.Scene;import javafx.scene.control.Label;import javafx.scene.control.Slider;import javafx.scene.layout.VBox;import javafx.scene.paint.Color;import javafx.stage.Stage; public class SliderExample extends Application { public void start(Stage stage) { // create label Label label = new Label("Select the Brightness"); Label l = new Label(" "); // set the color of the text l.setTextFill(Color.BLACK); // create slider Slider slider = new Slider(); // set the value of property min, // max and value slider.setMin(0); slider.setMax(100); slider.setValue(80); // enable TickLabels and Tick Marks slider.setShowTickLabels(true); slider.setShowTickMarks(true); slider.setBlockIncrement(10); // Adding Listener to value property. slider.valueProperty().addListener( new ChangeListener<Number>() { public void changed(ObservableValue <? extends Number > observable, Number oldValue, Number newValue) { l.setText("value: " + newValue); } }); // create a VBox VBox root = new VBox(); root.setPadding(new Insets(20)); root.setSpacing(10); root.getChildren().addAll(label, slider, l); stage.setTitle("Slider Sample"); // create Scene and add to the frame Scene scene = new Scene(root, 350, 200); stage.setScene(scene); stage.show(); } // Main Method public static void main(String[] args) { // Launch Application Application.launch(args); }}
Output:
Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Slider.html
sweetyty
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Set in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jan, 2022"
},
{
"code": null,
"e": 660,
"s": 28,
"text": "A Slider is a Control in JavaFX which is used to display a continuous or discrete range of valid numeric choices and allows the user to interact with the control. A slider is rendered as a vertical or horizontal bar with a knob that the user can slide to indicate the desired value. A slider can also have tick marks and labels to indicate the intervals along the bar. The three fundamental variables of the slider are min, max, and value. The value should always be a number within the range defined by min and max. min should always be less than to max. min defaults to 0, whereas max defaults to 100.Constructors of the class: "
},
{
"code": null,
"e": 705,
"s": 660,
"text": "Slider(): Creates a default Slider instance."
},
{
"code": null,
"e": 840,
"s": 705,
"text": "Slider(double min, double max, double value): Constructs a Slider control with the specified slider min, max and current value values."
},
{
"code": null,
"e": 863,
"s": 840,
"text": "Commonly Used Methods:"
},
{
"code": null,
"e": 915,
"s": 863,
"text": "Below programs illustrate the use of Slider class: "
},
{
"code": null,
"e": 1115,
"s": 915,
"text": "Simple Java program to implement the Slider Class: In this program we will create a group and Scene. Add Scene to the frame. Then, create a Slider and add it to the frame. Now launch the application."
},
{
"code": null,
"e": 1120,
"s": 1115,
"text": "Java"
},
{
"code": "// Java program to implement the Slider Classimport javafx.application.Application;import javafx.scene.Group;import javafx.scene.Scene;import javafx.scene.control.Slider;import javafx.stage.Stage; public class SliderExample extends Application { public void start(Stage stage) { // creating group Group root = new Group(); Scene scene = new Scene(root, 600, 400); // set Scene to the stage stage.setScene(scene); // set title for the frame stage.setTitle(\"Slider Sample\"); // create slider Slider slider = new Slider(); // add slider to the frame root.getChildren().add(slider); stage.show(); } // Main Method public static void main(String[] args) { // launch the application launch(args); }}",
"e": 1942,
"s": 1120,
"text": null
},
{
"code": null,
"e": 1950,
"s": 1942,
"text": "Output:"
},
{
"code": null,
"e": 2270,
"s": 1950,
"text": "Java program to implement Slider class by using TickMarks and TickLabels: In this program we will create a Group and scene. Add the scene to the frame. Create a slider with specified min, max and value. Enable the Marks and Labels. Set MajorTickUnit with the specified value. Add the Slider to the frame and display it."
},
{
"code": null,
"e": 2275,
"s": 2270,
"text": "Java"
},
{
"code": "// Java program to implement Slider class// by using TickMarks and TickLabelsimport javafx.application.Application;import javafx.scene.Group;import javafx.scene.Scene;import javafx.scene.control.Slider;import javafx.stage.Stage; public class SliderExample extends Application { public void start(Stage stage) { Group root = new Group(); // create a Scene Scene scene = new Scene(root, 600, 400); // add Scene to the frame stage.setScene(scene); // set title of the frame stage.setTitle(\"Slider Sample\"); // Creates a slider Slider slider = new Slider(0, 1, 0.5); // enable the marks slider.setShowTickMarks(true); // enable the Labels slider.setShowTickLabels(true); // set Major tick unit slider.setMajorTickUnit(0.25f); // sets the value of the property // blockIncrement slider.setBlockIncrement(0.1f); root.getChildren().add(slider); // display stage.show(); } // Main Method public static void main(String[] args) { // Launch the application launch(args); }}",
"e": 3434,
"s": 2275,
"text": null
},
{
"code": null,
"e": 3443,
"s": 3434,
"text": "Output :"
},
{
"code": null,
"e": 4012,
"s": 3443,
"text": "Java program to implement Slider Class using ChangeListener: In this program, we will create a Label and set the color for the text. Create a slider and set its min, max and value. Enable TickLabels and TickMarks. Set the value of the property blockIncrement. setBlockIncrement() method defines the distance that the thumb moves when a user clicks on the track. Add ChangeListener, on moving the slider the value of the brightness changes which will show in the label. Create a VBox and add to the frame. Create Scene and to the frame. Finally, launch the application."
},
{
"code": null,
"e": 4017,
"s": 4012,
"text": "Java"
},
{
"code": "// Java program to implement Slider Class// using ChangeListenerimport javafx.application.Application;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.geometry.Insets;import javafx.scene.Scene;import javafx.scene.control.Label;import javafx.scene.control.Slider;import javafx.scene.layout.VBox;import javafx.scene.paint.Color;import javafx.stage.Stage; public class SliderExample extends Application { public void start(Stage stage) { // create label Label label = new Label(\"Select the Brightness\"); Label l = new Label(\" \"); // set the color of the text l.setTextFill(Color.BLACK); // create slider Slider slider = new Slider(); // set the value of property min, // max and value slider.setMin(0); slider.setMax(100); slider.setValue(80); // enable TickLabels and Tick Marks slider.setShowTickLabels(true); slider.setShowTickMarks(true); slider.setBlockIncrement(10); // Adding Listener to value property. slider.valueProperty().addListener( new ChangeListener<Number>() { public void changed(ObservableValue <? extends Number > observable, Number oldValue, Number newValue) { l.setText(\"value: \" + newValue); } }); // create a VBox VBox root = new VBox(); root.setPadding(new Insets(20)); root.setSpacing(10); root.getChildren().addAll(label, slider, l); stage.setTitle(\"Slider Sample\"); // create Scene and add to the frame Scene scene = new Scene(root, 350, 200); stage.setScene(scene); stage.show(); } // Main Method public static void main(String[] args) { // Launch Application Application.launch(args); }}",
"e": 5915,
"s": 4017,
"text": null
},
{
"code": null,
"e": 5923,
"s": 5915,
"text": "Output:"
},
{
"code": null,
"e": 6099,
"s": 5923,
"text": "Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Slider.html"
},
{
"code": null,
"e": 6108,
"s": 6099,
"text": "sweetyty"
},
{
"code": null,
"e": 6115,
"s": 6108,
"text": "JavaFX"
},
{
"code": null,
"e": 6120,
"s": 6115,
"text": "Java"
},
{
"code": null,
"e": 6125,
"s": 6120,
"text": "Java"
},
{
"code": null,
"e": 6223,
"s": 6125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6274,
"s": 6223,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 6305,
"s": 6274,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 6335,
"s": 6305,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 6353,
"s": 6335,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 6368,
"s": 6353,
"text": "Stream In Java"
},
{
"code": null,
"e": 6388,
"s": 6368,
"text": "Collections in Java"
},
{
"code": null,
"e": 6412,
"s": 6388,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 6444,
"s": 6412,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6464,
"s": 6444,
"text": "Stack Class in Java"
}
] |
How to add readonly attribute to an input tag in JavaScript ? | 24 May, 2019
Use setAttribute() Method to add the readonly attribute to the form input field using JavaScript.
setAttribute() Method: This method adds the defined attribute to an element, and gives it the defined value. If the specified attribute already present, then the value is being set or changed.
Syntax:
element.setAttribute( attributeName, attributeValue )
Parameters:
attributeName: It is required parameter. It specifies the name of the attribute to be added.
attributeValue: It is required parameter. It specifies the value of the attribute to be added.
Example 1: In this example the read-only attribute of form input text field is enabled by accessing the property.
<!DOCTYPE HTML> <html> <head> <title> Add a readonly attribute to an input tag </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p style = "font-size: 15px; font-weight: bold;"> The readonly attribute is added to input box on click on the button. </p> <form> Input : <input id = "Input" type="text" name="input_field" /> </form> <br> <button onclick = "GFG_Run()"> click here </button> <p id = "GFG_down" style = "color: green; font-size: 20px; font-weight: bold;"> </p> <script> function GFG_Run() { document.getElementById('Input').readOnly = true; document.getElementById("GFG_down").innerHTML = "Read-Only attribute enabled"; } </script> </body> </html>
Output:
Before click on the button:
After click on the button:
Example 2: In this example the read-only attribute of form input text field is enabled by using setAttribute() method .
<!DOCTYPE HTML> <html> <head> <title> Add a readonly attribute to an input tag </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p style = "font-size: 15px; font-weight: bold;"> The readonly attribute is added to input box on click on the button. </p> <form> Input : <input id = "Input" type="text" name="input_field" /> </form> <br> <button onclick = "GFG_Run()"> click here </button> <p id = "GFG_down" style = "color: green; font-size: 20px; font-weight: bold;"> </p> <script> function GFG_Run() { document.getElementById('Input').setAttribute('readonly', true); document.getElementById("GFG_down").innerHTML = "Read-Only attribute enabled"; } </script> </body> </html>
Output:
Before click on the button:
After click on the button:
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 May, 2019"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "Use setAttribute() Method to add the readonly attribute to the form input field using JavaScript."
},
{
"code": null,
"e": 319,
"s": 126,
"text": "setAttribute() Method: This method adds the defined attribute to an element, and gives it the defined value. If the specified attribute already present, then the value is being set or changed."
},
{
"code": null,
"e": 327,
"s": 319,
"text": "Syntax:"
},
{
"code": null,
"e": 381,
"s": 327,
"text": "element.setAttribute( attributeName, attributeValue )"
},
{
"code": null,
"e": 393,
"s": 381,
"text": "Parameters:"
},
{
"code": null,
"e": 486,
"s": 393,
"text": "attributeName: It is required parameter. It specifies the name of the attribute to be added."
},
{
"code": null,
"e": 581,
"s": 486,
"text": "attributeValue: It is required parameter. It specifies the value of the attribute to be added."
},
{
"code": null,
"e": 695,
"s": 581,
"text": "Example 1: In this example the read-only attribute of form input text field is enabled by accessing the property."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Add a readonly attribute to an input tag </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p style = \"font-size: 15px; font-weight: bold;\"> The readonly attribute is added to input box on click on the button. </p> <form> Input : <input id = \"Input\" type=\"text\" name=\"input_field\" /> </form> <br> <button onclick = \"GFG_Run()\"> click here </button> <p id = \"GFG_down\" style = \"color: green; font-size: 20px; font-weight: bold;\"> </p> <script> function GFG_Run() { document.getElementById('Input').readOnly = true; document.getElementById(\"GFG_down\").innerHTML = \"Read-Only attribute enabled\"; } </script> </body> </html> ",
"e": 1822,
"s": 695,
"text": null
},
{
"code": null,
"e": 1830,
"s": 1822,
"text": "Output:"
},
{
"code": null,
"e": 1858,
"s": 1830,
"text": "Before click on the button:"
},
{
"code": null,
"e": 1885,
"s": 1858,
"text": "After click on the button:"
},
{
"code": null,
"e": 2005,
"s": 1885,
"text": "Example 2: In this example the read-only attribute of form input text field is enabled by using setAttribute() method ."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Add a readonly attribute to an input tag </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p style = \"font-size: 15px; font-weight: bold;\"> The readonly attribute is added to input box on click on the button. </p> <form> Input : <input id = \"Input\" type=\"text\" name=\"input_field\" /> </form> <br> <button onclick = \"GFG_Run()\"> click here </button> <p id = \"GFG_down\" style = \"color: green; font-size: 20px; font-weight: bold;\"> </p> <script> function GFG_Run() { document.getElementById('Input').setAttribute('readonly', true); document.getElementById(\"GFG_down\").innerHTML = \"Read-Only attribute enabled\"; } </script> </body> </html> ",
"e": 3127,
"s": 2005,
"text": null
},
{
"code": null,
"e": 3135,
"s": 3127,
"text": "Output:"
},
{
"code": null,
"e": 3163,
"s": 3135,
"text": "Before click on the button:"
},
{
"code": null,
"e": 3190,
"s": 3163,
"text": "After click on the button:"
},
{
"code": null,
"e": 3201,
"s": 3190,
"text": "JavaScript"
},
{
"code": null,
"e": 3218,
"s": 3201,
"text": "Web Technologies"
},
{
"code": null,
"e": 3245,
"s": 3218,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3343,
"s": 3245,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3404,
"s": 3343,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3476,
"s": 3404,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3516,
"s": 3476,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3557,
"s": 3516,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3603,
"s": 3557,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 3636,
"s": 3603,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3698,
"s": 3636,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3759,
"s": 3698,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3809,
"s": 3759,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
math.Inf() Function in Golang With Examples | 19 Oct, 2021
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can find positive infinity (if sign >= 0) or negative infinity (if sign < 0) with the help of the Inf() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access the Inf() function. Syntax:
func Inf(sign int) float64
Example 1:
C
// Golang program to illustrate the// math.Inf() Functionpackage main import ( "fmt" "math") // Main functionfunc main() { // Finding positive infinity // and negative infinity // Using Inf() function res_1 := math.Inf(-1) res_2 := math.Inf(1) // Displaying the result fmt.Println("Result 1: ", res_1) fmt.Println("Result 2: ", res_2) }
Output:
Result 1: -Inf
Result 2: +Inf
Example 2:
C
// Golang program to illustrate the// math.Inf() Functionpackage main import ( "fmt" "math") // Main functionfunc main() { // Finding positive infinity // and negative infinity // Using Inf() function nvalue := math.Inf(2) mvalue := math.Inf(-3) fmt.Println("Positive infinity: ", nvalue) fmt.Println("Negative infinity: ", mvalue) }
Output:
Positive infinity: +Inf
Negative infinity: -Inf
sweetyty
Golang-Math
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 458,
"s": 28,
"text": "Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can find positive infinity (if sign >= 0) or negative infinity (if sign < 0) with the help of the Inf() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access the Inf() function. Syntax: "
},
{
"code": null,
"e": 485,
"s": 458,
"text": "func Inf(sign int) float64"
},
{
"code": null,
"e": 497,
"s": 485,
"text": "Example 1: "
},
{
"code": null,
"e": 499,
"s": 497,
"text": "C"
},
{
"code": "// Golang program to illustrate the// math.Inf() Functionpackage main import ( \"fmt\" \"math\") // Main functionfunc main() { // Finding positive infinity // and negative infinity // Using Inf() function res_1 := math.Inf(-1) res_2 := math.Inf(1) // Displaying the result fmt.Println(\"Result 1: \", res_1) fmt.Println(\"Result 2: \", res_2) }",
"e": 868,
"s": 499,
"text": null
},
{
"code": null,
"e": 877,
"s": 868,
"text": "Output: "
},
{
"code": null,
"e": 907,
"s": 877,
"text": "Result 1: -Inf\nResult 2: +Inf"
},
{
"code": null,
"e": 919,
"s": 907,
"text": "Example 2: "
},
{
"code": null,
"e": 921,
"s": 919,
"text": "C"
},
{
"code": "// Golang program to illustrate the// math.Inf() Functionpackage main import ( \"fmt\" \"math\") // Main functionfunc main() { // Finding positive infinity // and negative infinity // Using Inf() function nvalue := math.Inf(2) mvalue := math.Inf(-3) fmt.Println(\"Positive infinity: \", nvalue) fmt.Println(\"Negative infinity: \", mvalue) }",
"e": 1284,
"s": 921,
"text": null
},
{
"code": null,
"e": 1293,
"s": 1284,
"text": "Output: "
},
{
"code": null,
"e": 1343,
"s": 1293,
"text": "Positive infinity: +Inf\nNegative infinity: -Inf"
},
{
"code": null,
"e": 1354,
"s": 1345,
"text": "sweetyty"
},
{
"code": null,
"e": 1366,
"s": 1354,
"text": "Golang-Math"
},
{
"code": null,
"e": 1378,
"s": 1366,
"text": "Go Language"
}
] |
Passing a function as a parameter in C++ | 30 Jun, 2021
A function is a set of statements that take inputs, perform some specific computation, and produce output. The idea to use functions is to perform some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs. The general form of a function is:
return_type function_name([ arg1_type arg1_name, ... ]) {
// Perform Operations
}
Passing a function as an argument is a useful concept in C/C++. This concept has already been used while passing a custom comparator function as an argument in std::sort() to sort a sequence of objects as per the need. In this article, we will discuss different ways to design functions that accept another function as an argument.
Passing pointer to a function:
A function can also be passed to another function by passing its address to that function. Below is the C++ program to illustrate the same:
C++
// C++ program to pass function as a// pointer to any function #include <iostream>using namespace std; // Function that add two numbersint add(int x, int y){ return x + y;} // Function that multiplies two// numbersint multiply(int x, int y){ return x * y;} // Function that takes a pointer// to a functionint invoke(int x, int y, int (*func)(int, int)){ return func(x, y);} // Driver Codeint main(){ // Pass pointers to add & multiply // function as required cout << "Addition of 20 and 10 is "; cout << invoke(20, 10, &add) << '\n'; cout << "Multiplication of 20" << " and 10 is "; cout << invoke(20, 10, &multiply) << '\n'; return 0;}
Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200
Using std::function<>:
In C++ 11, there is a std::function<> template class that allows to pass functions as objects. An object of std::function<> can be created as follows.
std::function<return_type(arg1_type, arg2-type...)> obj_name
// This object can be use to call the function as below
return_type catch_variable = obj_name(arg1, arg2);
Below is the program to illustrate the passing of a function object as a parameter to another function:
C++
// C++ program to illustrate the passing// of functions as an object parameter#include <functional>#include <iostream>using namespace std; // Define add and multiply to// return respective valuesint add(int x, int y){ return x + y;}int multiply(int x, int y){ return x * y;} // Function that accepts an object of// type std::function<> as a parameter// as wellint invoke(int x, int y, function<int(int, int)> func){ return func(x, y);} // Driver codeint main(){ // Pass the required function as // parameter using its name cout << "Addition of 20 and 10 is "; cout << invoke(20, 10, &add) << '\n'; cout << "Multiplication of 20" << " and 10 is "; cout << invoke(20, 10, &multiply) << '\n'; return 0;}
Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200
Using lambdas:
Lambdas in C++ provides a way to define inline, one-time, anonymous function objects. These lambdas can be defined in a place where it is required to pass a function as an argument. Below is the C++ program to illustrate the same:
C++
// C++ program to pass the function as// parameter as a lambda expression#include <functional>#include <iostream>using namespace std; // Function that takes a pointer// to a functionint invoke(int x, int y, function<int(int, int)> func){ return func(x, y);} // Driver Codeint main(){ // Define lambdas for addition and // multiplication operation where // we want to pass another function // as a parameter // Perform Addition cout << "Addition of 20 and 10 is "; int k = invoke(20, 10, [](int x, int y) -> int { return x + y; }); cout << k << '\n'; // Perform Multiplication cout << "Multiplication of 20" << " and 10 is "; int l = invoke(20, 10, [](int x, int y) -> int { return x * y; }); cout << l << '\n'; return 0;}
Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200
CPP-Basics
CPP-Functions
C++
C++ Programs
CPP
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, 2021"
},
{
"code": null,
"e": 381,
"s": 52,
"text": "A function is a set of statements that take inputs, perform some specific computation, and produce output. The idea to use functions is to perform some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs. The general form of a function is:"
},
{
"code": null,
"e": 439,
"s": 381,
"text": "return_type function_name([ arg1_type arg1_name, ... ]) {"
},
{
"code": null,
"e": 466,
"s": 439,
"text": " // Perform Operations"
},
{
"code": null,
"e": 468,
"s": 466,
"text": "}"
},
{
"code": null,
"e": 800,
"s": 468,
"text": "Passing a function as an argument is a useful concept in C/C++. This concept has already been used while passing a custom comparator function as an argument in std::sort() to sort a sequence of objects as per the need. In this article, we will discuss different ways to design functions that accept another function as an argument."
},
{
"code": null,
"e": 831,
"s": 800,
"text": "Passing pointer to a function:"
},
{
"code": null,
"e": 971,
"s": 831,
"text": "A function can also be passed to another function by passing its address to that function. Below is the C++ program to illustrate the same:"
},
{
"code": null,
"e": 975,
"s": 971,
"text": "C++"
},
{
"code": "// C++ program to pass function as a// pointer to any function #include <iostream>using namespace std; // Function that add two numbersint add(int x, int y){ return x + y;} // Function that multiplies two// numbersint multiply(int x, int y){ return x * y;} // Function that takes a pointer// to a functionint invoke(int x, int y, int (*func)(int, int)){ return func(x, y);} // Driver Codeint main(){ // Pass pointers to add & multiply // function as required cout << \"Addition of 20 and 10 is \"; cout << invoke(20, 10, &add) << '\\n'; cout << \"Multiplication of 20\" << \" and 10 is \"; cout << invoke(20, 10, &multiply) << '\\n'; return 0;}",
"e": 1685,
"s": 975,
"text": null
},
{
"code": null,
"e": 1749,
"s": 1685,
"text": "Addition of 20 and 10 is 30\nMultiplication of 20 and 10 is 200\n"
},
{
"code": null,
"e": 1772,
"s": 1749,
"text": "Using std::function<>:"
},
{
"code": null,
"e": 1924,
"s": 1772,
"text": "In C++ 11, there is a std::function<> template class that allows to pass functions as objects. An object of std::function<> can be created as follows. "
},
{
"code": null,
"e": 1985,
"s": 1924,
"text": "std::function<return_type(arg1_type, arg2-type...)> obj_name"
},
{
"code": null,
"e": 2049,
"s": 1985,
"text": " // This object can be use to call the function as below"
},
{
"code": null,
"e": 2100,
"s": 2049,
"text": "return_type catch_variable = obj_name(arg1, arg2);"
},
{
"code": null,
"e": 2204,
"s": 2100,
"text": "Below is the program to illustrate the passing of a function object as a parameter to another function:"
},
{
"code": null,
"e": 2208,
"s": 2204,
"text": "C++"
},
{
"code": "// C++ program to illustrate the passing// of functions as an object parameter#include <functional>#include <iostream>using namespace std; // Define add and multiply to// return respective valuesint add(int x, int y){ return x + y;}int multiply(int x, int y){ return x * y;} // Function that accepts an object of// type std::function<> as a parameter// as wellint invoke(int x, int y, function<int(int, int)> func){ return func(x, y);} // Driver codeint main(){ // Pass the required function as // parameter using its name cout << \"Addition of 20 and 10 is \"; cout << invoke(20, 10, &add) << '\\n'; cout << \"Multiplication of 20\" << \" and 10 is \"; cout << invoke(20, 10, &multiply) << '\\n'; return 0;}",
"e": 2980,
"s": 2208,
"text": null
},
{
"code": null,
"e": 3044,
"s": 2980,
"text": "Addition of 20 and 10 is 30\nMultiplication of 20 and 10 is 200\n"
},
{
"code": null,
"e": 3059,
"s": 3044,
"text": "Using lambdas:"
},
{
"code": null,
"e": 3291,
"s": 3059,
"text": "Lambdas in C++ provides a way to define inline, one-time, anonymous function objects. These lambdas can be defined in a place where it is required to pass a function as an argument. Below is the C++ program to illustrate the same: "
},
{
"code": null,
"e": 3295,
"s": 3291,
"text": "C++"
},
{
"code": "// C++ program to pass the function as// parameter as a lambda expression#include <functional>#include <iostream>using namespace std; // Function that takes a pointer// to a functionint invoke(int x, int y, function<int(int, int)> func){ return func(x, y);} // Driver Codeint main(){ // Define lambdas for addition and // multiplication operation where // we want to pass another function // as a parameter // Perform Addition cout << \"Addition of 20 and 10 is \"; int k = invoke(20, 10, [](int x, int y) -> int { return x + y; }); cout << k << '\\n'; // Perform Multiplication cout << \"Multiplication of 20\" << \" and 10 is \"; int l = invoke(20, 10, [](int x, int y) -> int { return x * y; }); cout << l << '\\n'; return 0;}",
"e": 4249,
"s": 3295,
"text": null
},
{
"code": null,
"e": 4313,
"s": 4249,
"text": "Addition of 20 and 10 is 30\nMultiplication of 20 and 10 is 200\n"
},
{
"code": null,
"e": 4324,
"s": 4313,
"text": "CPP-Basics"
},
{
"code": null,
"e": 4338,
"s": 4324,
"text": "CPP-Functions"
},
{
"code": null,
"e": 4342,
"s": 4338,
"text": "C++"
},
{
"code": null,
"e": 4355,
"s": 4342,
"text": "C++ Programs"
},
{
"code": null,
"e": 4359,
"s": 4355,
"text": "CPP"
}
] |
Java Swing | ScrollPaneLayout Class | 20 May, 2022
The layout manager used by JScrollPane. JScrollPaneLayout is based on nine components: a viewport, two scrollbars, a row header, a column header, and four “corner” components.
Constructor of the class:
ScrollPaneLayout(): It is used to Construct a new ScrollPaneLayout.
Commonly Used Methods:
removeLayoutComponent(Component comp): Removes the specified component from the layout.getColumnHeader(): It returns the JViewport object that is the column header.getVerticalScrollBar(): Returns the JScrollBar object that handles the vertical scrolling.getHorizontalScrollBar(): Returns the JScrollBar object that handles the horizontal scrolling.addLayoutComponent(String st, Component c): Adds the specified component to the layout.getViewport(): Returns the JViewport object that displays the scrollable contents.getCorner(String key):It is used to returns the Component at the specified corner.
removeLayoutComponent(Component comp): Removes the specified component from the layout.
getColumnHeader(): It returns the JViewport object that is the column header.
getVerticalScrollBar(): Returns the JScrollBar object that handles the vertical scrolling.
getHorizontalScrollBar(): Returns the JScrollBar object that handles the horizontal scrolling.
addLayoutComponent(String st, Component c): Adds the specified component to the layout.
getViewport(): Returns the JViewport object that displays the scrollable contents.
getCorner(String key):It is used to returns the Component at the specified corner.
Below programs illustrate the use of ScrollPaneLayout class:
1. The following program illustrates the use of ScrollPaneLayout by arranging several JLabel components in a JFrame, whose instance class is “Geeks“. We create one JScrollPane component named “scrollpane” and one JList component named “list“. We set the size and visibility of the frame by using setSize() and setVisible() method. The layout is set by using setLayout() method.
Java
// Java Program to illustrate the// ScrollPaneLayout classimport java.awt.BorderLayout;import javax.swing.JFrame;import javax.swing.JList;import javax.swing.JScrollPane; // create a class Geeks extending JFramepublic class Geeks extends JFrame { // Declaration of objects of the // JScrollPane class. JScrollPane scrollpane; // Constructor of Geeks class public Geeks() { // used to call super class // variables and methods super("JScrollPane Demonstration"); // Function to set size of JFrame. setSize(300, 200); // Function to set Default close // operation of JFrame. setDefaultCloseOperation(EXIT_ON_CLOSE); // to contain a string value String categories[] = {"Geeks", "Language", "Java", "Sudo Placement", "Python", "CS Subject", "Operating System", "Data Structure", "Algorithm", "PHP language", "JAVASCRIPT", "C Sharp" }; // Creating Object of "JList" class JList list = new JList(categories); // Creating Object of // "scrollpane" class scrollpane = new JScrollPane(list); // to get content pane getContentPane().add(scrollpane, BorderLayout.CENTER); } // Main Method public static void main(String args[]) { // Creating Object of Geeks class. Geeks sl = new Geeks(); // Function to set visibility of JFrame. sl.setVisible(true); }}
Output:
2. The following program illustrates the use of ScrollPaneLayout by arranging several JLabel components in a JFrame, whose instance class is named as “ScrollPanel”. We create one JScrollPane component named “scrollpane”. Also, JRadioButtonand ButtonGroup are created. We set the size and visibility of the frame by using setSize() and setVisible() method. The layout is set by using setLayout() method.
Java
// Java Program to illustrate the// ScrollPaneLayout classimport java.awt.BorderLayout;import java.awt.GridLayout;import javax.swing.ButtonGroup;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JRadioButton;import javax.swing.JScrollPane; // create a class ScrollPanel// extending JFramepublic class ScrollPanel extends JFrame { // Declaration of objects of the // JScrollPane class JScrollPane scrollpane; // Constructor of ScrollPanel class public ScrollPanel() { // used to call super class // variables and methods super("JScrollPane Demonstration"); // Function to set size of JFrame. setSize(300, 200); // Function to set Default // close operation of JFrame. setDefaultCloseOperation(EXIT_ON_CLOSE); init(); // Function to set // visible of JFrame. setVisible(true); } // class init public void init() { // Declaration of objects // of JRadioButton class. JRadioButton form[][] = new JRadioButton[12][5]; // to contain a string count String counts[] = {"", "1 star", "2 star", "3 star", "4 star", "5 star"}; // to contain a string value String categories[] = {"Geeks", "Language", "Java", "Sudo Placement", "Python", "CS Subject", "Operating System", "Data Structure", "Algorithm", "PHP language", "JAVASCRIPT", "C Sharp" }; // Declaration of objects // of the JPanel class. JPanel p = new JPanel(); // Function to set size of JFrame. p.setSize(600, 400); // Function to set Layout of JFrame. p.setLayout(new GridLayout(13, 6, 10, 0)); // for loop for (int row = 0; row < 13; row++) { // Declaration of objects // of ButtonGroup class ButtonGroup bg = new ButtonGroup(); for (int col = 0; col < 6; col++) { // If condition if (row == 0) { // add new Jlabel p.add(new JLabel(counts[col])); } else { // If condition if (col == 0) { // add new Jlabel p.add(new JLabel(categories[row - 1])); } else { form[row - 1][col - 1] = new JRadioButton(); // add form in ButtonGroup bg.add(form[row - 1][col - 1]); // add form in JFrame p.add(form[row - 1][col - 1]); } } } } // Declaration of objects // of scrollpane class. scrollpane = new JScrollPane(p); // to get content pane getContentPane().add(scrollpane, BorderLayout.CENTER); } // Main Method public static void main(String args[]) { new ScrollPanel(); }}
Output:
Note: The above programs might not run in an online IDE. Please use an offline compiler.
Reference: https://docs.oracle.com/javase/7/docs/api/javax/swing/ScrollPaneLayout.html
anikaseth98
rkbhola5
java-swing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 May, 2022"
},
{
"code": null,
"e": 228,
"s": 52,
"text": "The layout manager used by JScrollPane. JScrollPaneLayout is based on nine components: a viewport, two scrollbars, a row header, a column header, and four “corner” components."
},
{
"code": null,
"e": 255,
"s": 228,
"text": "Constructor of the class: "
},
{
"code": null,
"e": 323,
"s": 255,
"text": "ScrollPaneLayout(): It is used to Construct a new ScrollPaneLayout."
},
{
"code": null,
"e": 347,
"s": 323,
"text": "Commonly Used Methods: "
},
{
"code": null,
"e": 947,
"s": 347,
"text": "removeLayoutComponent(Component comp): Removes the specified component from the layout.getColumnHeader(): It returns the JViewport object that is the column header.getVerticalScrollBar(): Returns the JScrollBar object that handles the vertical scrolling.getHorizontalScrollBar(): Returns the JScrollBar object that handles the horizontal scrolling.addLayoutComponent(String st, Component c): Adds the specified component to the layout.getViewport(): Returns the JViewport object that displays the scrollable contents.getCorner(String key):It is used to returns the Component at the specified corner."
},
{
"code": null,
"e": 1035,
"s": 947,
"text": "removeLayoutComponent(Component comp): Removes the specified component from the layout."
},
{
"code": null,
"e": 1113,
"s": 1035,
"text": "getColumnHeader(): It returns the JViewport object that is the column header."
},
{
"code": null,
"e": 1204,
"s": 1113,
"text": "getVerticalScrollBar(): Returns the JScrollBar object that handles the vertical scrolling."
},
{
"code": null,
"e": 1299,
"s": 1204,
"text": "getHorizontalScrollBar(): Returns the JScrollBar object that handles the horizontal scrolling."
},
{
"code": null,
"e": 1387,
"s": 1299,
"text": "addLayoutComponent(String st, Component c): Adds the specified component to the layout."
},
{
"code": null,
"e": 1470,
"s": 1387,
"text": "getViewport(): Returns the JViewport object that displays the scrollable contents."
},
{
"code": null,
"e": 1553,
"s": 1470,
"text": "getCorner(String key):It is used to returns the Component at the specified corner."
},
{
"code": null,
"e": 1615,
"s": 1553,
"text": "Below programs illustrate the use of ScrollPaneLayout class: "
},
{
"code": null,
"e": 1993,
"s": 1615,
"text": "1. The following program illustrates the use of ScrollPaneLayout by arranging several JLabel components in a JFrame, whose instance class is “Geeks“. We create one JScrollPane component named “scrollpane” and one JList component named “list“. We set the size and visibility of the frame by using setSize() and setVisible() method. The layout is set by using setLayout() method."
},
{
"code": null,
"e": 1998,
"s": 1993,
"text": "Java"
},
{
"code": "// Java Program to illustrate the// ScrollPaneLayout classimport java.awt.BorderLayout;import javax.swing.JFrame;import javax.swing.JList;import javax.swing.JScrollPane; // create a class Geeks extending JFramepublic class Geeks extends JFrame { // Declaration of objects of the // JScrollPane class. JScrollPane scrollpane; // Constructor of Geeks class public Geeks() { // used to call super class // variables and methods super(\"JScrollPane Demonstration\"); // Function to set size of JFrame. setSize(300, 200); // Function to set Default close // operation of JFrame. setDefaultCloseOperation(EXIT_ON_CLOSE); // to contain a string value String categories[] = {\"Geeks\", \"Language\", \"Java\", \"Sudo Placement\", \"Python\", \"CS Subject\", \"Operating System\", \"Data Structure\", \"Algorithm\", \"PHP language\", \"JAVASCRIPT\", \"C Sharp\" }; // Creating Object of \"JList\" class JList list = new JList(categories); // Creating Object of // \"scrollpane\" class scrollpane = new JScrollPane(list); // to get content pane getContentPane().add(scrollpane, BorderLayout.CENTER); } // Main Method public static void main(String args[]) { // Creating Object of Geeks class. Geeks sl = new Geeks(); // Function to set visibility of JFrame. sl.setVisible(true); }}",
"e": 3602,
"s": 1998,
"text": null
},
{
"code": null,
"e": 3611,
"s": 3602,
"text": "Output: "
},
{
"code": null,
"e": 4014,
"s": 3611,
"text": "2. The following program illustrates the use of ScrollPaneLayout by arranging several JLabel components in a JFrame, whose instance class is named as “ScrollPanel”. We create one JScrollPane component named “scrollpane”. Also, JRadioButtonand ButtonGroup are created. We set the size and visibility of the frame by using setSize() and setVisible() method. The layout is set by using setLayout() method."
},
{
"code": null,
"e": 4019,
"s": 4014,
"text": "Java"
},
{
"code": "// Java Program to illustrate the// ScrollPaneLayout classimport java.awt.BorderLayout;import java.awt.GridLayout;import javax.swing.ButtonGroup;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JRadioButton;import javax.swing.JScrollPane; // create a class ScrollPanel// extending JFramepublic class ScrollPanel extends JFrame { // Declaration of objects of the // JScrollPane class JScrollPane scrollpane; // Constructor of ScrollPanel class public ScrollPanel() { // used to call super class // variables and methods super(\"JScrollPane Demonstration\"); // Function to set size of JFrame. setSize(300, 200); // Function to set Default // close operation of JFrame. setDefaultCloseOperation(EXIT_ON_CLOSE); init(); // Function to set // visible of JFrame. setVisible(true); } // class init public void init() { // Declaration of objects // of JRadioButton class. JRadioButton form[][] = new JRadioButton[12][5]; // to contain a string count String counts[] = {\"\", \"1 star\", \"2 star\", \"3 star\", \"4 star\", \"5 star\"}; // to contain a string value String categories[] = {\"Geeks\", \"Language\", \"Java\", \"Sudo Placement\", \"Python\", \"CS Subject\", \"Operating System\", \"Data Structure\", \"Algorithm\", \"PHP language\", \"JAVASCRIPT\", \"C Sharp\" }; // Declaration of objects // of the JPanel class. JPanel p = new JPanel(); // Function to set size of JFrame. p.setSize(600, 400); // Function to set Layout of JFrame. p.setLayout(new GridLayout(13, 6, 10, 0)); // for loop for (int row = 0; row < 13; row++) { // Declaration of objects // of ButtonGroup class ButtonGroup bg = new ButtonGroup(); for (int col = 0; col < 6; col++) { // If condition if (row == 0) { // add new Jlabel p.add(new JLabel(counts[col])); } else { // If condition if (col == 0) { // add new Jlabel p.add(new JLabel(categories[row - 1])); } else { form[row - 1][col - 1] = new JRadioButton(); // add form in ButtonGroup bg.add(form[row - 1][col - 1]); // add form in JFrame p.add(form[row - 1][col - 1]); } } } } // Declaration of objects // of scrollpane class. scrollpane = new JScrollPane(p); // to get content pane getContentPane().add(scrollpane, BorderLayout.CENTER); } // Main Method public static void main(String args[]) { new ScrollPanel(); }}",
"e": 7302,
"s": 4019,
"text": null
},
{
"code": null,
"e": 7310,
"s": 7302,
"text": "Output:"
},
{
"code": null,
"e": 7399,
"s": 7310,
"text": "Note: The above programs might not run in an online IDE. Please use an offline compiler."
},
{
"code": null,
"e": 7487,
"s": 7399,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/javax/swing/ScrollPaneLayout.html "
},
{
"code": null,
"e": 7499,
"s": 7487,
"text": "anikaseth98"
},
{
"code": null,
"e": 7508,
"s": 7499,
"text": "rkbhola5"
},
{
"code": null,
"e": 7519,
"s": 7508,
"text": "java-swing"
},
{
"code": null,
"e": 7524,
"s": 7519,
"text": "Java"
},
{
"code": null,
"e": 7529,
"s": 7524,
"text": "Java"
},
{
"code": null,
"e": 7627,
"s": 7529,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7642,
"s": 7627,
"text": "Stream In Java"
},
{
"code": null,
"e": 7663,
"s": 7642,
"text": "Introduction to Java"
},
{
"code": null,
"e": 7684,
"s": 7663,
"text": "Constructors in Java"
},
{
"code": null,
"e": 7703,
"s": 7684,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 7720,
"s": 7703,
"text": "Generics in Java"
},
{
"code": null,
"e": 7750,
"s": 7720,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 7776,
"s": 7750,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 7792,
"s": 7776,
"text": "Strings in Java"
},
{
"code": null,
"e": 7829,
"s": 7792,
"text": "Differences between JDK, JRE and JVM"
}
] |
Handwritten Digit Recognition using Neural Network | 29 Oct, 2021
Handwritten digit recognition using MNIST dataset is a major project made with the help of Neural Network. It basically detects the scanned images of handwritten digits.
We have taken this a step further where our handwritten digit recognition system not only detects scanned images of handwritten digits but also allows writing digits on the screen with the help of an integrated GUI for recognition.
We will approach this project by using a three-layered Neural Network.
The input layer: It distributes the features of our examples to the next layer for calculation of activations of the next layer.
The hidden layer: They are made of hidden units called activations providing nonlinear ties for the network. A number of hidden layers can vary according to our requirements.
The output layer: The nodes here are called output units. It provides us with the final prediction of the Neural Network on the basis of which final predictions can be made.
A neural network is a model inspired by how the brain works. It consists of multiple layers having many activations, this activation resembles neurons of our brain. A neural network tries to learn a set of parameters in a set of data which could help to recognize the underlying relationships. Neural networks can adapt to changing input; so the network generates the best possible result without needing to redesign the output criteria.
We have implemented a Neural Network with 1 hidden layer having 100 activation units (excluding bias units). The data is loaded from a .mat file, features(X) and labels(y) were extracted. Then features are divided by 255 to rescale them into a range of [0,1] to avoid overflow during computation. Data is split up into 60,000 training and 10,000 testing examples. Feedforward is performed with the training set for calculating the hypothesis and then backpropagation is done in order to reduce the error between the layers. The regularization parameter lambda is set to 0.1 to address the problem of overfitting. Optimizer is run for 70 iterations to find the best fit model.
Layers of Neural Network
Note:
Save all .py files in the same directory.
Download dataset from https://www.kaggle.com/avnishnish/mnist-original/download
Importing all the required libraries, extract the data from mnist-original.mat file. Then features and labels will be separated from extracted data. After that data will be split into training (60,000) and testing (10,000) examples. Randomly initialize Thetas in the range of [-0.15, +0.15] to break symmetry and get better results. Further, the optimizer is called for the training of weights, to minimize the cost function for appropriate predictions. We have used the “minimize” optimizer from “scipy.optimize” library with “L-BFGS-B” method. We have calculated the test, the “training set accuracy and precision using “predict” function.
Python3
from scipy.io import loadmatimport numpy as npfrom Model import neural_networkfrom RandInitialize import initialisefrom Prediction import predictfrom scipy.optimize import minimize # Loading mat filedata = loadmat('mnist-original.mat') # Extracting features from mat fileX = data['data']X = X.transpose() # Normalizing the dataX = X / 255 # Extracting labels from mat filey = data['label']y = y.flatten() # Splitting data into training set with 60,000 examplesX_train = X[:60000, :]y_train = y[:60000] # Splitting data into testing set with 10,000 examplesX_test = X[60000:, :]y_test = y[60000:] m = X.shape[0]input_layer_size = 784 # Images are of (28 X 28) px so there will be 784 featureshidden_layer_size = 100num_labels = 10 # There are 10 classes [0, 9] # Randomly initialising Thetasinitial_Theta1 = initialise(hidden_layer_size, input_layer_size)initial_Theta2 = initialise(num_labels, hidden_layer_size) # Unrolling parameters into a single column vectorinitial_nn_params = np.concatenate((initial_Theta1.flatten(), initial_Theta2.flatten()))maxiter = 100lambda_reg = 0.1 # To avoid overfittingmyargs = (input_layer_size, hidden_layer_size, num_labels, X_train, y_train, lambda_reg) # Calling minimize function to minimize cost function and to train weightsresults = minimize(neural_network, x0=initial_nn_params, args=myargs, options={'disp': True, 'maxiter': maxiter}, method="L-BFGS-B", jac=True) nn_params = results["x"] # Trained Theta is extracted # Weights are split back to Theta1, Theta2Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)], ( hidden_layer_size, input_layer_size + 1)) # shape = (100, 785)Theta2 = np.reshape(nn_params[hidden_layer_size * (input_layer_size + 1):], (num_labels, hidden_layer_size + 1)) # shape = (10, 101) # Checking test set accuracy of our modelpred = predict(Theta1, Theta2, X_test)print('Test Set Accuracy: {:f}'.format((np.mean(pred == y_test) * 100))) # Checking train set accuracy of our modelpred = predict(Theta1, Theta2, X_train)print('Training Set Accuracy: {:f}'.format((np.mean(pred == y_train) * 100))) # Evaluating precision of our modeltrue_positive = 0for i in range(len(pred)): if pred[i] == y_train[i]: true_positive += 1false_positive = len(y_train) - true_positiveprint('Precision =', true_positive/(true_positive + false_positive)) # Saving Thetas in .txt filenp.savetxt('Theta1.txt', Theta1, delimiter=' ')np.savetxt('Theta2.txt', Theta2, delimiter=' ')
It randomly initializes theta between a range of [-epsilon, +epsilon].
Python3
import numpy as np def initialise(a, b): epsilon = 0.15 c = np.random.rand(a, b + 1) * ( # Randomly initialises values of thetas between [-epsilon, +epsilon] 2 * epsilon) - epsilon return c
The function performs feed-forward and backpropagation.
Forward propagation: Input data is fed in the forward direction through the network. Each hidden layer accepts the input data, processes it as per the activation function and passes it to the successive layer. We will use the sigmoid function as our “activation function”.
Backward propagation: It is the practice of fine-tuning the weights of a neural net based on the error rate obtained in the previous iteration.
It also calculates cross-entropy costs for checking the errors between the prediction and original values. In the end, the gradient is calculated for the optimization objective.
Python3
import numpy as np def neural_network(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lamb): # Weights are split back to Theta1, Theta2 Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)], (hidden_layer_size, input_layer_size + 1)) Theta2 = np.reshape(nn_params[hidden_layer_size * (input_layer_size + 1):], (num_labels, hidden_layer_size + 1)) # Forward propagation m = X.shape[0] one_matrix = np.ones((m, 1)) X = np.append(one_matrix, X, axis=1) # Adding bias unit to first layer a1 = X z2 = np.dot(X, Theta1.transpose()) a2 = 1 / (1 + np.exp(-z2)) # Activation for second layer one_matrix = np.ones((m, 1)) a2 = np.append(one_matrix, a2, axis=1) # Adding bias unit to hidden layer z3 = np.dot(a2, Theta2.transpose()) a3 = 1 / (1 + np.exp(-z3)) # Activation for third layer # Changing the y labels into vectors of boolean values. # For each label between 0 and 9, there will be a vector of length 10 # where the ith element will be 1 if the label equals i y_vect = np.zeros((m, 10)) for i in range(m): y_vect[i, int(y[i])] = 1 # Calculating cost function J = (1 / m) * (np.sum(np.sum(-y_vect * np.log(a3) - (1 - y_vect) * np.log(1 - a3)))) + (lamb / (2 * m)) * ( sum(sum(pow(Theta1[:, 1:], 2))) + sum(sum(pow(Theta2[:, 1:], 2)))) # backprop Delta3 = a3 - y_vect Delta2 = np.dot(Delta3, Theta2) * a2 * (1 - a2) Delta2 = Delta2[:, 1:] # gradient Theta1[:, 0] = 0 Theta1_grad = (1 / m) * np.dot(Delta2.transpose(), a1) + (lamb / m) * Theta1 Theta2[:, 0] = 0 Theta2_grad = (1 / m) * np.dot(Delta3.transpose(), a2) + (lamb / m) * Theta2 grad = np.concatenate((Theta1_grad.flatten(), Theta2_grad.flatten())) return J, grad
It performs forward propagation to predict the digit.
Python3
import numpy as np def predict(Theta1, Theta2, X): m = X.shape[0] one_matrix = np.ones((m, 1)) X = np.append(one_matrix, X, axis=1) # Adding bias unit to first layer z2 = np.dot(X, Theta1.transpose()) a2 = 1 / (1 + np.exp(-z2)) # Activation for second layer one_matrix = np.ones((m, 1)) a2 = np.append(one_matrix, a2, axis=1) # Adding bias unit to hidden layer z3 = np.dot(a2, Theta2.transpose()) a3 = 1 / (1 + np.exp(-z3)) # Activation for third layer p = (np.argmax(a3, axis=1)) # Predicting the class on the basis of max value of hypothesis return p
It launches a GUI for writing digits. The image of the digit is stored in the same directory after converting it to grayscale and reducing the size to (28 X 28) pixels.
Python3
from tkinter import *import numpy as npfrom PIL import ImageGrabfrom Prediction import predict window = Tk()window.title("Handwritten digit recognition")l1 = Label() def MyProject(): global l1 widget = cv # Setting co-ordinates of canvas x = window.winfo_rootx() + widget.winfo_x() y = window.winfo_rooty() + widget.winfo_y() x1 = x + widget.winfo_width() y1 = y + widget.winfo_height() # Image is captured from canvas and is resized to (28 X 28) px img = ImageGrab.grab().crop((x, y, x1, y1)).resize((28, 28)) # Converting rgb to grayscale image img = img.convert('L') # Extracting pixel matrix of image and converting it to a vector of (1, 784) x = np.asarray(img) vec = np.zeros((1, 784)) k = 0 for i in range(28): for j in range(28): vec[0][k] = x[i][j] k += 1 # Loading Thetas Theta1 = np.loadtxt('Theta1.txt') Theta2 = np.loadtxt('Theta2.txt') # Calling function for prediction pred = predict(Theta1, Theta2, vec / 255) # Displaying the result l1 = Label(window, text="Digit = " + str(pred[0]), font=('Algerian', 20)) l1.place(x=230, y=420) lastx, lasty = None, None # Clears the canvasdef clear_widget(): global cv, l1 cv.delete("all") l1.destroy() # Activate canvasdef event_activation(event): global lastx, lasty cv.bind('<B1-Motion>', draw_lines) lastx, lasty = event.x, event.y # To draw on canvasdef draw_lines(event): global lastx, lasty x, y = event.x, event.y cv.create_line((lastx, lasty, x, y), width=30, fill='white', capstyle=ROUND, smooth=TRUE, splinesteps=12) lastx, lasty = x, y # LabelL1 = Label(window, text="Handwritten Digit Recoginition", font=('Algerian', 25), fg="blue")L1.place(x=35, y=10) # Button to clear canvasb1 = Button(window, text="1. Clear Canvas", font=('Algerian', 15), bg="orange", fg="black", command=clear_widget)b1.place(x=120, y=370) # Button to predict digit drawn on canvasb2 = Button(window, text="2. Prediction", font=('Algerian', 15), bg="white", fg="red", command=MyProject)b2.place(x=320, y=370) # Setting properties of canvascv = Canvas(window, width=350, height=290, bg='black')cv.place(x=120, y=70) cv.bind('<Button-1>', event_activation)window.geometry("600x500")window.mainloop()
Training set accuracy of 99.440000%
Test set accuracy of 97.320000%
Precision of 0.9944
This article is contributed by:
Utkarsh Shaw (https://auth.geeksforgeeks.org/user/utkarshshaw/profile)Tania (https://auth.geeksforgeeks.org/user/taniachanana02/profile)Rishab Mamgai (https://auth.geeksforgeeks.org/user/rishabmamgai/profile)
Utkarsh Shaw (https://auth.geeksforgeeks.org/user/utkarshshaw/profile)
Tania (https://auth.geeksforgeeks.org/user/taniachanana02/profile)
Rishab Mamgai (https://auth.geeksforgeeks.org/user/rishabmamgai/profile)
utkarshshaw
akshaysingh98088
ProGeek 2021
Machine Learning
ProGeek
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
E-commerce Website using Django
College Management System using Django - Python Project
How to Build a Simple Note Android App using MVVM and Room Database?
How to Make a Scientific Calculator Android App using Android Studio?
Personalized Task Manager in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 223,
"s": 52,
"text": "Handwritten digit recognition using MNIST dataset is a major project made with the help of Neural Network. It basically detects the scanned images of handwritten digits. "
},
{
"code": null,
"e": 456,
"s": 223,
"text": "We have taken this a step further where our handwritten digit recognition system not only detects scanned images of handwritten digits but also allows writing digits on the screen with the help of an integrated GUI for recognition. "
},
{
"code": null,
"e": 528,
"s": 456,
"text": "We will approach this project by using a three-layered Neural Network. "
},
{
"code": null,
"e": 657,
"s": 528,
"text": "The input layer: It distributes the features of our examples to the next layer for calculation of activations of the next layer."
},
{
"code": null,
"e": 832,
"s": 657,
"text": "The hidden layer: They are made of hidden units called activations providing nonlinear ties for the network. A number of hidden layers can vary according to our requirements."
},
{
"code": null,
"e": 1006,
"s": 832,
"text": "The output layer: The nodes here are called output units. It provides us with the final prediction of the Neural Network on the basis of which final predictions can be made."
},
{
"code": null,
"e": 1444,
"s": 1006,
"text": "A neural network is a model inspired by how the brain works. It consists of multiple layers having many activations, this activation resembles neurons of our brain. A neural network tries to learn a set of parameters in a set of data which could help to recognize the underlying relationships. Neural networks can adapt to changing input; so the network generates the best possible result without needing to redesign the output criteria."
},
{
"code": null,
"e": 2121,
"s": 1444,
"text": "We have implemented a Neural Network with 1 hidden layer having 100 activation units (excluding bias units). The data is loaded from a .mat file, features(X) and labels(y) were extracted. Then features are divided by 255 to rescale them into a range of [0,1] to avoid overflow during computation. Data is split up into 60,000 training and 10,000 testing examples. Feedforward is performed with the training set for calculating the hypothesis and then backpropagation is done in order to reduce the error between the layers. The regularization parameter lambda is set to 0.1 to address the problem of overfitting. Optimizer is run for 70 iterations to find the best fit model. "
},
{
"code": null,
"e": 2147,
"s": 2121,
"text": "Layers of Neural Network"
},
{
"code": null,
"e": 2153,
"s": 2147,
"text": "Note:"
},
{
"code": null,
"e": 2195,
"s": 2153,
"text": "Save all .py files in the same directory."
},
{
"code": null,
"e": 2275,
"s": 2195,
"text": "Download dataset from https://www.kaggle.com/avnishnish/mnist-original/download"
},
{
"code": null,
"e": 2917,
"s": 2275,
"text": "Importing all the required libraries, extract the data from mnist-original.mat file. Then features and labels will be separated from extracted data. After that data will be split into training (60,000) and testing (10,000) examples. Randomly initialize Thetas in the range of [-0.15, +0.15] to break symmetry and get better results. Further, the optimizer is called for the training of weights, to minimize the cost function for appropriate predictions. We have used the “minimize” optimizer from “scipy.optimize” library with “L-BFGS-B” method. We have calculated the test, the “training set accuracy and precision using “predict” function."
},
{
"code": null,
"e": 2925,
"s": 2917,
"text": "Python3"
},
{
"code": "from scipy.io import loadmatimport numpy as npfrom Model import neural_networkfrom RandInitialize import initialisefrom Prediction import predictfrom scipy.optimize import minimize # Loading mat filedata = loadmat('mnist-original.mat') # Extracting features from mat fileX = data['data']X = X.transpose() # Normalizing the dataX = X / 255 # Extracting labels from mat filey = data['label']y = y.flatten() # Splitting data into training set with 60,000 examplesX_train = X[:60000, :]y_train = y[:60000] # Splitting data into testing set with 10,000 examplesX_test = X[60000:, :]y_test = y[60000:] m = X.shape[0]input_layer_size = 784 # Images are of (28 X 28) px so there will be 784 featureshidden_layer_size = 100num_labels = 10 # There are 10 classes [0, 9] # Randomly initialising Thetasinitial_Theta1 = initialise(hidden_layer_size, input_layer_size)initial_Theta2 = initialise(num_labels, hidden_layer_size) # Unrolling parameters into a single column vectorinitial_nn_params = np.concatenate((initial_Theta1.flatten(), initial_Theta2.flatten()))maxiter = 100lambda_reg = 0.1 # To avoid overfittingmyargs = (input_layer_size, hidden_layer_size, num_labels, X_train, y_train, lambda_reg) # Calling minimize function to minimize cost function and to train weightsresults = minimize(neural_network, x0=initial_nn_params, args=myargs, options={'disp': True, 'maxiter': maxiter}, method=\"L-BFGS-B\", jac=True) nn_params = results[\"x\"] # Trained Theta is extracted # Weights are split back to Theta1, Theta2Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)], ( hidden_layer_size, input_layer_size + 1)) # shape = (100, 785)Theta2 = np.reshape(nn_params[hidden_layer_size * (input_layer_size + 1):], (num_labels, hidden_layer_size + 1)) # shape = (10, 101) # Checking test set accuracy of our modelpred = predict(Theta1, Theta2, X_test)print('Test Set Accuracy: {:f}'.format((np.mean(pred == y_test) * 100))) # Checking train set accuracy of our modelpred = predict(Theta1, Theta2, X_train)print('Training Set Accuracy: {:f}'.format((np.mean(pred == y_train) * 100))) # Evaluating precision of our modeltrue_positive = 0for i in range(len(pred)): if pred[i] == y_train[i]: true_positive += 1false_positive = len(y_train) - true_positiveprint('Precision =', true_positive/(true_positive + false_positive)) # Saving Thetas in .txt filenp.savetxt('Theta1.txt', Theta1, delimiter=' ')np.savetxt('Theta2.txt', Theta2, delimiter=' ')",
"e": 5450,
"s": 2925,
"text": null
},
{
"code": null,
"e": 5521,
"s": 5450,
"text": "It randomly initializes theta between a range of [-epsilon, +epsilon]."
},
{
"code": null,
"e": 5529,
"s": 5521,
"text": "Python3"
},
{
"code": "import numpy as np def initialise(a, b): epsilon = 0.15 c = np.random.rand(a, b + 1) * ( # Randomly initialises values of thetas between [-epsilon, +epsilon] 2 * epsilon) - epsilon return c",
"e": 5739,
"s": 5529,
"text": null
},
{
"code": null,
"e": 5796,
"s": 5739,
"text": "The function performs feed-forward and backpropagation. "
},
{
"code": null,
"e": 6069,
"s": 5796,
"text": "Forward propagation: Input data is fed in the forward direction through the network. Each hidden layer accepts the input data, processes it as per the activation function and passes it to the successive layer. We will use the sigmoid function as our “activation function”."
},
{
"code": null,
"e": 6213,
"s": 6069,
"text": "Backward propagation: It is the practice of fine-tuning the weights of a neural net based on the error rate obtained in the previous iteration."
},
{
"code": null,
"e": 6394,
"s": 6213,
"text": "It also calculates cross-entropy costs for checking the errors between the prediction and original values. In the end, the gradient is calculated for the optimization objective. "
},
{
"code": null,
"e": 6402,
"s": 6394,
"text": "Python3"
},
{
"code": "import numpy as np def neural_network(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lamb): # Weights are split back to Theta1, Theta2 Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)], (hidden_layer_size, input_layer_size + 1)) Theta2 = np.reshape(nn_params[hidden_layer_size * (input_layer_size + 1):], (num_labels, hidden_layer_size + 1)) # Forward propagation m = X.shape[0] one_matrix = np.ones((m, 1)) X = np.append(one_matrix, X, axis=1) # Adding bias unit to first layer a1 = X z2 = np.dot(X, Theta1.transpose()) a2 = 1 / (1 + np.exp(-z2)) # Activation for second layer one_matrix = np.ones((m, 1)) a2 = np.append(one_matrix, a2, axis=1) # Adding bias unit to hidden layer z3 = np.dot(a2, Theta2.transpose()) a3 = 1 / (1 + np.exp(-z3)) # Activation for third layer # Changing the y labels into vectors of boolean values. # For each label between 0 and 9, there will be a vector of length 10 # where the ith element will be 1 if the label equals i y_vect = np.zeros((m, 10)) for i in range(m): y_vect[i, int(y[i])] = 1 # Calculating cost function J = (1 / m) * (np.sum(np.sum(-y_vect * np.log(a3) - (1 - y_vect) * np.log(1 - a3)))) + (lamb / (2 * m)) * ( sum(sum(pow(Theta1[:, 1:], 2))) + sum(sum(pow(Theta2[:, 1:], 2)))) # backprop Delta3 = a3 - y_vect Delta2 = np.dot(Delta3, Theta2) * a2 * (1 - a2) Delta2 = Delta2[:, 1:] # gradient Theta1[:, 0] = 0 Theta1_grad = (1 / m) * np.dot(Delta2.transpose(), a1) + (lamb / m) * Theta1 Theta2[:, 0] = 0 Theta2_grad = (1 / m) * np.dot(Delta3.transpose(), a2) + (lamb / m) * Theta2 grad = np.concatenate((Theta1_grad.flatten(), Theta2_grad.flatten())) return J, grad",
"e": 8237,
"s": 6402,
"text": null
},
{
"code": null,
"e": 8291,
"s": 8237,
"text": "It performs forward propagation to predict the digit."
},
{
"code": null,
"e": 8299,
"s": 8291,
"text": "Python3"
},
{
"code": "import numpy as np def predict(Theta1, Theta2, X): m = X.shape[0] one_matrix = np.ones((m, 1)) X = np.append(one_matrix, X, axis=1) # Adding bias unit to first layer z2 = np.dot(X, Theta1.transpose()) a2 = 1 / (1 + np.exp(-z2)) # Activation for second layer one_matrix = np.ones((m, 1)) a2 = np.append(one_matrix, a2, axis=1) # Adding bias unit to hidden layer z3 = np.dot(a2, Theta2.transpose()) a3 = 1 / (1 + np.exp(-z3)) # Activation for third layer p = (np.argmax(a3, axis=1)) # Predicting the class on the basis of max value of hypothesis return p",
"e": 8891,
"s": 8299,
"text": null
},
{
"code": null,
"e": 9061,
"s": 8891,
"text": "It launches a GUI for writing digits. The image of the digit is stored in the same directory after converting it to grayscale and reducing the size to (28 X 28) pixels. "
},
{
"code": null,
"e": 9069,
"s": 9061,
"text": "Python3"
},
{
"code": "from tkinter import *import numpy as npfrom PIL import ImageGrabfrom Prediction import predict window = Tk()window.title(\"Handwritten digit recognition\")l1 = Label() def MyProject(): global l1 widget = cv # Setting co-ordinates of canvas x = window.winfo_rootx() + widget.winfo_x() y = window.winfo_rooty() + widget.winfo_y() x1 = x + widget.winfo_width() y1 = y + widget.winfo_height() # Image is captured from canvas and is resized to (28 X 28) px img = ImageGrab.grab().crop((x, y, x1, y1)).resize((28, 28)) # Converting rgb to grayscale image img = img.convert('L') # Extracting pixel matrix of image and converting it to a vector of (1, 784) x = np.asarray(img) vec = np.zeros((1, 784)) k = 0 for i in range(28): for j in range(28): vec[0][k] = x[i][j] k += 1 # Loading Thetas Theta1 = np.loadtxt('Theta1.txt') Theta2 = np.loadtxt('Theta2.txt') # Calling function for prediction pred = predict(Theta1, Theta2, vec / 255) # Displaying the result l1 = Label(window, text=\"Digit = \" + str(pred[0]), font=('Algerian', 20)) l1.place(x=230, y=420) lastx, lasty = None, None # Clears the canvasdef clear_widget(): global cv, l1 cv.delete(\"all\") l1.destroy() # Activate canvasdef event_activation(event): global lastx, lasty cv.bind('<B1-Motion>', draw_lines) lastx, lasty = event.x, event.y # To draw on canvasdef draw_lines(event): global lastx, lasty x, y = event.x, event.y cv.create_line((lastx, lasty, x, y), width=30, fill='white', capstyle=ROUND, smooth=TRUE, splinesteps=12) lastx, lasty = x, y # LabelL1 = Label(window, text=\"Handwritten Digit Recoginition\", font=('Algerian', 25), fg=\"blue\")L1.place(x=35, y=10) # Button to clear canvasb1 = Button(window, text=\"1. Clear Canvas\", font=('Algerian', 15), bg=\"orange\", fg=\"black\", command=clear_widget)b1.place(x=120, y=370) # Button to predict digit drawn on canvasb2 = Button(window, text=\"2. Prediction\", font=('Algerian', 15), bg=\"white\", fg=\"red\", command=MyProject)b2.place(x=320, y=370) # Setting properties of canvascv = Canvas(window, width=350, height=290, bg='black')cv.place(x=120, y=70) cv.bind('<Button-1>', event_activation)window.geometry(\"600x500\")window.mainloop()",
"e": 11351,
"s": 9069,
"text": null
},
{
"code": null,
"e": 11387,
"s": 11351,
"text": "Training set accuracy of 99.440000%"
},
{
"code": null,
"e": 11421,
"s": 11387,
"text": "Test set accuracy of 97.320000% "
},
{
"code": null,
"e": 11441,
"s": 11421,
"text": "Precision of 0.9944"
},
{
"code": null,
"e": 11474,
"s": 11441,
"text": "This article is contributed by: "
},
{
"code": null,
"e": 11683,
"s": 11474,
"text": "Utkarsh Shaw (https://auth.geeksforgeeks.org/user/utkarshshaw/profile)Tania (https://auth.geeksforgeeks.org/user/taniachanana02/profile)Rishab Mamgai (https://auth.geeksforgeeks.org/user/rishabmamgai/profile)"
},
{
"code": null,
"e": 11754,
"s": 11683,
"text": "Utkarsh Shaw (https://auth.geeksforgeeks.org/user/utkarshshaw/profile)"
},
{
"code": null,
"e": 11821,
"s": 11754,
"text": "Tania (https://auth.geeksforgeeks.org/user/taniachanana02/profile)"
},
{
"code": null,
"e": 11894,
"s": 11821,
"text": "Rishab Mamgai (https://auth.geeksforgeeks.org/user/rishabmamgai/profile)"
},
{
"code": null,
"e": 11906,
"s": 11894,
"text": "utkarshshaw"
},
{
"code": null,
"e": 11923,
"s": 11906,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 11936,
"s": 11923,
"text": "ProGeek 2021"
},
{
"code": null,
"e": 11953,
"s": 11936,
"text": "Machine Learning"
},
{
"code": null,
"e": 11961,
"s": 11953,
"text": "ProGeek"
},
{
"code": null,
"e": 11968,
"s": 11961,
"text": "Python"
},
{
"code": null,
"e": 11985,
"s": 11968,
"text": "Machine Learning"
},
{
"code": null,
"e": 12083,
"s": 11985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12106,
"s": 12083,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 12130,
"s": 12106,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 12168,
"s": 12130,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 12209,
"s": 12168,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 12242,
"s": 12209,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 12274,
"s": 12242,
"text": "E-commerce Website using Django"
},
{
"code": null,
"e": 12330,
"s": 12274,
"text": "College Management System using Django - Python Project"
},
{
"code": null,
"e": 12399,
"s": 12330,
"text": "How to Build a Simple Note Android App using MVVM and Room Database?"
},
{
"code": null,
"e": 12469,
"s": 12399,
"text": "How to Make a Scientific Calculator Android App using Android Studio?"
}
] |
DFA in LEX code which accepts even number of zeros and even number of ones | 17 Dec, 2021
Lex is a computer program that generates lexical analyzers, which is commonly used with the YACC parser generator. Lex, originally written by Mike Lesk and Eric Schmidt and described in 1975, is the standard lexical analyzer generator on many Unix systems, and an equivalent tool is specified as part of the POSIX standard. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
Deterministic Finite Acceptor – In the theory of computation, a branch of theoretical computer science, a deterministic finite automaton (DFA)— also known as a deterministic finite acceptor (DFA) and a deterministic finite state machine (DFSM)— is a finite-state machine that accepts and rejects strings of symbols and only produces a unique computation (or run) of the automaton for each input string. Deterministic refers to the uniqueness of the computation. In search of the simplest models to capture finite-state machines, McCulloch and Pitts were among the first researchers to introduce a concept similar to finite automata in 1943.
Approach –
LEX provides us with an INITIAL state by default. So to make a DFA, use this initial state as the initial state of the DFA. Define two more states A and B where B is the dead state that would be used if encounter a wrong or invalid input. When the user gets input that is invalid input, move to state B and the print message “INVALID” and if the user reaches INITIAL state from state A with a “\n” then display a message “Not Accepted”. But if the user get a \n on the initial state, the user display a message “Accepted”.
Examples –
Input : 1001
Output : Accepted
Input : hjabdba
Output : INVALID
To implement the above DFA, the user needs to write the below code in a lex file with a .l Extension.
NOTE :
To compile a lex program, user need a UNIX system and flex which can be installed using sudo apt-get install flex With all the above specification open unix terminal and do the following: 1. Use the lex program to change the specification file into a C language program. The resulting program is in the lex.yy.c file. 2. Use the cc command with the -ll flag to compile and link the program with a library of lex subroutines. The resulting executable program is in the a.out file.
lex lextest
cc lex.yy.c -lfl
Code –
C++
%{%} %s A B %%<INITIAL>1 BEGIN INITIAL;<INITIAL>0 BEGIN A;<INITIAL>[^0|\n] BEGIN B;<INITIAL>\n BEGIN INITIAL; printf("Accepted\n");<A>1 BEGIN A;<A>0 BEGIN INITIAL;<A>[^0|\n] BEGIN B;<A>\n BEGIN INITIAL; printf("Not Accepted\n");<B>0 BEGIN B;<B>1 BEGIN B;<B>[^0|\n] BEGIN B;<B>\n {BEGIN INITIAL; printf("INVALID\n");}%% void main(){yylex();}
Output –
nickhil@NICKHIL:~$ lex prpg11.l
nickhil@NICKHIL:~$ cc lex.yy.c -lfl
nickhil@NICKHIL:~$ ./a.out
1000
Not Accepted
hello
INVALID
01010101
Accepted
METHOD 2:-
Approach:-
LEX provides us with an INITIAL state by default. So to make a DFA, use this as the initial state of the DFA. We define four more states: A, B, C, and DEAD where DEAD state would be used if encountering, a wrong or invalid input. When user input an invalid character, move to DEAD state and print message “INVALID” and if input string ends at state INITIAL then display a message “Accepted”. If input string ends at state A, B, C then display a message “Not Accepted”.
LEX CODE:-
%{
%}
%s A B C DEAD
%%
<INITIAL>1 BEGIN A;
<INITIAL>0 BEGIN B;
<INITIAL>[^01\n] BEGIN DEAD;
<INITIAL>\n BEGIN INITIAL; {printf("Accepted\n");}
<A>1 BEGIN INITIAL;
<A>0 BEGIN C;
<A>[^01\n] BEGIN DEAD;
<A>\n BEGIN INITIAL; {printf("Not Accepted\n");}
<B>1 BEGIN C;
<B>0 BEGIN INITIAL;
<B>[^01\n] BEGIN DEAD;
<B>\n BEGIN INITIAL; {printf("Not Accepted\n");}
<C>1 BEGIN B;
<C>0 BEGIN A;
<C>[^01\n] BEGIN DEAD;
<C>\n BEGIN INITIAL; {printf("Not Accepted\n");}
<DEAD>[^\n] BEGIN DEAD;
<DEAD>\n BEGIN INITIAL; {printf("Invalid\n");}
%%
int main()
{
printf("Enter String\n");
yylex();
return 0;
}
OUTPUT:-
kashyap@kashyap-singh:~$ lex e0e1.l
Kashyap@Kashyap-singh:~$ cc lex.yy.c -lfl
Kashyap@Kashyap-singh:~$ ./a.out
1010
Accepted
hello
INVALID
11100
Not Accepted
111100
Accepted
0001
Not Accepted
Prateek Bajaj
Akash Gangwar
kashyapsingh
arorakashish0911
Lex program
Misc
Theory of Computation & Automata
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Virtualization In Cloud Computing and Types
Association Rule
OOPs | Object Oriented Design
Java Math min() method with Examples
std::unique in C++
Introduction of Finite Automata
Difference between DFA and NFA
Turing Machine in TOC
Chomsky Hierarchy in Theory of Computation
Boyer-Moore Majority Voting Algorithm | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 514,
"s": 54,
"text": "Lex is a computer program that generates lexical analyzers, which is commonly used with the YACC parser generator. Lex, originally written by Mike Lesk and Eric Schmidt and described in 1975, is the standard lexical analyzer generator on many Unix systems, and an equivalent tool is specified as part of the POSIX standard. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language."
},
{
"code": null,
"e": 1155,
"s": 514,
"text": "Deterministic Finite Acceptor – In the theory of computation, a branch of theoretical computer science, a deterministic finite automaton (DFA)— also known as a deterministic finite acceptor (DFA) and a deterministic finite state machine (DFSM)— is a finite-state machine that accepts and rejects strings of symbols and only produces a unique computation (or run) of the automaton for each input string. Deterministic refers to the uniqueness of the computation. In search of the simplest models to capture finite-state machines, McCulloch and Pitts were among the first researchers to introduce a concept similar to finite automata in 1943."
},
{
"code": null,
"e": 1166,
"s": 1155,
"text": "Approach –"
},
{
"code": null,
"e": 1689,
"s": 1166,
"text": "LEX provides us with an INITIAL state by default. So to make a DFA, use this initial state as the initial state of the DFA. Define two more states A and B where B is the dead state that would be used if encounter a wrong or invalid input. When the user gets input that is invalid input, move to state B and the print message “INVALID” and if the user reaches INITIAL state from state A with a “\\n” then display a message “Not Accepted”. But if the user get a \\n on the initial state, the user display a message “Accepted”."
},
{
"code": null,
"e": 1702,
"s": 1689,
"text": "Examples – "
},
{
"code": null,
"e": 1767,
"s": 1702,
"text": "Input : 1001\nOutput : Accepted\n\nInput : hjabdba\nOutput : INVALID"
},
{
"code": null,
"e": 1869,
"s": 1767,
"text": "To implement the above DFA, the user needs to write the below code in a lex file with a .l Extension."
},
{
"code": null,
"e": 1878,
"s": 1869,
"text": "NOTE : "
},
{
"code": null,
"e": 2358,
"s": 1878,
"text": "To compile a lex program, user need a UNIX system and flex which can be installed using sudo apt-get install flex With all the above specification open unix terminal and do the following: 1. Use the lex program to change the specification file into a C language program. The resulting program is in the lex.yy.c file. 2. Use the cc command with the -ll flag to compile and link the program with a library of lex subroutines. The resulting executable program is in the a.out file."
},
{
"code": null,
"e": 2387,
"s": 2358,
"text": "lex lextest\ncc lex.yy.c -lfl"
},
{
"code": null,
"e": 2394,
"s": 2387,
"text": "Code –"
},
{
"code": null,
"e": 2398,
"s": 2394,
"text": "C++"
},
{
"code": "%{%} %s A B %%<INITIAL>1 BEGIN INITIAL;<INITIAL>0 BEGIN A;<INITIAL>[^0|\\n] BEGIN B;<INITIAL>\\n BEGIN INITIAL; printf(\"Accepted\\n\");<A>1 BEGIN A;<A>0 BEGIN INITIAL;<A>[^0|\\n] BEGIN B;<A>\\n BEGIN INITIAL; printf(\"Not Accepted\\n\");<B>0 BEGIN B;<B>1 BEGIN B;<B>[^0|\\n] BEGIN B;<B>\\n {BEGIN INITIAL; printf(\"INVALID\\n\");}%% void main(){yylex();}",
"e": 2739,
"s": 2398,
"text": null
},
{
"code": null,
"e": 2749,
"s": 2739,
"text": "Output – "
},
{
"code": null,
"e": 2894,
"s": 2749,
"text": "nickhil@NICKHIL:~$ lex prpg11.l\nnickhil@NICKHIL:~$ cc lex.yy.c -lfl\nnickhil@NICKHIL:~$ ./a.out\n1000\nNot Accepted\nhello\nINVALID\n01010101\nAccepted"
},
{
"code": null,
"e": 2905,
"s": 2894,
"text": "METHOD 2:-"
},
{
"code": null,
"e": 2916,
"s": 2905,
"text": "Approach:-"
},
{
"code": null,
"e": 3386,
"s": 2916,
"text": "LEX provides us with an INITIAL state by default. So to make a DFA, use this as the initial state of the DFA. We define four more states: A, B, C, and DEAD where DEAD state would be used if encountering, a wrong or invalid input. When user input an invalid character, move to DEAD state and print message “INVALID” and if input string ends at state INITIAL then display a message “Accepted”. If input string ends at state A, B, C then display a message “Not Accepted”. "
},
{
"code": null,
"e": 3397,
"s": 3386,
"text": "LEX CODE:-"
},
{
"code": null,
"e": 4029,
"s": 3397,
"text": "%{\n\n%}\n\n%s A B C DEAD\n\n%%\n\n<INITIAL>1 BEGIN A;\n\n<INITIAL>0 BEGIN B;\n\n<INITIAL>[^01\\n] BEGIN DEAD;\n\n<INITIAL>\\n BEGIN INITIAL; {printf(\"Accepted\\n\");}\n\n<A>1 BEGIN INITIAL;\n\n<A>0 BEGIN C;\n\n<A>[^01\\n] BEGIN DEAD;\n\n<A>\\n BEGIN INITIAL; {printf(\"Not Accepted\\n\");}\n\n<B>1 BEGIN C;\n\n<B>0 BEGIN INITIAL;\n\n<B>[^01\\n] BEGIN DEAD;\n\n<B>\\n BEGIN INITIAL; {printf(\"Not Accepted\\n\");} \n\n<C>1 BEGIN B;\n\n<C>0 BEGIN A;\n\n<C>[^01\\n] BEGIN DEAD;\n\n<C>\\n BEGIN INITIAL; {printf(\"Not Accepted\\n\");} \n\n<DEAD>[^\\n] BEGIN DEAD;\n\n<DEAD>\\n BEGIN INITIAL; {printf(\"Invalid\\n\");} \n\n%%\n\nint main()\n\n{\n\n printf(\"Enter String\\n\");\n\n yylex();\n\n return 0;\n\n}"
},
{
"code": null,
"e": 4038,
"s": 4029,
"text": "OUTPUT:-"
},
{
"code": null,
"e": 4230,
"s": 4038,
"text": "kashyap@kashyap-singh:~$ lex e0e1.l\nKashyap@Kashyap-singh:~$ cc lex.yy.c -lfl\nKashyap@Kashyap-singh:~$ ./a.out\n1010\nAccepted\nhello\nINVALID\n11100\nNot Accepted\n111100\nAccepted\n0001\nNot Accepted"
},
{
"code": null,
"e": 4244,
"s": 4230,
"text": "Prateek Bajaj"
},
{
"code": null,
"e": 4258,
"s": 4244,
"text": "Akash Gangwar"
},
{
"code": null,
"e": 4271,
"s": 4258,
"text": "kashyapsingh"
},
{
"code": null,
"e": 4288,
"s": 4271,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4300,
"s": 4288,
"text": "Lex program"
},
{
"code": null,
"e": 4305,
"s": 4300,
"text": "Misc"
},
{
"code": null,
"e": 4338,
"s": 4305,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 4343,
"s": 4338,
"text": "Misc"
},
{
"code": null,
"e": 4348,
"s": 4343,
"text": "Misc"
},
{
"code": null,
"e": 4446,
"s": 4348,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4490,
"s": 4446,
"text": "Virtualization In Cloud Computing and Types"
},
{
"code": null,
"e": 4507,
"s": 4490,
"text": "Association Rule"
},
{
"code": null,
"e": 4537,
"s": 4507,
"text": "OOPs | Object Oriented Design"
},
{
"code": null,
"e": 4574,
"s": 4537,
"text": "Java Math min() method with Examples"
},
{
"code": null,
"e": 4593,
"s": 4574,
"text": "std::unique in C++"
},
{
"code": null,
"e": 4625,
"s": 4593,
"text": "Introduction of Finite Automata"
},
{
"code": null,
"e": 4656,
"s": 4625,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 4678,
"s": 4656,
"text": "Turing Machine in TOC"
},
{
"code": null,
"e": 4721,
"s": 4678,
"text": "Chomsky Hierarchy in Theory of Computation"
}
] |
Tata 1MG Interview Experience for SDE-1 (On-Campus) | 08 Dec, 2021
This is an On-campus offer. Eligibility Criteria was a minimum of 7 pointer. There were a total of 4 rounds (1 Coding Test+2 Technical Interviews+ 1 Managerial)
Round 1 (Coding Assessment): It has 3 Coding Question of medium-hard level and time limit was 1 hour only. I don’t exactly remember the questions but I was able to do only two of them completely.
Only 14 students were shortlisted for next round.
Suggestion: I would suggest doing coding practice from sites like GeeksforGeeks, Leetcode etc as it will give the confidence to solve problems.
Tips:
Don’t spend too much time on the first question you pick, if you are not able to do the first one try doing the second.
Read the instructions very carefully
Focus on the test input, then handle edge cases
Then 3 rounds of Interviews was scheduled one day.
Round 2(Technical Interview 80 min): First, the interviewer introduced himself and then asked to introduce myself. Then he asked about the projects I did. After an introductory discussion on projects, he gave me 3 coding questions on their personal live code environment.
He asked me to explain the approach first and then code it down. I had to explain the time complexity of each solution and optimal code if possible with lesser time complexity.
First question was based on cache memory, he has given me a function with arguments and i have to just write it’s definition. After 5-10 minutes of discussion I was able to solve the problem and code it down. The approach uses concept of hashing. I would rate it as a easy problem.
The second problem was Print all possible words from phone digits, I have already done this question before and I explained him the logic of my approach and he seems satisfied with it. It was sort of medium-level difficulty.
Question: https://www.geeksforgeeks.org/find-possible-words-phone-digits/
Last question was slight variation of Count the number of words with given prefix using Trie. Instead of returning count i just need to print all the words. I gave him a brute force approach with which he was not satisfied. Then he gave me time to think and asked for more optimized approach. Then after 5 min i gave him this Trie solution and then i explained him the structure of trie along with the code
Question: https://www.geeksforgeeks.org/count-the-number-of-words-with-given-prefix-using-trie/
Round 3(Technical Interview 80 min): In this round interviewer gave me 2 coding questions and asked me to code on any editor of my choice. I opened VS code to code those problems.
The first question was Largest Sum Contiguous Subarray. I explained him my approach (Kadane’s algorithm) and he seems satisfied with it and asked to code it down.
Question: https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/
The second question was LRU cache problem. I gave him brute force solution but interviewer was not satisfied. I was stuck for some time, then he helped me with data structure (doubly linked list). After 15-20 min of discussion I was able to do that question and code it down.
Question: https://www.geeksforgeeks.org/lru-cache-implementation/
Suggestion: Even if have done coding question previously it’s completely your responsibility to start the solution from basic idea and further you can proceed with optimization. Do not directly jump on the most optimized solution. And if you are feeling any difficulty, you can discuss it with interviewer.
Round 3(Managerial 40 min): The interviewer was very friendly. He asked me about myself and previous interviews.
Then he jumped on my projects. I explained him and answered all the follow up questions
After share link to 1MG website and asked me design DB for it. He gave me 5-10 min to think and design DB.
Finally in the end, he asked me standard HR type question like where do you see yourself in 2 years, startup with 2X salary or stable company with X salary, why you want to join us etc.
Finally, after 2 hours results came and 4 students were selected. Luckily, I was one of them.
Tips for interviews:
Listen to the question carefully and clear all your doubts at the same time before proceeding to solution
Even If you are stuck, discuss your thinking process with the interviewer. They can help you with some hints.
Prepare HR question before coming to interviews.
Stay calm, confident and be in sync with interviewer all the time
1mg
Marketing
On-Campus
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1
Amazon Interview Experience SDE-2 (3 Years Experienced)
TCS Ninja Interview Experience (2020 batch)
Write It Up: Share Your Interview Experiences
Samsung RnD Coding Round Questions
Tiger Analytics Interview Experience for Data Analyst (On-Campus)
Nagarro Interview Experience
Amazon Interview Experience for SDE-1 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 189,
"s": 28,
"text": "This is an On-campus offer. Eligibility Criteria was a minimum of 7 pointer. There were a total of 4 rounds (1 Coding Test+2 Technical Interviews+ 1 Managerial)"
},
{
"code": null,
"e": 385,
"s": 189,
"text": "Round 1 (Coding Assessment): It has 3 Coding Question of medium-hard level and time limit was 1 hour only. I don’t exactly remember the questions but I was able to do only two of them completely."
},
{
"code": null,
"e": 435,
"s": 385,
"text": "Only 14 students were shortlisted for next round."
},
{
"code": null,
"e": 579,
"s": 435,
"text": "Suggestion: I would suggest doing coding practice from sites like GeeksforGeeks, Leetcode etc as it will give the confidence to solve problems."
},
{
"code": null,
"e": 587,
"s": 579,
"text": "Tips: "
},
{
"code": null,
"e": 707,
"s": 587,
"text": "Don’t spend too much time on the first question you pick, if you are not able to do the first one try doing the second."
},
{
"code": null,
"e": 744,
"s": 707,
"text": "Read the instructions very carefully"
},
{
"code": null,
"e": 792,
"s": 744,
"text": "Focus on the test input, then handle edge cases"
},
{
"code": null,
"e": 843,
"s": 792,
"text": "Then 3 rounds of Interviews was scheduled one day."
},
{
"code": null,
"e": 1115,
"s": 843,
"text": "Round 2(Technical Interview 80 min): First, the interviewer introduced himself and then asked to introduce myself. Then he asked about the projects I did. After an introductory discussion on projects, he gave me 3 coding questions on their personal live code environment."
},
{
"code": null,
"e": 1292,
"s": 1115,
"text": "He asked me to explain the approach first and then code it down. I had to explain the time complexity of each solution and optimal code if possible with lesser time complexity."
},
{
"code": null,
"e": 1574,
"s": 1292,
"text": "First question was based on cache memory, he has given me a function with arguments and i have to just write it’s definition. After 5-10 minutes of discussion I was able to solve the problem and code it down. The approach uses concept of hashing. I would rate it as a easy problem."
},
{
"code": null,
"e": 1802,
"s": 1574,
"text": "The second problem was Print all possible words from phone digits, I have already done this question before and I explained him the logic of my approach and he seems satisfied with it. It was sort of medium-level difficulty. "
},
{
"code": null,
"e": 1876,
"s": 1802,
"text": "Question: https://www.geeksforgeeks.org/find-possible-words-phone-digits/"
},
{
"code": null,
"e": 2284,
"s": 1876,
"text": "Last question was slight variation of Count the number of words with given prefix using Trie. Instead of returning count i just need to print all the words. I gave him a brute force approach with which he was not satisfied. Then he gave me time to think and asked for more optimized approach. Then after 5 min i gave him this Trie solution and then i explained him the structure of trie along with the code"
},
{
"code": null,
"e": 2380,
"s": 2284,
"text": "Question: https://www.geeksforgeeks.org/count-the-number-of-words-with-given-prefix-using-trie/"
},
{
"code": null,
"e": 2560,
"s": 2380,
"text": "Round 3(Technical Interview 80 min): In this round interviewer gave me 2 coding questions and asked me to code on any editor of my choice. I opened VS code to code those problems."
},
{
"code": null,
"e": 2723,
"s": 2560,
"text": "The first question was Largest Sum Contiguous Subarray. I explained him my approach (Kadane’s algorithm) and he seems satisfied with it and asked to code it down."
},
{
"code": null,
"e": 2796,
"s": 2723,
"text": "Question: https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/"
},
{
"code": null,
"e": 3072,
"s": 2796,
"text": "The second question was LRU cache problem. I gave him brute force solution but interviewer was not satisfied. I was stuck for some time, then he helped me with data structure (doubly linked list). After 15-20 min of discussion I was able to do that question and code it down."
},
{
"code": null,
"e": 3138,
"s": 3072,
"text": "Question: https://www.geeksforgeeks.org/lru-cache-implementation/"
},
{
"code": null,
"e": 3445,
"s": 3138,
"text": "Suggestion: Even if have done coding question previously it’s completely your responsibility to start the solution from basic idea and further you can proceed with optimization. Do not directly jump on the most optimized solution. And if you are feeling any difficulty, you can discuss it with interviewer."
},
{
"code": null,
"e": 3560,
"s": 3445,
"text": "Round 3(Managerial 40 min): The interviewer was very friendly. He asked me about myself and previous interviews. "
},
{
"code": null,
"e": 3648,
"s": 3560,
"text": "Then he jumped on my projects. I explained him and answered all the follow up questions"
},
{
"code": null,
"e": 3755,
"s": 3648,
"text": "After share link to 1MG website and asked me design DB for it. He gave me 5-10 min to think and design DB."
},
{
"code": null,
"e": 3941,
"s": 3755,
"text": "Finally in the end, he asked me standard HR type question like where do you see yourself in 2 years, startup with 2X salary or stable company with X salary, why you want to join us etc."
},
{
"code": null,
"e": 4036,
"s": 3941,
"text": "Finally, after 2 hours results came and 4 students were selected. Luckily, I was one of them. "
},
{
"code": null,
"e": 4057,
"s": 4036,
"text": "Tips for interviews:"
},
{
"code": null,
"e": 4163,
"s": 4057,
"text": "Listen to the question carefully and clear all your doubts at the same time before proceeding to solution"
},
{
"code": null,
"e": 4273,
"s": 4163,
"text": "Even If you are stuck, discuss your thinking process with the interviewer. They can help you with some hints."
},
{
"code": null,
"e": 4322,
"s": 4273,
"text": "Prepare HR question before coming to interviews."
},
{
"code": null,
"e": 4388,
"s": 4322,
"text": "Stay calm, confident and be in sync with interviewer all the time"
},
{
"code": null,
"e": 4392,
"s": 4388,
"text": "1mg"
},
{
"code": null,
"e": 4402,
"s": 4392,
"text": "Marketing"
},
{
"code": null,
"e": 4412,
"s": 4402,
"text": "On-Campus"
},
{
"code": null,
"e": 4434,
"s": 4412,
"text": "Interview Experiences"
},
{
"code": null,
"e": 4532,
"s": 4434,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4602,
"s": 4532,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 4675,
"s": 4602,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 4713,
"s": 4675,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 4769,
"s": 4713,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 4813,
"s": 4769,
"text": "TCS Ninja Interview Experience (2020 batch)"
},
{
"code": null,
"e": 4859,
"s": 4813,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 4894,
"s": 4859,
"text": "Samsung RnD Coding Round Questions"
},
{
"code": null,
"e": 4960,
"s": 4894,
"text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)"
},
{
"code": null,
"e": 4989,
"s": 4960,
"text": "Nagarro Interview Experience"
}
] |
Kotlin Grouping | 17 Sep, 2019
The Kotlin standard library helps in grouping collection elements with the help of extension functions. Grouping means collecting items by category. Here, we have a groupBy() function which takes lambda function and returns a map. In this map, each key is the result of lambda and corresponding value is the list of elements.We can also use groupBy() function with second lambda expression, which is also called value transformation function. If we use two lambda functions then the produced key of keySelector mapped with the results of value transformation function instead of original elements.
Kotlin program to demonstrate using groupBy() function –
fun main(args: Array<String>) { val fruits = listOf("apple", "apricot", "banana", "cherries", "berries", "cucumber") println(fruits.groupBy { it.first().toUpperCase() }) println(fruits.groupBy(keySelector = { it.first() }, valueTransform = { it.toUpperCase() }))}
Output:
{A=[apple, apricot], B=[banana, berries], C=[cherries, cucumber]}
{a=[APPLE, APRICOT], b=[BANANA, BERRIES], c=[CHERRIES, CUCUMBER]}
If we want to apply some operations to group elements then it can be done by applying the function to all group at a time with the help of groupingBy() function. An instance of grouping type will be returned.
We can perform these operations on groups:
eachcount(): it counts the items in each group.
fold() and reduce(): perform these operation on each group separately and return the result.
aggregate(): it is generic way of grouping means applying a specific operation subsequently to all the elements in each group and returns the result. So, it is used to implement custom operations.
Kotlin program to demonstrate groupingBy() function –
fun main(args: Array<String>) { val fruits = listOf("apple", "apricot", "banana", "cherries", "berries", "cucumber") println(fruits.groupingBy { it.first() }.eachCount())}
Output:
{a=2, b=2, c=2}
Kotlin Collections
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 626,
"s": 28,
"text": "The Kotlin standard library helps in grouping collection elements with the help of extension functions. Grouping means collecting items by category. Here, we have a groupBy() function which takes lambda function and returns a map. In this map, each key is the result of lambda and corresponding value is the list of elements.We can also use groupBy() function with second lambda expression, which is also called value transformation function. If we use two lambda functions then the produced key of keySelector mapped with the results of value transformation function instead of original elements."
},
{
"code": null,
"e": 683,
"s": 626,
"text": "Kotlin program to demonstrate using groupBy() function –"
},
{
"code": "fun main(args: Array<String>) { val fruits = listOf(\"apple\", \"apricot\", \"banana\", \"cherries\", \"berries\", \"cucumber\") println(fruits.groupBy { it.first().toUpperCase() }) println(fruits.groupBy(keySelector = { it.first() }, valueTransform = { it.toUpperCase() }))}",
"e": 970,
"s": 683,
"text": null
},
{
"code": null,
"e": 978,
"s": 970,
"text": "Output:"
},
{
"code": null,
"e": 1111,
"s": 978,
"text": "{A=[apple, apricot], B=[banana, berries], C=[cherries, cucumber]}\n{a=[APPLE, APRICOT], b=[BANANA, BERRIES], c=[CHERRIES, CUCUMBER]}\n"
},
{
"code": null,
"e": 1320,
"s": 1111,
"text": "If we want to apply some operations to group elements then it can be done by applying the function to all group at a time with the help of groupingBy() function. An instance of grouping type will be returned."
},
{
"code": null,
"e": 1363,
"s": 1320,
"text": "We can perform these operations on groups:"
},
{
"code": null,
"e": 1411,
"s": 1363,
"text": "eachcount(): it counts the items in each group."
},
{
"code": null,
"e": 1504,
"s": 1411,
"text": "fold() and reduce(): perform these operation on each group separately and return the result."
},
{
"code": null,
"e": 1701,
"s": 1504,
"text": "aggregate(): it is generic way of grouping means applying a specific operation subsequently to all the elements in each group and returns the result. So, it is used to implement custom operations."
},
{
"code": null,
"e": 1755,
"s": 1701,
"text": "Kotlin program to demonstrate groupingBy() function –"
},
{
"code": "fun main(args: Array<String>) { val fruits = listOf(\"apple\", \"apricot\", \"banana\", \"cherries\", \"berries\", \"cucumber\") println(fruits.groupingBy { it.first() }.eachCount())}",
"e": 1940,
"s": 1755,
"text": null
},
{
"code": null,
"e": 1948,
"s": 1940,
"text": "Output:"
},
{
"code": null,
"e": 1965,
"s": 1948,
"text": "{a=2, b=2, c=2}\n"
},
{
"code": null,
"e": 1984,
"s": 1965,
"text": "Kotlin Collections"
},
{
"code": null,
"e": 1991,
"s": 1984,
"text": "Picked"
},
{
"code": null,
"e": 1998,
"s": 1991,
"text": "Kotlin"
}
] |
How to Get the Body of Request in Spring Boot? | 10 Nov, 2021
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, etc.
There are several other concepts present in java that increase the user-friendly interaction between the java code and the programmer such as generic, Access specifiers, Annotations, etc these features add an extra property to the class as well as the method of the java program. In this article, we will discuss how to get the body of the incoming request in the spring boot.
@RequestBody: Annotation is used to get request body in the incoming request.
Note: First we need to establish the spring application in our project.
Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer and then use an IDE to create a sample GET route. Therefore, to do this, the following steps are followed sequentially as follows:
Step 1: Go to Spring Initializr
Fill in the details as per the requirements. For this application:
Project: Maven
Language: Java
Spring Boot: 2.2.8
Packaging: JAR
Java: 8
Dependencies: Spring Web
Step 2: Click on Generate which will download the starter project.
Step 3: Extract the zip file. Now open a suitable IDE and then go to File->New->Project from existing sources->Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync.
Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project.
Step 4: Go to src -> main -> java -> com.gfg.Spring.boot.app and create a java class with the name Controller and add the annotation @RestController. Now create a GET API as shown below as follows:
Example 1: Person.java
// Class
public class Person {
// Attributes of Person
int id;
String name;
int age;
// Constructor of this class
public Person(int id, String name, int age) {
// this keyword refers to current instance object
this.id = id;
this.name = name;
this.age = age;
}
// Method of Person class
// toString() method
public String toString() {
// Simply returning the name and age of person
return id + " " + name + " " + age;
}
Example 2: Controller.java
@RestController
// Class
public class Controller {
@GetMapping("/Get")
void getBody(@RequestBody Person ob) {
// Print and display the person object
System.out.println(ob);
}
}
This application is now ready to run. Run the SpringBootAppApplication class and wait for the Tomcat server to start.
Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file.
Step 5: Now go to the Postman and add URL address and make get request
Output: Lastly output will be generated on terminal/CMD below as follows:
1 Aayush 32
Java-Spring-Boot
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 440,
"s": 28,
"text": "Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, etc."
},
{
"code": null,
"e": 817,
"s": 440,
"text": "There are several other concepts present in java that increase the user-friendly interaction between the java code and the programmer such as generic, Access specifiers, Annotations, etc these features add an extra property to the class as well as the method of the java program. In this article, we will discuss how to get the body of the incoming request in the spring boot."
},
{
"code": null,
"e": 895,
"s": 817,
"text": "@RequestBody: Annotation is used to get request body in the incoming request."
},
{
"code": null,
"e": 967,
"s": 895,
"text": "Note: First we need to establish the spring application in our project."
},
{
"code": null,
"e": 1471,
"s": 967,
"text": "Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer and then use an IDE to create a sample GET route. Therefore, to do this, the following steps are followed sequentially as follows:"
},
{
"code": null,
"e": 1503,
"s": 1471,
"text": "Step 1: Go to Spring Initializr"
},
{
"code": null,
"e": 1570,
"s": 1503,
"text": "Fill in the details as per the requirements. For this application:"
},
{
"code": null,
"e": 1673,
"s": 1570,
"text": "Project: Maven\nLanguage: Java\nSpring Boot: 2.2.8\nPackaging: JAR\nJava: 8\nDependencies: Spring Web "
},
{
"code": null,
"e": 1740,
"s": 1673,
"text": "Step 2: Click on Generate which will download the starter project."
},
{
"code": null,
"e": 1955,
"s": 1740,
"text": "Step 3: Extract the zip file. Now open a suitable IDE and then go to File->New->Project from existing sources->Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync."
},
{
"code": null,
"e": 2093,
"s": 1955,
"text": "Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project."
},
{
"code": null,
"e": 2291,
"s": 2093,
"text": "Step 4: Go to src -> main -> java -> com.gfg.Spring.boot.app and create a java class with the name Controller and add the annotation @RestController. Now create a GET API as shown below as follows:"
},
{
"code": null,
"e": 2314,
"s": 2291,
"text": "Example 1: Person.java"
},
{
"code": null,
"e": 2835,
"s": 2314,
"text": "// Class\npublic class Person {\n\n // Attributes of Person\n int id;\n String name;\n int age;\n\n // Constructor of this class\n public Person(int id, String name, int age) {\n\n // this keyword refers to current instance object\n this.id = id;\n this.name = name;\n this.age = age;\n }\n\n // Method of Person class\n // toString() method\n public String toString() {\n\n // Simply returning the name and age of person\n return id + \" \" + name + \" \" + age;\n }\n "
},
{
"code": null,
"e": 2862,
"s": 2835,
"text": "Example 2: Controller.java"
},
{
"code": null,
"e": 3092,
"s": 2862,
"text": "@RestController\n\n// Class\npublic class Controller {\n\n @GetMapping(\"/Get\")\n\n void getBody(@RequestBody Person ob) {\n\n // Print and display the person object\n System.out.println(ob);\n }\n}"
},
{
"code": null,
"e": 3210,
"s": 3092,
"text": "This application is now ready to run. Run the SpringBootAppApplication class and wait for the Tomcat server to start."
},
{
"code": null,
"e": 3317,
"s": 3210,
"text": "Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file."
},
{
"code": null,
"e": 3388,
"s": 3317,
"text": "Step 5: Now go to the Postman and add URL address and make get request"
},
{
"code": null,
"e": 3463,
"s": 3388,
"text": "Output: Lastly output will be generated on terminal/CMD below as follows: "
},
{
"code": null,
"e": 3476,
"s": 3463,
"text": " 1 Aayush 32"
},
{
"code": null,
"e": 3493,
"s": 3476,
"text": "Java-Spring-Boot"
},
{
"code": null,
"e": 3498,
"s": 3493,
"text": "Java"
},
{
"code": null,
"e": 3503,
"s": 3498,
"text": "Java"
}
] |
MongoDB – Update() Method | 22 Oct, 2020
The update() method updates the values in the existing document in the collections of MongoDB. When you update your document the value of the _id field remains unchanged. By default, the db.collection.update() method updates a single document. Include the option multi: true to update all documents that match the given query. This method can be used for a single updating of documents as well as multi documents.
Syntax:
db.COLLECTION_NAME.update({SELECTION_CRITERIA}, {$set:{UPDATED_DATA}}, {
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>
})
Parameters:
The first parameter is the Older value in the form of Documents. Documents are a structure created of file and value pairs, similar to JSON objects.
The second parameter must contain a $set keyword to update the following specify document value.
The third parameter is optional.
Optional Parameters:
Upsert: The default value of this parameter is false. When it is true it will make a new document in the collection when no document matches the given condition in the update method.
multi: The default value of this parameter is false. When it is true the update method update all the documents that meet the query condition. Otherwise, it will update only one document.
writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
Collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array.
hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error.
Examples:
In the following examples, we are working with:
Database: gfg
Collections: student
Document: Three documents contains name and the age of the students
Update the name of the document whose name key has avi value to hello world.
db.student.update({name:"avi"},{$set:{name:"helloword"}})
Here, the first parameter is the document whose value to be changed {name:”avi”} and the second parameter is set keyword means to set(update) the following matched key value with the older key value.
Note: The value of the key must be of the same datatype that was defined in the collection.
Update the age of the document whose name is prachi to 20.
db.student.update({name:"prachi"},{$set:{age:20}}
Here, the first parameter is the document whose value to be changed {name:”prachi”} and the second parameter is set keyword means to set(update) the value of the age field to 20.
MongoDB
MongoDB-method
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - sort() Method
MongoDB - FindOne() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Regex
MongoDB - Compound Indexes
MongoDB updateMany() Method - db.Collection.updateMany()
MongoDB Cursor
Mongoose | update() Function | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Oct, 2020"
},
{
"code": null,
"e": 468,
"s": 54,
"text": "The update() method updates the values in the existing document in the collections of MongoDB. When you update your document the value of the _id field remains unchanged. By default, the db.collection.update() method updates a single document. Include the option multi: true to update all documents that match the given query. This method can be used for a single updating of documents as well as multi documents."
},
{
"code": null,
"e": 476,
"s": 468,
"text": "Syntax:"
},
{
"code": null,
"e": 748,
"s": 476,
"text": "db.COLLECTION_NAME.update({SELECTION_CRITERIA}, {$set:{UPDATED_DATA}}, {\n upsert: <boolean>,\n multi: <boolean>,\n writeConcern: <document>,\n collation: <document>,\n arrayFilters: [ <filterdocument1>, ... ],\n hint: <document|string> \n })\n\n"
},
{
"code": null,
"e": 760,
"s": 748,
"text": "Parameters:"
},
{
"code": null,
"e": 909,
"s": 760,
"text": "The first parameter is the Older value in the form of Documents. Documents are a structure created of file and value pairs, similar to JSON objects."
},
{
"code": null,
"e": 1006,
"s": 909,
"text": "The second parameter must contain a $set keyword to update the following specify document value."
},
{
"code": null,
"e": 1039,
"s": 1006,
"text": "The third parameter is optional."
},
{
"code": null,
"e": 1060,
"s": 1039,
"text": "Optional Parameters:"
},
{
"code": null,
"e": 1243,
"s": 1060,
"text": "Upsert: The default value of this parameter is false. When it is true it will make a new document in the collection when no document matches the given condition in the update method."
},
{
"code": null,
"e": 1431,
"s": 1243,
"text": "multi: The default value of this parameter is false. When it is true the update method update all the documents that meet the query condition. Otherwise, it will update only one document."
},
{
"code": null,
"e": 1558,
"s": 1431,
"text": "writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document."
},
{
"code": null,
"e": 1786,
"s": 1558,
"text": "Collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document."
},
{
"code": null,
"e": 1964,
"s": 1786,
"text": "arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array."
},
{
"code": null,
"e": 2197,
"s": 1964,
"text": "hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error."
},
{
"code": null,
"e": 2207,
"s": 2197,
"text": "Examples:"
},
{
"code": null,
"e": 2255,
"s": 2207,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 2269,
"s": 2255,
"text": "Database: gfg"
},
{
"code": null,
"e": 2290,
"s": 2269,
"text": "Collections: student"
},
{
"code": null,
"e": 2358,
"s": 2290,
"text": "Document: Three documents contains name and the age of the students"
},
{
"code": null,
"e": 2435,
"s": 2358,
"text": "Update the name of the document whose name key has avi value to hello world."
},
{
"code": null,
"e": 2494,
"s": 2435,
"text": "db.student.update({name:\"avi\"},{$set:{name:\"helloword\"}})\n"
},
{
"code": null,
"e": 2694,
"s": 2494,
"text": "Here, the first parameter is the document whose value to be changed {name:”avi”} and the second parameter is set keyword means to set(update) the following matched key value with the older key value."
},
{
"code": null,
"e": 2786,
"s": 2694,
"text": "Note: The value of the key must be of the same datatype that was defined in the collection."
},
{
"code": null,
"e": 2845,
"s": 2786,
"text": "Update the age of the document whose name is prachi to 20."
},
{
"code": null,
"e": 2896,
"s": 2845,
"text": "db.student.update({name:\"prachi\"},{$set:{age:20}}\n"
},
{
"code": null,
"e": 3075,
"s": 2896,
"text": "Here, the first parameter is the document whose value to be changed {name:”prachi”} and the second parameter is set keyword means to set(update) the value of the age field to 20."
},
{
"code": null,
"e": 3083,
"s": 3075,
"text": "MongoDB"
},
{
"code": null,
"e": 3098,
"s": 3083,
"text": "MongoDB-method"
},
{
"code": null,
"e": 3106,
"s": 3098,
"text": "MongoDB"
},
{
"code": null,
"e": 3204,
"s": 3106,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3242,
"s": 3204,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 3267,
"s": 3242,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 3291,
"s": 3267,
"text": "MongoDB - sort() Method"
},
{
"code": null,
"e": 3318,
"s": 3291,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 3373,
"s": 3318,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 3389,
"s": 3373,
"text": "MongoDB - Regex"
},
{
"code": null,
"e": 3416,
"s": 3389,
"text": "MongoDB - Compound Indexes"
},
{
"code": null,
"e": 3473,
"s": 3416,
"text": "MongoDB updateMany() Method - db.Collection.updateMany()"
},
{
"code": null,
"e": 3488,
"s": 3473,
"text": "MongoDB Cursor"
}
] |
Python - Dictionary | Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result −
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']
When the above code is executed, it produces the following result −
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
When the above code is executed, it produces the following result −
dict['Age']: 8
dict['School']: DPS School
You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
This produces the following result. Note that an exception is raised because after del dict dictionary does not exist any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note − del() method is discussed in subsequent section.
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys −
(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. For example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result −
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example −
#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'
Python includes the following dictionary functions −
Compares elements of both dict.
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
Produces a printable string representation of a dictionary
Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.
Python includes following dictionary methods −
Removes all elements of dictionary dict
Returns a shallow copy of dictionary dict
Create a new dictionary with keys from seq and values set to value.
For key key, returns value or default if key not in dictionary
Returns true if key in dictionary dict, false otherwise
Returns a list of dict's (key, value) tuple pairs
Returns list of dictionary dict's keys
Similar to get(), but will set dict[key]=default if key is not already in dict
Adds dictionary dict2's key-values pairs to dict
Returns list of dictionary dict's values | [
{
"code": null,
"e": 2607,
"s": 2378,
"text": "Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}."
},
{
"code": null,
"e": 2799,
"s": 2607,
"text": "Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples."
},
{
"code": null,
"e": 2943,
"s": 2799,
"text": "To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −"
},
{
"code": null,
"e": 3086,
"s": 2943,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Name']: \", dict['Name']\nprint \"dict['Age']: \", dict['Age']"
},
{
"code": null,
"e": 3155,
"s": 3086,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3192,
"s": 3155,
"text": "dict['Name']: Zara\ndict['Age']: 7\n"
},
{
"code": null,
"e": 3306,
"s": 3192,
"text": "If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −"
},
{
"code": null,
"e": 3416,
"s": 3306,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Alice']: \", dict['Alice']"
},
{
"code": null,
"e": 3485,
"s": 3416,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3639,
"s": 3485,
"text": "dict['Alice']:\nTraceback (most recent call last):\n File \"test.py\", line 4, in <module>\n print \"dict['Alice']: \", dict['Alice'];\nKeyError: 'Alice'\n"
},
{
"code": null,
"e": 3808,
"s": 3639,
"text": "You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −"
},
{
"code": null,
"e": 4044,
"s": 3808,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndict['Age'] = 8; # update existing entry\ndict['School'] = \"DPS School\"; # Add new entry\n\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']"
},
{
"code": null,
"e": 4112,
"s": 4044,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4157,
"s": 4112,
"text": "dict['Age']: 8\ndict['School']: DPS School\n"
},
{
"code": null,
"e": 4317,
"s": 4157,
"text": "You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation."
},
{
"code": null,
"e": 4420,
"s": 4317,
"text": "To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −"
},
{
"code": null,
"e": 4709,
"s": 4420,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndel dict['Name']; # remove entry with key 'Name'\ndict.clear(); # remove all entries in dict\ndel dict ; # delete entire dictionary\n\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']"
},
{
"code": null,
"e": 4838,
"s": 4709,
"text": "This produces the following result. Note that an exception is raised because after del dict dictionary does not exist any more −"
},
{
"code": null,
"e": 5012,
"s": 4838,
"text": "dict['Age']:\nTraceback (most recent call last):\n File \"test.py\", line 8, in <module>\n print \"dict['Age']: \", dict['Age'];\nTypeError: 'type' object is unsubscriptable\n"
},
{
"code": null,
"e": 5068,
"s": 5012,
"text": "Note − del() method is discussed in subsequent section."
},
{
"code": null,
"e": 5238,
"s": 5068,
"text": "Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys."
},
{
"code": null,
"e": 5305,
"s": 5238,
"text": "There are two important points to remember about dictionary keys −"
},
{
"code": null,
"e": 5482,
"s": 5305,
"text": "(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. For example −"
},
{
"code": null,
"e": 5589,
"s": 5482,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}\nprint \"dict['Name']: \", dict['Name']"
},
{
"code": null,
"e": 5658,
"s": 5589,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 5680,
"s": 5658,
"text": "dict['Name']: Manni\n"
},
{
"code": null,
"e": 5853,
"s": 5680,
"text": "(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example −"
},
{
"code": null,
"e": 5945,
"s": 5853,
"text": "#!/usr/bin/python\n\ndict = {['Name']: 'Zara', 'Age': 7}\nprint \"dict['Name']: \", dict['Name']"
},
{
"code": null,
"e": 6013,
"s": 5945,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 6166,
"s": 6013,
"text": "Traceback (most recent call last):\n File \"test.py\", line 3, in <module>\n dict = {['Name']: 'Zara', 'Age': 7};\nTypeError: unhashable type: 'list'\n"
},
{
"code": null,
"e": 6219,
"s": 6166,
"text": "Python includes the following dictionary functions −"
},
{
"code": null,
"e": 6251,
"s": 6219,
"text": "Compares elements of both dict."
},
{
"code": null,
"e": 6355,
"s": 6251,
"text": "Gives the total length of the dictionary. This would be equal to the number of items in the dictionary."
},
{
"code": null,
"e": 6414,
"s": 6355,
"text": "Produces a printable string representation of a dictionary"
},
{
"code": null,
"e": 6529,
"s": 6414,
"text": "Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type."
},
{
"code": null,
"e": 6576,
"s": 6529,
"text": "Python includes following dictionary methods −"
},
{
"code": null,
"e": 6616,
"s": 6576,
"text": "Removes all elements of dictionary dict"
},
{
"code": null,
"e": 6658,
"s": 6616,
"text": "Returns a shallow copy of dictionary dict"
},
{
"code": null,
"e": 6726,
"s": 6658,
"text": "Create a new dictionary with keys from seq and values set to value."
},
{
"code": null,
"e": 6789,
"s": 6726,
"text": "For key key, returns value or default if key not in dictionary"
},
{
"code": null,
"e": 6845,
"s": 6789,
"text": "Returns true if key in dictionary dict, false otherwise"
},
{
"code": null,
"e": 6895,
"s": 6845,
"text": "Returns a list of dict's (key, value) tuple pairs"
},
{
"code": null,
"e": 6934,
"s": 6895,
"text": "Returns list of dictionary dict's keys"
},
{
"code": null,
"e": 7013,
"s": 6934,
"text": "Similar to get(), but will set dict[key]=default if key is not already in dict"
},
{
"code": null,
"e": 7062,
"s": 7013,
"text": "Adds dictionary dict2's key-values pairs to dict"
}
] |
Python Program to Implement Queue Data Structure using Linked List | When it is required to implement a queue data structure using a linked list, a method to add (enqueue operation) elements to the linked list, and a method to delete (dequeue operation) the elements of the linked list are defined.
Below is a demonstration for the same −
Live Demo
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue_structure:
def __init__(self):
self.head = None
self.last = None
def enqueue_operation(self, data):
if self.last is None:
self.head = Node(data)
self.last = self.head
else:
self.last.next = Node(data)
self.last = self.last.next
def dequeue_operation(self):
if self.head is None:
return None
else:
val_returned = self.head.data
self.head = self.head.next
return val_returned
my_instance = Queue_structure()
while True:
print('enqueue <value>')
print('dequeue')
print('quit')
my_input = input('What operation would you like to perform ? ').split()
operation = my_input[0].strip().lower()
if operation == 'enqueue':
my_instance.enqueue_operation(int(my_input[1]))
elif operation == 'dequeue':
dequeued = my_instance.dequeue_operation()
if dequeued is None:
print('The queue is empty.')
else:
print('The deleted element is : ', int(dequeued))
elif operation == 'quit':
break
enqueue <value>
dequeue
quit
What operation would you like to perform ? enqueue 45
enqueue <value>
dequeue
quit
What operation would you like to perform ? enqueue 12
enqueue <value>
dequeue
quit
What operation would you like to perform ? dequeue
The deleted element is : 45
enqueue <value>
dequeue
quit
What operation would you like to perform ? quit
The ‘Node’ class is created.
The ‘Node’ class is created.
Another ‘Queue_structure’ class with required attributes is created.
Another ‘Queue_structure’ class with required attributes is created.
It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’.
It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’.
A method named enqueue_operation’ is defined, that helps add a value to the queue.
A method named enqueue_operation’ is defined, that helps add a value to the queue.
Another method named ‘dequeue_operation’ is defined, that helps delete a value from the queue, and returns the deleted value.
Another method named ‘dequeue_operation’ is defined, that helps delete a value from the queue, and returns the deleted value.
An instance of the ‘Queue_structure’ is created.
An instance of the ‘Queue_structure’ is created.
Three options are given, such as ‘enqueue’, ‘dequeue’, and ‘quit’.
Three options are given, such as ‘enqueue’, ‘dequeue’, and ‘quit’.
The ‘enqueue’ option adds a specific value to the stack.
The ‘enqueue’ option adds a specific value to the stack.
The ‘dequeue’ option deletes the element from the queue.
The ‘dequeue’ option deletes the element from the queue.
The ‘quit’ option comes out of the loop.
The ‘quit’ option comes out of the loop.
Based on the input/choice by user, the respective operations are performed.
Based on the input/choice by user, the respective operations are performed.
This output is displayed on the console.
This output is displayed on the console. | [
{
"code": null,
"e": 1417,
"s": 1187,
"text": "When it is required to implement a queue data structure using a linked list, a method to add (enqueue operation) elements to the linked list, and a method to delete (dequeue operation) the elements of the linked list are defined."
},
{
"code": null,
"e": 1457,
"s": 1417,
"text": "Below is a demonstration for the same −"
},
{
"code": null,
"e": 1468,
"s": 1457,
"text": " Live Demo"
},
{
"code": null,
"e": 2626,
"s": 1468,
"text": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass Queue_structure:\n def __init__(self):\n self.head = None\n self.last = None\n\n def enqueue_operation(self, data):\n if self.last is None:\n self.head = Node(data)\n self.last = self.head\n else:\n self.last.next = Node(data)\n self.last = self.last.next\n\n def dequeue_operation(self):\n if self.head is None:\n return None\n else:\n val_returned = self.head.data\n self.head = self.head.next\n return val_returned\n\nmy_instance = Queue_structure()\nwhile True:\n print('enqueue <value>')\n print('dequeue')\n print('quit')\n my_input = input('What operation would you like to perform ? ').split()\n\n operation = my_input[0].strip().lower()\n if operation == 'enqueue':\n my_instance.enqueue_operation(int(my_input[1]))\n elif operation == 'dequeue':\n dequeued = my_instance.dequeue_operation()\n if dequeued is None:\n print('The queue is empty.')\n else:\n print('The deleted element is : ', int(dequeued))\n elif operation == 'quit':\n break"
},
{
"code": null,
"e": 2977,
"s": 2626,
"text": "enqueue <value>\ndequeue\nquit\nWhat operation would you like to perform ? enqueue 45\nenqueue <value>\ndequeue\nquit\nWhat operation would you like to perform ? enqueue 12\nenqueue <value>\ndequeue\nquit\nWhat operation would you like to perform ? dequeue\nThe deleted element is : 45\nenqueue <value>\ndequeue\nquit\nWhat operation would you like to perform ? quit"
},
{
"code": null,
"e": 3006,
"s": 2977,
"text": "The ‘Node’ class is created."
},
{
"code": null,
"e": 3035,
"s": 3006,
"text": "The ‘Node’ class is created."
},
{
"code": null,
"e": 3104,
"s": 3035,
"text": "Another ‘Queue_structure’ class with required attributes is created."
},
{
"code": null,
"e": 3173,
"s": 3104,
"text": "Another ‘Queue_structure’ class with required attributes is created."
},
{
"code": null,
"e": 3271,
"s": 3173,
"text": "It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’."
},
{
"code": null,
"e": 3369,
"s": 3271,
"text": "It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’."
},
{
"code": null,
"e": 3452,
"s": 3369,
"text": "A method named enqueue_operation’ is defined, that helps add a value to the queue."
},
{
"code": null,
"e": 3535,
"s": 3452,
"text": "A method named enqueue_operation’ is defined, that helps add a value to the queue."
},
{
"code": null,
"e": 3661,
"s": 3535,
"text": "Another method named ‘dequeue_operation’ is defined, that helps delete a value from the queue, and returns the deleted value."
},
{
"code": null,
"e": 3787,
"s": 3661,
"text": "Another method named ‘dequeue_operation’ is defined, that helps delete a value from the queue, and returns the deleted value."
},
{
"code": null,
"e": 3836,
"s": 3787,
"text": "An instance of the ‘Queue_structure’ is created."
},
{
"code": null,
"e": 3885,
"s": 3836,
"text": "An instance of the ‘Queue_structure’ is created."
},
{
"code": null,
"e": 3952,
"s": 3885,
"text": "Three options are given, such as ‘enqueue’, ‘dequeue’, and ‘quit’."
},
{
"code": null,
"e": 4019,
"s": 3952,
"text": "Three options are given, such as ‘enqueue’, ‘dequeue’, and ‘quit’."
},
{
"code": null,
"e": 4076,
"s": 4019,
"text": "The ‘enqueue’ option adds a specific value to the stack."
},
{
"code": null,
"e": 4133,
"s": 4076,
"text": "The ‘enqueue’ option adds a specific value to the stack."
},
{
"code": null,
"e": 4190,
"s": 4133,
"text": "The ‘dequeue’ option deletes the element from the queue."
},
{
"code": null,
"e": 4247,
"s": 4190,
"text": "The ‘dequeue’ option deletes the element from the queue."
},
{
"code": null,
"e": 4288,
"s": 4247,
"text": "The ‘quit’ option comes out of the loop."
},
{
"code": null,
"e": 4329,
"s": 4288,
"text": "The ‘quit’ option comes out of the loop."
},
{
"code": null,
"e": 4405,
"s": 4329,
"text": "Based on the input/choice by user, the respective operations are performed."
},
{
"code": null,
"e": 4481,
"s": 4405,
"text": "Based on the input/choice by user, the respective operations are performed."
},
{
"code": null,
"e": 4522,
"s": 4481,
"text": "This output is displayed on the console."
},
{
"code": null,
"e": 4563,
"s": 4522,
"text": "This output is displayed on the console."
}
] |
WebRTC - Session Description Protocol | The SDP is an important part of the WebRTC. It is a protocol that is intended to describe media communication sessions. It does not deliver the media data but is used for negotiation between peers of various audio and video codecs, network topologies, and other device information. It also needs to be easily transportable. Simply put we need a string-based profile with all the information about the user's device. This is where SDP comes in.
The SDP is a well-known method of establishing media connections as it appeared in the late 90s. It has been used in a vast amount of other types of applications before WebRTC like phone and text-based chatting.
The SDP is string data containing sets of key-value pairs, separated by line breaks −
key = value\n
The key is a single character that sets the type of the value. The value is a machine-readable configuration value.
The SDP covers media description and media constraints for a given user. When we start using RTCPeerConnection object later we will be able easily print this to the javascript console.
The SDP is the first part of the peer connection. Peers have to exchange SDP data with the help of the signaling channel in order to establish a connection.
This is an example of an SDP offer −
v=0
o=- 487255629242026503 2 IN IP4 127.0.0.1
s=-
t=0 0
a=group:BUNDLE audio video
a=msid-semantic: WMS 6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG
m=audio 9 RTP/SAVPF 111 103 104 9 0 8 106 105 13 126
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:8a1/LJqQMzBmYtes
a=ice-pwd:sbfskHYHACygyHW1wVi8GZM+
a=ice-options:google-ice
a=fingerprint:sha-256 28:4C:19:10:97:56:FB:22:57:9E:5A:88:28:F3:04:
DF:37:D0:7D:55:C3:D1:59:B0:B2:81 :FB:9D:DF:CB:15:A8
a=setup:actpass
a=mid:audio
a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
a=sendrecv
a=rtcp-mux
a=rtpmap:111 opus/48000/2
a=fmtp:111 minptime=10
a=rtpmap:103 ISAC/16000
a=rtpmap:104 ISAC/32000
a=rtpmap:9 G722/8000
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:106 CN/32000
a=rtpmap:105 CN/16000
a=rtpmap:13 CN/8000
a=rtpmap:126 telephone-event/8000
a=maxptime:60
a=ssrc:3607952327 cname:v1SBHP7c76XqYcWx
a=ssrc:3607952327 msid:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG 9eb1f6d5-c3b246fe
-b46b-63ea11c46c74
a=ssrc:3607952327 mslabel:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG
a=ssrc:3607952327 label:9eb1f6d5-c3b2-46fe-b46b-63ea11c46c74
m=video 9 RTP/SAVPF 100 116 117 96
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:8a1/LJqQMzBmYtes
a=ice-pwd:sbfskHYHACygyHW1wVi8GZM+
a=ice-options:google-ice
a=fingerprint:sha-256 28:4C:19:10:97:56:FB:22:57:9E:5A:88:28:F3:04:
DF:37:D0:7D:55:C3:D1:59:B0:B2:81 :FB:9D:DF:CB:15:A8
a=setup:actpass
a=mid:video
a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
a=sendrecv
a=rtcp-mux
a=rtpmap:100 VP8/90000
a=rtcp-fb:100 ccm fir
a=rtcp-fb:100 nack
a=rtcp-fb:100 nack pli
a=rtcp-fb:100 goog-remb
a=rtpmap:116 red/90000
a=rtpmap:117 ulpfec/90000
a=rtpmap:96 rtx/90000
a=fmtp:96 apt=100
a=ssrc-group:FID 1175220440 3592114481
a=ssrc:1175220440 cname:v1SBHP7c76XqYcWx
a=ssrc:1175220440 msid:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG
43d2eec3-7116-4b29-ad33-466c9358bfb3
a=ssrc:1175220440 mslabel:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG
a=ssrc:1175220440 label:43d2eec3-7116-4b29-ad33-466c9358bfb3
a=ssrc:3592114481 cname:v1SBHP7c76XqYcWx
a=ssrc:3592114481 msid:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG
43d2eec3-7116-4b29-ad33-466c9358bfb3
a=ssrc:3592114481 mslabel:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG
a=ssrc:3592114481 label:43d2eec3-7116-4b29-ad33-466c9358bfb3
This is taken from my own laptop. It is complex to understand at first glance. It starts with identifying the connection with the IP address, then sets up basic information about my request, audio and video information, encryption type. So the goal is not to understand every line, but to get familiar with it because you will never have to work with it directly.
The following is an SDP answer −
v=0
o=- 5504016820010393753 2 IN IP4 127.0.0.1
s=-
t=0 0
a=group:BUNDLE audio video
a=msid-semantic: WMS
m=audio 9 RTP/SAVPF 111 103 104 9 0 8 106 105 13 126
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:RjDpYl08FRKBqZ4A
a=ice-pwd:wSgwewyvypHhyxrcZELBLOBO
a=fingerprint:sha-256 28:4C:19:10:97:56:FB:22:57:9E:5A:88:28:
F3:04:DF:37:D0:7D:55:C3:D1:59:B0:B2:81 :FB:9D:DF:CB:15:A8
a=setup:active
a=mid:audio
a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
a=recvonly
a=rtcp-mux
a=rtpmap:111 opus/48000/2
a=fmtp:111 minptime=10
a=rtpmap:103 ISAC/16000
a=rtpmap:104 ISAC/32000
a=rtpmap:9 G722/8000
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:106 CN/32000
a=rtpmap:105 CN/16000
a=rtpmap:13 CN/8000
a=rtpmap:126 telephone-event/8000
a=maxptime:60
m=video 9 RTP/SAVPF 100 116 117 96
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:RjDpYl08FRKBqZ4A
a=ice-pwd:wSgwewyvypHhyxrcZELBLOBO
a=fingerprint:sha-256 28:4C:19:10:97:56:FB:22:57:9E:5A:88:28:
F3:04:DF:37:D0:7D:55:C3:D1:59:B0:B2:81 :FB:9D:DF:CB:15:A8
a=setup:active
a=mid:video
a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
a=recvonly
a=rtcp-mux
a=rtpmap:100 VP8/90000
a=rtcp-fb:100 ccm fir
a=rtcp-fb:100 nack
a=rtcp-fb:100 nack pli
a=rtcp-fb:100 goog-remb
a=rtpmap:116 red/90000
a=rtpmap:117 ulpfec/90000
a=rtpmap:96 rtx/90000
a=fmtp:96 apt=100
You can find more SDP examples at https://www.rfc-editor.org/rfc/rfc4317.txt as well as more detailed specification at http://tools.ietf.org/html/rfc4566.
To sum up, the SDP acts as a text-based profile of your device to other users trying to connect to you. | [
{
"code": null,
"e": 2465,
"s": 2021,
"text": "The SDP is an important part of the WebRTC. It is a protocol that is intended to describe media communication sessions. It does not deliver the media data but is used for negotiation between peers of various audio and video codecs, network topologies, and other device information. It also needs to be easily transportable. Simply put we need a string-based profile with all the information about the user's device. This is where SDP comes in."
},
{
"code": null,
"e": 2677,
"s": 2465,
"text": "The SDP is a well-known method of establishing media connections as it appeared in the late 90s. It has been used in a vast amount of other types of applications before WebRTC like phone and text-based chatting."
},
{
"code": null,
"e": 2763,
"s": 2677,
"text": "The SDP is string data containing sets of key-value pairs, separated by line breaks −"
},
{
"code": null,
"e": 2778,
"s": 2763,
"text": "key = value\\n\n"
},
{
"code": null,
"e": 2894,
"s": 2778,
"text": "The key is a single character that sets the type of the value. The value is a machine-readable configuration value."
},
{
"code": null,
"e": 3079,
"s": 2894,
"text": "The SDP covers media description and media constraints for a given user. When we start using RTCPeerConnection object later we will be able easily print this to the javascript console."
},
{
"code": null,
"e": 3236,
"s": 3079,
"text": "The SDP is the first part of the peer connection. Peers have to exchange SDP data with the help of the signaling channel in order to establish a connection."
},
{
"code": null,
"e": 3273,
"s": 3236,
"text": "This is an example of an SDP offer −"
},
{
"code": null,
"e": 5725,
"s": 3273,
"text": "v=0 \no=- 487255629242026503 2 IN IP4 127.0.0.1 \ns=- \nt=0 0 \n\na=group:BUNDLE audio video \na=msid-semantic: WMS 6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG \nm=audio 9 RTP/SAVPF 111 103 104 9 0 8 106 105 13 126 \nc=IN IP4 0.0.0.0\n\na=rtcp:9 IN IP4 0.0.0.0 \na=ice-ufrag:8a1/LJqQMzBmYtes \na=ice-pwd:sbfskHYHACygyHW1wVi8GZM+ \na=ice-options:google-ice \na=fingerprint:sha-256 28:4C:19:10:97:56:FB:22:57:9E:5A:88:28:F3:04:\n DF:37:D0:7D:55:C3:D1:59:B0:B2:81 :FB:9D:DF:CB:15:A8 \na=setup:actpass \na=mid:audio \na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level \na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time \n\na=sendrecv \na=rtcp-mux \na=rtpmap:111 opus/48000/2 \na=fmtp:111 minptime=10 \na=rtpmap:103 ISAC/16000 \na=rtpmap:104 ISAC/32000 \na=rtpmap:9 G722/8000 \na=rtpmap:0 PCMU/8000 \na=rtpmap:8 PCMA/8000 \na=rtpmap:106 CN/32000 \na=rtpmap:105 CN/16000 \na=rtpmap:13 CN/8000 \na=rtpmap:126 telephone-event/8000 \n\na=maxptime:60 \na=ssrc:3607952327 cname:v1SBHP7c76XqYcWx \na=ssrc:3607952327 msid:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG 9eb1f6d5-c3b246fe\n -b46b-63ea11c46c74 \na=ssrc:3607952327 mslabel:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG \na=ssrc:3607952327 label:9eb1f6d5-c3b2-46fe-b46b-63ea11c46c74 \nm=video 9 RTP/SAVPF 100 116 117 96 \n\nc=IN IP4 0.0.0.0 \na=rtcp:9 IN IP4 0.0.0.0 \na=ice-ufrag:8a1/LJqQMzBmYtes\na=ice-pwd:sbfskHYHACygyHW1wVi8GZM+ \na=ice-options:google-ice \n\na=fingerprint:sha-256 28:4C:19:10:97:56:FB:22:57:9E:5A:88:28:F3:04:\n DF:37:D0:7D:55:C3:D1:59:B0:B2:81 :FB:9D:DF:CB:15:A8 \na=setup:actpass \na=mid:video \na=extmap:2 urn:ietf:params:rtp-hdrext:toffset \na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n\na=sendrecv \na=rtcp-mux \na=rtpmap:100 VP8/90000 \na=rtcp-fb:100 ccm fir \na=rtcp-fb:100 nack \na=rtcp-fb:100 nack pli \na=rtcp-fb:100 goog-remb \na=rtpmap:116 red/90000 \na=rtpmap:117 ulpfec/90000 \na=rtpmap:96 rtx/90000 \n\na=fmtp:96 apt=100 \na=ssrc-group:FID 1175220440 3592114481 \na=ssrc:1175220440 cname:v1SBHP7c76XqYcWx \na=ssrc:1175220440 msid:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG\n 43d2eec3-7116-4b29-ad33-466c9358bfb3 \na=ssrc:1175220440 mslabel:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG \na=ssrc:1175220440 label:43d2eec3-7116-4b29-ad33-466c9358bfb3 \na=ssrc:3592114481 cname:v1SBHP7c76XqYcWx \na=ssrc:3592114481 msid:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG\n 43d2eec3-7116-4b29-ad33-466c9358bfb3 \na=ssrc:3592114481 mslabel:6x9ZxQZqpo19FRr3Q0xsWC2JJ1lVsk2JE0sG \na=ssrc:3592114481 label:43d2eec3-7116-4b29-ad33-466c9358bfb3"
},
{
"code": null,
"e": 6089,
"s": 5725,
"text": "This is taken from my own laptop. It is complex to understand at first glance. It starts with identifying the connection with the IP address, then sets up basic information about my request, audio and video information, encryption type. So the goal is not to understand every line, but to get familiar with it because you will never have to work with it directly."
},
{
"code": null,
"e": 6122,
"s": 6089,
"text": "The following is an SDP answer −"
},
{
"code": null,
"e": 7634,
"s": 6122,
"text": "v=0 \no=- 5504016820010393753 2 IN IP4 127.0.0.1 \ns=- \nt=0 0 \na=group:BUNDLE audio video \na=msid-semantic: WMS \nm=audio 9 RTP/SAVPF 111 103 104 9 0 8 106 105 13 126 \nc=IN IP4 0.0.0.0 \n\na=rtcp:9 IN IP4 0.0.0.0 \na=ice-ufrag:RjDpYl08FRKBqZ4A \na=ice-pwd:wSgwewyvypHhyxrcZELBLOBO \na=fingerprint:sha-256 28:4C:19:10:97:56:FB:22:57:9E:5A:88:28:\n F3:04:DF:37:D0:7D:55:C3:D1:59:B0:B2:81 :FB:9D:DF:CB:15:A8 \na=setup:active \na=mid:audio \na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level \na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time \n\na=recvonly \na=rtcp-mux \na=rtpmap:111 opus/48000/2 \na=fmtp:111 minptime=10 \na=rtpmap:103 ISAC/16000 \na=rtpmap:104 ISAC/32000 \na=rtpmap:9 G722/8000 \na=rtpmap:0 PCMU/8000 \na=rtpmap:8 PCMA/8000 \na=rtpmap:106 CN/32000 \na=rtpmap:105 CN/16000 \na=rtpmap:13 CN/8000 \na=rtpmap:126 telephone-event/8000 \n\na=maxptime:60 \nm=video 9 RTP/SAVPF 100 116 117 96\nc=IN IP4 0.0.0.0 \na=rtcp:9 IN IP4 0.0.0.0 \na=ice-ufrag:RjDpYl08FRKBqZ4A \na=ice-pwd:wSgwewyvypHhyxrcZELBLOBO \na=fingerprint:sha-256 28:4C:19:10:97:56:FB:22:57:9E:5A:88:28:\n F3:04:DF:37:D0:7D:55:C3:D1:59:B0:B2:81 :FB:9D:DF:CB:15:A8 \na=setup:active \na=mid:video \na=extmap:2 urn:ietf:params:rtp-hdrext:toffset \na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n\na=recvonly \na=rtcp-mux \na=rtpmap:100 VP8/90000 \na=rtcp-fb:100 ccm fir \na=rtcp-fb:100 nack \na=rtcp-fb:100 nack pli \na=rtcp-fb:100 goog-remb \na=rtpmap:116 red/90000 \na=rtpmap:117 ulpfec/90000 \na=rtpmap:96 rtx/90000 \na=fmtp:96 apt=100"
},
{
"code": null,
"e": 7790,
"s": 7634,
"text": "You can find more SDP examples at https://www.rfc-editor.org/rfc/rfc4317.txt as well as more detailed specification at http://tools.ietf.org/html/rfc4566."
}
] |
Getting the list of all the matches Java regular expressions | Java does not provide any method to retrieve the list of all matches we need to use Lists and add the results to it in the while loop.
Live Demo
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ListOfMatches{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\\d+";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
ArrayList list = new ArrayList();
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
list.add(matcher.group());
}
Iterator it = list.iterator();
System.out.println("List of matches: ");
while(it.hasNext()){
System.out.println(it.next());
}
}
}
Enter input text:
sample 1432 text 53 with 363 numbers
List of matches:
1432
53
363 | [
{
"code": null,
"e": 1322,
"s": 1187,
"text": "Java does not provide any method to retrieve the list of all matches we need to use Lists and add the results to it in the while loop."
},
{
"code": null,
"e": 1333,
"s": 1322,
"text": " Live Demo"
},
{
"code": null,
"e": 2169,
"s": 1333,
"text": "import java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class ListOfMatches{\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input text: \");\n String input = sc.nextLine();\n String regex = \"\\\\d+\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n ArrayList list = new ArrayList();\n //Matching the compiled pattern in the String\n Matcher matcher = pattern.matcher(input);\n while (matcher.find()) {\n list.add(matcher.group());\n }\n Iterator it = list.iterator();\n System.out.println(\"List of matches: \");\n while(it.hasNext()){\n System.out.println(it.next());\n }\n }\n}"
},
{
"code": null,
"e": 2253,
"s": 2169,
"text": "Enter input text:\nsample 1432 text 53 with 363 numbers\nList of matches:\n1432\n53\n363"
}
] |
Program to check if a string contains any special character | 12 Jun, 2022
Given a string, the task is to check if that string contains any special character (defined special character set). If any special character found, don’t accept that string.Examples :
Input : Geeks$For$Geeks
Output : String is not accepted.
Input : Geeks For Geeks
Output : String is accepted
Approach : Make a regular expression(regex) object of all the special characters that we don’t want, then pass a string in search method. If any one character of string is matching with regex object then search method returns a match object otherwise return None.Below is the implementation :
C++
Python3
PHP
// C++ program to check if a string// contains any special character // import required packages#include <iostream>#include <regex>using namespace std; // Function checks if the string// contains any special charactervoid run(string str){ // Make own character set regex regx("[@_!#$%^&*()<>?/|}{~:]"); // Pass the string in regex_search // method if(regex_search(str, regx) == 0) cout << "String is accepted"; else cout << "String is not accepted.";} // Driver Codeint main(){ // Enter the string string str = "Geeks$For$Geeks"; // Calling run function run(str); return 0;} // This code is contributed by Yash_R
# Python3 program to check if a string# contains any special character # import required packageimport re # Function checks if the string# contains any special characterdef run(string): # Make own character set and pass # this as argument in compile method regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]') # Pass the string in search # method of regex object. if(regex.search(string) == None): print("String is accepted") else: print("String is not accepted.") # Driver Codeif __name__ == '__main__' : # Enter the string string = "Geeks$For$Geeks" # calling run function run(string)
<?Php// PHP program to check if a string// contains any special character // Function checks if the string// contains any special characterfunction run($string){ $regex = preg_match('[@_!#$%^&*()<>?/\|}{~:]', $string); if($regex) print("String is accepted"); else print("String is not accepted.");} // Driver Code // Enter the string$string = 'Geeks$For$Geeks'; // calling run functionrun($string); // This code is contributed by Aman ojha?>
String is not accepted.
Method: To check if a special character is present in a given string or not, firstly group all special characters as one set. Then using for loop and if statements check for special characters. If any special character is found then increment the value of c. Finally, check if the c value is greater than zero then print string is not accepted otherwise print string is accepted.
Python3
# Python code# to check if any special character is present#in a given string or not # input stringn="Geeks$For$Geeks"n.split()c=0s='[@_!#$%^&*()<>?/\|}{~:]' # special character setfor i in range(len(n)): # checking if any special character is present in given string or not if n[i] in s: c+=1 # if special character found then add 1 to the c # if c value is greater than 0 then print no# means special character is found in string if c: print("string is not accepted")else: print("string accepted") # this code is contributed by gangarajula laxmi
string is not accepted
Aman ojha
Yash_R
mallapraveen2014
laxmigangarajula03
Python Regex-programs
Python string-programs
python-regex
python-string
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Jun, 2022"
},
{
"code": null,
"e": 239,
"s": 53,
"text": "Given a string, the task is to check if that string contains any special character (defined special character set). If any special character found, don’t accept that string.Examples : "
},
{
"code": null,
"e": 349,
"s": 239,
"text": "Input : Geeks$For$Geeks\nOutput : String is not accepted.\n\nInput : Geeks For Geeks\nOutput : String is accepted"
},
{
"code": null,
"e": 646,
"s": 351,
"text": "Approach : Make a regular expression(regex) object of all the special characters that we don’t want, then pass a string in search method. If any one character of string is matching with regex object then search method returns a match object otherwise return None.Below is the implementation : "
},
{
"code": null,
"e": 650,
"s": 646,
"text": "C++"
},
{
"code": null,
"e": 658,
"s": 650,
"text": "Python3"
},
{
"code": null,
"e": 662,
"s": 658,
"text": "PHP"
},
{
"code": "// C++ program to check if a string// contains any special character // import required packages#include <iostream>#include <regex>using namespace std; // Function checks if the string// contains any special charactervoid run(string str){ // Make own character set regex regx(\"[@_!#$%^&*()<>?/|}{~:]\"); // Pass the string in regex_search // method if(regex_search(str, regx) == 0) cout << \"String is accepted\"; else cout << \"String is not accepted.\";} // Driver Codeint main(){ // Enter the string string str = \"Geeks$For$Geeks\"; // Calling run function run(str); return 0;} // This code is contributed by Yash_R",
"e": 1339,
"s": 662,
"text": null
},
{
"code": "# Python3 program to check if a string# contains any special character # import required packageimport re # Function checks if the string# contains any special characterdef run(string): # Make own character set and pass # this as argument in compile method regex = re.compile('[@_!#$%^&*()<>?/\\|}{~:]') # Pass the string in search # method of regex object. if(regex.search(string) == None): print(\"String is accepted\") else: print(\"String is not accepted.\") # Driver Codeif __name__ == '__main__' : # Enter the string string = \"Geeks$For$Geeks\" # calling run function run(string)",
"e": 1999,
"s": 1339,
"text": null
},
{
"code": "<?Php// PHP program to check if a string// contains any special character // Function checks if the string// contains any special characterfunction run($string){ $regex = preg_match('[@_!#$%^&*()<>?/\\|}{~:]', $string); if($regex) print(\"String is accepted\"); else print(\"String is not accepted.\");} // Driver Code // Enter the string$string = 'Geeks$For$Geeks'; // calling run functionrun($string); // This code is contributed by Aman ojha?>",
"e": 2513,
"s": 1999,
"text": null
},
{
"code": null,
"e": 2537,
"s": 2513,
"text": "String is not accepted."
},
{
"code": null,
"e": 2919,
"s": 2537,
"text": "Method: To check if a special character is present in a given string or not, firstly group all special characters as one set. Then using for loop and if statements check for special characters. If any special character is found then increment the value of c. Finally, check if the c value is greater than zero then print string is not accepted otherwise print string is accepted. "
},
{
"code": null,
"e": 2927,
"s": 2919,
"text": "Python3"
},
{
"code": "# Python code# to check if any special character is present#in a given string or not # input stringn=\"Geeks$For$Geeks\"n.split()c=0s='[@_!#$%^&*()<>?/\\|}{~:]' # special character setfor i in range(len(n)): # checking if any special character is present in given string or not if n[i] in s: c+=1 # if special character found then add 1 to the c # if c value is greater than 0 then print no# means special character is found in string if c: print(\"string is not accepted\")else: print(\"string accepted\") # this code is contributed by gangarajula laxmi",
"e": 3498,
"s": 2927,
"text": null
},
{
"code": null,
"e": 3521,
"s": 3498,
"text": "string is not accepted"
},
{
"code": null,
"e": 3533,
"s": 3523,
"text": "Aman ojha"
},
{
"code": null,
"e": 3540,
"s": 3533,
"text": "Yash_R"
},
{
"code": null,
"e": 3557,
"s": 3540,
"text": "mallapraveen2014"
},
{
"code": null,
"e": 3576,
"s": 3557,
"text": "laxmigangarajula03"
},
{
"code": null,
"e": 3598,
"s": 3576,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 3621,
"s": 3598,
"text": "Python string-programs"
},
{
"code": null,
"e": 3634,
"s": 3621,
"text": "python-regex"
},
{
"code": null,
"e": 3648,
"s": 3634,
"text": "python-string"
},
{
"code": null,
"e": 3655,
"s": 3648,
"text": "Python"
},
{
"code": null,
"e": 3671,
"s": 3655,
"text": "Python Programs"
}
] |
Data Scraping for Android Apps using google-play-scraper in Node.js | 19 Oct, 2020
The most commonly existing method for scraping the web is the one in which we use selenium & beautifulsoup in Python. Even though it helps us in a variety of tasks, if we are specifically looking to extract information about an already existing android app on the google play store for research purposes or even for self-use, there’s another way of doing things.
The google-play-scraper is a Node.js module that helps in scraping App data from the Google Play store by providing methods that make our job easy.
Installation:
npm install google-play-scraper
Important methods:1. app: It returns the entire data associated with that application.
Parameters:
appId: The id associated with the app on Google Play. It can be seen in the “?id=” of the URL.
lang: It is an optional parameter. It has a default value of “en” for English. If we want out app data to be fetched in a different language. We can provide the two-letter code of that language to this parameter.
country: It is also an optional parameter. It has a default value of “us” for the United States of America. This parameter is helpful when the app we’re looking at is available only in specific countries.
Example:
var gPlayScraper = require('google-play-scraper'); gPlayScraper.app({appId: 'free.programming.programming'}) .then(console.log, console.log);
Output:
[ { title: 'Learn DS & Algo, Programming Interview Preparation',
description:
'GeeksforGeeks is a one-stop destination for programmers.
The app features 20000+ Programming Questions, 40, 000+....',
descriptionHTML:
'GeeksforGeeks is a one-stop destination for programmers.....',
summary:
'Learn Data Structures Algorithms, C Programming, C++,
Java, Python, JS, Aptitude',
installs: '500, 000+',
minInstalls: 500000,
score: 4.6594124,
...
developer: 'GeeksforGeeks',
developerId: 'GeeksforGeeks',
developerEmail: '[email protected]',
developerWebsite: 'https://www.geeksforgeeks.org/',
developerAddress: 'Noida, UP, India',
privacyPolicy: 'https://www.geeksforgeeks.org/privacy-policy/',
developerInternalID: '5323597028845965498',
genre: 'Education',
genreId: 'EDUCATION',
.....' ],
.....
url:
'https://play.google.com/store/apps/details?id=free.programming.programming&hl=en&gl=us' } ]
2. search: It retrieves a list of apps that results in searching by the given term.
Parameters:
term: It contains the search term.
num: The number of apps that we wish to retrieve. It is an optional parameter with the default value of 20. Note that the maximum value of this parameter can be 250.
lang: It is an optional parameter. It has a default value of “en” for English. If we want out app data to be fetched in a different language, we can provide the two-letter code of that language to this parameter.
country: It is also an optional parameter. It has a default value of “us” for the United States of America. This parameter is helpful when the app we’re looking at is available only in specific countries.
price: We can pass “all” to return both free and paid apps, “free” for free apps and “paid” for paid apps.
Example:
var gPlayScraper = require('google-play-scraper'); gPlayScraper.search({ term: "tech", num: 2 }).then(console.log, console.log);
Output:
[ { title: 'CNET: Best Tech News, Reviews, Videos & Deals',
appId: 'com.cbsinteractive.cnet',
url:
'https://play.google.com/store/apps/details?id=com.cbsinteractive.cnet',
icon:
'https://lh3.googleusercontent.com/DeIoPrQ4jp2STHmWzbWI8Ss8JRnPgFrmDoOLje2PXcpA7CQN8hFxOvxXCSOOEGLUUQ',
developer: 'CBS Interactive, Inc.',
developerId: 'CBS+Interactive, +Inc.',
priceText: 'FREE',
currency: undefined,
price: 0,
free: true,
summary:
'Breaking technology news and expert product how-tos,
comparisons, advice & tips',
scoreText: '4.0',
score: 4 },
{ title: 'Tech Coach',
appId: 'com.asurion.solutohome.verizon',
..
score: 4.4551244 } ]
3. suggest: It takes a string input and returns a list containing five suggestions to complete our search query.
Parameters:
term: The term we want to get suggestions for.
lang: It is an optional parameter. It has a default value of “en” for English. If we want out app data to be fetched in a different language, we can provide the two-letter code of that language to this parameter.
country: It is also an optional parameter. It has a default value of “us” for the United States of America. This parameter is helpful when the app we’re looking at is available only in specific countries.
Example:
var gPlayScraper = require('google-play-scraper'); gPlayScraper.suggest({term: 'algorithms'}).then(console.log);
Output:
[ 'algorithms',
'algorithms to live by',
'algorithms and data structures',
'algorithms explained and animated',
"algorithms for rubik's cube" ]
4. permissions: It returns the list of permissions an app has access to.
Parameters:
appId: The id associated with the app on Google Play. It can be seen in the “?id=” of the URL.
lang: It is an optional parameter. It has a default value of “en” for English. If we want out app data to be fetched in a different language, we can provide the two-letter code of that language to this parameter.
Example:
var gPlayScraper = require('google-play-scraper'); // Let's analyse the permissions requested by SHAREitgPlayScraper.permissions({appId: 'com.lenovo.anyshare.gps'}). .then(console.log, console.log);
Output:
[ { permission: 'take pictures and videos', type: 'Camera' },
{ permission:
"add or modify calendar events and send email to
guests without owners' knowledge",
type: 'Calendar' },
{ permission: 'record audio', type: 'Microphone' },
{ permission: 'read sensitive log data',
type: 'Device & app history' },
{ permission: 'retrieve running apps',
type: 'Device & app history' },
....
{ permission: 'send sticky broadcast', type: 'Other' },
{ permission: 'expand/collapse status bar', type: 'Other' },
{ permission: 'control vibration', type: 'Other' } ]
The other methods which you can take a look at are:
list: It returns the list of applications from one of the collections at Google Play.
developer: It returns the list of applications by the given developer name.
reviews: It returns a page full of the reviews of the currently specified app.
similar: It returns a list of apps that are similar to the apps that are specified.
categories: It returns a list of categories available on the Google Play Store.
preritpathak
Node.js-Misc
Node.js
Web Technologies
Web technologies Questions
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Oct, 2020"
},
{
"code": null,
"e": 391,
"s": 28,
"text": "The most commonly existing method for scraping the web is the one in which we use selenium & beautifulsoup in Python. Even though it helps us in a variety of tasks, if we are specifically looking to extract information about an already existing android app on the google play store for research purposes or even for self-use, there’s another way of doing things."
},
{
"code": null,
"e": 539,
"s": 391,
"text": "The google-play-scraper is a Node.js module that helps in scraping App data from the Google Play store by providing methods that make our job easy."
},
{
"code": null,
"e": 553,
"s": 539,
"text": "Installation:"
},
{
"code": null,
"e": 585,
"s": 553,
"text": "npm install google-play-scraper"
},
{
"code": null,
"e": 672,
"s": 585,
"text": "Important methods:1. app: It returns the entire data associated with that application."
},
{
"code": null,
"e": 684,
"s": 672,
"text": "Parameters:"
},
{
"code": null,
"e": 779,
"s": 684,
"text": "appId: The id associated with the app on Google Play. It can be seen in the “?id=” of the URL."
},
{
"code": null,
"e": 992,
"s": 779,
"text": "lang: It is an optional parameter. It has a default value of “en” for English. If we want out app data to be fetched in a different language. We can provide the two-letter code of that language to this parameter."
},
{
"code": null,
"e": 1197,
"s": 992,
"text": "country: It is also an optional parameter. It has a default value of “us” for the United States of America. This parameter is helpful when the app we’re looking at is available only in specific countries."
},
{
"code": null,
"e": 1206,
"s": 1197,
"text": "Example:"
},
{
"code": "var gPlayScraper = require('google-play-scraper'); gPlayScraper.app({appId: 'free.programming.programming'}) .then(console.log, console.log);",
"e": 1352,
"s": 1206,
"text": null
},
{
"code": null,
"e": 1360,
"s": 1352,
"text": "Output:"
},
{
"code": null,
"e": 2313,
"s": 1360,
"text": "[ { title: 'Learn DS & Algo, Programming Interview Preparation',\n description:\n 'GeeksforGeeks is a one-stop destination for programmers.\n The app features 20000+ Programming Questions, 40, 000+....',\n descriptionHTML:\n 'GeeksforGeeks is a one-stop destination for programmers.....',\n summary:\n 'Learn Data Structures Algorithms, C Programming, C++,\n Java, Python, JS, Aptitude',\n installs: '500, 000+',\n minInstalls: 500000,\n score: 4.6594124,\n ...\n developer: 'GeeksforGeeks',\n developerId: 'GeeksforGeeks',\n developerEmail: '[email protected]',\n developerWebsite: 'https://www.geeksforgeeks.org/',\n developerAddress: 'Noida, UP, India',\n privacyPolicy: 'https://www.geeksforgeeks.org/privacy-policy/',\n developerInternalID: '5323597028845965498',\n genre: 'Education',\n genreId: 'EDUCATION',\n .....' ],\n .....\n url:\n 'https://play.google.com/store/apps/details?id=free.programming.programming&hl=en&gl=us' } ]\n"
},
{
"code": null,
"e": 2397,
"s": 2313,
"text": "2. search: It retrieves a list of apps that results in searching by the given term."
},
{
"code": null,
"e": 2409,
"s": 2397,
"text": "Parameters:"
},
{
"code": null,
"e": 2444,
"s": 2409,
"text": "term: It contains the search term."
},
{
"code": null,
"e": 2610,
"s": 2444,
"text": "num: The number of apps that we wish to retrieve. It is an optional parameter with the default value of 20. Note that the maximum value of this parameter can be 250."
},
{
"code": null,
"e": 2823,
"s": 2610,
"text": "lang: It is an optional parameter. It has a default value of “en” for English. If we want out app data to be fetched in a different language, we can provide the two-letter code of that language to this parameter."
},
{
"code": null,
"e": 3028,
"s": 2823,
"text": "country: It is also an optional parameter. It has a default value of “us” for the United States of America. This parameter is helpful when the app we’re looking at is available only in specific countries."
},
{
"code": null,
"e": 3135,
"s": 3028,
"text": "price: We can pass “all” to return both free and paid apps, “free” for free apps and “paid” for paid apps."
},
{
"code": null,
"e": 3144,
"s": 3135,
"text": "Example:"
},
{
"code": "var gPlayScraper = require('google-play-scraper'); gPlayScraper.search({ term: \"tech\", num: 2 }).then(console.log, console.log);",
"e": 3281,
"s": 3144,
"text": null
},
{
"code": null,
"e": 3289,
"s": 3281,
"text": "Output:"
},
{
"code": null,
"e": 4002,
"s": 3289,
"text": "[ { title: 'CNET: Best Tech News, Reviews, Videos & Deals',\n appId: 'com.cbsinteractive.cnet',\n url:\n 'https://play.google.com/store/apps/details?id=com.cbsinteractive.cnet',\n icon:\n 'https://lh3.googleusercontent.com/DeIoPrQ4jp2STHmWzbWI8Ss8JRnPgFrmDoOLje2PXcpA7CQN8hFxOvxXCSOOEGLUUQ',\n developer: 'CBS Interactive, Inc.',\n developerId: 'CBS+Interactive, +Inc.',\n priceText: 'FREE',\n currency: undefined,\n price: 0,\n free: true,\n summary:\n 'Breaking technology news and expert product how-tos,\n comparisons, advice & tips',\n scoreText: '4.0',\n score: 4 },\n { title: 'Tech Coach',\n appId: 'com.asurion.solutohome.verizon',\n ..\n score: 4.4551244 } ]\n"
},
{
"code": null,
"e": 4115,
"s": 4002,
"text": "3. suggest: It takes a string input and returns a list containing five suggestions to complete our search query."
},
{
"code": null,
"e": 4127,
"s": 4115,
"text": "Parameters:"
},
{
"code": null,
"e": 4174,
"s": 4127,
"text": "term: The term we want to get suggestions for."
},
{
"code": null,
"e": 4387,
"s": 4174,
"text": "lang: It is an optional parameter. It has a default value of “en” for English. If we want out app data to be fetched in a different language, we can provide the two-letter code of that language to this parameter."
},
{
"code": null,
"e": 4592,
"s": 4387,
"text": "country: It is also an optional parameter. It has a default value of “us” for the United States of America. This parameter is helpful when the app we’re looking at is available only in specific countries."
},
{
"code": null,
"e": 4601,
"s": 4592,
"text": "Example:"
},
{
"code": "var gPlayScraper = require('google-play-scraper'); gPlayScraper.suggest({term: 'algorithms'}).then(console.log);",
"e": 4715,
"s": 4601,
"text": null
},
{
"code": null,
"e": 4723,
"s": 4715,
"text": "Output:"
},
{
"code": null,
"e": 4876,
"s": 4723,
"text": "[ 'algorithms',\n 'algorithms to live by',\n 'algorithms and data structures',\n 'algorithms explained and animated',\n \"algorithms for rubik's cube\" ]\n"
},
{
"code": null,
"e": 4949,
"s": 4876,
"text": "4. permissions: It returns the list of permissions an app has access to."
},
{
"code": null,
"e": 4961,
"s": 4949,
"text": "Parameters:"
},
{
"code": null,
"e": 5056,
"s": 4961,
"text": "appId: The id associated with the app on Google Play. It can be seen in the “?id=” of the URL."
},
{
"code": null,
"e": 5269,
"s": 5056,
"text": "lang: It is an optional parameter. It has a default value of “en” for English. If we want out app data to be fetched in a different language, we can provide the two-letter code of that language to this parameter."
},
{
"code": null,
"e": 5278,
"s": 5269,
"text": "Example:"
},
{
"code": "var gPlayScraper = require('google-play-scraper'); // Let's analyse the permissions requested by SHAREitgPlayScraper.permissions({appId: 'com.lenovo.anyshare.gps'}). .then(console.log, console.log);",
"e": 5483,
"s": 5278,
"text": null
},
{
"code": null,
"e": 5491,
"s": 5483,
"text": "Output:"
},
{
"code": null,
"e": 6082,
"s": 5491,
"text": "[ { permission: 'take pictures and videos', type: 'Camera' },\n { permission:\n \"add or modify calendar events and send email to\n guests without owners' knowledge\",\n type: 'Calendar' },\n { permission: 'record audio', type: 'Microphone' },\n { permission: 'read sensitive log data',\n type: 'Device & app history' },\n { permission: 'retrieve running apps',\n type: 'Device & app history' },\n ....\n { permission: 'send sticky broadcast', type: 'Other' },\n { permission: 'expand/collapse status bar', type: 'Other' },\n { permission: 'control vibration', type: 'Other' } ]\n"
},
{
"code": null,
"e": 6134,
"s": 6082,
"text": "The other methods which you can take a look at are:"
},
{
"code": null,
"e": 6220,
"s": 6134,
"text": "list: It returns the list of applications from one of the collections at Google Play."
},
{
"code": null,
"e": 6296,
"s": 6220,
"text": "developer: It returns the list of applications by the given developer name."
},
{
"code": null,
"e": 6375,
"s": 6296,
"text": "reviews: It returns a page full of the reviews of the currently specified app."
},
{
"code": null,
"e": 6459,
"s": 6375,
"text": "similar: It returns a list of apps that are similar to the apps that are specified."
},
{
"code": null,
"e": 6539,
"s": 6459,
"text": "categories: It returns a list of categories available on the Google Play Store."
},
{
"code": null,
"e": 6552,
"s": 6539,
"text": "preritpathak"
},
{
"code": null,
"e": 6565,
"s": 6552,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 6573,
"s": 6565,
"text": "Node.js"
},
{
"code": null,
"e": 6590,
"s": 6573,
"text": "Web Technologies"
},
{
"code": null,
"e": 6617,
"s": 6590,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 6633,
"s": 6617,
"text": "Write From Home"
},
{
"code": null,
"e": 6731,
"s": 6633,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6763,
"s": 6731,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 6798,
"s": 6763,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 6868,
"s": 6798,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 6895,
"s": 6868,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 6920,
"s": 6895,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 6982,
"s": 6920,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7043,
"s": 6982,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 7093,
"s": 7043,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 7136,
"s": 7093,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Google Guice - Method Injection | Injection is a process of injecting dependeny into an object. Method injection is used to set value object as dependency to the object. See the example below.
Create a java class named GuiceTester.
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.ImplementedBy;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
public class GuiceTester {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new TextEditorModule());
TextEditor editor = injector.getInstance(TextEditor.class);
editor.makeSpellCheck();
}
}
class TextEditor {
private SpellChecker spellChecker;
@Inject
public TextEditor( SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void makeSpellCheck(){
spellChecker.checkSpelling();
}
}
//Binding Module
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(String.class)
.annotatedWith(Names.named("JDBC"))
.toInstance("jdbc:mysql://localhost:5326/emp");
}
}
@ImplementedBy(SpellCheckerImpl.class)
interface SpellChecker {
public void checkSpelling();
}
//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
private String dbUrl;
public SpellCheckerImpl(){}
@Inject
public void setDbUrl(@Named("JDBC") String dbUrl){
this.dbUrl = dbUrl;
}
@Override
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
System.out.println(dbUrl);
}
}
Compile and run the file, you will see the following output. | [
{
"code": null,
"e": 2395,
"s": 2236,
"text": "Injection is a process of injecting dependeny into an object. Method injection is used to set value object as dependency to the object. See the example below."
},
{
"code": null,
"e": 2434,
"s": 2395,
"text": "Create a java class named GuiceTester."
},
{
"code": null,
"e": 3911,
"s": 2434,
"text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\nimport com.google.inject.name.Names;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n bind(String.class)\n .annotatedWith(Names.named(\"JDBC\"))\n .toInstance(\"jdbc:mysql://localhost:5326/emp\");\n } \n}\n\n@ImplementedBy(SpellCheckerImpl.class)\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n \n private String dbUrl;\n\n public SpellCheckerImpl(){}\n \n @Inject \n public void setDbUrl(@Named(\"JDBC\") String dbUrl){\n this.dbUrl = dbUrl;\n }\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl); \n }\n}"
}
] |
Find the longest path in a matrix with given constraints in C++ | Suppose we have one square matrix of order n. It has all distinct elements. So we have to find the maximum length path, such that all cells along the path are in increasing order with a difference of 1. From one cell we can move to four directions. Left, Right, Top and Bottom. So if the matrix is like −
So the output will be 4. As the longest path is 6→7→8→ 9
To solve this problem, we will follow this idea. We will calculate longest path beginning with every cell. Once we have got the longest for all cells, we return maximum of all longest paths.
One important observation in this approach is many overlapping sub-problems. So this problem can be solved using Dynamic Programming. Here we will use a lookup table dp[][] to check if a problem is already solved or not.
#include <iostream>
#define n 3
using namespace std;
int getLongestPathLengthUtil(int i, int j, int matrix[n][n], int table[n][n]) {
if (i < 0 || i >= n || j < 0 || j >= n)
return 0;
if (table[i][j] != -1)
return table[i][j];
int x = INT_MIN, y = INT_MIN, z = INT_MIN, w = INT_MIN;
if (j < n - 1 && ((matrix[i][j] + 1) == matrix[i][j + 1]))
x = 1 + getLongestPathLengthUtil(i, j + 1, matrix, table);
if (j > 0 && (matrix[i][j] + 1 == matrix[i][j - 1]))
y = 1 + getLongestPathLengthUtil(i, j - 1, matrix, table);
if (i > 0 && (matrix[i][j] + 1 == matrix[i - 1][j]))
z = 1 + getLongestPathLengthUtil(i - 1, j, matrix, table);
if (i < n - 1 && (matrix[i][j] + 1 == matrix[i + 1][j]))
w = 1 + getLongestPathLengthUtil(i + 1, j, matrix, table);
return table[i][j] = max(x, max(y, max(z, max(w, 1))));
}
int getLongestPathLength(int matrix[n][n]) {
int result = 1;
int table[n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
table[i][j] = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (table[i][j] == -1)
getLongestPathLengthUtil(i, j, matrix, table);
result = max(result, table[i][j]);
}
}
return result;
}
int main() {
int mat[n][n] = { { 1, 2, 9 },
{ 5, 3, 8 },
{ 4, 6, 7 } };
cout << "Length of the longest path is "<< getLongestPathLength(mat);
}
Length of the longest path is 4 | [
{
"code": null,
"e": 1367,
"s": 1062,
"text": "Suppose we have one square matrix of order n. It has all distinct elements. So we have to find the maximum length path, such that all cells along the path are in increasing order with a difference of 1. From one cell we can move to four directions. Left, Right, Top and Bottom. So if the matrix is like −"
},
{
"code": null,
"e": 1424,
"s": 1367,
"text": "So the output will be 4. As the longest path is 6→7→8→ 9"
},
{
"code": null,
"e": 1615,
"s": 1424,
"text": "To solve this problem, we will follow this idea. We will calculate longest path beginning with every cell. Once we have got the longest for all cells, we return maximum of all longest paths."
},
{
"code": null,
"e": 1836,
"s": 1615,
"text": "One important observation in this approach is many overlapping sub-problems. So this problem can be solved using Dynamic Programming. Here we will use a lookup table dp[][] to check if a problem is already solved or not."
},
{
"code": null,
"e": 3249,
"s": 1836,
"text": "#include <iostream>\n#define n 3\nusing namespace std;\nint getLongestPathLengthUtil(int i, int j, int matrix[n][n], int table[n][n]) {\n if (i < 0 || i >= n || j < 0 || j >= n)\n return 0;\n if (table[i][j] != -1)\n return table[i][j];\n int x = INT_MIN, y = INT_MIN, z = INT_MIN, w = INT_MIN;\n if (j < n - 1 && ((matrix[i][j] + 1) == matrix[i][j + 1]))\n x = 1 + getLongestPathLengthUtil(i, j + 1, matrix, table);\n if (j > 0 && (matrix[i][j] + 1 == matrix[i][j - 1]))\n y = 1 + getLongestPathLengthUtil(i, j - 1, matrix, table);\n if (i > 0 && (matrix[i][j] + 1 == matrix[i - 1][j]))\n z = 1 + getLongestPathLengthUtil(i - 1, j, matrix, table);\n if (i < n - 1 && (matrix[i][j] + 1 == matrix[i + 1][j]))\n w = 1 + getLongestPathLengthUtil(i + 1, j, matrix, table);\n return table[i][j] = max(x, max(y, max(z, max(w, 1))));\n}\nint getLongestPathLength(int matrix[n][n]) {\n int result = 1;\n int table[n][n];\n for(int i = 0; i < n; i++)\n for(int j = 0; j < n; j++)\n table[i][j] = -1;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n if (table[i][j] == -1)\n getLongestPathLengthUtil(i, j, matrix, table);\n result = max(result, table[i][j]);\n }\n }\n return result;\n}\nint main() {\n int mat[n][n] = { { 1, 2, 9 },\n { 5, 3, 8 },\n { 4, 6, 7 } };\n cout << \"Length of the longest path is \"<< getLongestPathLength(mat);\n}"
},
{
"code": null,
"e": 3281,
"s": 3249,
"text": "Length of the longest path is 4"
}
] |
Predicting How Expensive A Healthcare Provider is for the Government | by Tristan Bonds | Towards Data Science | As Metis Data Science Bootcamp students, we were tasked to build a linear regression model for our first individual project. Simple enough right? Just draw a line through data.
Not so fast!
As a healthcare professional, I was excited to use this algorithm to solve a problem in the medical field. But what I quickly found out was, before any modeling, a successful machine learning project starts with picking the right kind of data. Linear regression works best with continuous numerical data which excludes several sources of publicly available healthcare data. However, it turns out that Medicare payment data is a perfect fit.
But why care about Medicare? Medicare is a government-funded health insurance program currently covering 44 million people, or 1 in 8 individuals in the U.S. (1). That carries with it some huge public health and financial implications for the government. As soon as you turn 65, you’re eligible for it with a few exceptions such as younger people with disabilities or those suffering from end stage renal disease. And this population is only getting bigger. In fact, the Census Bureau estimates that by 2030, the elderly population alone will nearly double to 78 million people or 1 in 5 Americans (2).
On top of this, it seems likely that Medicare is going to be increasingly more important in the coming years due to its prevalence in political discussions around the country. If the United States were to adopt a single-payer system, such as the proposed Medicare-for-All, it would be essential for us to lower costs wherever possible, and the effective usage of data could help to achieve this.
One way to do this would be to look at healthcare provider costs. You can follow along with my code on my GitHub repository; I’ve organized it chronologically with this article for your convenience.
After searching the Center for Medicare and Medicaid Services website, I was able to acquire the most recent provider payment data which had over 1 million rows, each corresponding to a healthcare organization or individual provider, and 70 features.
But as expected, this data was quite a mess. So in order to glean the most reliable insight I could, I decided to narrow down what I was measuring to only individual providers in the U.S, excluding territories and military zones.
I then replaced all missing values in columns with count or percentage data with zeroes. It is likely that if a provider doesn’t have patients with a certain disease, the field is just left blank; this means it should have been relatively safe to impute nulls without losing much fidelity.
There was also some documentation provided for the meaning of each column name. I decided the target variable should be total_medicare_payment_amt, which is the total amount the government paid for all the provider’s services per patient after deductible and coinsurance amounts have been subtracted. Additionally, I removed all columns that were either unnecessary (like provider names) or that would lead to possible data leakage (like other price-based columns).
Finally I was left with a little over 990,000 clean rows with 38 features. Let’s begin!
Using the Statsmodels python library, I just threw all my data into the ordinary least squares (OLS) linear regression to see how it would perform initially with no modifications.
As previously mentioned, linear regression tries to find a linear relationship between independent variables and a dependent variable. Above, you can see the simplest univariate form with only one independent variable or feature. It uses the equation y = mx + b to find the best fit with the data; m is the slope coefficient and b is the y intercept.
But obviously with 38 features, this linear regression problem is a lot more complex. In this case, there will be 38 “mx” terms added together, with each m term corresponding to the size and direction of the effect that specific variable is having on the dependent variable. In geometric terms, we will be fitting a 38th dimensional hyperplane to 39th dimensional space (instead of a line). If you find a way to visualize this, let me know!
Ok, so now we have some intuition for the model, but how do we determine how well the model is doing?
The metric that is commonly used here is called the coefficient of determination or R-squared. Essentially, it is the percentage of variance of the target variable that is predicted by the features. We want an R-squared close to 1 which indicates that the model is very predictive.
But let’s dive a little deeper into the actual formula of R-squared because it helps us to understand how we are evaluating the model. The most naive method we could use to predict Medicare costs would be to just guess the average cost. That is the green ȳ (called y-bar) in the the diagram above. This will be our baseline.
But we can do a lot better than that by using linear regression or the red ŷ (called y-hat). Now we just find how off these two predictions are from the actual value and divide them by each other (SSE/SST). This will tell us the percentage of variance the model cannot explain. But what we really want to know is what percentage of variance this model does explain. Subtracting that value from 1 will get us there.
1 - (Error Sum of Squares/Total Sum of Squares) or 1 - (SSE/SST)
And after running the initial model, the R-squared was 0.619. That means that our model only accounts for about 62% of the variation in the data. That’s not too good.
But wait! Linear regression has many assumptions and it is important to check if our data is actually working for this model.
Assumption #1: Is there a linear relationship between the target variable and the features?
For illustration purposes, if we use the feature of total medicare cost, it’s not entirely clear. To rectify this situation, we could do some feature engineering. One option is to do a logarithmic transformation of both the feature and the target.
Wow! That’s a dramatic improvement. Anyone can draw a line through that! As you can see, it is often the case that we need to transform the data in specific ways to make it conform to the assumptions of the model we are using.
Note: Always remember to undo this transformation afterwards in order to return your value back to the original context. Because after all, what does the logarithm of Medicare costs even mean?
Assumption #2: Are the target and the features normally distributed?
In the above figure, the left plot shows the target variable before using a logarithmic transformation; as you can see, it is terribly right skewed. The right plot, on the other hand, shows how applying this transformation results in a remarkably normal distribution.
Assumption #3: Is there little to no multicollinearity among the features?
Multicollinearity is when the features are highly correlated with each other. Above, we see a heat map where the darker colors indicate strong positive correlations. Ideally, we would see only light colors everywhere else except the diagonal line across the middle, as obviously a variable will be perfectly correlated with itself.
But in reality, we see darker colors popping up all over the place, which indicates we are violating this assumption. This can lead to imprecise regression coefficients or worse, changes in sign for the same features in different samples, which makes it difficult to reliably extract meaning out of those coefficients.
The way to go about solving this is to remove features until there is no longer any collinearity. As will be discussed later, regularization techniques do this for you by zeroing out coefficients of some of the features that are collinear with each other.
Assumption #4: Are the residuals correlated with themselves?
An autocorrelation happens when the residuals for a specific feature are not independent from each other. This is considered bad because it indicates the model is not extracting all the information possible from the data, and thus, we see it in the residuals.
This can be measured through the Durbin-Watson test. Values near 2 indicate no autocorrelation, while values near 0 or 4 indicate strong autocorrelations. Our initial model has a value of 1.998, indicating that the model is extracting as much information as possible and the assumption has been met.
Assumption #5: Is the data homoskedastic?
What we want to avoid here is heteroskedasticity, a big word with a simple explanation. This is when the variance of the residuals change across the range of values in a feature.
As you can see in this hypothetical example, it is very clear that the variance gets wider as age increase. This is not good as it means that our model will get worse at making predictions the older someone gets. What we really want is a consistent predictability and variance across the entire range of values, known as homoskedasticity. In other words, the two dotted red lines would be parallel to each other.
Here we see the predicted values versus the residuals for our model on the Medicare data. This doesn’t look good at all. There is a harsh cut off in the negative residuals (due to government cost always being greater than or equal to 0) and the variance is completely inconsistent across the range of values.
But after applying the logarithmic transformation that we did before, the plot looks relatively homoskedastic now and we have met this assumption. Boom!
So after checking the assumptions of all the features, I decided to apply a log transformation to 3 features and the target variable.
Now, I put this newly transformed data back into the model and after training, it produced an R-squared of 0.92. Fantastic! This is a solid result as the new model can explain 30% more of the variance in the data versus the baseline model. This demonstrates how important it is to transform your data to meet the assumptions of the model you have chosen.
But this was just an OLS model. We can apply the regularization techniques briefly mentioned before which should further strengthen our model. These add an extra term to the cost function, penalizing the model for complexity. This is a good idea because simpler models are typically better than complex ones as they tend to be less susceptible to overfitting.
In other words, complex models tend to fit training data super well but perform poorly on unseen data. I switched over to the scikit-learn library to do this regularization, along with adding in more rigor to the process with a test-train split and cross validation.
I experimented with both ridge and LASSO regression and did hyper parameter tuning of the alpha terms which determine how strong the regularization will be. Surprisingly, both models with optimized alphas performed basically exactly the same as the OLS model with an R-squared of 0.92, with ridge being insignificantly better than LASSO. This indicates that regularization did not significantly help the model.
The LASSO coefficients support this finding as well. LASSO typically zeroes out any redundant features, leaving only a few remaining. In contrast, the best LASSO model only zeroed out 1 out of the 38 features. This is a surprising result, indicating that most features contribute to the predictability of the model and thus stronger regularization would only hurt the model’s performance.
Speaking of coefficients, we can determine the importance of each feature by looking at the sign and magnitude of the coefficients. This allows us to provide valuable business insights to our stakeholders, in this case the Center for Medicare and Medicaid Services.
From the top 10 features, I found it interesting that the fourth most important feature was the number of white patients a provider has. This is alarming as the model actually seems to care about race in some meaningful way.
This could possibly be exposing an underlying fault of the system, indicating that the white population is over-represented and thus, makes up a significantly larger percentage of the Medicare cost in comparison to other races. Other research needs to be done to determine the root cause but it is very possible that lack of access for underserved populations may contribute to this.
This is a powerful result and a example of the value that data science has for society. I was amazed to find that not only could I use this algorithm to improve a stakeholder’s bottom line but to also reveal social disparities. This is one of the main reasons I love data science; it can have immensely powerful effects on our society.
Looking at the top most expensive specialties, surgery clearly stands out. And it makes sense; surgery is incredibly expensive. This means that the government would best spend their efforts reducing surgery costs in order to most significantly impact their bottom line.
In terms of medical conditions, largely preventable chronic diseases take the cake. This finding is a double-edged sword and falls in line with what we already know. Sadly, it means that most of these Medicare patients are suffering from diseases that they didn’t ever have to suffer from if they had just had different lifestyle choices. From both a financial and an ethical perspective, this is absolutely terrible.
But on a more positive note, this means that the government can save incredible amounts of money while also reducing immense amounts of suffering by beginning to focus on preventive lifestyle medicine instead of reactive treatments, such as surgery.
Obviously, we didn’t need data science to tell us to eat better and move more. But this further supports what we all know is necessary for the well being of everyone in society.
And in the process, we built a model to accurately predict how expensive a healthcare provider is for the government. Saving money and saving lives, what more could we ask for? | [
{
"code": null,
"e": 349,
"s": 172,
"text": "As Metis Data Science Bootcamp students, we were tasked to build a linear regression model for our first individual project. Simple enough right? Just draw a line through data."
},
{
"code": null,
"e": 362,
"s": 349,
"text": "Not so fast!"
},
{
"code": null,
"e": 803,
"s": 362,
"text": "As a healthcare professional, I was excited to use this algorithm to solve a problem in the medical field. But what I quickly found out was, before any modeling, a successful machine learning project starts with picking the right kind of data. Linear regression works best with continuous numerical data which excludes several sources of publicly available healthcare data. However, it turns out that Medicare payment data is a perfect fit."
},
{
"code": null,
"e": 1406,
"s": 803,
"text": "But why care about Medicare? Medicare is a government-funded health insurance program currently covering 44 million people, or 1 in 8 individuals in the U.S. (1). That carries with it some huge public health and financial implications for the government. As soon as you turn 65, you’re eligible for it with a few exceptions such as younger people with disabilities or those suffering from end stage renal disease. And this population is only getting bigger. In fact, the Census Bureau estimates that by 2030, the elderly population alone will nearly double to 78 million people or 1 in 5 Americans (2)."
},
{
"code": null,
"e": 1802,
"s": 1406,
"text": "On top of this, it seems likely that Medicare is going to be increasingly more important in the coming years due to its prevalence in political discussions around the country. If the United States were to adopt a single-payer system, such as the proposed Medicare-for-All, it would be essential for us to lower costs wherever possible, and the effective usage of data could help to achieve this."
},
{
"code": null,
"e": 2001,
"s": 1802,
"text": "One way to do this would be to look at healthcare provider costs. You can follow along with my code on my GitHub repository; I’ve organized it chronologically with this article for your convenience."
},
{
"code": null,
"e": 2252,
"s": 2001,
"text": "After searching the Center for Medicare and Medicaid Services website, I was able to acquire the most recent provider payment data which had over 1 million rows, each corresponding to a healthcare organization or individual provider, and 70 features."
},
{
"code": null,
"e": 2482,
"s": 2252,
"text": "But as expected, this data was quite a mess. So in order to glean the most reliable insight I could, I decided to narrow down what I was measuring to only individual providers in the U.S, excluding territories and military zones."
},
{
"code": null,
"e": 2772,
"s": 2482,
"text": "I then replaced all missing values in columns with count or percentage data with zeroes. It is likely that if a provider doesn’t have patients with a certain disease, the field is just left blank; this means it should have been relatively safe to impute nulls without losing much fidelity."
},
{
"code": null,
"e": 3238,
"s": 2772,
"text": "There was also some documentation provided for the meaning of each column name. I decided the target variable should be total_medicare_payment_amt, which is the total amount the government paid for all the provider’s services per patient after deductible and coinsurance amounts have been subtracted. Additionally, I removed all columns that were either unnecessary (like provider names) or that would lead to possible data leakage (like other price-based columns)."
},
{
"code": null,
"e": 3326,
"s": 3238,
"text": "Finally I was left with a little over 990,000 clean rows with 38 features. Let’s begin!"
},
{
"code": null,
"e": 3506,
"s": 3326,
"text": "Using the Statsmodels python library, I just threw all my data into the ordinary least squares (OLS) linear regression to see how it would perform initially with no modifications."
},
{
"code": null,
"e": 3857,
"s": 3506,
"text": "As previously mentioned, linear regression tries to find a linear relationship between independent variables and a dependent variable. Above, you can see the simplest univariate form with only one independent variable or feature. It uses the equation y = mx + b to find the best fit with the data; m is the slope coefficient and b is the y intercept."
},
{
"code": null,
"e": 4298,
"s": 3857,
"text": "But obviously with 38 features, this linear regression problem is a lot more complex. In this case, there will be 38 “mx” terms added together, with each m term corresponding to the size and direction of the effect that specific variable is having on the dependent variable. In geometric terms, we will be fitting a 38th dimensional hyperplane to 39th dimensional space (instead of a line). If you find a way to visualize this, let me know!"
},
{
"code": null,
"e": 4400,
"s": 4298,
"text": "Ok, so now we have some intuition for the model, but how do we determine how well the model is doing?"
},
{
"code": null,
"e": 4682,
"s": 4400,
"text": "The metric that is commonly used here is called the coefficient of determination or R-squared. Essentially, it is the percentage of variance of the target variable that is predicted by the features. We want an R-squared close to 1 which indicates that the model is very predictive."
},
{
"code": null,
"e": 5008,
"s": 4682,
"text": "But let’s dive a little deeper into the actual formula of R-squared because it helps us to understand how we are evaluating the model. The most naive method we could use to predict Medicare costs would be to just guess the average cost. That is the green ȳ (called y-bar) in the the diagram above. This will be our baseline."
},
{
"code": null,
"e": 5424,
"s": 5008,
"text": "But we can do a lot better than that by using linear regression or the red ŷ (called y-hat). Now we just find how off these two predictions are from the actual value and divide them by each other (SSE/SST). This will tell us the percentage of variance the model cannot explain. But what we really want to know is what percentage of variance this model does explain. Subtracting that value from 1 will get us there."
},
{
"code": null,
"e": 5489,
"s": 5424,
"text": "1 - (Error Sum of Squares/Total Sum of Squares) or 1 - (SSE/SST)"
},
{
"code": null,
"e": 5656,
"s": 5489,
"text": "And after running the initial model, the R-squared was 0.619. That means that our model only accounts for about 62% of the variation in the data. That’s not too good."
},
{
"code": null,
"e": 5782,
"s": 5656,
"text": "But wait! Linear regression has many assumptions and it is important to check if our data is actually working for this model."
},
{
"code": null,
"e": 5874,
"s": 5782,
"text": "Assumption #1: Is there a linear relationship between the target variable and the features?"
},
{
"code": null,
"e": 6122,
"s": 5874,
"text": "For illustration purposes, if we use the feature of total medicare cost, it’s not entirely clear. To rectify this situation, we could do some feature engineering. One option is to do a logarithmic transformation of both the feature and the target."
},
{
"code": null,
"e": 6349,
"s": 6122,
"text": "Wow! That’s a dramatic improvement. Anyone can draw a line through that! As you can see, it is often the case that we need to transform the data in specific ways to make it conform to the assumptions of the model we are using."
},
{
"code": null,
"e": 6542,
"s": 6349,
"text": "Note: Always remember to undo this transformation afterwards in order to return your value back to the original context. Because after all, what does the logarithm of Medicare costs even mean?"
},
{
"code": null,
"e": 6611,
"s": 6542,
"text": "Assumption #2: Are the target and the features normally distributed?"
},
{
"code": null,
"e": 6879,
"s": 6611,
"text": "In the above figure, the left plot shows the target variable before using a logarithmic transformation; as you can see, it is terribly right skewed. The right plot, on the other hand, shows how applying this transformation results in a remarkably normal distribution."
},
{
"code": null,
"e": 6954,
"s": 6879,
"text": "Assumption #3: Is there little to no multicollinearity among the features?"
},
{
"code": null,
"e": 7286,
"s": 6954,
"text": "Multicollinearity is when the features are highly correlated with each other. Above, we see a heat map where the darker colors indicate strong positive correlations. Ideally, we would see only light colors everywhere else except the diagonal line across the middle, as obviously a variable will be perfectly correlated with itself."
},
{
"code": null,
"e": 7605,
"s": 7286,
"text": "But in reality, we see darker colors popping up all over the place, which indicates we are violating this assumption. This can lead to imprecise regression coefficients or worse, changes in sign for the same features in different samples, which makes it difficult to reliably extract meaning out of those coefficients."
},
{
"code": null,
"e": 7861,
"s": 7605,
"text": "The way to go about solving this is to remove features until there is no longer any collinearity. As will be discussed later, regularization techniques do this for you by zeroing out coefficients of some of the features that are collinear with each other."
},
{
"code": null,
"e": 7922,
"s": 7861,
"text": "Assumption #4: Are the residuals correlated with themselves?"
},
{
"code": null,
"e": 8182,
"s": 7922,
"text": "An autocorrelation happens when the residuals for a specific feature are not independent from each other. This is considered bad because it indicates the model is not extracting all the information possible from the data, and thus, we see it in the residuals."
},
{
"code": null,
"e": 8482,
"s": 8182,
"text": "This can be measured through the Durbin-Watson test. Values near 2 indicate no autocorrelation, while values near 0 or 4 indicate strong autocorrelations. Our initial model has a value of 1.998, indicating that the model is extracting as much information as possible and the assumption has been met."
},
{
"code": null,
"e": 8524,
"s": 8482,
"text": "Assumption #5: Is the data homoskedastic?"
},
{
"code": null,
"e": 8703,
"s": 8524,
"text": "What we want to avoid here is heteroskedasticity, a big word with a simple explanation. This is when the variance of the residuals change across the range of values in a feature."
},
{
"code": null,
"e": 9116,
"s": 8703,
"text": "As you can see in this hypothetical example, it is very clear that the variance gets wider as age increase. This is not good as it means that our model will get worse at making predictions the older someone gets. What we really want is a consistent predictability and variance across the entire range of values, known as homoskedasticity. In other words, the two dotted red lines would be parallel to each other."
},
{
"code": null,
"e": 9425,
"s": 9116,
"text": "Here we see the predicted values versus the residuals for our model on the Medicare data. This doesn’t look good at all. There is a harsh cut off in the negative residuals (due to government cost always being greater than or equal to 0) and the variance is completely inconsistent across the range of values."
},
{
"code": null,
"e": 9578,
"s": 9425,
"text": "But after applying the logarithmic transformation that we did before, the plot looks relatively homoskedastic now and we have met this assumption. Boom!"
},
{
"code": null,
"e": 9712,
"s": 9578,
"text": "So after checking the assumptions of all the features, I decided to apply a log transformation to 3 features and the target variable."
},
{
"code": null,
"e": 10067,
"s": 9712,
"text": "Now, I put this newly transformed data back into the model and after training, it produced an R-squared of 0.92. Fantastic! This is a solid result as the new model can explain 30% more of the variance in the data versus the baseline model. This demonstrates how important it is to transform your data to meet the assumptions of the model you have chosen."
},
{
"code": null,
"e": 10427,
"s": 10067,
"text": "But this was just an OLS model. We can apply the regularization techniques briefly mentioned before which should further strengthen our model. These add an extra term to the cost function, penalizing the model for complexity. This is a good idea because simpler models are typically better than complex ones as they tend to be less susceptible to overfitting."
},
{
"code": null,
"e": 10694,
"s": 10427,
"text": "In other words, complex models tend to fit training data super well but perform poorly on unseen data. I switched over to the scikit-learn library to do this regularization, along with adding in more rigor to the process with a test-train split and cross validation."
},
{
"code": null,
"e": 11105,
"s": 10694,
"text": "I experimented with both ridge and LASSO regression and did hyper parameter tuning of the alpha terms which determine how strong the regularization will be. Surprisingly, both models with optimized alphas performed basically exactly the same as the OLS model with an R-squared of 0.92, with ridge being insignificantly better than LASSO. This indicates that regularization did not significantly help the model."
},
{
"code": null,
"e": 11494,
"s": 11105,
"text": "The LASSO coefficients support this finding as well. LASSO typically zeroes out any redundant features, leaving only a few remaining. In contrast, the best LASSO model only zeroed out 1 out of the 38 features. This is a surprising result, indicating that most features contribute to the predictability of the model and thus stronger regularization would only hurt the model’s performance."
},
{
"code": null,
"e": 11760,
"s": 11494,
"text": "Speaking of coefficients, we can determine the importance of each feature by looking at the sign and magnitude of the coefficients. This allows us to provide valuable business insights to our stakeholders, in this case the Center for Medicare and Medicaid Services."
},
{
"code": null,
"e": 11985,
"s": 11760,
"text": "From the top 10 features, I found it interesting that the fourth most important feature was the number of white patients a provider has. This is alarming as the model actually seems to care about race in some meaningful way."
},
{
"code": null,
"e": 12369,
"s": 11985,
"text": "This could possibly be exposing an underlying fault of the system, indicating that the white population is over-represented and thus, makes up a significantly larger percentage of the Medicare cost in comparison to other races. Other research needs to be done to determine the root cause but it is very possible that lack of access for underserved populations may contribute to this."
},
{
"code": null,
"e": 12705,
"s": 12369,
"text": "This is a powerful result and a example of the value that data science has for society. I was amazed to find that not only could I use this algorithm to improve a stakeholder’s bottom line but to also reveal social disparities. This is one of the main reasons I love data science; it can have immensely powerful effects on our society."
},
{
"code": null,
"e": 12975,
"s": 12705,
"text": "Looking at the top most expensive specialties, surgery clearly stands out. And it makes sense; surgery is incredibly expensive. This means that the government would best spend their efforts reducing surgery costs in order to most significantly impact their bottom line."
},
{
"code": null,
"e": 13393,
"s": 12975,
"text": "In terms of medical conditions, largely preventable chronic diseases take the cake. This finding is a double-edged sword and falls in line with what we already know. Sadly, it means that most of these Medicare patients are suffering from diseases that they didn’t ever have to suffer from if they had just had different lifestyle choices. From both a financial and an ethical perspective, this is absolutely terrible."
},
{
"code": null,
"e": 13643,
"s": 13393,
"text": "But on a more positive note, this means that the government can save incredible amounts of money while also reducing immense amounts of suffering by beginning to focus on preventive lifestyle medicine instead of reactive treatments, such as surgery."
},
{
"code": null,
"e": 13821,
"s": 13643,
"text": "Obviously, we didn’t need data science to tell us to eat better and move more. But this further supports what we all know is necessary for the well being of everyone in society."
}
] |
Introduction to Markov Chain Programming | by Juan Nathaniel | Towards Data Science | Imagine the following scenario: you want to know whether the weather tomorrow is going to be sunny or rainy. Now, you might have a natural intuition based on your experience and historical observation of the weather. If for the past 1 week the weather has been sunny, then you have a 90% certainty that tomorrow will also be sunny. But if for the previous week or so the weather has been rainy, then the probability of tomorrow being sunny does not look too good: only at 50% chance. This scenario can be described as a Markov Chain process.
But what is a Markov Chain, formally? Markov Chain is a mathematical system that describes a collection of transitions from one state to the other according to certain stochastic or probabilistic rules.
Take for example our earlier scenario for predicting the next day’s weather. If today’s weather is sunny, then based on our (reliable) experience, the probability for the weather tomorrow transitioning to rainy is 10% and sunny 90%. On the other hand, if at present the weather is rainy, then the probability for tomorrow remaining rainy is 50% and sunny 50%.
These changes (or the lack thereof) between different states are called transitions while the variable of interest (ie. rainy or sunny) are called states.
For these transitions, however, to be qualified as Markov Chain, they must satisfy the Markov Property. The property states that the probability of transition is entirely dependent only on the current state, and not on the preceding set of sequences. This characteristic allows Markov Chain to be memory-less.
Now that we have covered what is actually Markov Chain, let’s discuss why is it worthwhile to get familiar with. Markov Chain has many applications in the real-world processes, such as in game theory, physics, economics, signal processing, information theory, and many more.
Furthermore, this seemingly simple process serves as the basis for many more complex stochastic simulation methods such as Markov Chain Monte Carlo (MCMC) or Hidden Markov Chain. Also, Markov Chain is a precursor for many of the modern data science techniques, such as being one of the building blocks for Bayesian statistics.
In all, Markov Chain will serve as a good starting point for you to understand more advanced statistical modelling techniques in data science. It is imperative, therefore, to get your hands dirty by understanding the basics of Markov Process through a mathematical understanding and coding its algorithm implementation.
The Markov Chain model represents the probabilities for state transitions as a transition matrix. If the system has N possible states (eg. N=2 for our weather prediction case), then the transition matrix will have a N x N shaped transition matrix. Subsequently, the individual entry for the matrix, N(i, j), will indicate the probability of transition between state i and state j.
For our weather prediction case, the transition matrix, T can be illustrated as:
What will happen if you want to determine the probability over multiple steps, say for the weather to rain over the next M days? You can simply raise the transition probability to the power of M.
Let’s try to code the above example in Python.
Import the necessary libraries
Import the necessary libraries
import numpy as npimport random as rm
2. Define the states and their probabilities (NOTE: ensure that the total probability in each row sums up to 1)
states = ["sunny", rainy"]transitions = [["SS", "SR"],["RS", "RR"]]T = [[0.9, 0.1],[0.5, 0.5]]
3. Lets write the (rather tedious) Markov Chain function to predict the weather for the next n number of days! (NOTE: you should probably look for better Python library that abstracts the implementation of Markov Chain).
4. Run the program, say, for the next 5 days.
future_weathers = weather_forecast(n_days = 5)
We have discussed what is Markov Chain descriptively and formally, and why is it important to learn its basic principle. We have also coded a very basic Markov process from scratch. Now that you are familiar with how a Markov Chain works, you can deep dive into more complex stochastic modelling techniques, such as the Hidden Markov Process or MCMC. Stay tuned for more of these follow-up contents!
Do subscribe to my Email newsletter: https://tinyurl.com/2npw2fnz where I regularly summarize AI research papers in plain English and beautiful visualization. | [
{
"code": null,
"e": 713,
"s": 171,
"text": "Imagine the following scenario: you want to know whether the weather tomorrow is going to be sunny or rainy. Now, you might have a natural intuition based on your experience and historical observation of the weather. If for the past 1 week the weather has been sunny, then you have a 90% certainty that tomorrow will also be sunny. But if for the previous week or so the weather has been rainy, then the probability of tomorrow being sunny does not look too good: only at 50% chance. This scenario can be described as a Markov Chain process."
},
{
"code": null,
"e": 916,
"s": 713,
"text": "But what is a Markov Chain, formally? Markov Chain is a mathematical system that describes a collection of transitions from one state to the other according to certain stochastic or probabilistic rules."
},
{
"code": null,
"e": 1276,
"s": 916,
"text": "Take for example our earlier scenario for predicting the next day’s weather. If today’s weather is sunny, then based on our (reliable) experience, the probability for the weather tomorrow transitioning to rainy is 10% and sunny 90%. On the other hand, if at present the weather is rainy, then the probability for tomorrow remaining rainy is 50% and sunny 50%."
},
{
"code": null,
"e": 1431,
"s": 1276,
"text": "These changes (or the lack thereof) between different states are called transitions while the variable of interest (ie. rainy or sunny) are called states."
},
{
"code": null,
"e": 1741,
"s": 1431,
"text": "For these transitions, however, to be qualified as Markov Chain, they must satisfy the Markov Property. The property states that the probability of transition is entirely dependent only on the current state, and not on the preceding set of sequences. This characteristic allows Markov Chain to be memory-less."
},
{
"code": null,
"e": 2016,
"s": 1741,
"text": "Now that we have covered what is actually Markov Chain, let’s discuss why is it worthwhile to get familiar with. Markov Chain has many applications in the real-world processes, such as in game theory, physics, economics, signal processing, information theory, and many more."
},
{
"code": null,
"e": 2343,
"s": 2016,
"text": "Furthermore, this seemingly simple process serves as the basis for many more complex stochastic simulation methods such as Markov Chain Monte Carlo (MCMC) or Hidden Markov Chain. Also, Markov Chain is a precursor for many of the modern data science techniques, such as being one of the building blocks for Bayesian statistics."
},
{
"code": null,
"e": 2663,
"s": 2343,
"text": "In all, Markov Chain will serve as a good starting point for you to understand more advanced statistical modelling techniques in data science. It is imperative, therefore, to get your hands dirty by understanding the basics of Markov Process through a mathematical understanding and coding its algorithm implementation."
},
{
"code": null,
"e": 3044,
"s": 2663,
"text": "The Markov Chain model represents the probabilities for state transitions as a transition matrix. If the system has N possible states (eg. N=2 for our weather prediction case), then the transition matrix will have a N x N shaped transition matrix. Subsequently, the individual entry for the matrix, N(i, j), will indicate the probability of transition between state i and state j."
},
{
"code": null,
"e": 3125,
"s": 3044,
"text": "For our weather prediction case, the transition matrix, T can be illustrated as:"
},
{
"code": null,
"e": 3321,
"s": 3125,
"text": "What will happen if you want to determine the probability over multiple steps, say for the weather to rain over the next M days? You can simply raise the transition probability to the power of M."
},
{
"code": null,
"e": 3368,
"s": 3321,
"text": "Let’s try to code the above example in Python."
},
{
"code": null,
"e": 3399,
"s": 3368,
"text": "Import the necessary libraries"
},
{
"code": null,
"e": 3430,
"s": 3399,
"text": "Import the necessary libraries"
},
{
"code": null,
"e": 3468,
"s": 3430,
"text": "import numpy as npimport random as rm"
},
{
"code": null,
"e": 3580,
"s": 3468,
"text": "2. Define the states and their probabilities (NOTE: ensure that the total probability in each row sums up to 1)"
},
{
"code": null,
"e": 3675,
"s": 3580,
"text": "states = [\"sunny\", rainy\"]transitions = [[\"SS\", \"SR\"],[\"RS\", \"RR\"]]T = [[0.9, 0.1],[0.5, 0.5]]"
},
{
"code": null,
"e": 3896,
"s": 3675,
"text": "3. Lets write the (rather tedious) Markov Chain function to predict the weather for the next n number of days! (NOTE: you should probably look for better Python library that abstracts the implementation of Markov Chain)."
},
{
"code": null,
"e": 3942,
"s": 3896,
"text": "4. Run the program, say, for the next 5 days."
},
{
"code": null,
"e": 3989,
"s": 3942,
"text": "future_weathers = weather_forecast(n_days = 5)"
},
{
"code": null,
"e": 4389,
"s": 3989,
"text": "We have discussed what is Markov Chain descriptively and formally, and why is it important to learn its basic principle. We have also coded a very basic Markov process from scratch. Now that you are familiar with how a Markov Chain works, you can deep dive into more complex stochastic modelling techniques, such as the Hidden Markov Process or MCMC. Stay tuned for more of these follow-up contents!"
}
] |
How to set image to center of an responsive navbar ? - GeeksforGeeks | 21 Dec, 2020
In order to make a website responsive, the clever to-do is by using Bootstrap. By using Bootstrap, we can make our website look good and responsive.
There are two ways to set an image or logo in the center of a responsive navbar. They are:
Using CSS
Using Bootstrap
Now let’s understand each of them.
Using CSS: In this method, we use our own styling to center the image in the navbar. We are going to embed CSS code into HTML code. Here we have given flex property to our brand (image or logo), the width of 100%, and justify-content as the center. These properties set our logo in the center of the navbar.
Example:
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <style type="text/css"> .navbar-brand { display: flex; width: 100%; justify-content: center; } </style></head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <!-- Brand and toggle get grouped for better mobile display --> <a class="navbar-brand" href="#"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200921155935/gfglogo-300x39.png" width="300" height="50" alt="" /> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target= "#bs-example-navbar-collapse-1" aria-controls="bs-example-navbar-collapse-1" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <!-- Anything inside of collapse navbar-collapse goes into the "hamburger" --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="#"> Home <span class="sr-only"> (current) </span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Item1 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Item2 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Item3</a> </li> </ul> </div> </nav> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity= "sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.1/web-animations.min.js"> </script></body> </html>
Output:
We can see that the GeeksforGeeks logo is aligned in the center of the navbar while all other navbar items are in the right.
Using Bootstrap: In this method, we can save ourselves from writing extra CSS code. We just need to add a div tag with the class as a container and put the navbar-brand(image or logo) inside this div. After that, we just need to add the class mx-auto to the navbar-brand class. The mx-auto class is a Bootstrap class just adjusts the margin on both the left and right sides to align the content in the center.
Example:
<!DOCTYPE html><html> <head> <title>Navbar</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" type="text/css" href="gfg.css" /></head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <!-- Brand and toggle get grouped for better mobile display --> <div class="container"> <a class="navbar-brand mx-auto" href="#"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200921155935/gfglogo-300x39.png" width="200" height="50" alt="" /> </a> </div> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target ="#bs-example-navbar-collapse-1" aria-controls="bs-example-navbar-collapse-1" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <!-- Anything inside of collapse navbar-collapse goes into the "hamburger" --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="#"> Home<span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">Item1</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Item2</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Item3</a> </li> </ul> </div> </nav> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.1/web-animations.min.js"> </script></body> </html>
Output:
We can see that the GeeksforGeeks logo is aligned to the center of the navbar while all other navbar items are in the right. In these two ways, we can image in the center of a responsive navbar.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Bootstrap-4
Bootstrap-Misc
HTML-Misc
Picked
Technical Scripter 2020
Bootstrap
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Difference between Bootstrap 4 and Bootstrap 5
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 ? | [
{
"code": null,
"e": 24865,
"s": 24837,
"text": "\n21 Dec, 2020"
},
{
"code": null,
"e": 25014,
"s": 24865,
"text": "In order to make a website responsive, the clever to-do is by using Bootstrap. By using Bootstrap, we can make our website look good and responsive."
},
{
"code": null,
"e": 25106,
"s": 25014,
"text": "There are two ways to set an image or logo in the center of a responsive navbar. They are: "
},
{
"code": null,
"e": 25116,
"s": 25106,
"text": "Using CSS"
},
{
"code": null,
"e": 25132,
"s": 25116,
"text": "Using Bootstrap"
},
{
"code": null,
"e": 25167,
"s": 25132,
"text": "Now let’s understand each of them."
},
{
"code": null,
"e": 25475,
"s": 25167,
"text": "Using CSS: In this method, we use our own styling to center the image in the navbar. We are going to embed CSS code into HTML code. Here we have given flex property to our brand (image or logo), the width of 100%, and justify-content as the center. These properties set our logo in the center of the navbar."
},
{
"code": null,
"e": 25484,
"s": 25475,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\" integrity=\"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh\" crossorigin=\"anonymous\" /> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> <style type=\"text/css\"> .navbar-brand { display: flex; width: 100%; justify-content: center; } </style></head> <body> <nav class=\"navbar navbar-expand-lg navbar-dark bg-primary\"> <!-- Brand and toggle get grouped for better mobile display --> <a class=\"navbar-brand\" href=\"#\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200921155935/gfglogo-300x39.png\" width=\"300\" height=\"50\" alt=\"\" /> </a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target= \"#bs-example-navbar-collapse-1\" aria-controls=\"bs-example-navbar-collapse-1\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <!-- Anything inside of collapse navbar-collapse goes into the \"hamburger\" --> <div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\"> <ul class=\"navbar-nav ml-auto\"> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Home <span class=\"sr-only\"> (current) </span> </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Item1 </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Item2 </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Item3</a> </li> </ul> </div> </nav> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity= \"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.1/web-animations.min.js\"> </script></body> </html>",
"e": 28342,
"s": 25484,
"text": null
},
{
"code": null,
"e": 28350,
"s": 28342,
"text": "Output:"
},
{
"code": null,
"e": 28475,
"s": 28350,
"text": "We can see that the GeeksforGeeks logo is aligned in the center of the navbar while all other navbar items are in the right."
},
{
"code": null,
"e": 28885,
"s": 28475,
"text": "Using Bootstrap: In this method, we can save ourselves from writing extra CSS code. We just need to add a div tag with the class as a container and put the navbar-brand(image or logo) inside this div. After that, we just need to add the class mx-auto to the navbar-brand class. The mx-auto class is a Bootstrap class just adjusts the margin on both the left and right sides to align the content in the center."
},
{
"code": null,
"e": 28894,
"s": 28885,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Navbar</title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\" integrity=\"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh\" crossorigin=\"anonymous\" /> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"gfg.css\" /></head> <body> <nav class=\"navbar navbar-expand-lg navbar-dark bg-primary\"> <!-- Brand and toggle get grouped for better mobile display --> <div class=\"container\"> <a class=\"navbar-brand mx-auto\" href=\"#\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200921155935/gfglogo-300x39.png\" width=\"200\" height=\"50\" alt=\"\" /> </a> </div> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target =\"#bs-example-navbar-collapse-1\" aria-controls=\"bs-example-navbar-collapse-1\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <!-- Anything inside of collapse navbar-collapse goes into the \"hamburger\" --> <div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\"> <ul class=\"navbar-nav ml-auto\"> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Home<span class=\"sr-only\">(current)</span> </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">Item1</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">Item2</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">Item3</a> </li> </ul> </div> </nav> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity=\"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.1/web-animations.min.js\"> </script></body> </html>",
"e": 31591,
"s": 28894,
"text": null
},
{
"code": null,
"e": 31599,
"s": 31591,
"text": "Output:"
},
{
"code": null,
"e": 31794,
"s": 31599,
"text": "We can see that the GeeksforGeeks logo is aligned to the center of the navbar while all other navbar items are in the right. In these two ways, we can image in the center of a responsive navbar."
},
{
"code": null,
"e": 31931,
"s": 31794,
"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": 31943,
"s": 31931,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 31958,
"s": 31943,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 31968,
"s": 31958,
"text": "HTML-Misc"
},
{
"code": null,
"e": 31975,
"s": 31968,
"text": "Picked"
},
{
"code": null,
"e": 31999,
"s": 31975,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 32009,
"s": 31999,
"text": "Bootstrap"
},
{
"code": null,
"e": 32014,
"s": 32009,
"text": "HTML"
},
{
"code": null,
"e": 32033,
"s": 32014,
"text": "Technical Scripter"
},
{
"code": null,
"e": 32050,
"s": 32033,
"text": "Web Technologies"
},
{
"code": null,
"e": 32055,
"s": 32050,
"text": "HTML"
},
{
"code": null,
"e": 32153,
"s": 32055,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32162,
"s": 32153,
"text": "Comments"
},
{
"code": null,
"e": 32175,
"s": 32162,
"text": "Old Comments"
},
{
"code": null,
"e": 32216,
"s": 32175,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 32257,
"s": 32216,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 32320,
"s": 32257,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 32353,
"s": 32320,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 32400,
"s": 32353,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 32462,
"s": 32400,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32512,
"s": 32462,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 32572,
"s": 32512,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 32620,
"s": 32572,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Python Regex: re.search() VS re.findall() - GeeksforGeeks | 11 Jan, 2022
Prerequisite: Regular Expression with Examples | Python
A Regular expression (sometimes called a Rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace”-like operations. Regular expressions are a generalized way to match patterns with sequences of characters.
Module Regular Expressions (RE) specifies a set of strings (pattern) that matches it. To understand the RE analogy, MetaCharacters are useful, important and will be used in functions of module re.
There are a total of 14 metacharacters and will be discussed as they follow into functions:
\ Used to drop the special meaning of character
following it (discussed below)
[] Represent a character class
^ Matches the beginning
$ Matches the end
. Matches any character except newline
? Matches zero or one occurrence.
| Means OR (Matches with any of the characters
separated by it.
* Any number of occurrences (including 0 occurrences)
+ One or more occurrences
{} Indicate number of occurrences of a preceding RE
to match.
() Enclose a group of REs
re.search() method either returns None (if the pattern doesn’t match), or a re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data.
Example:
Python3
# A Python program to demonstrate working of re.match(). import re # Lets use a regular expression to match a date string # in the form of Month name followed by day number regex = r"([a-zA-Z]+) (\d+)" match = re.search(regex, "I was born on June 24") if match != None: # We reach here when the expression "([a-zA-Z]+) (\d+)" # matches the date string. # This will print [14, 21), since it matches at index 14 # and ends at 21. print("Match at index % s, % s" % (match.start(), match.end())) # We us group() method to get all the matches and # captured groups. The groups contain the matched values. # In particular: # match.group(0) always returns the fully matched string # match.group(1) match.group(2), ... return the capture # groups in order from left to right in the input string # match.group() is equivalent to match.group(0) # So this will print "June 24" print("Full match: % s" % (match.group(0))) # So this will print "June" print("Month: % s" % (match.group(1))) # So this will print "24" print("Day: % s" % (match.group(2))) else: print("The regex pattern does not match.")
Output:
Match at index 14, 21
Full match: June 24
Month: June
Day: 24
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.
Example:
Python3
# A Python program to demonstrate working of # findall() import re # A sample text string where regular expression # is searched. string = """Hello my Number is 123456789 and my friend's number is 987654321""" # A sample regular expression to find digits. regex = '\d+' match = re.findall(regex, string) print(match)
Output:
['123456789', '987654321']
rkbhola5
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace() | [
{
"code": null,
"e": 41161,
"s": 41133,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 41217,
"s": 41161,
"text": "Prerequisite: Regular Expression with Examples | Python"
},
{
"code": null,
"e": 41537,
"s": 41217,
"text": "A Regular expression (sometimes called a Rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace”-like operations. Regular expressions are a generalized way to match patterns with sequences of characters."
},
{
"code": null,
"e": 41734,
"s": 41537,
"text": "Module Regular Expressions (RE) specifies a set of strings (pattern) that matches it. To understand the RE analogy, MetaCharacters are useful, important and will be used in functions of module re."
},
{
"code": null,
"e": 41826,
"s": 41734,
"text": "There are a total of 14 metacharacters and will be discussed as they follow into functions:"
},
{
"code": null,
"e": 42316,
"s": 41826,
"text": "\\ Used to drop the special meaning of character\n following it (discussed below)\n[] Represent a character class\n^ Matches the beginning\n$ Matches the end\n. Matches any character except newline\n? Matches zero or one occurrence.\n| Means OR (Matches with any of the characters\n separated by it.\n* Any number of occurrences (including 0 occurrences)\n+ One or more occurrences\n{} Indicate number of occurrences of a preceding RE \n to match.\n() Enclose a group of REs\n"
},
{
"code": null,
"e": 42596,
"s": 42316,
"text": "re.search() method either returns None (if the pattern doesn’t match), or a re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data."
},
{
"code": null,
"e": 42605,
"s": 42596,
"text": "Example:"
},
{
"code": null,
"e": 42613,
"s": 42605,
"text": "Python3"
},
{
"code": "# A Python program to demonstrate working of re.match(). import re # Lets use a regular expression to match a date string # in the form of Month name followed by day number regex = r\"([a-zA-Z]+) (\\d+)\" match = re.search(regex, \"I was born on June 24\") if match != None: # We reach here when the expression \"([a-zA-Z]+) (\\d+)\" # matches the date string. # This will print [14, 21), since it matches at index 14 # and ends at 21. print(\"Match at index % s, % s\" % (match.start(), match.end())) # We us group() method to get all the matches and # captured groups. The groups contain the matched values. # In particular: # match.group(0) always returns the fully matched string # match.group(1) match.group(2), ... return the capture # groups in order from left to right in the input string # match.group() is equivalent to match.group(0) # So this will print \"June 24\" print(\"Full match: % s\" % (match.group(0))) # So this will print \"June\" print(\"Month: % s\" % (match.group(1))) # So this will print \"24\" print(\"Day: % s\" % (match.group(2))) else: print(\"The regex pattern does not match.\")",
"e": 43814,
"s": 42613,
"text": null
},
{
"code": null,
"e": 43822,
"s": 43814,
"text": "Output:"
},
{
"code": null,
"e": 43885,
"s": 43822,
"text": "Match at index 14, 21\nFull match: June 24\nMonth: June\nDay: 24\n"
},
{
"code": null,
"e": 44046,
"s": 43885,
"text": "Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found."
},
{
"code": null,
"e": 44055,
"s": 44046,
"text": "Example:"
},
{
"code": null,
"e": 44063,
"s": 44055,
"text": "Python3"
},
{
"code": "# A Python program to demonstrate working of # findall() import re # A sample text string where regular expression # is searched. string = \"\"\"Hello my Number is 123456789 and my friend's number is 987654321\"\"\" # A sample regular expression to find digits. regex = '\\d+' match = re.findall(regex, string) print(match) ",
"e": 44418,
"s": 44063,
"text": null
},
{
"code": null,
"e": 44426,
"s": 44418,
"text": "Output:"
},
{
"code": null,
"e": 44454,
"s": 44426,
"text": "['123456789', '987654321']\n"
},
{
"code": null,
"e": 44463,
"s": 44454,
"text": "rkbhola5"
},
{
"code": null,
"e": 44476,
"s": 44463,
"text": "python-regex"
},
{
"code": null,
"e": 44483,
"s": 44476,
"text": "Python"
},
{
"code": null,
"e": 44581,
"s": 44483,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44590,
"s": 44581,
"text": "Comments"
},
{
"code": null,
"e": 44603,
"s": 44590,
"text": "Old Comments"
},
{
"code": null,
"e": 44631,
"s": 44603,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 44681,
"s": 44631,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 44703,
"s": 44681,
"text": "Python map() function"
},
{
"code": null,
"e": 44747,
"s": 44703,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 44782,
"s": 44747,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 44804,
"s": 44782,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 44836,
"s": 44804,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 44866,
"s": 44836,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 44908,
"s": 44866,
"text": "Different ways to create Pandas Dataframe"
}
] |
reflect.Tag.Get() Function in Golang with Examples | 28 Apr, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Tag.Get() Function in Golang is used to find the value associated with key in the tag string, an empty string is returned if there is no such key in the tag. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (tag StructTag) Get(key string) string
Parameters: This function takes one parameters of string type, i.e. key.
Return Value: This function returns the value associated with key in the tag string.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.Tag.Get() Function package main import ( "fmt" "reflect") type Employee struct { ID string `auto_increment:"true" increment:"1"` Name string `varchar: "255"` Surname string `"varchar: "255"`} // Main functionfunc main() { e := Employee{} // c variable represents table columns c := reflect.TypeOf(e).Field(0).Tag fmt.Printf("%s\n\n", c) // use of Get method g := c.Get("increment") fmt.Printf("Get method: %s\n", g)}
Output:
auto_increment:"true" increment:"1"
Get method: 1
Example 2:
// Golang program to illustrate// reflect.Tag.Get() Function package main import ( "fmt" "reflect") // Main function func main() { type tag struct { val string `Value_1:"GeeksforGeeks" Value_2:"Best Platform :"` } src := tag {} st := reflect.TypeOf(src) field := st.Field(0) // use of Get method fmt.Println(field.Tag.Get("Value_2"), field.Tag.Get("Value_1")) }
Output:
Best Platform : GeeksforGeeks
Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to convert a string in lower case in Golang? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Apr, 2020"
},
{
"code": null,
"e": 455,
"s": 28,
"text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Tag.Get() Function in Golang is used to find the value associated with key in the tag string, an empty string is returned if there is no such key in the tag. To access this function, one needs to imports the reflect package in the program."
},
{
"code": null,
"e": 463,
"s": 455,
"text": "Syntax:"
},
{
"code": null,
"e": 508,
"s": 463,
"text": "func (tag StructTag) Get(key string) string\n"
},
{
"code": null,
"e": 581,
"s": 508,
"text": "Parameters: This function takes one parameters of string type, i.e. key."
},
{
"code": null,
"e": 666,
"s": 581,
"text": "Return Value: This function returns the value associated with key in the tag string."
},
{
"code": null,
"e": 731,
"s": 666,
"text": "Below examples illustrate the use of the above method in Golang:"
},
{
"code": null,
"e": 742,
"s": 731,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate// reflect.Tag.Get() Function package main import ( \"fmt\" \"reflect\") type Employee struct { ID string `auto_increment:\"true\" increment:\"1\"` Name string `varchar: \"255\"` Surname string `\"varchar: \"255\"`} // Main functionfunc main() { e := Employee{} // c variable represents table columns c := reflect.TypeOf(e).Field(0).Tag fmt.Printf(\"%s\\n\\n\", c) // use of Get method g := c.Get(\"increment\") fmt.Printf(\"Get method: %s\\n\", g)}",
"e": 1251,
"s": 742,
"text": null
},
{
"code": null,
"e": 1259,
"s": 1251,
"text": "Output:"
},
{
"code": null,
"e": 1311,
"s": 1259,
"text": "auto_increment:\"true\" increment:\"1\"\n\nGet method: 1\n"
},
{
"code": null,
"e": 1322,
"s": 1311,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate// reflect.Tag.Get() Function package main import ( \"fmt\" \"reflect\") // Main function func main() { type tag struct { val string `Value_1:\"GeeksforGeeks\" Value_2:\"Best Platform :\"` } src := tag {} st := reflect.TypeOf(src) field := st.Field(0) // use of Get method fmt.Println(field.Tag.Get(\"Value_2\"), field.Tag.Get(\"Value_1\")) }",
"e": 1731,
"s": 1322,
"text": null
},
{
"code": null,
"e": 1739,
"s": 1731,
"text": "Output:"
},
{
"code": null,
"e": 1770,
"s": 1739,
"text": "Best Platform : GeeksforGeeks\n"
},
{
"code": null,
"e": 1785,
"s": 1770,
"text": "Golang-reflect"
},
{
"code": null,
"e": 1797,
"s": 1785,
"text": "Go Language"
},
{
"code": null,
"e": 1895,
"s": 1797,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1946,
"s": 1895,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 1993,
"s": 1946,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 2006,
"s": 1993,
"text": "Arrays in Go"
},
{
"code": null,
"e": 2018,
"s": 2006,
"text": "Golang Maps"
},
{
"code": null,
"e": 2051,
"s": 2018,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 2072,
"s": 2051,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 2089,
"s": 2072,
"text": "Slices in Golang"
},
{
"code": null,
"e": 2143,
"s": 2089,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 2172,
"s": 2143,
"text": "How to Parse JSON in Golang?"
}
] |
Design a typing speed test game using JavaScript | 08 Oct, 2021
A typing test is designed to find how fast one types in a given amount of time. We will be designing a typing game using JavaScript that presents a simple typing challenge and finds the performance of typing by calculating the Characters Per Minute (CPM), Words Per Minute (WPM) and the accuracy of the typed characters.The game shows a series of quotes that have to be typed in a specified time limit, as fast as possible. A higher typing speed would show a higher WPM value. Incorrectly typed characters would be marked accordingly during typing.We will create the HTML layout first, style it using CSS and then write the logic in JavaScript. The HTML Layout: The HTML layout defines the element structure that would be shown on the page. This includes:
Header Portion: This section shows the statistics of the current typing session. This includes the display of the time left, number of errors, accuracy, WPM and CPM.
Quote Section: This section shows the current text that has to be typed in the input area.
Input Area: This section contains the input area where the text has to be typed.
Restart Button: This is the restart button which would be shown once the time runs out and the game finishes.
Code:
html
<html lang="en"><head> <title>Simple Speed Typer</title> <!-- link the CSS file here --> <link rel="stylesheet" href="style.css"></head><body> <div class="container"> <div class="heading"> Simple Speed Typing </div> <div class="header"> <div class="wpm"> <div class="header_text">WPM</div> <div class="curr_wpm">100</div> </div> <div class="cpm"> <div class="header_text">CPM</div> <div class="curr_cpm">100</div> </div> <div class="errors"> <div class="header_text">Errors</div> <div class="curr_errors">0</div> </div> <div class="timer"> <div class="header_text">Time</div> <div class="curr_time">60s</div> </div> <div class="accuracy"> <div class="header_text">% Accuracy</div> <div class="curr_accuracy">100</div> </div> </div> <div class="quote"> Click on the area below to start the game. </div> <textarea class="input_area" placeholder="start typing here..." oninput="processCurrentText()" onfocus="startGame()"> </textarea> <button class="restart_btn" onclick="resetValues()"> Restart </button> </div> <!-- link the JavaScript file here --> <script src="game.js"> </script></body></html>
Note: Each of the portions is filled with dummy data to make styling easier. The HTML code of the above is as follows.The CSS Styling: CSS is used to style the different portions and make it more visually appealing.
The header portion is displayed using the flex layout.
Adequate padding and margin are given to each element.
The text size of each element is such that it is easily readable by the user when playing the game.
Two additional classes are defined to denote the letters that are typed correctly or incorrectly. These classes would be dynamically added or removed when required.
Code:
html
body { background-color: #fe9801; color: black; text-align: center;} .container { display: flex; flex-direction: column; align-items: center;} .heading { margin-bottom: 20px; font-size: 3rem; color: black;} .header { display: flex; align-items: center;} .timer, .errors, .accuracy,.cpm, .wpm { background-color: #ccda46; height: 60px; width: 70px; margin: 8px; padding: 12px; border-radius: 20%; box-shadow: black 5px 8px 5px;} .cpm, .wpm { display: none;} .header_text { text-transform: uppercase; font-size: 0.6rem; font-weight: 600;} .curr_time, .curr_errors,.curr_accuracy, .curr_cpm,.curr_wpm { font-size: 2.75rem;} .quote { background-color: #ccda46; font-size: 1.5rem; margin: 10px; padding: 25px; box-shadow: black 5px 8px 5px;} .input_area { background-color: #f5f5c6; height: 80px; width: 40%; font-size: 1.5rem; font-weight: 600; margin: 15px; padding: 20px; border: 0px; box-shadow: black 5px 8px 5px;} .restart_btn { display: none; background-color: #326765; font-size: 1.5rem; padding: 10px; border: 0px; box-shadow: black 5px 8px 5px;} .incorrect_char { color: red; text-decoration: underline;} .correct_char { color: darkgreen;}
The result of the HTML layout and CSS styling would look like this:
Main Logic of the game: The main logic of the game is defined in a JavaScript file. There are several functions that work together to run the game.Step 1: Selecting all the elements and defining variablesThe required elements in the HTML layout are first selected using the querySelector() method. They are assigned variable names so that they could be easily accessed and modified. Other variables that would be accessed throughout the program are also defined in the beginning.
javascript
// define the time limitlet TIME_LIMIT = 60; // define quotes to be usedlet quotes_array = [ "Push yourself, because no one else is going to do it for you.", "Failure is the condiment that gives success its flavor.", "Wake up with determination. Go to bed with satisfaction.", "It's going to be hard, but hard does not mean impossible.", "Learning never exhausts the mind.", "The only way to do great work is to love what you do."]; // selecting required elementslet timer_text = document.querySelector(".curr_time");let accuracy_text = document.querySelector(".curr_accuracy");let error_text = document.querySelector(".curr_errors");let cpm_text = document.querySelector(".curr_cpm");let wpm_text = document.querySelector(".curr_wpm");let quote_text = document.querySelector(".quote");let input_area = document.querySelector(".input_area");let restart_btn = document.querySelector(".restart_btn");let cpm_group = document.querySelector(".cpm");let wpm_group = document.querySelector(".wpm");let error_group = document.querySelector(".errors");let accuracy_group = document.querySelector(".accuracy"); let timeLeft = TIME_LIMIT;let timeElapsed = 0;let total_errors = 0;let errors = 0;let accuracy = 0;let characterTyped = 0;let current_quote = "";let quoteNo = 0;let timer = null;
Step 2: Preparing the text to be displayedA function updateQuote() is defined which handles the following things:
Getting the text Quotes have been used as the text that has to be typed to play the game. Each quote is taken one by one from a predefined array. A variable keeps track of the current quote index and increments it whenever a new one is requested.
Splitting the characters into elements Each of the characters in the text is separated into a series of <span> elements. This makes it possible to individually change the color of each character depending upon if it has been correctly typed by the user. These elements are appended to a variable quote_text.
javascript
function updateQuote() { quote_text.textContent = null; current_quote = quotes_array[quoteNo]; // separate each character and make an element // out of each of them to individually style them current_quote.split('').forEach(char => { const charSpan = document.createElement('span') charSpan.innerText = char quote_text.appendChild(charSpan) }) // roll over to the first quote if (quoteNo < quotes_array.length - 1) quoteNo++; else quoteNo = 0;}
Step 3: Getting the currently typed text by the userA function processCurrentText() is defined which will be invoked whenever the user types or changes anything in the input box. It is hence used with the oninput event handler of the input box. This function handles the following things:
Getting the current value of the input box The value property of the input area is used to get the current text typed by the user. This is split into an array of characters to compare with the quote text. This is stored in curr_input_array.
Coloring the characters of the quote text The characters of the displayed quote are colored ‘red’ or ‘green’ depending on whether it has been typed correctly. This is done by selecting the span elements of the quote we have created earlier and looping through them. The element has then applied the classes created above depending on if it matches the typed text.
Calculating the errors and accuracy Every time the user makes a mistake during typing, the errors variable is incremented. This is used to calculate the accuracy value by dividing the number of correctly typed characters with the total number of characters typed by the user.
Moving to next quote When the length of the input text matches the quote text length, the updateQuote() function is called which changes the quote and clears the input area. The number of total errors is also updated to be used for the next quote.
javascript
function processCurrentText() { // get current input text and split it curr_input = input_area.value; curr_input_array = curr_input.split(''); // increment total characters typed characterTyped++; errors = 0; quoteSpanArray = quote_text.querySelectorAll('span'); quoteSpanArray.forEach((char, index) => { let typedChar = curr_input_array[index] // character not currently typed if (typedChar == null) { char.classList.remove('correct_char'); char.classList.remove('incorrect_char'); // correct character } else if (typedChar === char.innerText) { char.classList.add('correct_char'); char.classList.remove('incorrect_char'); // incorrect character } else { char.classList.add('incorrect_char'); char.classList.remove('correct_char'); // increment number of errors errors++; } }); // display the number of errors error_text.textContent = total_errors + errors; // update accuracy text let correctCharacters = (characterTyped - (total_errors + errors)); let accuracyVal = ((correctCharacters / characterTyped) * 100); accuracy_text.textContent = Math.round(accuracyVal); // if current text is completely typed // irrespective of errors if (curr_input.length == current_quote.length) { updateQuote(); // update total errors total_errors += errors; // clear the input area input_area.value = ""; }}
Coloring of the characters based its correctness
Step 4: Starting a new gameA function startGame() is defined which will be invoked when the user focuses on the input box. It is hence used with the onfocus event handler of the input box. This function handles the following things:
Reset all values All the values are reset to their default ones before the starting of a new game. We create a different function named resetValues() which handles this.
Update the quote text A new quote text is made ready and displayed by calling the updateQuote() function.
Creating a new timer A timer keeps track of the number of seconds left and displays it to the user. It is created using the setInterval() method which repeatedly calls the updateTimer() function defined below. Before creating a new timer, the previous timer instance is cleared using clearInterval().
javascript
function startGame() { resetValues(); updateQuote(); // clear old and start a new timer clearInterval(timer); timer = setInterval(updateTimer, 1000);} function resetValues() { timeLeft = TIME_LIMIT; timeElapsed = 0; errors = 0; total_errors = 0; accuracy = 0; characterTyped = 0; quoteNo = 0; input_area.disabled = false; input_area.value = ""; quote_text.textContent = 'Click on the area below to start the game.'; accuracy_text.textContent = 100; timer_text.textContent = timeLeft + 's'; error_text.textContent = 0; restart_btn.style.display = "none"; cpm_group.style.display = "none"; wpm_group.style.display = "none";}
Step 5: Updating the timerA function updateTimer() is defined which will be invoked every second to keep track fo the time. This function handles the following things:
Update the time values All the variables that keep track of the time are updated. The timeLeft value is decremented, the timeElapsed value is incremented, and the timer text is updated to the current time left.
Finishing the game This portion is triggered when the time limit is reached. It calls the finishGame() function defined below which finishes the game.
javascript
function updateTimer() { if (timeLeft > 0) { // decrease the current time left timeLeft--; // increase the time elapsed timeElapsed++; // update the timer text timer_text.textContent = timeLeft + "s"; } else { // finish the game finishGame(); }}
Step 6: Finishing the gameA function finishGame() is defined which will be invoked when the game has to be finished. This function handles the following things:
Deleting the timer The timer instance created before is removed.
Displaying the restart game text and button The quoted text displayed to the user is changed to one that indicates that the game is over. The ‘Restart’ button is also displayed by setting the display property to ‘block’.
Calculating the CPM and WPM of the current session The Characters Per Minute (CPM) is calculated by dividing the total number of characters typed with the time elapsed and then multiplying the result with 60. It is rounded off to prevent decimal points.The Words Per Minute (WPM) is calculated by dividing the CPM by 5 and then multiplying the result with 60. The 5 denotes the average number of characters per word. It is rounded off to prevent decimal points.
The Characters Per Minute (CPM) is calculated by dividing the total number of characters typed with the time elapsed and then multiplying the result with 60. It is rounded off to prevent decimal points.The Words Per Minute (WPM) is calculated by dividing the CPM by 5 and then multiplying the result with 60. The 5 denotes the average number of characters per word. It is rounded off to prevent decimal points.
The Characters Per Minute (CPM) is calculated by dividing the total number of characters typed with the time elapsed and then multiplying the result with 60. It is rounded off to prevent decimal points.
The Words Per Minute (WPM) is calculated by dividing the CPM by 5 and then multiplying the result with 60. The 5 denotes the average number of characters per word. It is rounded off to prevent decimal points.
javascript
function finishGame() { // stop the timer clearInterval(timer); // disable the input area input_area.disabled = true; // show finishing text quote_text.textContent = "Click on restart to start a new game."; // display restart button restart_btn.style.display = "block"; // calculate cpm and wpm cpm = Math.round(((characterTyped / timeElapsed) * 60)); wpm = Math.round((((characterTyped / 5) / timeElapsed) * 60)); // update cpm and wpm text cpm_text.textContent = cpm; wpm_text.textContent = wpm; // display the cpm and wpm cpm_group.style.display = "block"; wpm_group.style.display = "block";}
Final DemonstrationThe game is now ready to be played in any browser.
Source Code: https://github.com/sayantanm19/js-simple-typing-game
kashishsoda
JavaScript-Misc
Technical Scripter 2019
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 809,
"s": 52,
"text": "A typing test is designed to find how fast one types in a given amount of time. We will be designing a typing game using JavaScript that presents a simple typing challenge and finds the performance of typing by calculating the Characters Per Minute (CPM), Words Per Minute (WPM) and the accuracy of the typed characters.The game shows a series of quotes that have to be typed in a specified time limit, as fast as possible. A higher typing speed would show a higher WPM value. Incorrectly typed characters would be marked accordingly during typing.We will create the HTML layout first, style it using CSS and then write the logic in JavaScript. The HTML Layout: The HTML layout defines the element structure that would be shown on the page. This includes: "
},
{
"code": null,
"e": 975,
"s": 809,
"text": "Header Portion: This section shows the statistics of the current typing session. This includes the display of the time left, number of errors, accuracy, WPM and CPM."
},
{
"code": null,
"e": 1066,
"s": 975,
"text": "Quote Section: This section shows the current text that has to be typed in the input area."
},
{
"code": null,
"e": 1147,
"s": 1066,
"text": "Input Area: This section contains the input area where the text has to be typed."
},
{
"code": null,
"e": 1257,
"s": 1147,
"text": "Restart Button: This is the restart button which would be shown once the time runs out and the game finishes."
},
{
"code": null,
"e": 1265,
"s": 1257,
"text": "Code: "
},
{
"code": null,
"e": 1270,
"s": 1265,
"text": "html"
},
{
"code": "<html lang=\"en\"><head> <title>Simple Speed Typer</title> <!-- link the CSS file here --> <link rel=\"stylesheet\" href=\"style.css\"></head><body> <div class=\"container\"> <div class=\"heading\"> Simple Speed Typing </div> <div class=\"header\"> <div class=\"wpm\"> <div class=\"header_text\">WPM</div> <div class=\"curr_wpm\">100</div> </div> <div class=\"cpm\"> <div class=\"header_text\">CPM</div> <div class=\"curr_cpm\">100</div> </div> <div class=\"errors\"> <div class=\"header_text\">Errors</div> <div class=\"curr_errors\">0</div> </div> <div class=\"timer\"> <div class=\"header_text\">Time</div> <div class=\"curr_time\">60s</div> </div> <div class=\"accuracy\"> <div class=\"header_text\">% Accuracy</div> <div class=\"curr_accuracy\">100</div> </div> </div> <div class=\"quote\"> Click on the area below to start the game. </div> <textarea class=\"input_area\" placeholder=\"start typing here...\" oninput=\"processCurrentText()\" onfocus=\"startGame()\"> </textarea> <button class=\"restart_btn\" onclick=\"resetValues()\"> Restart </button> </div> <!-- link the JavaScript file here --> <script src=\"game.js\"> </script></body></html>",
"e": 2568,
"s": 1270,
"text": null
},
{
"code": null,
"e": 2785,
"s": 2568,
"text": "Note: Each of the portions is filled with dummy data to make styling easier. The HTML code of the above is as follows.The CSS Styling: CSS is used to style the different portions and make it more visually appealing. "
},
{
"code": null,
"e": 2840,
"s": 2785,
"text": "The header portion is displayed using the flex layout."
},
{
"code": null,
"e": 2895,
"s": 2840,
"text": "Adequate padding and margin are given to each element."
},
{
"code": null,
"e": 2995,
"s": 2895,
"text": "The text size of each element is such that it is easily readable by the user when playing the game."
},
{
"code": null,
"e": 3160,
"s": 2995,
"text": "Two additional classes are defined to denote the letters that are typed correctly or incorrectly. These classes would be dynamically added or removed when required."
},
{
"code": null,
"e": 3168,
"s": 3160,
"text": "Code: "
},
{
"code": null,
"e": 3173,
"s": 3168,
"text": "html"
},
{
"code": "body { background-color: #fe9801; color: black; text-align: center;} .container { display: flex; flex-direction: column; align-items: center;} .heading { margin-bottom: 20px; font-size: 3rem; color: black;} .header { display: flex; align-items: center;} .timer, .errors, .accuracy,.cpm, .wpm { background-color: #ccda46; height: 60px; width: 70px; margin: 8px; padding: 12px; border-radius: 20%; box-shadow: black 5px 8px 5px;} .cpm, .wpm { display: none;} .header_text { text-transform: uppercase; font-size: 0.6rem; font-weight: 600;} .curr_time, .curr_errors,.curr_accuracy, .curr_cpm,.curr_wpm { font-size: 2.75rem;} .quote { background-color: #ccda46; font-size: 1.5rem; margin: 10px; padding: 25px; box-shadow: black 5px 8px 5px;} .input_area { background-color: #f5f5c6; height: 80px; width: 40%; font-size: 1.5rem; font-weight: 600; margin: 15px; padding: 20px; border: 0px; box-shadow: black 5px 8px 5px;} .restart_btn { display: none; background-color: #326765; font-size: 1.5rem; padding: 10px; border: 0px; box-shadow: black 5px 8px 5px;} .incorrect_char { color: red; text-decoration: underline;} .correct_char { color: darkgreen;}",
"e": 4365,
"s": 3173,
"text": null
},
{
"code": null,
"e": 4435,
"s": 4365,
"text": "The result of the HTML layout and CSS styling would look like this: "
},
{
"code": null,
"e": 4916,
"s": 4435,
"text": "Main Logic of the game: The main logic of the game is defined in a JavaScript file. There are several functions that work together to run the game.Step 1: Selecting all the elements and defining variablesThe required elements in the HTML layout are first selected using the querySelector() method. They are assigned variable names so that they could be easily accessed and modified. Other variables that would be accessed throughout the program are also defined in the beginning. "
},
{
"code": null,
"e": 4927,
"s": 4916,
"text": "javascript"
},
{
"code": "// define the time limitlet TIME_LIMIT = 60; // define quotes to be usedlet quotes_array = [ \"Push yourself, because no one else is going to do it for you.\", \"Failure is the condiment that gives success its flavor.\", \"Wake up with determination. Go to bed with satisfaction.\", \"It's going to be hard, but hard does not mean impossible.\", \"Learning never exhausts the mind.\", \"The only way to do great work is to love what you do.\"]; // selecting required elementslet timer_text = document.querySelector(\".curr_time\");let accuracy_text = document.querySelector(\".curr_accuracy\");let error_text = document.querySelector(\".curr_errors\");let cpm_text = document.querySelector(\".curr_cpm\");let wpm_text = document.querySelector(\".curr_wpm\");let quote_text = document.querySelector(\".quote\");let input_area = document.querySelector(\".input_area\");let restart_btn = document.querySelector(\".restart_btn\");let cpm_group = document.querySelector(\".cpm\");let wpm_group = document.querySelector(\".wpm\");let error_group = document.querySelector(\".errors\");let accuracy_group = document.querySelector(\".accuracy\"); let timeLeft = TIME_LIMIT;let timeElapsed = 0;let total_errors = 0;let errors = 0;let accuracy = 0;let characterTyped = 0;let current_quote = \"\";let quoteNo = 0;let timer = null;",
"e": 6214,
"s": 4927,
"text": null
},
{
"code": null,
"e": 6330,
"s": 6214,
"text": "Step 2: Preparing the text to be displayedA function updateQuote() is defined which handles the following things: "
},
{
"code": null,
"e": 6577,
"s": 6330,
"text": "Getting the text Quotes have been used as the text that has to be typed to play the game. Each quote is taken one by one from a predefined array. A variable keeps track of the current quote index and increments it whenever a new one is requested."
},
{
"code": null,
"e": 6885,
"s": 6577,
"text": "Splitting the characters into elements Each of the characters in the text is separated into a series of <span> elements. This makes it possible to individually change the color of each character depending upon if it has been correctly typed by the user. These elements are appended to a variable quote_text."
},
{
"code": null,
"e": 6898,
"s": 6887,
"text": "javascript"
},
{
"code": "function updateQuote() { quote_text.textContent = null; current_quote = quotes_array[quoteNo]; // separate each character and make an element // out of each of them to individually style them current_quote.split('').forEach(char => { const charSpan = document.createElement('span') charSpan.innerText = char quote_text.appendChild(charSpan) }) // roll over to the first quote if (quoteNo < quotes_array.length - 1) quoteNo++; else quoteNo = 0;}",
"e": 7369,
"s": 6898,
"text": null
},
{
"code": null,
"e": 7659,
"s": 7369,
"text": "Step 3: Getting the currently typed text by the userA function processCurrentText() is defined which will be invoked whenever the user types or changes anything in the input box. It is hence used with the oninput event handler of the input box. This function handles the following things: "
},
{
"code": null,
"e": 7900,
"s": 7659,
"text": "Getting the current value of the input box The value property of the input area is used to get the current text typed by the user. This is split into an array of characters to compare with the quote text. This is stored in curr_input_array."
},
{
"code": null,
"e": 8264,
"s": 7900,
"text": "Coloring the characters of the quote text The characters of the displayed quote are colored ‘red’ or ‘green’ depending on whether it has been typed correctly. This is done by selecting the span elements of the quote we have created earlier and looping through them. The element has then applied the classes created above depending on if it matches the typed text."
},
{
"code": null,
"e": 8542,
"s": 8264,
"text": "Calculating the errors and accuracy Every time the user makes a mistake during typing, the errors variable is incremented. This is used to calculate the accuracy value by dividing the number of correctly typed characters with the total number of characters typed by the user. "
},
{
"code": null,
"e": 8790,
"s": 8542,
"text": "Moving to next quote When the length of the input text matches the quote text length, the updateQuote() function is called which changes the quote and clears the input area. The number of total errors is also updated to be used for the next quote."
},
{
"code": null,
"e": 8803,
"s": 8792,
"text": "javascript"
},
{
"code": "function processCurrentText() { // get current input text and split it curr_input = input_area.value; curr_input_array = curr_input.split(''); // increment total characters typed characterTyped++; errors = 0; quoteSpanArray = quote_text.querySelectorAll('span'); quoteSpanArray.forEach((char, index) => { let typedChar = curr_input_array[index] // character not currently typed if (typedChar == null) { char.classList.remove('correct_char'); char.classList.remove('incorrect_char'); // correct character } else if (typedChar === char.innerText) { char.classList.add('correct_char'); char.classList.remove('incorrect_char'); // incorrect character } else { char.classList.add('incorrect_char'); char.classList.remove('correct_char'); // increment number of errors errors++; } }); // display the number of errors error_text.textContent = total_errors + errors; // update accuracy text let correctCharacters = (characterTyped - (total_errors + errors)); let accuracyVal = ((correctCharacters / characterTyped) * 100); accuracy_text.textContent = Math.round(accuracyVal); // if current text is completely typed // irrespective of errors if (curr_input.length == current_quote.length) { updateQuote(); // update total errors total_errors += errors; // clear the input area input_area.value = \"\"; }}",
"e": 10212,
"s": 8803,
"text": null
},
{
"code": null,
"e": 10261,
"s": 10212,
"text": "Coloring of the characters based its correctness"
},
{
"code": null,
"e": 10495,
"s": 10261,
"text": "Step 4: Starting a new gameA function startGame() is defined which will be invoked when the user focuses on the input box. It is hence used with the onfocus event handler of the input box. This function handles the following things: "
},
{
"code": null,
"e": 10667,
"s": 10495,
"text": "Reset all values All the values are reset to their default ones before the starting of a new game. We create a different function named resetValues() which handles this. "
},
{
"code": null,
"e": 10775,
"s": 10667,
"text": "Update the quote text A new quote text is made ready and displayed by calling the updateQuote() function. "
},
{
"code": null,
"e": 11076,
"s": 10775,
"text": "Creating a new timer A timer keeps track of the number of seconds left and displays it to the user. It is created using the setInterval() method which repeatedly calls the updateTimer() function defined below. Before creating a new timer, the previous timer instance is cleared using clearInterval()."
},
{
"code": null,
"e": 11089,
"s": 11078,
"text": "javascript"
},
{
"code": "function startGame() { resetValues(); updateQuote(); // clear old and start a new timer clearInterval(timer); timer = setInterval(updateTimer, 1000);} function resetValues() { timeLeft = TIME_LIMIT; timeElapsed = 0; errors = 0; total_errors = 0; accuracy = 0; characterTyped = 0; quoteNo = 0; input_area.disabled = false; input_area.value = \"\"; quote_text.textContent = 'Click on the area below to start the game.'; accuracy_text.textContent = 100; timer_text.textContent = timeLeft + 's'; error_text.textContent = 0; restart_btn.style.display = \"none\"; cpm_group.style.display = \"none\"; wpm_group.style.display = \"none\";}",
"e": 11736,
"s": 11089,
"text": null
},
{
"code": null,
"e": 11905,
"s": 11736,
"text": "Step 5: Updating the timerA function updateTimer() is defined which will be invoked every second to keep track fo the time. This function handles the following things: "
},
{
"code": null,
"e": 12116,
"s": 11905,
"text": "Update the time values All the variables that keep track of the time are updated. The timeLeft value is decremented, the timeElapsed value is incremented, and the timer text is updated to the current time left."
},
{
"code": null,
"e": 12267,
"s": 12116,
"text": "Finishing the game This portion is triggered when the time limit is reached. It calls the finishGame() function defined below which finishes the game."
},
{
"code": null,
"e": 12280,
"s": 12269,
"text": "javascript"
},
{
"code": "function updateTimer() { if (timeLeft > 0) { // decrease the current time left timeLeft--; // increase the time elapsed timeElapsed++; // update the timer text timer_text.textContent = timeLeft + \"s\"; } else { // finish the game finishGame(); }}",
"e": 12556,
"s": 12280,
"text": null
},
{
"code": null,
"e": 12718,
"s": 12556,
"text": "Step 6: Finishing the gameA function finishGame() is defined which will be invoked when the game has to be finished. This function handles the following things: "
},
{
"code": null,
"e": 12783,
"s": 12718,
"text": "Deleting the timer The timer instance created before is removed."
},
{
"code": null,
"e": 13004,
"s": 12783,
"text": "Displaying the restart game text and button The quoted text displayed to the user is changed to one that indicates that the game is over. The ‘Restart’ button is also displayed by setting the display property to ‘block’."
},
{
"code": null,
"e": 13466,
"s": 13004,
"text": "Calculating the CPM and WPM of the current session The Characters Per Minute (CPM) is calculated by dividing the total number of characters typed with the time elapsed and then multiplying the result with 60. It is rounded off to prevent decimal points.The Words Per Minute (WPM) is calculated by dividing the CPM by 5 and then multiplying the result with 60. The 5 denotes the average number of characters per word. It is rounded off to prevent decimal points."
},
{
"code": null,
"e": 13877,
"s": 13466,
"text": "The Characters Per Minute (CPM) is calculated by dividing the total number of characters typed with the time elapsed and then multiplying the result with 60. It is rounded off to prevent decimal points.The Words Per Minute (WPM) is calculated by dividing the CPM by 5 and then multiplying the result with 60. The 5 denotes the average number of characters per word. It is rounded off to prevent decimal points."
},
{
"code": null,
"e": 14080,
"s": 13877,
"text": "The Characters Per Minute (CPM) is calculated by dividing the total number of characters typed with the time elapsed and then multiplying the result with 60. It is rounded off to prevent decimal points."
},
{
"code": null,
"e": 14289,
"s": 14080,
"text": "The Words Per Minute (WPM) is calculated by dividing the CPM by 5 and then multiplying the result with 60. The 5 denotes the average number of characters per word. It is rounded off to prevent decimal points."
},
{
"code": null,
"e": 14302,
"s": 14291,
"text": "javascript"
},
{
"code": "function finishGame() { // stop the timer clearInterval(timer); // disable the input area input_area.disabled = true; // show finishing text quote_text.textContent = \"Click on restart to start a new game.\"; // display restart button restart_btn.style.display = \"block\"; // calculate cpm and wpm cpm = Math.round(((characterTyped / timeElapsed) * 60)); wpm = Math.round((((characterTyped / 5) / timeElapsed) * 60)); // update cpm and wpm text cpm_text.textContent = cpm; wpm_text.textContent = wpm; // display the cpm and wpm cpm_group.style.display = \"block\"; wpm_group.style.display = \"block\";}",
"e": 14921,
"s": 14302,
"text": null
},
{
"code": null,
"e": 14992,
"s": 14921,
"text": "Final DemonstrationThe game is now ready to be played in any browser. "
},
{
"code": null,
"e": 15059,
"s": 14992,
"text": "Source Code: https://github.com/sayantanm19/js-simple-typing-game "
},
{
"code": null,
"e": 15071,
"s": 15059,
"text": "kashishsoda"
},
{
"code": null,
"e": 15087,
"s": 15071,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 15111,
"s": 15087,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 15122,
"s": 15111,
"text": "JavaScript"
},
{
"code": null,
"e": 15141,
"s": 15122,
"text": "Technical Scripter"
},
{
"code": null,
"e": 15158,
"s": 15141,
"text": "Web Technologies"
}
] |
OS Path module in Python | The os.path module is a very extensively used module that is handy when processing files from different places in the system. It is used for different purposes such as for merging, normalizing and retrieving path names in python . All of these functions accept either only bytes or only string objects as their parameters. Its results are specific to the OS on which it is being run.
This function gives us the last part of the path which may be a folder or a file name. Please the difference in how the path is mentioned in Windows and Linux in terms of the backslash and the forward slash.
import os
# In windows
fldr = os.path.basename("C:\\Users\\xyz\\Documents\\My Web Sites")
print(fldr)
file = os.path.basename("C:\\Users\\xyz\\Documents\\My Web Sites\\intro.html")
print(file)
# In nix*
fldr = os.path.basename("/Documents/MyWebSites")
print(fldr)
file = os.path.basename("/Documents/MyWebSites/music.txt")
print(file)
Running the above code gives us the following result −
My Web Sites
intro.html
MyWebSites
music.txt
This function gives us the directory name where the folder or file is located.
import os
# In windows
DIR = os.path.dirname("C:\\Users\\xyz\\Documents\\My Web Sites")
print(DIR)
# In nix*
DIR = os.path.dirname("/Documents/MyWebSites")
print(DIR)
Running the above code gives us the following result −
C:\Users\xyz\Documents
/Documents
Sometimes we may need to check if the complete path given, represents a folder or a file. If the file does not exist then it will give False as the output. If the file exists then the output is True.
print(IS_FILE)
IS_FILE = os.path.isfile("C:\\Users\\xyz\\Documents\\My Web Sites\\intro.html")
print(IS_FILE)
# In nix*
IS_FILE = os.path.isfile("/Documents/MyWebSites")
print(IS_FILE)
IS_FILE = os.path.isfile("/Documents/MyWebSites/music.txt")
print(IS_FILE)
Running the above code gives us the following result −
False
True
False
True
This is a interesting function which will normalize the given path by eliminating extra slashes or changing the backslash to forward slash depending on which OS it is. As you can see the output below varies depending on which OS you run the program on.
import os
# Windows path
NORM_PATH = os.path.normpath("C:/Users/Pradeep/Documents/My Web Sites")
print(NORM_PATH)
# Unix Path
NORM_PATH = os.path.normpath("/home/ubuuser//Documents/")
print(NORM_PATH)
Running the above code gives us the following result −
# Running in Windows
C:\Users\Pradeep\Documents\My Web Sites
\home\ubuuser\Documents
# Running in Linux
C:/Users/Pradeep/Documents/My Web Sites
/home/ubuuser/Documents | [
{
"code": null,
"e": 1571,
"s": 1187,
"text": "The os.path module is a very extensively used module that is handy when processing files from different places in the system. It is used for different purposes such as for merging, normalizing and retrieving path names in python . All of these functions accept either only bytes or only string objects as their parameters. Its results are specific to the OS on which it is being run."
},
{
"code": null,
"e": 1779,
"s": 1571,
"text": "This function gives us the last part of the path which may be a folder or a file name. Please the difference in how the path is mentioned in Windows and Linux in terms of the backslash and the forward slash."
},
{
"code": null,
"e": 2114,
"s": 1779,
"text": "import os\n# In windows\nfldr = os.path.basename(\"C:\\\\Users\\\\xyz\\\\Documents\\\\My Web Sites\")\nprint(fldr)\nfile = os.path.basename(\"C:\\\\Users\\\\xyz\\\\Documents\\\\My Web Sites\\\\intro.html\")\nprint(file)\n# In nix*\nfldr = os.path.basename(\"/Documents/MyWebSites\")\nprint(fldr)\nfile = os.path.basename(\"/Documents/MyWebSites/music.txt\")\nprint(file)"
},
{
"code": null,
"e": 2169,
"s": 2114,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2214,
"s": 2169,
"text": "My Web Sites\nintro.html\nMyWebSites\nmusic.txt"
},
{
"code": null,
"e": 2293,
"s": 2214,
"text": "This function gives us the directory name where the folder or file is located."
},
{
"code": null,
"e": 2460,
"s": 2293,
"text": "import os\n# In windows\nDIR = os.path.dirname(\"C:\\\\Users\\\\xyz\\\\Documents\\\\My Web Sites\")\nprint(DIR)\n# In nix*\nDIR = os.path.dirname(\"/Documents/MyWebSites\")\nprint(DIR)"
},
{
"code": null,
"e": 2515,
"s": 2460,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2549,
"s": 2515,
"text": "C:\\Users\\xyz\\Documents\n/Documents"
},
{
"code": null,
"e": 2752,
"s": 2549,
"text": "Sometimes we may need to check if the complete path given, represents a folder or a file. If the file does not exist then it will give False as the output. If the file exists then the output is True. "
},
{
"code": null,
"e": 3013,
"s": 2752,
"text": "print(IS_FILE)\nIS_FILE = os.path.isfile(\"C:\\\\Users\\\\xyz\\\\Documents\\\\My Web Sites\\\\intro.html\")\nprint(IS_FILE)\n# In nix*\nIS_FILE = os.path.isfile(\"/Documents/MyWebSites\")\nprint(IS_FILE)\nIS_FILE = os.path.isfile(\"/Documents/MyWebSites/music.txt\")\nprint(IS_FILE)\n"
},
{
"code": null,
"e": 3068,
"s": 3013,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3090,
"s": 3068,
"text": "False\nTrue\nFalse\nTrue"
},
{
"code": null,
"e": 3343,
"s": 3090,
"text": "This is a interesting function which will normalize the given path by eliminating extra slashes or changing the backslash to forward slash depending on which OS it is. As you can see the output below varies depending on which OS you run the program on."
},
{
"code": null,
"e": 3544,
"s": 3343,
"text": "import os\n# Windows path\nNORM_PATH = os.path.normpath(\"C:/Users/Pradeep/Documents/My Web Sites\")\nprint(NORM_PATH)\n# Unix Path\nNORM_PATH = os.path.normpath(\"/home/ubuuser//Documents/\")\nprint(NORM_PATH)"
},
{
"code": null,
"e": 3599,
"s": 3544,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3768,
"s": 3599,
"text": "# Running in Windows\nC:\\Users\\Pradeep\\Documents\\My Web Sites\n\\home\\ubuuser\\Documents\n\n# Running in Linux\nC:/Users/Pradeep/Documents/My Web Sites\n/home/ubuuser/Documents"
}
] |
Segments in Computer Graphics | 11 May, 2018
To view an entire image or a part of image with various attributes, we need to organize image information in a particular manner since existing structure of display file does not satisfy our requirements of viewing an image. To achieve this display, file is divided into Segments. Each segment corresponds to a component and is associated with a set of attributes and image transformation parameters like scaling, rotation. Presence of Segment allows :
Subdivision of picture.
Visualization of particular part of picture.
Scaling, rotation and translation of picture.
Types of Segments :
Posted Segment : When visible attribute of segment is set to 1, it is called Posted segment. This is included in active segment list.
Unposted Segment : When visible attribute of segment is set to 0, it is called Unposted segment. This is not included in active segment list.
Functions for Segmenting the display :
Segment Creation : Segment must be created or opened when no other segment is open, since two segments can’t be opened at the same time because it’s difficult to assign drawing instruction to particular segment. The segment created must be given a name to identify it which must be a valid one and there should be no segment with the same name. After this, we initialize items in segment table under our segment name and the first instruction of this segment is allocated at next free storage in display file and attributes of segments are initialized to default.Algorithm :If any segment is open, give error message : “Segment is still open” and go to step 8.Read the name of the new segment.If the segment name is not valid, give error message : “Segment name not a valid name” and go to step 8.If given segment name already exists, give error message : “Segment name already exists in name list” and go to step 8.Make next free storage area in display file as start of new segment.Initialize size of new segment to 0 and all its attributes to their default values.Inform that the new segment is now open.Stop.Closing a Segment : After completing entry of all display file instructions, the segment needs to be closed for which it has to be renamed, which is done by changing the name of currently open segment as 0. Now the segment with name 0 is open i.e. unnamed segment is open and if two unnamed segments are present in display file one needs to be deleted.Algorithm :If any segment is not open, give error message : “No segment is open now” and go to step 6.Change the name of currently opened segment to any unnamed segment, lets say 0.Delete any other unnamed segment instruction which may have been saved and initialize above unnamed segment with no instructions.Make the next free storage area available in display file as start of the unnamed segment.Initialize size of unnamed segment to 0.Stop.Deleting a Segment : To delete a particular segment from display file, we must just delete that one segment without destroying or reforming the entire display and recover space occupied by this segment. Use this space for some other segment. The method to achieve this depends upon the data structure used to represent display file. In case of arrays, the gap left by deleted segment is filled by shifting up all the segments following it.Algorithm :Read the name of the segment to be deleted.If segment name is not valid, give error message : “Segment name is not a valid name” and go to step 8.If the segment is open, give error message : “Can’t delete an open segment” and go to step 8.If size of segment is less than 0, no processing is required and go to step 8.The segments which follow the deleted segment are shifted by its size.Recover deleted space by resetting index of next free instruction.The starting position of shifted segments is adjusted by subtracting the size of deleted segment from it.Stop.Renaming a Segment : This is done to achieve Double Buffering i.e. the idea of storing two images, one to show and other to create, alter and for animation.Algorithm :If both old and new segment names are not valid, give error message : “Segment names are not valid names” and go to step 6.If any of two segments is open, give error message : “Segments are still open” and go to step 6.If new segment name given already exists in the display list, give error message : “Segment name already exists” and go to step 6.The old segment table entry are copied into new position.Delete the old segment.Stop.
Segment Creation : Segment must be created or opened when no other segment is open, since two segments can’t be opened at the same time because it’s difficult to assign drawing instruction to particular segment. The segment created must be given a name to identify it which must be a valid one and there should be no segment with the same name. After this, we initialize items in segment table under our segment name and the first instruction of this segment is allocated at next free storage in display file and attributes of segments are initialized to default.Algorithm :If any segment is open, give error message : “Segment is still open” and go to step 8.Read the name of the new segment.If the segment name is not valid, give error message : “Segment name not a valid name” and go to step 8.If given segment name already exists, give error message : “Segment name already exists in name list” and go to step 8.Make next free storage area in display file as start of new segment.Initialize size of new segment to 0 and all its attributes to their default values.Inform that the new segment is now open.Stop.
If any segment is open, give error message : “Segment is still open” and go to step 8.Read the name of the new segment.If the segment name is not valid, give error message : “Segment name not a valid name” and go to step 8.If given segment name already exists, give error message : “Segment name already exists in name list” and go to step 8.Make next free storage area in display file as start of new segment.Initialize size of new segment to 0 and all its attributes to their default values.Inform that the new segment is now open.Stop.
If any segment is open, give error message : “Segment is still open” and go to step 8.
Read the name of the new segment.
If the segment name is not valid, give error message : “Segment name not a valid name” and go to step 8.
If given segment name already exists, give error message : “Segment name already exists in name list” and go to step 8.
Make next free storage area in display file as start of new segment.
Initialize size of new segment to 0 and all its attributes to their default values.
Inform that the new segment is now open.
Stop.
Closing a Segment : After completing entry of all display file instructions, the segment needs to be closed for which it has to be renamed, which is done by changing the name of currently open segment as 0. Now the segment with name 0 is open i.e. unnamed segment is open and if two unnamed segments are present in display file one needs to be deleted.Algorithm :If any segment is not open, give error message : “No segment is open now” and go to step 6.Change the name of currently opened segment to any unnamed segment, lets say 0.Delete any other unnamed segment instruction which may have been saved and initialize above unnamed segment with no instructions.Make the next free storage area available in display file as start of the unnamed segment.Initialize size of unnamed segment to 0.Stop.
If any segment is not open, give error message : “No segment is open now” and go to step 6.Change the name of currently opened segment to any unnamed segment, lets say 0.Delete any other unnamed segment instruction which may have been saved and initialize above unnamed segment with no instructions.Make the next free storage area available in display file as start of the unnamed segment.Initialize size of unnamed segment to 0.Stop.
If any segment is not open, give error message : “No segment is open now” and go to step 6.
Change the name of currently opened segment to any unnamed segment, lets say 0.
Delete any other unnamed segment instruction which may have been saved and initialize above unnamed segment with no instructions.
Make the next free storage area available in display file as start of the unnamed segment.
Initialize size of unnamed segment to 0.
Stop.
Deleting a Segment : To delete a particular segment from display file, we must just delete that one segment without destroying or reforming the entire display and recover space occupied by this segment. Use this space for some other segment. The method to achieve this depends upon the data structure used to represent display file. In case of arrays, the gap left by deleted segment is filled by shifting up all the segments following it.Algorithm :Read the name of the segment to be deleted.If segment name is not valid, give error message : “Segment name is not a valid name” and go to step 8.If the segment is open, give error message : “Can’t delete an open segment” and go to step 8.If size of segment is less than 0, no processing is required and go to step 8.The segments which follow the deleted segment are shifted by its size.Recover deleted space by resetting index of next free instruction.The starting position of shifted segments is adjusted by subtracting the size of deleted segment from it.Stop.
Algorithm :
Read the name of the segment to be deleted.If segment name is not valid, give error message : “Segment name is not a valid name” and go to step 8.If the segment is open, give error message : “Can’t delete an open segment” and go to step 8.If size of segment is less than 0, no processing is required and go to step 8.The segments which follow the deleted segment are shifted by its size.Recover deleted space by resetting index of next free instruction.The starting position of shifted segments is adjusted by subtracting the size of deleted segment from it.Stop.
Read the name of the segment to be deleted.
If segment name is not valid, give error message : “Segment name is not a valid name” and go to step 8.
If the segment is open, give error message : “Can’t delete an open segment” and go to step 8.
If size of segment is less than 0, no processing is required and go to step 8.
The segments which follow the deleted segment are shifted by its size.
Recover deleted space by resetting index of next free instruction.
The starting position of shifted segments is adjusted by subtracting the size of deleted segment from it.
Stop.
Renaming a Segment : This is done to achieve Double Buffering i.e. the idea of storing two images, one to show and other to create, alter and for animation.Algorithm :If both old and new segment names are not valid, give error message : “Segment names are not valid names” and go to step 6.If any of two segments is open, give error message : “Segments are still open” and go to step 6.If new segment name given already exists in the display list, give error message : “Segment name already exists” and go to step 6.The old segment table entry are copied into new position.Delete the old segment.Stop.
If both old and new segment names are not valid, give error message : “Segment names are not valid names” and go to step 6.If any of two segments is open, give error message : “Segments are still open” and go to step 6.If new segment name given already exists in the display list, give error message : “Segment name already exists” and go to step 6.The old segment table entry are copied into new position.Delete the old segment.Stop.
If both old and new segment names are not valid, give error message : “Segment names are not valid names” and go to step 6.
If any of two segments is open, give error message : “Segments are still open” and go to step 6.
If new segment name given already exists in the display list, give error message : “Segment name already exists” and go to step 6.
The old segment table entry are copied into new position.
Delete the old segment.
Stop.
Advantages of using segmented display :
Segmentation allows to organize display files in sub-picture structure.
It allows to apply different set of attributes to different portions of image.
It makes it easier to the picture by changing/replacing segments.
It allows application of transformation on selective portions of image.
computer-graphics
Advanced Computer Subject
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, 2018"
},
{
"code": null,
"e": 507,
"s": 54,
"text": "To view an entire image or a part of image with various attributes, we need to organize image information in a particular manner since existing structure of display file does not satisfy our requirements of viewing an image. To achieve this display, file is divided into Segments. Each segment corresponds to a component and is associated with a set of attributes and image transformation parameters like scaling, rotation. Presence of Segment allows :"
},
{
"code": null,
"e": 531,
"s": 507,
"text": "Subdivision of picture."
},
{
"code": null,
"e": 576,
"s": 531,
"text": "Visualization of particular part of picture."
},
{
"code": null,
"e": 622,
"s": 576,
"text": "Scaling, rotation and translation of picture."
},
{
"code": null,
"e": 642,
"s": 622,
"text": "Types of Segments :"
},
{
"code": null,
"e": 776,
"s": 642,
"text": "Posted Segment : When visible attribute of segment is set to 1, it is called Posted segment. This is included in active segment list."
},
{
"code": null,
"e": 918,
"s": 776,
"text": "Unposted Segment : When visible attribute of segment is set to 0, it is called Unposted segment. This is not included in active segment list."
},
{
"code": null,
"e": 957,
"s": 918,
"text": "Functions for Segmenting the display :"
},
{
"code": null,
"e": 4481,
"s": 957,
"text": "Segment Creation : Segment must be created or opened when no other segment is open, since two segments can’t be opened at the same time because it’s difficult to assign drawing instruction to particular segment. The segment created must be given a name to identify it which must be a valid one and there should be no segment with the same name. After this, we initialize items in segment table under our segment name and the first instruction of this segment is allocated at next free storage in display file and attributes of segments are initialized to default.Algorithm :If any segment is open, give error message : “Segment is still open” and go to step 8.Read the name of the new segment.If the segment name is not valid, give error message : “Segment name not a valid name” and go to step 8.If given segment name already exists, give error message : “Segment name already exists in name list” and go to step 8.Make next free storage area in display file as start of new segment.Initialize size of new segment to 0 and all its attributes to their default values.Inform that the new segment is now open.Stop.Closing a Segment : After completing entry of all display file instructions, the segment needs to be closed for which it has to be renamed, which is done by changing the name of currently open segment as 0. Now the segment with name 0 is open i.e. unnamed segment is open and if two unnamed segments are present in display file one needs to be deleted.Algorithm :If any segment is not open, give error message : “No segment is open now” and go to step 6.Change the name of currently opened segment to any unnamed segment, lets say 0.Delete any other unnamed segment instruction which may have been saved and initialize above unnamed segment with no instructions.Make the next free storage area available in display file as start of the unnamed segment.Initialize size of unnamed segment to 0.Stop.Deleting a Segment : To delete a particular segment from display file, we must just delete that one segment without destroying or reforming the entire display and recover space occupied by this segment. Use this space for some other segment. The method to achieve this depends upon the data structure used to represent display file. In case of arrays, the gap left by deleted segment is filled by shifting up all the segments following it.Algorithm :Read the name of the segment to be deleted.If segment name is not valid, give error message : “Segment name is not a valid name” and go to step 8.If the segment is open, give error message : “Can’t delete an open segment” and go to step 8.If size of segment is less than 0, no processing is required and go to step 8.The segments which follow the deleted segment are shifted by its size.Recover deleted space by resetting index of next free instruction.The starting position of shifted segments is adjusted by subtracting the size of deleted segment from it.Stop.Renaming a Segment : This is done to achieve Double Buffering i.e. the idea of storing two images, one to show and other to create, alter and for animation.Algorithm :If both old and new segment names are not valid, give error message : “Segment names are not valid names” and go to step 6.If any of two segments is open, give error message : “Segments are still open” and go to step 6.If new segment name given already exists in the display list, give error message : “Segment name already exists” and go to step 6.The old segment table entry are copied into new position.Delete the old segment.Stop."
},
{
"code": null,
"e": 5594,
"s": 4481,
"text": "Segment Creation : Segment must be created or opened when no other segment is open, since two segments can’t be opened at the same time because it’s difficult to assign drawing instruction to particular segment. The segment created must be given a name to identify it which must be a valid one and there should be no segment with the same name. After this, we initialize items in segment table under our segment name and the first instruction of this segment is allocated at next free storage in display file and attributes of segments are initialized to default.Algorithm :If any segment is open, give error message : “Segment is still open” and go to step 8.Read the name of the new segment.If the segment name is not valid, give error message : “Segment name not a valid name” and go to step 8.If given segment name already exists, give error message : “Segment name already exists in name list” and go to step 8.Make next free storage area in display file as start of new segment.Initialize size of new segment to 0 and all its attributes to their default values.Inform that the new segment is now open.Stop."
},
{
"code": null,
"e": 6133,
"s": 5594,
"text": "If any segment is open, give error message : “Segment is still open” and go to step 8.Read the name of the new segment.If the segment name is not valid, give error message : “Segment name not a valid name” and go to step 8.If given segment name already exists, give error message : “Segment name already exists in name list” and go to step 8.Make next free storage area in display file as start of new segment.Initialize size of new segment to 0 and all its attributes to their default values.Inform that the new segment is now open.Stop."
},
{
"code": null,
"e": 6220,
"s": 6133,
"text": "If any segment is open, give error message : “Segment is still open” and go to step 8."
},
{
"code": null,
"e": 6254,
"s": 6220,
"text": "Read the name of the new segment."
},
{
"code": null,
"e": 6359,
"s": 6254,
"text": "If the segment name is not valid, give error message : “Segment name not a valid name” and go to step 8."
},
{
"code": null,
"e": 6479,
"s": 6359,
"text": "If given segment name already exists, give error message : “Segment name already exists in name list” and go to step 8."
},
{
"code": null,
"e": 6548,
"s": 6479,
"text": "Make next free storage area in display file as start of new segment."
},
{
"code": null,
"e": 6632,
"s": 6548,
"text": "Initialize size of new segment to 0 and all its attributes to their default values."
},
{
"code": null,
"e": 6673,
"s": 6632,
"text": "Inform that the new segment is now open."
},
{
"code": null,
"e": 6679,
"s": 6673,
"text": "Stop."
},
{
"code": null,
"e": 7477,
"s": 6679,
"text": "Closing a Segment : After completing entry of all display file instructions, the segment needs to be closed for which it has to be renamed, which is done by changing the name of currently open segment as 0. Now the segment with name 0 is open i.e. unnamed segment is open and if two unnamed segments are present in display file one needs to be deleted.Algorithm :If any segment is not open, give error message : “No segment is open now” and go to step 6.Change the name of currently opened segment to any unnamed segment, lets say 0.Delete any other unnamed segment instruction which may have been saved and initialize above unnamed segment with no instructions.Make the next free storage area available in display file as start of the unnamed segment.Initialize size of unnamed segment to 0.Stop."
},
{
"code": null,
"e": 7912,
"s": 7477,
"text": "If any segment is not open, give error message : “No segment is open now” and go to step 6.Change the name of currently opened segment to any unnamed segment, lets say 0.Delete any other unnamed segment instruction which may have been saved and initialize above unnamed segment with no instructions.Make the next free storage area available in display file as start of the unnamed segment.Initialize size of unnamed segment to 0.Stop."
},
{
"code": null,
"e": 8004,
"s": 7912,
"text": "If any segment is not open, give error message : “No segment is open now” and go to step 6."
},
{
"code": null,
"e": 8084,
"s": 8004,
"text": "Change the name of currently opened segment to any unnamed segment, lets say 0."
},
{
"code": null,
"e": 8214,
"s": 8084,
"text": "Delete any other unnamed segment instruction which may have been saved and initialize above unnamed segment with no instructions."
},
{
"code": null,
"e": 8305,
"s": 8214,
"text": "Make the next free storage area available in display file as start of the unnamed segment."
},
{
"code": null,
"e": 8346,
"s": 8305,
"text": "Initialize size of unnamed segment to 0."
},
{
"code": null,
"e": 8352,
"s": 8346,
"text": "Stop."
},
{
"code": null,
"e": 9366,
"s": 8352,
"text": "Deleting a Segment : To delete a particular segment from display file, we must just delete that one segment without destroying or reforming the entire display and recover space occupied by this segment. Use this space for some other segment. The method to achieve this depends upon the data structure used to represent display file. In case of arrays, the gap left by deleted segment is filled by shifting up all the segments following it.Algorithm :Read the name of the segment to be deleted.If segment name is not valid, give error message : “Segment name is not a valid name” and go to step 8.If the segment is open, give error message : “Can’t delete an open segment” and go to step 8.If size of segment is less than 0, no processing is required and go to step 8.The segments which follow the deleted segment are shifted by its size.Recover deleted space by resetting index of next free instruction.The starting position of shifted segments is adjusted by subtracting the size of deleted segment from it.Stop."
},
{
"code": null,
"e": 9378,
"s": 9366,
"text": "Algorithm :"
},
{
"code": null,
"e": 9942,
"s": 9378,
"text": "Read the name of the segment to be deleted.If segment name is not valid, give error message : “Segment name is not a valid name” and go to step 8.If the segment is open, give error message : “Can’t delete an open segment” and go to step 8.If size of segment is less than 0, no processing is required and go to step 8.The segments which follow the deleted segment are shifted by its size.Recover deleted space by resetting index of next free instruction.The starting position of shifted segments is adjusted by subtracting the size of deleted segment from it.Stop."
},
{
"code": null,
"e": 9986,
"s": 9942,
"text": "Read the name of the segment to be deleted."
},
{
"code": null,
"e": 10090,
"s": 9986,
"text": "If segment name is not valid, give error message : “Segment name is not a valid name” and go to step 8."
},
{
"code": null,
"e": 10184,
"s": 10090,
"text": "If the segment is open, give error message : “Can’t delete an open segment” and go to step 8."
},
{
"code": null,
"e": 10263,
"s": 10184,
"text": "If size of segment is less than 0, no processing is required and go to step 8."
},
{
"code": null,
"e": 10334,
"s": 10263,
"text": "The segments which follow the deleted segment are shifted by its size."
},
{
"code": null,
"e": 10401,
"s": 10334,
"text": "Recover deleted space by resetting index of next free instruction."
},
{
"code": null,
"e": 10507,
"s": 10401,
"text": "The starting position of shifted segments is adjusted by subtracting the size of deleted segment from it."
},
{
"code": null,
"e": 10513,
"s": 10507,
"text": "Stop."
},
{
"code": null,
"e": 11115,
"s": 10513,
"text": "Renaming a Segment : This is done to achieve Double Buffering i.e. the idea of storing two images, one to show and other to create, alter and for animation.Algorithm :If both old and new segment names are not valid, give error message : “Segment names are not valid names” and go to step 6.If any of two segments is open, give error message : “Segments are still open” and go to step 6.If new segment name given already exists in the display list, give error message : “Segment name already exists” and go to step 6.The old segment table entry are copied into new position.Delete the old segment.Stop."
},
{
"code": null,
"e": 11550,
"s": 11115,
"text": "If both old and new segment names are not valid, give error message : “Segment names are not valid names” and go to step 6.If any of two segments is open, give error message : “Segments are still open” and go to step 6.If new segment name given already exists in the display list, give error message : “Segment name already exists” and go to step 6.The old segment table entry are copied into new position.Delete the old segment.Stop."
},
{
"code": null,
"e": 11674,
"s": 11550,
"text": "If both old and new segment names are not valid, give error message : “Segment names are not valid names” and go to step 6."
},
{
"code": null,
"e": 11771,
"s": 11674,
"text": "If any of two segments is open, give error message : “Segments are still open” and go to step 6."
},
{
"code": null,
"e": 11902,
"s": 11771,
"text": "If new segment name given already exists in the display list, give error message : “Segment name already exists” and go to step 6."
},
{
"code": null,
"e": 11960,
"s": 11902,
"text": "The old segment table entry are copied into new position."
},
{
"code": null,
"e": 11984,
"s": 11960,
"text": "Delete the old segment."
},
{
"code": null,
"e": 11990,
"s": 11984,
"text": "Stop."
},
{
"code": null,
"e": 12030,
"s": 11990,
"text": "Advantages of using segmented display :"
},
{
"code": null,
"e": 12102,
"s": 12030,
"text": "Segmentation allows to organize display files in sub-picture structure."
},
{
"code": null,
"e": 12181,
"s": 12102,
"text": "It allows to apply different set of attributes to different portions of image."
},
{
"code": null,
"e": 12247,
"s": 12181,
"text": "It makes it easier to the picture by changing/replacing segments."
},
{
"code": null,
"e": 12319,
"s": 12247,
"text": "It allows application of transformation on selective portions of image."
},
{
"code": null,
"e": 12337,
"s": 12319,
"text": "computer-graphics"
},
{
"code": null,
"e": 12363,
"s": 12337,
"text": "Advanced Computer Subject"
}
] |
C++ Program to Find Fibonacci Numbers using Dynamic Programming | The Fibonacci sequence is like this,
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,......
In this sequence the nth term is the sum of (n-1)th and (n-2)th terms.
To generate we can use the recursive approach, but in dynamic programming the procedure is simpler. It can store all Fibonacci numbers in a table, by using that table it can easily generate the next terms in this sequence.
Input − Take the term number as an input. Say it is 10
Output − The 10th fibinacci term is 55
Input
max number of terms.
Output
The nth Fibonacci term.
Begin
define array named fibo of size n+2
fibo[0] := 0
fibo[1] := 1
for i := 2 to n, do
fibo[i] := fibo[i-1] + fibo[i-2]
done
return fibo[n]
End
#include<iostream>
using namespace std;
int genFibonacci(int n) {
int fibo[n+2]; //array to store fibonacci values
// 0th and 1st number of the series are 0 and 1
fibo[0] = 0;
fibo[1] = 1;
for (int i = 2; i <= n; i++) {
fibo[i] = fibo[i-1] + fibo[i-2]; //generate ith term using previous
two terms
}
return fibo[n];
}
int main () {
int n;
cout << "Enter number of terms: "; cin >>n;
cout << n<<" th Fibonacci Terms: "<<genFibonacci(n)<<endl;
}
Enter number of terms: 10
10th Fibonacci Terms: 55 | [
{
"code": null,
"e": 1224,
"s": 1187,
"text": "The Fibonacci sequence is like this,"
},
{
"code": null,
"e": 1267,
"s": 1224,
"text": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,......"
},
{
"code": null,
"e": 1338,
"s": 1267,
"text": "In this sequence the nth term is the sum of (n-1)th and (n-2)th terms."
},
{
"code": null,
"e": 1561,
"s": 1338,
"text": "To generate we can use the recursive approach, but in dynamic programming the procedure is simpler. It can store all Fibonacci numbers in a table, by using that table it can easily generate the next terms in this sequence."
},
{
"code": null,
"e": 1616,
"s": 1561,
"text": "Input − Take the term number as an input. Say it is 10"
},
{
"code": null,
"e": 1655,
"s": 1616,
"text": "Output − The 10th fibinacci term is 55"
},
{
"code": null,
"e": 1661,
"s": 1655,
"text": "Input"
},
{
"code": null,
"e": 1682,
"s": 1661,
"text": "max number of terms."
},
{
"code": null,
"e": 1689,
"s": 1682,
"text": "Output"
},
{
"code": null,
"e": 1713,
"s": 1689,
"text": "The nth Fibonacci term."
},
{
"code": null,
"e": 1858,
"s": 1713,
"text": "Begin\ndefine array named fibo of size n+2\nfibo[0] := 0\nfibo[1] := 1\nfor i := 2 to n, do\nfibo[i] := fibo[i-1] + fibo[i-2]\ndone\nreturn fibo[n]\nEnd"
},
{
"code": null,
"e": 2344,
"s": 1858,
"text": "#include<iostream>\nusing namespace std;\nint genFibonacci(int n) {\n int fibo[n+2]; //array to store fibonacci values\n // 0th and 1st number of the series are 0 and 1\n fibo[0] = 0;\n fibo[1] = 1;\n for (int i = 2; i <= n; i++) {\n fibo[i] = fibo[i-1] + fibo[i-2]; //generate ith term using previous\n two terms\n }\n return fibo[n];\n}\nint main () {\n int n;\n cout << \"Enter number of terms: \"; cin >>n;\n cout << n<<\" th Fibonacci Terms: \"<<genFibonacci(n)<<endl;\n}"
},
{
"code": null,
"e": 2395,
"s": 2344,
"text": "Enter number of terms: 10\n10th Fibonacci Terms: 55"
}
] |
Class isInstance() method in Java with Examples | 27 Nov, 2019
The isInstance() method of java.lang.Class class is used to check if the specified object is compatible to be assigned to the instance of this Class. The method returns true if the specified object is non-null and can be cast to the instance of this Class. It returns false otherwise.
Syntax:
public boolean isInstance(Object object)
Parameter: This method accepts object as parameter which is the specified object to checked for compatibility to this Class instance.
Return Value: This method returns true if the specified object is non-null and can be cast to the instance of this Class. It returns false otherwise.
Below programs demonstrate the isInstance() method.
Example 1:
// Java program to demonstrate isInstance() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // get the Class instance using forName() method Class c = Class.forName("java.lang.String"); System.out.println("Class represented by c: " + c.toString()); // Check if object c is compatible // using isInstance() method System.out.println("Is c compatible: " + myClass.isInstance(c)); }}
Class represented by myClass: class Test
Class represented by c: class java.lang.String
Is c compatible: false
Example 2:
// Java program to demonstrate isInstance() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // get the Class instance using forName() method Class c = Class.forName("Test"); System.out.println("Class represented by c: " + c.toString()); // Check if object c is compatible // using isInstance() method System.out.println("Is c compatible: " + myClass.isInstance(c)); }}
Class represented by myClass: class Test
Class represented by c: class Test
Is c compatible: false
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#isInstance-java.lang.Object-
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Nov, 2019"
},
{
"code": null,
"e": 313,
"s": 28,
"text": "The isInstance() method of java.lang.Class class is used to check if the specified object is compatible to be assigned to the instance of this Class. The method returns true if the specified object is non-null and can be cast to the instance of this Class. It returns false otherwise."
},
{
"code": null,
"e": 321,
"s": 313,
"text": "Syntax:"
},
{
"code": null,
"e": 363,
"s": 321,
"text": "public boolean isInstance(Object object)\n"
},
{
"code": null,
"e": 497,
"s": 363,
"text": "Parameter: This method accepts object as parameter which is the specified object to checked for compatibility to this Class instance."
},
{
"code": null,
"e": 647,
"s": 497,
"text": "Return Value: This method returns true if the specified object is non-null and can be cast to the instance of this Class. It returns false otherwise."
},
{
"code": null,
"e": 699,
"s": 647,
"text": "Below programs demonstrate the isInstance() method."
},
{
"code": null,
"e": 710,
"s": 699,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate isInstance() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // get the Class instance using forName() method Class c = Class.forName(\"java.lang.String\"); System.out.println(\"Class represented by c: \" + c.toString()); // Check if object c is compatible // using isInstance() method System.out.println(\"Is c compatible: \" + myClass.isInstance(c)); }}",
"e": 1466,
"s": 710,
"text": null
},
{
"code": null,
"e": 1578,
"s": 1466,
"text": "Class represented by myClass: class Test\nClass represented by c: class java.lang.String\nIs c compatible: false\n"
},
{
"code": null,
"e": 1589,
"s": 1578,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate isInstance() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // get the Class instance using forName() method Class c = Class.forName(\"Test\"); System.out.println(\"Class represented by c: \" + c.toString()); // Check if object c is compatible // using isInstance() method System.out.println(\"Is c compatible: \" + myClass.isInstance(c)); }}",
"e": 2333,
"s": 1589,
"text": null
},
{
"code": null,
"e": 2433,
"s": 2333,
"text": "Class represented by myClass: class Test\nClass represented by c: class Test\nIs c compatible: false\n"
},
{
"code": null,
"e": 2536,
"s": 2433,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#isInstance-java.lang.Object-"
},
{
"code": null,
"e": 2551,
"s": 2536,
"text": "Java-Functions"
},
{
"code": null,
"e": 2569,
"s": 2551,
"text": "Java-lang package"
},
{
"code": null,
"e": 2585,
"s": 2569,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 2590,
"s": 2585,
"text": "Java"
},
{
"code": null,
"e": 2595,
"s": 2590,
"text": "Java"
}
] |
Python | filecmp.cmpfiles() method | 19 Mar, 2022
Filecmp module in Python provides functions to compare files and directories. This module comes under Python’s standard utility modules. This module also consider the properties of files and directories for comparison in addition to data in them.filecmp.cmpfiles() method in Python is used to compare files in two directories. Multiple files can be compared using this method. This method returns three lists of file names namely match, mismatch and errors. The match list contains the list of files that matched on comparison, the mismatch list contains the names of those files that don’t, and the errors lists contains the names of files which could not be compared.This method by default performs shallow comparison (as by default shallow = True) that means only the os.stat() signatures (like size, date modified etc.) of files are compared and if they have identical signatures then files are considered to be equal irrespective of contents of the files. If shallow is set to False then the comparison is done by comparing the contents of the files.
Syntax: filecmp.cmpfiles(dir1, dir2, common, shallow = True) Parameter: dir1: The path of first directory. It can be a string, bytes or os.PathLike object representing the path of the directory. dir2: The path of second directory. It can be a string, bytes or os.PathLike object representing the path of the directory. common: A list representing the names of the files that will be compared in dir1 and dir2. shallow (optional): A bool value ‘True’ or ‘False’. The default value of this parameter is True. If its value is True then only the metadata of files are compared. If False then the contents of the files are compared.Return Type: This method returns a tuple of three lists which represents match, mismatch and errors lists.
For Example:
filecmp.cmpfiles(dir1, dir2, [file1, file2, fil3]) will compare dir1/file1 with dir2/file1, dir1/file2 with dir2/file2 and dir1/file3 with dir2/file3 and will return match, mismatch and errors list.
Example: Use of filecmp.cmpfiles() method to compare files in two directories.
Python3
# Python program to explain filecmp.cmpfiles() method # importing filecmp moduleimport filecmp # Path of first directorydir1 = "/home / User / Documents" # Path of second directorydir2 = "/home / User / Desktop" # Common filescommon = ["file1.txt", "file2.txt", "file3.txt"] # Shallow compare the files# common in both directories match, mismatch, errors = filecmp.cmpfiles(dir1, dir2, common) # Print the result of# shallow comparisonprint("Shallow comparison:")print("Match :", match)print("Mismatch :", mismatch)print("Errors :", errors, "\n") # Compare the# contents of both files# (i.e deep comparison)match, mismatch, errors = filecmp.cmpfiles(dir1, dir2, common, shallow = False) # Print the result of# deep comparisonprint("Deep comparison:")print("Match :", match)print("Mismatch :", mismatch)print("Errors :", errors)
Shallow comparison:
Match : ['file1.txt', 'file2.txt', 'file3.txt']
Mismatch : []
Errors : []
Deep comparison:
Match : ['file1.txt', 'file2.txt']
Mismatch : ['file3.txt']
Errors : []
thechosenone
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Mar, 2022"
},
{
"code": null,
"e": 1086,
"s": 28,
"text": "Filecmp module in Python provides functions to compare files and directories. This module comes under Python’s standard utility modules. This module also consider the properties of files and directories for comparison in addition to data in them.filecmp.cmpfiles() method in Python is used to compare files in two directories. Multiple files can be compared using this method. This method returns three lists of file names namely match, mismatch and errors. The match list contains the list of files that matched on comparison, the mismatch list contains the names of those files that don’t, and the errors lists contains the names of files which could not be compared.This method by default performs shallow comparison (as by default shallow = True) that means only the os.stat() signatures (like size, date modified etc.) of files are compared and if they have identical signatures then files are considered to be equal irrespective of contents of the files. If shallow is set to False then the comparison is done by comparing the contents of the files. "
},
{
"code": null,
"e": 1822,
"s": 1086,
"text": "Syntax: filecmp.cmpfiles(dir1, dir2, common, shallow = True) Parameter: dir1: The path of first directory. It can be a string, bytes or os.PathLike object representing the path of the directory. dir2: The path of second directory. It can be a string, bytes or os.PathLike object representing the path of the directory. common: A list representing the names of the files that will be compared in dir1 and dir2. shallow (optional): A bool value ‘True’ or ‘False’. The default value of this parameter is True. If its value is True then only the metadata of files are compared. If False then the contents of the files are compared.Return Type: This method returns a tuple of three lists which represents match, mismatch and errors lists. "
},
{
"code": null,
"e": 1836,
"s": 1822,
"text": "For Example: "
},
{
"code": null,
"e": 2037,
"s": 1836,
"text": "filecmp.cmpfiles(dir1, dir2, [file1, file2, fil3]) will compare dir1/file1 with dir2/file1, dir1/file2 with dir2/file2 and dir1/file3 with dir2/file3 and will return match, mismatch and errors list. "
},
{
"code": null,
"e": 2117,
"s": 2037,
"text": "Example: Use of filecmp.cmpfiles() method to compare files in two directories. "
},
{
"code": null,
"e": 2125,
"s": 2117,
"text": "Python3"
},
{
"code": "# Python program to explain filecmp.cmpfiles() method # importing filecmp moduleimport filecmp # Path of first directorydir1 = \"/home / User / Documents\" # Path of second directorydir2 = \"/home / User / Desktop\" # Common filescommon = [\"file1.txt\", \"file2.txt\", \"file3.txt\"] # Shallow compare the files# common in both directories match, mismatch, errors = filecmp.cmpfiles(dir1, dir2, common) # Print the result of# shallow comparisonprint(\"Shallow comparison:\")print(\"Match :\", match)print(\"Mismatch :\", mismatch)print(\"Errors :\", errors, \"\\n\") # Compare the# contents of both files# (i.e deep comparison)match, mismatch, errors = filecmp.cmpfiles(dir1, dir2, common, shallow = False) # Print the result of# deep comparisonprint(\"Deep comparison:\")print(\"Match :\", match)print(\"Mismatch :\", mismatch)print(\"Errors :\", errors)",
"e": 3002,
"s": 2125,
"text": null
},
{
"code": null,
"e": 3188,
"s": 3002,
"text": "Shallow comparison:\nMatch : ['file1.txt', 'file2.txt', 'file3.txt']\nMismatch : []\nErrors : [] \n\nDeep comparison:\nMatch : ['file1.txt', 'file2.txt']\nMismatch : ['file3.txt']\nErrors : []"
},
{
"code": null,
"e": 3203,
"s": 3190,
"text": "thechosenone"
},
{
"code": null,
"e": 3218,
"s": 3203,
"text": "python-utility"
},
{
"code": null,
"e": 3225,
"s": 3218,
"text": "Python"
},
{
"code": null,
"e": 3323,
"s": 3225,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3341,
"s": 3323,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3383,
"s": 3341,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3405,
"s": 3383,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3440,
"s": 3405,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3466,
"s": 3440,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3498,
"s": 3466,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3527,
"s": 3498,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3554,
"s": 3527,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3584,
"s": 3554,
"text": "Iterate over a list in Python"
}
] |
ReactJS | Implementing State & Lifecycle | 22 Jan, 2021
We have seen so far what a React web-app is, the states and lifecycle of a React component. We also created a basic clock using a function to re-render the page at each second which if you think can be achieved with or without React. React doesn’t recommend using multiple renders instead it uses a stateful approach where the page is re-rendered once a state is altered. Our aim for this article will be to take up the code we had written in the previous article, and create a stateful solution that will help us achieve the same result. To start let us recall what we had developed in the previous article,
Open your react project directory and edit the Index.js file from src folder:
src index.js:
javascript
import React from 'react';import ReactDOM from 'react-dom'; function showTime(){const myElement = ( <div> <h1>Welcome to GeeksforGeeks!</h1> <h2>{new Date().toLocaleTimeString()}</h2> </div> ); ReactDOM.render( myElement, document.getElementById("root")); } setInterval(showTime, 1000)
Now what is the component in the above example ? Actually, if you pay attention there is no component whatsoever. We are assigning a nested JSX element named “myElement” to contain the latest time and rendering the same every second, which is one of the worst ways to implement using React. Now we will start to implement it using the state and lifecycle methods which will require a classful component, let us start by creating one beforehand.
Open your react project directory and edit the Index.js file from src folder:
src index.js:
javascript
import React from 'react';import ReactDOM from 'react-dom'; class Clock extends React.Component {}
Now that we have defined the class to be “Clock” we must think of the process first. “Props” is the set of attributes that rarely change while “State” is the set of observable attributes that are supposed to change over time. Now if we think about our own situation, our clock has exactly two parts one is the title that says “Welcome to GeeksforGeeks!” this should be implemented using props as it will not be changing throughout the lifetime; the other part is the time itself that should be changed at each second. Let us just use the constructor and render method to first create the backbone method to show the title and time without updating it at regular intervals.
javascript
import React from 'react';import ReactDOM from 'react-dom'; class Clock extends React.Component { constructor(props) { super(props); this.state = { time : new Date() }; } render() { return ( <div><h1>Welcome to { this.props.title } !</h1> <h2>{this.state.time}</h2></div> ); }} ReactDOM.render( <Clock title="GeeksforGeeks" />, document.getElementById('root'));
Now that we have created our own component Clock and have rendered what we require, we only need to figure out a way of updating the time each second. Now it is clear that we have to set an interval to update the state at each second and this should be done as soon as the clock component is mounted. Thus, we have to use a lifecycle function componentDidMount() where we will set an interval to update the state, and to make the app efficient we will use componentWillUnmount() method to clear the interval. Let us see the following implementation.
Open your react project directory and edit the Index.js file from src folder:
src index.js:
javascript
import React from 'react';import ReactDOM from 'react-dom'; class Clock extends React.Component { constructor(props) { super(props); this.state = { time : new Date() }; } // As soon as the Clock is mounted. // Start the interval "timer". // Call tick() every second. componentDidMount() { this.timer = setInterval( () => this.tick(), 1000); } // Before unmounting the Clock, // Clear the interval "Timer" // This step is a memory efficient step. componentWillUnmount() { clearInterval(this.timer); } // This function updates the state, // invokes re-render at each second. tick() { this.setState({ time : new Date() }); } render() { return ( <div><h1>Welcome to { this.props.title } !</h1> <h2>{this.state.time.toLocaleTimeString()}</h2></div> ); }} ReactDOM.render( <Clock title="GeeksforGeeks" />, document.getElementById('root'));
Congratulations! You just created a React web app using States, Props, and some lifecycle methods. You might be asking is that all? No, it isn’t even a nibble of the whole platter stay tuned for the upcoming articles where we dive deeper into React and create some more projects on the go.
shubhamyadav4
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 663,
"s": 54,
"text": "We have seen so far what a React web-app is, the states and lifecycle of a React component. We also created a basic clock using a function to re-render the page at each second which if you think can be achieved with or without React. React doesn’t recommend using multiple renders instead it uses a stateful approach where the page is re-rendered once a state is altered. Our aim for this article will be to take up the code we had written in the previous article, and create a stateful solution that will help us achieve the same result. To start let us recall what we had developed in the previous article,"
},
{
"code": null,
"e": 741,
"s": 663,
"text": "Open your react project directory and edit the Index.js file from src folder:"
},
{
"code": null,
"e": 756,
"s": 741,
"text": "src index.js: "
},
{
"code": null,
"e": 767,
"s": 756,
"text": "javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom'; function showTime(){const myElement = ( <div> <h1>Welcome to GeeksforGeeks!</h1> <h2>{new Date().toLocaleTimeString()}</h2> </div> ); ReactDOM.render( myElement, document.getElementById(\"root\")); } setInterval(showTime, 1000)",
"e": 1182,
"s": 767,
"text": null
},
{
"code": null,
"e": 1628,
"s": 1182,
"text": "Now what is the component in the above example ? Actually, if you pay attention there is no component whatsoever. We are assigning a nested JSX element named “myElement” to contain the latest time and rendering the same every second, which is one of the worst ways to implement using React. Now we will start to implement it using the state and lifecycle methods which will require a classful component, let us start by creating one beforehand. "
},
{
"code": null,
"e": 1706,
"s": 1628,
"text": "Open your react project directory and edit the Index.js file from src folder:"
},
{
"code": null,
"e": 1721,
"s": 1706,
"text": "src index.js: "
},
{
"code": null,
"e": 1732,
"s": 1721,
"text": "javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom'; class Clock extends React.Component {}",
"e": 1831,
"s": 1732,
"text": null
},
{
"code": null,
"e": 2506,
"s": 1831,
"text": "Now that we have defined the class to be “Clock” we must think of the process first. “Props” is the set of attributes that rarely change while “State” is the set of observable attributes that are supposed to change over time. Now if we think about our own situation, our clock has exactly two parts one is the title that says “Welcome to GeeksforGeeks!” this should be implemented using props as it will not be changing throughout the lifetime; the other part is the time itself that should be changed at each second. Let us just use the constructor and render method to first create the backbone method to show the title and time without updating it at regular intervals. "
},
{
"code": null,
"e": 2517,
"s": 2506,
"text": "javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom'; class Clock extends React.Component { constructor(props) { super(props); this.state = { time : new Date() }; } render() { return ( <div><h1>Welcome to { this.props.title } !</h1> <h2>{this.state.time}</h2></div> ); }} ReactDOM.render( <Clock title=\"GeeksforGeeks\" />, document.getElementById('root'));",
"e": 2950,
"s": 2517,
"text": null
},
{
"code": null,
"e": 3501,
"s": 2950,
"text": "Now that we have created our own component Clock and have rendered what we require, we only need to figure out a way of updating the time each second. Now it is clear that we have to set an interval to update the state at each second and this should be done as soon as the clock component is mounted. Thus, we have to use a lifecycle function componentDidMount() where we will set an interval to update the state, and to make the app efficient we will use componentWillUnmount() method to clear the interval. Let us see the following implementation. "
},
{
"code": null,
"e": 3579,
"s": 3501,
"text": "Open your react project directory and edit the Index.js file from src folder:"
},
{
"code": null,
"e": 3594,
"s": 3579,
"text": "src index.js: "
},
{
"code": null,
"e": 3605,
"s": 3594,
"text": "javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom'; class Clock extends React.Component { constructor(props) { super(props); this.state = { time : new Date() }; } // As soon as the Clock is mounted. // Start the interval \"timer\". // Call tick() every second. componentDidMount() { this.timer = setInterval( () => this.tick(), 1000); } // Before unmounting the Clock, // Clear the interval \"Timer\" // This step is a memory efficient step. componentWillUnmount() { clearInterval(this.timer); } // This function updates the state, // invokes re-render at each second. tick() { this.setState({ time : new Date() }); } render() { return ( <div><h1>Welcome to { this.props.title } !</h1> <h2>{this.state.time.toLocaleTimeString()}</h2></div> ); }} ReactDOM.render( <Clock title=\"GeeksforGeeks\" />, document.getElementById('root'));",
"e": 4625,
"s": 3605,
"text": null
},
{
"code": null,
"e": 4916,
"s": 4625,
"text": "Congratulations! You just created a React web app using States, Props, and some lifecycle methods. You might be asking is that all? No, it isn’t even a nibble of the whole platter stay tuned for the upcoming articles where we dive deeper into React and create some more projects on the go. "
},
{
"code": null,
"e": 4930,
"s": 4916,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 4939,
"s": 4930,
"text": "react-js"
},
{
"code": null,
"e": 4956,
"s": 4939,
"text": "Web Technologies"
},
{
"code": null,
"e": 5054,
"s": 4956,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5087,
"s": 5054,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5149,
"s": 5087,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5210,
"s": 5149,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5260,
"s": 5210,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5303,
"s": 5260,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 5343,
"s": 5303,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5367,
"s": 5343,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 5400,
"s": 5367,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 5460,
"s": 5400,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
SAS | Delete Empty Rows | 30 Jul, 2019
Generally, when we import data from external sources such as Excel/CSV files, it loads additional rows that are totally blank. Sometimes empty values in the database also affect the desired output so it’s necessary to check missing cases and perform operations accordingly
Example:Input: The sample dataset looks like below have four variables – 1 character and 3 numeric. It would be used further in the example to demonstrate how to remove empty rows.
Create a SAS datasetThe below defined code is a sample dataset to perform delete empty operation.
data outdata;LENGTH name $12.;input name $ phys chem maths ;infile datalines missover;datalines;Shubhash 70 68 66 samar 55 . 85 ashutosh 54 78 89 varun 50 96 85 pratiksha . 68 93 ;run;
Output:
Method I: Removes complete row where all variables having blank/missing valuesOPTIONS missing = ' ';data readin; SET outdata; IF missing(cats(of _all_)) THEN DELETE;run;Note:The MISSING= system option is used to display the missing values as a single space rather than as the default period (.) options missing = ‘ ‘;The CATS function concatenates the values. It also removes leading and trailing blanks. cats(of _all_) – Concatenate all the variablesmissing(cats(of _all_)) – Identifies all the rows in which missing values exist in all the variables.Output:
OPTIONS missing = ' ';data readin; SET outdata; IF missing(cats(of _all_)) THEN DELETE;run;
Note:
The MISSING= system option is used to display the missing values as a single space rather than as the default period (.) options missing = ‘ ‘;
The CATS function concatenates the values. It also removes leading and trailing blanks. cats(of _all_) – Concatenate all the variables
missing(cats(of _all_)) – Identifies all the rows in which missing values exist in all the variables.
Output:
Method II: Removes only that rows where any of the variable has missing/blank valuesdata readin; SET outdata; IF cmiss(of _character_) OR nmiss(of _numeric_) > 0 THEN DELETE;run;In this case, we are using the OR operator to check if any of the variables have missing values. It returns 4 observations. Check out the output below –
data readin; SET outdata; IF cmiss(of _character_) OR nmiss(of _numeric_) > 0 THEN DELETE;run;
In this case, we are using the OR operator to check if any of the variables have missing values. It returns 4 observations. Check out the output below –
SAS Programming
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of Object Oriented Programming
Difference between for and while loop in C, C++, Java
Which Programming Language Should I Choose as a Beginner?
7 Highest Paying Programming Languages For Freelancers in 2022
Exception Handling in C#
Learn C++ Programming Step by Step - A 20 Day Curriculum!
C# | Variables
Top 10 Programming Languages for Blockchain Development
7 Best IDEs For C/C++ Developers in 2022
R - Charts and Graphs | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2019"
},
{
"code": null,
"e": 301,
"s": 28,
"text": "Generally, when we import data from external sources such as Excel/CSV files, it loads additional rows that are totally blank. Sometimes empty values in the database also affect the desired output so it’s necessary to check missing cases and perform operations accordingly"
},
{
"code": null,
"e": 482,
"s": 301,
"text": "Example:Input: The sample dataset looks like below have four variables – 1 character and 3 numeric. It would be used further in the example to demonstrate how to remove empty rows."
},
{
"code": null,
"e": 580,
"s": 482,
"text": "Create a SAS datasetThe below defined code is a sample dataset to perform delete empty operation."
},
{
"code": "data outdata;LENGTH name $12.;input name $ phys chem maths ;infile datalines missover;datalines;Shubhash 70 68 66 samar 55 . 85 ashutosh 54 78 89 varun 50 96 85 pratiksha . 68 93 ;run;",
"e": 780,
"s": 580,
"text": null
},
{
"code": null,
"e": 788,
"s": 780,
"text": "Output:"
},
{
"code": null,
"e": 1364,
"s": 788,
"text": "Method I: Removes complete row where all variables having blank/missing valuesOPTIONS missing = ' ';data readin; SET outdata; IF missing(cats(of _all_)) THEN DELETE;run;Note:The MISSING= system option is used to display the missing values as a single space rather than as the default period (.) options missing = ‘ ‘;The CATS function concatenates the values. It also removes leading and trailing blanks. cats(of _all_) – Concatenate all the variablesmissing(cats(of _all_)) – Identifies all the rows in which missing values exist in all the variables.Output:"
},
{
"code": "OPTIONS missing = ' ';data readin; SET outdata; IF missing(cats(of _all_)) THEN DELETE;run;",
"e": 1472,
"s": 1364,
"text": null
},
{
"code": null,
"e": 1478,
"s": 1472,
"text": "Note:"
},
{
"code": null,
"e": 1622,
"s": 1478,
"text": "The MISSING= system option is used to display the missing values as a single space rather than as the default period (.) options missing = ‘ ‘;"
},
{
"code": null,
"e": 1757,
"s": 1622,
"text": "The CATS function concatenates the values. It also removes leading and trailing blanks. cats(of _all_) – Concatenate all the variables"
},
{
"code": null,
"e": 1859,
"s": 1757,
"text": "missing(cats(of _all_)) – Identifies all the rows in which missing values exist in all the variables."
},
{
"code": null,
"e": 1867,
"s": 1859,
"text": "Output:"
},
{
"code": null,
"e": 2219,
"s": 1867,
"text": "Method II: Removes only that rows where any of the variable has missing/blank valuesdata readin; SET outdata; IF cmiss(of _character_) OR nmiss(of _numeric_) > 0 THEN DELETE;run;In this case, we are using the OR operator to check if any of the variables have missing values. It returns 4 observations. Check out the output below –"
},
{
"code": "data readin; SET outdata; IF cmiss(of _character_) OR nmiss(of _numeric_) > 0 THEN DELETE;run;",
"e": 2335,
"s": 2219,
"text": null
},
{
"code": null,
"e": 2488,
"s": 2335,
"text": "In this case, we are using the OR operator to check if any of the variables have missing values. It returns 4 observations. Check out the output below –"
},
{
"code": null,
"e": 2504,
"s": 2488,
"text": "SAS Programming"
},
{
"code": null,
"e": 2525,
"s": 2504,
"text": "Programming Language"
},
{
"code": null,
"e": 2623,
"s": 2525,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2667,
"s": 2623,
"text": "Introduction of Object Oriented Programming"
},
{
"code": null,
"e": 2721,
"s": 2667,
"text": "Difference between for and while loop in C, C++, Java"
},
{
"code": null,
"e": 2779,
"s": 2721,
"text": "Which Programming Language Should I Choose as a Beginner?"
},
{
"code": null,
"e": 2842,
"s": 2779,
"text": "7 Highest Paying Programming Languages For Freelancers in 2022"
},
{
"code": null,
"e": 2867,
"s": 2842,
"text": "Exception Handling in C#"
},
{
"code": null,
"e": 2925,
"s": 2867,
"text": "Learn C++ Programming Step by Step - A 20 Day Curriculum!"
},
{
"code": null,
"e": 2940,
"s": 2925,
"text": "C# | Variables"
},
{
"code": null,
"e": 2996,
"s": 2940,
"text": "Top 10 Programming Languages for Blockchain Development"
},
{
"code": null,
"e": 3037,
"s": 2996,
"text": "7 Best IDEs For C/C++ Developers in 2022"
}
] |
How To Change facet_wrap() Box Color in ggplot2 in R? | 19 Nov, 2021
In this article, we will discuss how to change facet_wrap() box color in ggplot2 in R Programming language.
Facet plots, where one subsets the data based on a categorical variable and makes a series of similar plots with the same scale. Facetting helps us to show the relationship between more than two categories of data. When you have multiple variables, with faceting it can be plotted in a single plot into smaller plots.
We can easily plot a facetted plot using the facet_wrap() function of the ggplot2 package. When we use facet_wrap() in ggplot2, by default it gives a title in a grey box.
Syntax: plot + facet_wrap( ~facet-variable)
Where:
facet-variable: determines the variable around which plots have to be divided.
Here, is a basic facet plot made using the diamonds data frame which is provided by R Language natively. We have used the facet_wrap() function with ~cut to divide the plot into facets according to their cut.
R
# load library ggridges and tidyverselibrary(ggridges)library(tidyverse) # Basic facet plot divided according to category cut# diamonds data frame is used in plot which# is provided natively by R Language# ggplot() function is used to plot the chartggplot(diamonds, aes(x="price", y="cut", fill="cut")) + # geom_density_ridges() function is used to draw ridgeline plot geom_density_ridges()+ # facet_wrap() function divides the plot in facets according to category of cut facet_wrap(~cut)
Output:
We can customize various aspects of a ggplot2 using the theme() function. To change the default grey fill color in the facet_wrap() title box, we need to use “strip.background” argument inside the theme() layer with color and fill property of element_rect() function.
Syntax: plot + theme( strip.background = element_rect( colour, fill ))
Where:
colour: determines the color of outline of box
fill: determines the color of background fill of box
Example:
In this example, we specified element_rect with yellow fill color and black for box outline color.
R
# load library ggridges and tidyverselibrary(ggridges)library(tidyverse) # ggplot() function is used to plot the chartggplot(diamonds, aes(x="price", y="cut", fill="cut")) + # geom_density_ridges() function is used# to draw ridgeline plotgeom_density_ridges()+ # facet_wrap() function divides the plot in# facets according to category of cutfacet_wrap(~cut)+ # strip.background parameter of theme# function is used to change color of box# color and fill property of element_rect()# function is used for color changetheme(legend.position="none", strip.background=element_rect(colour="black", fill="yellow"))
Output:
simmytarika5
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?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
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": "\n19 Nov, 2021"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "In this article, we will discuss how to change facet_wrap() box color in ggplot2 in R Programming language."
},
{
"code": null,
"e": 454,
"s": 136,
"text": "Facet plots, where one subsets the data based on a categorical variable and makes a series of similar plots with the same scale. Facetting helps us to show the relationship between more than two categories of data. When you have multiple variables, with faceting it can be plotted in a single plot into smaller plots."
},
{
"code": null,
"e": 625,
"s": 454,
"text": "We can easily plot a facetted plot using the facet_wrap() function of the ggplot2 package. When we use facet_wrap() in ggplot2, by default it gives a title in a grey box."
},
{
"code": null,
"e": 669,
"s": 625,
"text": "Syntax: plot + facet_wrap( ~facet-variable)"
},
{
"code": null,
"e": 676,
"s": 669,
"text": "Where:"
},
{
"code": null,
"e": 755,
"s": 676,
"text": "facet-variable: determines the variable around which plots have to be divided."
},
{
"code": null,
"e": 964,
"s": 755,
"text": "Here, is a basic facet plot made using the diamonds data frame which is provided by R Language natively. We have used the facet_wrap() function with ~cut to divide the plot into facets according to their cut."
},
{
"code": null,
"e": 966,
"s": 964,
"text": "R"
},
{
"code": "# load library ggridges and tidyverselibrary(ggridges)library(tidyverse) # Basic facet plot divided according to category cut# diamonds data frame is used in plot which# is provided natively by R Language# ggplot() function is used to plot the chartggplot(diamonds, aes(x=\"price\", y=\"cut\", fill=\"cut\")) + # geom_density_ridges() function is used to draw ridgeline plot geom_density_ridges()+ # facet_wrap() function divides the plot in facets according to category of cut facet_wrap(~cut)",
"e": 1457,
"s": 966,
"text": null
},
{
"code": null,
"e": 1469,
"s": 1461,
"text": "Output:"
},
{
"code": null,
"e": 1741,
"s": 1473,
"text": "We can customize various aspects of a ggplot2 using the theme() function. To change the default grey fill color in the facet_wrap() title box, we need to use “strip.background” argument inside the theme() layer with color and fill property of element_rect() function."
},
{
"code": null,
"e": 1814,
"s": 1743,
"text": "Syntax: plot + theme( strip.background = element_rect( colour, fill ))"
},
{
"code": null,
"e": 1822,
"s": 1814,
"text": "Where: "
},
{
"code": null,
"e": 1869,
"s": 1822,
"text": "colour: determines the color of outline of box"
},
{
"code": null,
"e": 1922,
"s": 1869,
"text": "fill: determines the color of background fill of box"
},
{
"code": null,
"e": 1933,
"s": 1924,
"text": "Example:"
},
{
"code": null,
"e": 2034,
"s": 1935,
"text": "In this example, we specified element_rect with yellow fill color and black for box outline color."
},
{
"code": null,
"e": 2038,
"s": 2036,
"text": "R"
},
{
"code": "# load library ggridges and tidyverselibrary(ggridges)library(tidyverse) # ggplot() function is used to plot the chartggplot(diamonds, aes(x=\"price\", y=\"cut\", fill=\"cut\")) + # geom_density_ridges() function is used# to draw ridgeline plotgeom_density_ridges()+ # facet_wrap() function divides the plot in# facets according to category of cutfacet_wrap(~cut)+ # strip.background parameter of theme# function is used to change color of box# color and fill property of element_rect()# function is used for color changetheme(legend.position=\"none\", strip.background=element_rect(colour=\"black\", fill=\"yellow\"))",
"e": 2685,
"s": 2038,
"text": null
},
{
"code": null,
"e": 2693,
"s": 2685,
"text": "Output:"
},
{
"code": null,
"e": 2706,
"s": 2693,
"text": "simmytarika5"
},
{
"code": null,
"e": 2713,
"s": 2706,
"text": "Picked"
},
{
"code": null,
"e": 2722,
"s": 2713,
"text": "R-ggplot"
},
{
"code": null,
"e": 2733,
"s": 2722,
"text": "R Language"
},
{
"code": null,
"e": 2831,
"s": 2733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2883,
"s": 2831,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2941,
"s": 2883,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2976,
"s": 2941,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3014,
"s": 2976,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3063,
"s": 3014,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3080,
"s": 3063,
"text": "R - if statement"
},
{
"code": null,
"e": 3117,
"s": 3080,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 3160,
"s": 3117,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3197,
"s": 3160,
"text": "How to import an Excel File into R ?"
}
] |
Different Ways To Check Java Version In Windows | 29 Oct, 2020
Java is a programming language that is platform-independent, popular, simple, secure, and statically typed. Before discussing let’s clear Java language needs a runtime platform so before going ahead let’s clear how java is present on the machine.
Java language comprises three components mainly:
Java Development Kit
Java Runtime Environment
Java Virtual Machine
Runtime Concepts than only we will check whether Java is there on the Platform (Operating System + Architecture)
1. Java Virtual Machine
This is a machine–specific software which is responsible for byte code on that machine and converts it into machine-specific instructions.
JVM is different for Windows
JVM is different for Linux
JVM is different for Different Platforms
So as a programmer we don’t need to check presence on the machine as it is pre-installed in the machine. It is responsible for running Java code line by line.
2. Java Runtime Environment
It is simply a package that provides an environment to only run our java code on the machine. No development takes place here because of the absence of developmental tools.
3. Java Development Kit
It is also a package that provides an environment to develop and execute where JRE is a part of it along with developmental tools.
JDK = JRE + Developmental Tools
JRE = JVM + Library Classes
Now, The first and Foremost step is to check the Java Development Kit in Windows which is also known as JDK. There are lots of versions of Java. Depending upon the operating system methods there are several methods to find the version of Installed JAVA on your Machine:
Let us discuss 3 standard methods in Windows
User needs to open Command Prompt and enter- ‘java -version’Open control panel and lookup for JavaDirectories method- Click the Menu ‘Start’ and typing About.java or readme file
User needs to open Command Prompt and enter- ‘java -version’
Open control panel and lookup for Java
Directories method- Click the Menu ‘Start’ and typing About.java or readme file
Taking one by one, showcasing in-depth individually
The CMD (Command Interpreter is a command-line Interface. It supports a set of commands and utilities; and has its own programming language for writing batch files. Open CMD and search java -version. First, we have to an environment variable to the installed path location of the java folder. Otherwise, it will show invalid command. It is called ‘Terminal’ in the case of mac operating systems.
java -version // CMD/Terminal command to check java version on the machine
In the case of Windows OS: It is showing java is installed on the machine with version 1.8.0 (See carefully at line number 5)
“1.8.0_144” is the version of the java
In the case of macOS: It is showing java is installed on the machine with version 14.0.1 ( see carefully at line number 2)
Open Control Panel and there is an option of the java on the interface of the control panel
Click on the java option and click about a small pop window will appear
In the case of Windows:
In the case of Mac: Click on the Java icon downside. System preferences in mac are the same as the Control panel in Windows.
Search Program and features in the control panel and search JAVA Named option
In the case of Windows: Simply custom search- About Java
In the case of Mac:
Press the command button followed by a spacebar without lifting fingers from the command button.
A popup box will appear for less than a second followed by another pop-up as shown below:
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
Initialize an ArrayList in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Oct, 2020"
},
{
"code": null,
"e": 275,
"s": 28,
"text": "Java is a programming language that is platform-independent, popular, simple, secure, and statically typed. Before discussing let’s clear Java language needs a runtime platform so before going ahead let’s clear how java is present on the machine."
},
{
"code": null,
"e": 324,
"s": 275,
"text": "Java language comprises three components mainly:"
},
{
"code": null,
"e": 345,
"s": 324,
"text": "Java Development Kit"
},
{
"code": null,
"e": 370,
"s": 345,
"text": "Java Runtime Environment"
},
{
"code": null,
"e": 393,
"s": 370,
"text": "Java Virtual Machine "
},
{
"code": null,
"e": 506,
"s": 393,
"text": "Runtime Concepts than only we will check whether Java is there on the Platform (Operating System + Architecture)"
},
{
"code": null,
"e": 530,
"s": 506,
"text": "1. Java Virtual Machine"
},
{
"code": null,
"e": 669,
"s": 530,
"text": "This is a machine–specific software which is responsible for byte code on that machine and converts it into machine-specific instructions."
},
{
"code": null,
"e": 768,
"s": 669,
"text": "JVM is different for Windows \nJVM is different for Linux\nJVM is different for Different Platforms\n"
},
{
"code": null,
"e": 927,
"s": 768,
"text": "So as a programmer we don’t need to check presence on the machine as it is pre-installed in the machine. It is responsible for running Java code line by line."
},
{
"code": null,
"e": 955,
"s": 927,
"text": "2. Java Runtime Environment"
},
{
"code": null,
"e": 1128,
"s": 955,
"text": "It is simply a package that provides an environment to only run our java code on the machine. No development takes place here because of the absence of developmental tools."
},
{
"code": null,
"e": 1153,
"s": 1128,
"text": "3. Java Development Kit "
},
{
"code": null,
"e": 1284,
"s": 1153,
"text": "It is also a package that provides an environment to develop and execute where JRE is a part of it along with developmental tools."
},
{
"code": null,
"e": 1316,
"s": 1284,
"text": "JDK = JRE + Developmental Tools"
},
{
"code": null,
"e": 1344,
"s": 1316,
"text": "JRE = JVM + Library Classes"
},
{
"code": null,
"e": 1614,
"s": 1344,
"text": "Now, The first and Foremost step is to check the Java Development Kit in Windows which is also known as JDK. There are lots of versions of Java. Depending upon the operating system methods there are several methods to find the version of Installed JAVA on your Machine:"
},
{
"code": null,
"e": 1659,
"s": 1614,
"text": "Let us discuss 3 standard methods in Windows"
},
{
"code": null,
"e": 1837,
"s": 1659,
"text": "User needs to open Command Prompt and enter- ‘java -version’Open control panel and lookup for JavaDirectories method- Click the Menu ‘Start’ and typing About.java or readme file"
},
{
"code": null,
"e": 1898,
"s": 1837,
"text": "User needs to open Command Prompt and enter- ‘java -version’"
},
{
"code": null,
"e": 1937,
"s": 1898,
"text": "Open control panel and lookup for Java"
},
{
"code": null,
"e": 2017,
"s": 1937,
"text": "Directories method- Click the Menu ‘Start’ and typing About.java or readme file"
},
{
"code": null,
"e": 2069,
"s": 2017,
"text": "Taking one by one, showcasing in-depth individually"
},
{
"code": null,
"e": 2465,
"s": 2069,
"text": "The CMD (Command Interpreter is a command-line Interface. It supports a set of commands and utilities; and has its own programming language for writing batch files. Open CMD and search java -version. First, we have to an environment variable to the installed path location of the java folder. Otherwise, it will show invalid command. It is called ‘Terminal’ in the case of mac operating systems."
},
{
"code": null,
"e": 2542,
"s": 2465,
"text": "java -version // CMD/Terminal command to check java version on the machine\n"
},
{
"code": null,
"e": 2668,
"s": 2542,
"text": "In the case of Windows OS: It is showing java is installed on the machine with version 1.8.0 (See carefully at line number 5)"
},
{
"code": null,
"e": 2708,
"s": 2668,
"text": "“1.8.0_144” is the version of the java"
},
{
"code": null,
"e": 2831,
"s": 2708,
"text": "In the case of macOS: It is showing java is installed on the machine with version 14.0.1 ( see carefully at line number 2)"
},
{
"code": null,
"e": 2923,
"s": 2831,
"text": "Open Control Panel and there is an option of the java on the interface of the control panel"
},
{
"code": null,
"e": 2995,
"s": 2923,
"text": "Click on the java option and click about a small pop window will appear"
},
{
"code": null,
"e": 3019,
"s": 2995,
"text": "In the case of Windows:"
},
{
"code": null,
"e": 3147,
"s": 3021,
"text": "In the case of Mac: Click on the Java icon downside. System preferences in mac are the same as the Control panel in Windows. "
},
{
"code": null,
"e": 3227,
"s": 3149,
"text": "Search Program and features in the control panel and search JAVA Named option"
},
{
"code": null,
"e": 3284,
"s": 3227,
"text": "In the case of Windows: Simply custom search- About Java"
},
{
"code": null,
"e": 3307,
"s": 3286,
"text": "In the case of Mac: "
},
{
"code": null,
"e": 3404,
"s": 3307,
"text": "Press the command button followed by a spacebar without lifting fingers from the command button."
},
{
"code": null,
"e": 3494,
"s": 3404,
"text": "A popup box will appear for less than a second followed by another pop-up as shown below:"
},
{
"code": null,
"e": 3508,
"s": 3496,
"text": "java-basics"
},
{
"code": null,
"e": 3513,
"s": 3508,
"text": "Java"
},
{
"code": null,
"e": 3518,
"s": 3513,
"text": "Java"
},
{
"code": null,
"e": 3616,
"s": 3518,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3635,
"s": 3616,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3665,
"s": 3635,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3680,
"s": 3665,
"text": "Stream In Java"
},
{
"code": null,
"e": 3698,
"s": 3680,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3718,
"s": 3698,
"text": "Collections in Java"
},
{
"code": null,
"e": 3742,
"s": 3718,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3774,
"s": 3742,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3786,
"s": 3774,
"text": "Set in Java"
},
{
"code": null,
"e": 3806,
"s": 3786,
"text": "Stack Class in Java"
}
] |
Python Bokeh – Visualizing the Iris Dataset | 03 Jul, 2020
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity.
Bokeh can be used to visualize the Iris flower dataset. Visualization is be done using the plotting module. Here we will be using the Iris dataset given to us by Bokeh.
To download the Iris dataset run the following command on the command line :
bokeh sampledata
Alternatively, we can also execute the following Python code :
import bokeh
bokeh.sampledata.download()
In the sample data provided by Bokeh, there is a file iris.csv, this is the Iris dataset. Below is a glimpse into the iris.csv file :
sepal_length sepal_width petal_length petal_width species
5.1 3.5 1.4 0.2 setosa
4.9 3 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5 3.6 1.4 0.2 setosa
The dataset contains 5 attributes which are :
sepal_length in cm
sepal_width in cm
petal_length in cm
petal_width in cm
species has 3 types of flower species :setosaversicolorvirginica
setosa
versicolor
virginica
Each species has 50 records and the total entries are 150.
We will be plotting graphs to visualize the clustering of the data for all the 3 species.
Example 1 : Here will be plotting a graph with length of petals as the x-axis and breadth of petals as the y-axis.
Import the required modules :figure, output_file and show from bokeh.plottingflowers from bokeh.sampledata.irisInstantiate a figure object with the title.Give the names to x-axis and y-axis.Plot the graphs for all the 3 species.Display the model.
Import the required modules :figure, output_file and show from bokeh.plottingflowers from bokeh.sampledata.iris
figure, output_file and show from bokeh.plotting
flowers from bokeh.sampledata.iris
Instantiate a figure object with the title.
Give the names to x-axis and y-axis.
Plot the graphs for all the 3 species.
Display the model.
# importing the modulesfrom bokeh.sampledata.iris import flowersfrom bokeh.plotting import figure, show, output_file # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Iris Visualization") # labeling the x-axis and the y-axisgraph.xaxis.axis_label = "Petal Length (in cm)"graph.yaxis.axis_label = "Petal Width (in cm)" # plotting for setosa petalsx = flowers[flowers["species"] == "setosa"]["petal_length"]y = flowers[flowers["species"] == "setosa"]["petal_width"]color = "blue"legend_label = "setosa petals"graph.circle(x, y, color = color, legend_label = legend_label) # plotting for versicolor petalsx = flowers[flowers["species"] == "versicolor"]["petal_length"]y = flowers[flowers["species"] == "versicolor"]["petal_width"]color = "yellow"legend_label = "versicolor petals"graph.circle(x, y, color = color, legend_label = legend_label) # plotting for virginica petalsx = flowers[flowers["species"] == "virginica"]["petal_length"]y = flowers[flowers["species"] == "virginica"]["petal_width"]color = "red"legend_label = "virginica petals"graph.circle(x, y, color = color, legend_label = legend_label) # relocating the legend table to # avoid abstruction of the graphgraph.legend.location = "top_left" # displaying the modelshow(graph)
Output :
Example 2 : Here will be plotting a scatter plot graph with both sepals and petals with length as the x-axis and breadth as the y-axis.
Import the required modules :figure, output_file and show from bokeh.plottingflowers from bokeh.sampledata.irisInstantiate a figure object with the title.Give the names to x-axis and y-axis.Plot the graphs for all the 3 species.Display the model.
Import the required modules :figure, output_file and show from bokeh.plottingflowers from bokeh.sampledata.iris
figure, output_file and show from bokeh.plotting
flowers from bokeh.sampledata.iris
Instantiate a figure object with the title.
Give the names to x-axis and y-axis.
Plot the graphs for all the 3 species.
Display the model.
# importing the modulesfrom bokeh.sampledata.iris import flowersfrom bokeh.plotting import figure, show, output_file # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Iris Visualization") # labeling the x-axis and the y-axisgraph.xaxis.axis_label = "Length (in cm)"graph.yaxis.axis_label = "Width (in cm)" # plotting for setosa petalsx = flowers[flowers["species"] == "setosa"]["petal_length"]y = flowers[flowers["species"] == "setosa"]["petal_width"]marker = "circle_cross"line_color = "blue"fill_color = "lightblue"fill_alpha = 0.4size = 10legend_label = "setosa petals"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # plotting for setosa sepalsx = flowers[flowers["species"] == "setosa"]["sepal_length"]y = flowers[flowers["species"] == "setosa"]["sepal_width"]marker = "square_cross"line_color = "blue"fill_color = "lightblue"fill_alpha = 0.4size = 10legend_label = "setosa sepals"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # plotting for versicolor petalsx = flowers[flowers["species"] == "versicolor"]["petal_length"]y = flowers[flowers["species"] == "versicolor"]["petal_width"]marker = "circle_cross"line_color = "yellow"fill_color = "lightyellow"fill_alpha = 0.4size = 10legend_label = "versicolor petals"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # plotting for versicolor sepalsx = flowers[flowers["species"] == "versicolor"]["sepal_length"]y = flowers[flowers["species"] == "versicolor"]["sepal_width"]marker = "square_cross"line_color = "yellow"fill_color = "lightyellow"fill_alpha = 0.4size = 10legend_label = "versicolor sepals"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # plotting for virginica petalsx = flowers[flowers["species"] == "virginica"]["petal_length"]y = flowers[flowers["species"] == "virginica"]["petal_width"]marker = "circle_cross"line_color = "red"fill_color = "lightcoral"fill_alpha = 0.4size = 10legend_label = "virginica petals"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # plotting for virginica sepalsx = flowers[flowers["species"] == "virginica"]["sepal_length"]y = flowers[flowers["species"] == "virginica"]["sepal_width"]marker = "square_cross"line_color = "red"fill_color = "lightcoral"fill_alpha = 0.4size = 10legend_label = "virginica sepals"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # relocating the legend table to # avoid abstruction of the graphgraph.legend.location = "top_left" # displaying the modelshow(graph)
Output :
Data Visualization
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 269,
"s": 28,
"text": "Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity."
},
{
"code": null,
"e": 438,
"s": 269,
"text": "Bokeh can be used to visualize the Iris flower dataset. Visualization is be done using the plotting module. Here we will be using the Iris dataset given to us by Bokeh."
},
{
"code": null,
"e": 515,
"s": 438,
"text": "To download the Iris dataset run the following command on the command line :"
},
{
"code": null,
"e": 532,
"s": 515,
"text": "bokeh sampledata"
},
{
"code": null,
"e": 595,
"s": 532,
"text": "Alternatively, we can also execute the following Python code :"
},
{
"code": null,
"e": 637,
"s": 595,
"text": "import bokeh\nbokeh.sampledata.download()\n"
},
{
"code": null,
"e": 771,
"s": 637,
"text": "In the sample data provided by Bokeh, there is a file iris.csv, this is the Iris dataset. Below is a glimpse into the iris.csv file :"
},
{
"code": null,
"e": 1093,
"s": 771,
"text": "sepal_length sepal_width petal_length petal_width species\n5.1 3.5 1.4 0.2 setosa\n4.9 3 1.4 0.2 setosa\n4.7 3.2 1.3 0.2 setosa\n4.6 3.1 1.5 0.2 setosa\n5 3.6 1.4 0.2 setosa\n"
},
{
"code": null,
"e": 1139,
"s": 1093,
"text": "The dataset contains 5 attributes which are :"
},
{
"code": null,
"e": 1158,
"s": 1139,
"text": "sepal_length in cm"
},
{
"code": null,
"e": 1176,
"s": 1158,
"text": "sepal_width in cm"
},
{
"code": null,
"e": 1195,
"s": 1176,
"text": "petal_length in cm"
},
{
"code": null,
"e": 1213,
"s": 1195,
"text": "petal_width in cm"
},
{
"code": null,
"e": 1278,
"s": 1213,
"text": "species has 3 types of flower species :setosaversicolorvirginica"
},
{
"code": null,
"e": 1285,
"s": 1278,
"text": "setosa"
},
{
"code": null,
"e": 1296,
"s": 1285,
"text": "versicolor"
},
{
"code": null,
"e": 1306,
"s": 1296,
"text": "virginica"
},
{
"code": null,
"e": 1365,
"s": 1306,
"text": "Each species has 50 records and the total entries are 150."
},
{
"code": null,
"e": 1455,
"s": 1365,
"text": "We will be plotting graphs to visualize the clustering of the data for all the 3 species."
},
{
"code": null,
"e": 1570,
"s": 1455,
"text": "Example 1 : Here will be plotting a graph with length of petals as the x-axis and breadth of petals as the y-axis."
},
{
"code": null,
"e": 1817,
"s": 1570,
"text": "Import the required modules :figure, output_file and show from bokeh.plottingflowers from bokeh.sampledata.irisInstantiate a figure object with the title.Give the names to x-axis and y-axis.Plot the graphs for all the 3 species.Display the model."
},
{
"code": null,
"e": 1929,
"s": 1817,
"text": "Import the required modules :figure, output_file and show from bokeh.plottingflowers from bokeh.sampledata.iris"
},
{
"code": null,
"e": 1978,
"s": 1929,
"text": "figure, output_file and show from bokeh.plotting"
},
{
"code": null,
"e": 2013,
"s": 1978,
"text": "flowers from bokeh.sampledata.iris"
},
{
"code": null,
"e": 2057,
"s": 2013,
"text": "Instantiate a figure object with the title."
},
{
"code": null,
"e": 2094,
"s": 2057,
"text": "Give the names to x-axis and y-axis."
},
{
"code": null,
"e": 2133,
"s": 2094,
"text": "Plot the graphs for all the 3 species."
},
{
"code": null,
"e": 2152,
"s": 2133,
"text": "Display the model."
},
{
"code": "# importing the modulesfrom bokeh.sampledata.iris import flowersfrom bokeh.plotting import figure, show, output_file # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Iris Visualization\") # labeling the x-axis and the y-axisgraph.xaxis.axis_label = \"Petal Length (in cm)\"graph.yaxis.axis_label = \"Petal Width (in cm)\" # plotting for setosa petalsx = flowers[flowers[\"species\"] == \"setosa\"][\"petal_length\"]y = flowers[flowers[\"species\"] == \"setosa\"][\"petal_width\"]color = \"blue\"legend_label = \"setosa petals\"graph.circle(x, y, color = color, legend_label = legend_label) # plotting for versicolor petalsx = flowers[flowers[\"species\"] == \"versicolor\"][\"petal_length\"]y = flowers[flowers[\"species\"] == \"versicolor\"][\"petal_width\"]color = \"yellow\"legend_label = \"versicolor petals\"graph.circle(x, y, color = color, legend_label = legend_label) # plotting for virginica petalsx = flowers[flowers[\"species\"] == \"virginica\"][\"petal_length\"]y = flowers[flowers[\"species\"] == \"virginica\"][\"petal_width\"]color = \"red\"legend_label = \"virginica petals\"graph.circle(x, y, color = color, legend_label = legend_label) # relocating the legend table to # avoid abstruction of the graphgraph.legend.location = \"top_left\" # displaying the modelshow(graph)",
"e": 3526,
"s": 2152,
"text": null
},
{
"code": null,
"e": 3536,
"s": 3526,
"text": "Output : "
},
{
"code": null,
"e": 3672,
"s": 3536,
"text": "Example 2 : Here will be plotting a scatter plot graph with both sepals and petals with length as the x-axis and breadth as the y-axis."
},
{
"code": null,
"e": 3919,
"s": 3672,
"text": "Import the required modules :figure, output_file and show from bokeh.plottingflowers from bokeh.sampledata.irisInstantiate a figure object with the title.Give the names to x-axis and y-axis.Plot the graphs for all the 3 species.Display the model."
},
{
"code": null,
"e": 4031,
"s": 3919,
"text": "Import the required modules :figure, output_file and show from bokeh.plottingflowers from bokeh.sampledata.iris"
},
{
"code": null,
"e": 4080,
"s": 4031,
"text": "figure, output_file and show from bokeh.plotting"
},
{
"code": null,
"e": 4115,
"s": 4080,
"text": "flowers from bokeh.sampledata.iris"
},
{
"code": null,
"e": 4159,
"s": 4115,
"text": "Instantiate a figure object with the title."
},
{
"code": null,
"e": 4196,
"s": 4159,
"text": "Give the names to x-axis and y-axis."
},
{
"code": null,
"e": 4235,
"s": 4196,
"text": "Plot the graphs for all the 3 species."
},
{
"code": null,
"e": 4254,
"s": 4235,
"text": "Display the model."
},
{
"code": "# importing the modulesfrom bokeh.sampledata.iris import flowersfrom bokeh.plotting import figure, show, output_file # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Iris Visualization\") # labeling the x-axis and the y-axisgraph.xaxis.axis_label = \"Length (in cm)\"graph.yaxis.axis_label = \"Width (in cm)\" # plotting for setosa petalsx = flowers[flowers[\"species\"] == \"setosa\"][\"petal_length\"]y = flowers[flowers[\"species\"] == \"setosa\"][\"petal_width\"]marker = \"circle_cross\"line_color = \"blue\"fill_color = \"lightblue\"fill_alpha = 0.4size = 10legend_label = \"setosa petals\"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # plotting for setosa sepalsx = flowers[flowers[\"species\"] == \"setosa\"][\"sepal_length\"]y = flowers[flowers[\"species\"] == \"setosa\"][\"sepal_width\"]marker = \"square_cross\"line_color = \"blue\"fill_color = \"lightblue\"fill_alpha = 0.4size = 10legend_label = \"setosa sepals\"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # plotting for versicolor petalsx = flowers[flowers[\"species\"] == \"versicolor\"][\"petal_length\"]y = flowers[flowers[\"species\"] == \"versicolor\"][\"petal_width\"]marker = \"circle_cross\"line_color = \"yellow\"fill_color = \"lightyellow\"fill_alpha = 0.4size = 10legend_label = \"versicolor petals\"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # plotting for versicolor sepalsx = flowers[flowers[\"species\"] == \"versicolor\"][\"sepal_length\"]y = flowers[flowers[\"species\"] == \"versicolor\"][\"sepal_width\"]marker = \"square_cross\"line_color = \"yellow\"fill_color = \"lightyellow\"fill_alpha = 0.4size = 10legend_label = \"versicolor sepals\"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # plotting for virginica petalsx = flowers[flowers[\"species\"] == \"virginica\"][\"petal_length\"]y = flowers[flowers[\"species\"] == \"virginica\"][\"petal_width\"]marker = \"circle_cross\"line_color = \"red\"fill_color = \"lightcoral\"fill_alpha = 0.4size = 10legend_label = \"virginica petals\"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # plotting for virginica sepalsx = flowers[flowers[\"species\"] == \"virginica\"][\"sepal_length\"]y = flowers[flowers[\"species\"] == \"virginica\"][\"sepal_width\"]marker = \"square_cross\"line_color = \"red\"fill_color = \"lightcoral\"fill_alpha = 0.4size = 10legend_label = \"virginica sepals\"graph.scatter(x, y, marker = marker, line_color = line_color, fill_color = fill_color, fill_alpha = fill_alpha, size = size, legend_label = legend_label) # relocating the legend table to # avoid abstruction of the graphgraph.legend.location = \"top_left\" # displaying the modelshow(graph)",
"e": 7815,
"s": 4254,
"text": null
},
{
"code": null,
"e": 7824,
"s": 7815,
"text": "Output :"
},
{
"code": null,
"e": 7843,
"s": 7824,
"text": "Data Visualization"
},
{
"code": null,
"e": 7856,
"s": 7843,
"text": "Python-Bokeh"
},
{
"code": null,
"e": 7863,
"s": 7856,
"text": "Python"
},
{
"code": null,
"e": 7961,
"s": 7863,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7989,
"s": 7961,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 8039,
"s": 7989,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 8061,
"s": 8039,
"text": "Python map() function"
},
{
"code": null,
"e": 8105,
"s": 8061,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 8123,
"s": 8105,
"text": "Python Dictionary"
},
{
"code": null,
"e": 8165,
"s": 8123,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 8188,
"s": 8165,
"text": "Taking input in Python"
},
{
"code": null,
"e": 8210,
"s": 8188,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 8245,
"s": 8210,
"text": "Read a file line by line in Python"
}
] |
numpy.trim_zeros() in Python | 27 Sep, 2019
numpy.trim_zeros function is used to trim the leading and/or trailing zeros from a 1-D array or sequence.
Syntax: numpy.trim_zeros(arr, trim)
Parameters:arr : 1-D array or sequencetrim : trim is an optional parameter with default value to be ‘fb'(front and back) we can either select ‘f'(front) and ‘b’ for back.
Returns: trimmed : 1-D array or sequence (without leading and/or trailing zeros as per user’s choice)
Code 1:
import numpy as geek gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0)) # without trim parameter# returns an array without leading and trailing zeros res = geek.trim_zeros(gfg)print(res)
Output :array([1, 5, 7, 0, 6, 2, 9, 0, 10])
Code 2:
import numpy as geek gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0)) # without trim parameter# returns an array without any leading zeros res = geek.trim_zeros(gfg, 'f')print(res)
Output :array([1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0])
Code 3:
import numpy as geek gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0)) # without trim parameter# returns an array without any trailing zeros res = geek.trim_zeros(gfg, 'b')print(res)
Output :array([0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10])
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Sep, 2019"
},
{
"code": null,
"e": 134,
"s": 28,
"text": "numpy.trim_zeros function is used to trim the leading and/or trailing zeros from a 1-D array or sequence."
},
{
"code": null,
"e": 170,
"s": 134,
"text": "Syntax: numpy.trim_zeros(arr, trim)"
},
{
"code": null,
"e": 341,
"s": 170,
"text": "Parameters:arr : 1-D array or sequencetrim : trim is an optional parameter with default value to be ‘fb'(front and back) we can either select ‘f'(front) and ‘b’ for back."
},
{
"code": null,
"e": 443,
"s": 341,
"text": "Returns: trimmed : 1-D array or sequence (without leading and/or trailing zeros as per user’s choice)"
},
{
"code": null,
"e": 451,
"s": 443,
"text": "Code 1:"
},
{
"code": "import numpy as geek gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0)) # without trim parameter# returns an array without leading and trailing zeros res = geek.trim_zeros(gfg)print(res)",
"e": 657,
"s": 451,
"text": null
},
{
"code": null,
"e": 702,
"s": 657,
"text": "Output :array([1, 5, 7, 0, 6, 2, 9, 0, 10])\n"
},
{
"code": null,
"e": 710,
"s": 702,
"text": "Code 2:"
},
{
"code": "import numpy as geek gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0)) # without trim parameter# returns an array without any leading zeros res = geek.trim_zeros(gfg, 'f')print(res)",
"e": 911,
"s": 710,
"text": null
},
{
"code": null,
"e": 962,
"s": 911,
"text": "Output :array([1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0])\n"
},
{
"code": null,
"e": 970,
"s": 962,
"text": "Code 3:"
},
{
"code": "import numpy as geek gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0)) # without trim parameter# returns an array without any trailing zeros res = geek.trim_zeros(gfg, 'b')print(res)",
"e": 1172,
"s": 970,
"text": null
},
{
"code": null,
"e": 1229,
"s": 1172,
"text": "Output :array([0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10])\n"
},
{
"code": null,
"e": 1242,
"s": 1229,
"text": "Python-numpy"
},
{
"code": null,
"e": 1249,
"s": 1242,
"text": "Python"
}
] |
GATE | GATE-CS-2015 (Set 2) | Question 11 | 28 Jun, 2021
Consider the following transaction involving two bank accounts x and y.
read(x); x := x – 50; write(x); read(y); y := y + 50; write(y)
The constraint that the sum of the accounts x and y should remain constant is that of
(A) Atomicity(B) Consistency(C) Isolation(D) DurabilityAnswer: (B)Explanation: Consistency in database systems refers to the requirement that any given database transaction must only change affected data in allowed ways, that is sum of x and y must not change.
Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 124,
"s": 52,
"text": "Consider the following transaction involving two bank accounts x and y."
},
{
"code": null,
"e": 193,
"s": 124,
"text": "read(x); x := x – 50; write(x); read(y); y := y + 50; write(y) "
},
{
"code": null,
"e": 279,
"s": 193,
"text": "The constraint that the sum of the accounts x and y should remain constant is that of"
},
{
"code": null,
"e": 540,
"s": 279,
"text": "(A) Atomicity(B) Consistency(C) Isolation(D) DurabilityAnswer: (B)Explanation: Consistency in database systems refers to the requirement that any given database transaction must only change affected data in allowed ways, that is sum of x and y must not change."
},
{
"code": null,
"e": 562,
"s": 540,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 583,
"s": 562,
"text": "GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 609,
"s": 583,
"text": "GATE-GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 614,
"s": 609,
"text": "GATE"
},
{
"code": null,
"e": 712,
"s": 614,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 754,
"s": 712,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 816,
"s": 754,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 850,
"s": 816,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 892,
"s": 850,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 934,
"s": 892,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 976,
"s": 934,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 51"
},
{
"code": null,
"e": 1010,
"s": 976,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 1044,
"s": 1010,
"text": "GATE | GATE-CS-2004 | Question 31"
},
{
"code": null,
"e": 1078,
"s": 1044,
"text": "GATE | GATE CS 2011 | Question 49"
}
] |
Post/Redirect/Get (PRG) Design Pattern | 04 May, 2020
Prerequisite- HTTP Protocol, GET and POST requests using Python
Introduction:
PRG is one of many design patterns used in web development. It is used to prevent the resubmission of a form caused by reloading the same web page after submitting the form. It removes redundancy of content to strengthen the SEO and makes the website user friendly. It is used by large, trusted online shops and other robust websites which are intended to be user friendly.
Problem:
When we try to submit a web form then a HTTP POST request is sent to the server. The server process the request and send response to the client with response code 2XX. When the client try to refresh/reload the web page, he/she unintentionally sends another HTTP POST request to the server with the same data as just before. This may cause undesired results, such as duplicate web purchases.
The browser pops up a warning message box after reload as shown below:
Internal working:
Below is the block diagram of internal working of the above problem.
Solution:
To avoid this problem many web developer use the POST/REDIRECT/GET pattern, instead of returning a web page directly, the POST returns a redirect to another web page or same depending on the requirements.
Internal working:
Below is the block diagram of internal working of the above solution.
A minimal python and HTML code using flask framework to demonstrate above concept.
Create a file called app.py in the project root directory and write the below code in it. And install flask using-$pip install flask
Create a file called app.py in the project root directory and write the below code in it. And install flask using-
$pip install flask
from flask import Flask, render_template, redirect, request, url_for # Initiate flask appapp = Flask(__name__) # Declare routes and [email protected]('/', methods =['GET', 'POST'])def home(): # If it is POST request the redirect if request.method =='POST': return redirect(url_for('home')) return render_template('home.html', title ='Home') if __name__=='__main__': app.run()
Create a folder templates in the project root directory and create a file home.html inside the templates directory and write the below code in it.
Create a folder templates in the project root directory and create a file home.html inside the templates directory and write the below code in it.
<!-- Create a form --><form action="" method="post"> <!-- Create a input box --> <input type="text", value="Suraj Yadav"><br><br> <!-- Create a submit button --> <input type="submit" value="Submit"></form>
To run the web server type in console:$python app.py
Output:
Running on http://127.0.0.1:5000/
$python app.py
Output:
Running on http://127.0.0.1:5000/
Go to web browser and type localhost:5000 and hit enter.
Go to web browser and type localhost:5000 and hit enter.
Console output:In the below image, the first GET request is made when we use localhost:5000, then we POST data to the server. Now, after processing the data server redirects us by making a GET request so the third GET request is made by the server and finally the fourth GET request is made when we try to refresh the page.
Note: Try to play with code without redirecting.
Web technologies
Design Pattern
Python
Python Programs
Web Technologies
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Builder Design Pattern
Unified Modeling Language (UML) | An Introduction
Adapter Pattern
MVC Design Pattern
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 May, 2020"
},
{
"code": null,
"e": 118,
"s": 54,
"text": "Prerequisite- HTTP Protocol, GET and POST requests using Python"
},
{
"code": null,
"e": 132,
"s": 118,
"text": "Introduction:"
},
{
"code": null,
"e": 508,
"s": 132,
"text": "PRG is one of many design patterns used in web development. It is used to prevent the resubmission of a form caused by reloading the same web page after submitting the form. It removes redundancy of content to strengthen the SEO and makes the website user friendly. It is used by large, trusted online shops and other robust websites which are intended to be user friendly."
},
{
"code": null,
"e": 517,
"s": 508,
"text": "Problem:"
},
{
"code": null,
"e": 908,
"s": 517,
"text": "When we try to submit a web form then a HTTP POST request is sent to the server. The server process the request and send response to the client with response code 2XX. When the client try to refresh/reload the web page, he/she unintentionally sends another HTTP POST request to the server with the same data as just before. This may cause undesired results, such as duplicate web purchases."
},
{
"code": null,
"e": 979,
"s": 908,
"text": "The browser pops up a warning message box after reload as shown below:"
},
{
"code": null,
"e": 997,
"s": 979,
"text": "Internal working:"
},
{
"code": null,
"e": 1066,
"s": 997,
"text": "Below is the block diagram of internal working of the above problem."
},
{
"code": null,
"e": 1076,
"s": 1066,
"text": "Solution:"
},
{
"code": null,
"e": 1281,
"s": 1076,
"text": "To avoid this problem many web developer use the POST/REDIRECT/GET pattern, instead of returning a web page directly, the POST returns a redirect to another web page or same depending on the requirements."
},
{
"code": null,
"e": 1299,
"s": 1281,
"text": "Internal working:"
},
{
"code": null,
"e": 1369,
"s": 1299,
"text": "Below is the block diagram of internal working of the above solution."
},
{
"code": null,
"e": 1452,
"s": 1369,
"text": "A minimal python and HTML code using flask framework to demonstrate above concept."
},
{
"code": null,
"e": 1586,
"s": 1452,
"text": "Create a file called app.py in the project root directory and write the below code in it. And install flask using-$pip install flask\n"
},
{
"code": null,
"e": 1701,
"s": 1586,
"text": "Create a file called app.py in the project root directory and write the below code in it. And install flask using-"
},
{
"code": null,
"e": 1721,
"s": 1701,
"text": "$pip install flask\n"
},
{
"code": "from flask import Flask, render_template, redirect, request, url_for # Initiate flask appapp = Flask(__name__) # Declare routes and [email protected]('/', methods =['GET', 'POST'])def home(): # If it is POST request the redirect if request.method =='POST': return redirect(url_for('home')) return render_template('home.html', title ='Home') if __name__=='__main__': app.run()",
"e": 2121,
"s": 1721,
"text": null
},
{
"code": null,
"e": 2268,
"s": 2121,
"text": "Create a folder templates in the project root directory and create a file home.html inside the templates directory and write the below code in it."
},
{
"code": null,
"e": 2415,
"s": 2268,
"text": "Create a folder templates in the project root directory and create a file home.html inside the templates directory and write the below code in it."
},
{
"code": "<!-- Create a form --><form action=\"\" method=\"post\"> <!-- Create a input box --> <input type=\"text\", value=\"Suraj Yadav\"><br><br> <!-- Create a submit button --> <input type=\"submit\" value=\"Submit\"></form>",
"e": 2633,
"s": 2415,
"text": null
},
{
"code": null,
"e": 2729,
"s": 2633,
"text": "To run the web server type in console:$python app.py\nOutput:\nRunning on http://127.0.0.1:5000/\n"
},
{
"code": null,
"e": 2787,
"s": 2729,
"text": "$python app.py\nOutput:\nRunning on http://127.0.0.1:5000/\n"
},
{
"code": null,
"e": 2844,
"s": 2787,
"text": "Go to web browser and type localhost:5000 and hit enter."
},
{
"code": null,
"e": 2901,
"s": 2844,
"text": "Go to web browser and type localhost:5000 and hit enter."
},
{
"code": null,
"e": 3225,
"s": 2901,
"text": "Console output:In the below image, the first GET request is made when we use localhost:5000, then we POST data to the server. Now, after processing the data server redirects us by making a GET request so the third GET request is made by the server and finally the fourth GET request is made when we try to refresh the page."
},
{
"code": null,
"e": 3274,
"s": 3225,
"text": "Note: Try to play with code without redirecting."
},
{
"code": null,
"e": 3291,
"s": 3274,
"text": "Web technologies"
},
{
"code": null,
"e": 3306,
"s": 3291,
"text": "Design Pattern"
},
{
"code": null,
"e": 3313,
"s": 3306,
"text": "Python"
},
{
"code": null,
"e": 3329,
"s": 3313,
"text": "Python Programs"
},
{
"code": null,
"e": 3346,
"s": 3329,
"text": "Web Technologies"
},
{
"code": null,
"e": 3362,
"s": 3346,
"text": "Write From Home"
},
{
"code": null,
"e": 3460,
"s": 3362,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3498,
"s": 3460,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 3521,
"s": 3498,
"text": "Builder Design Pattern"
},
{
"code": null,
"e": 3571,
"s": 3521,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 3587,
"s": 3571,
"text": "Adapter Pattern"
},
{
"code": null,
"e": 3606,
"s": 3587,
"text": "MVC Design Pattern"
},
{
"code": null,
"e": 3634,
"s": 3606,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3684,
"s": 3634,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3706,
"s": 3684,
"text": "Python map() function"
},
{
"code": null,
"e": 3724,
"s": 3706,
"text": "Python Dictionary"
}
] |
Prime functions in Python SymPy | 20 Oct, 2020
How to get prime numbers quickly in python using library functions?Library functions always make our code easy so here we are going to discuss some library function in python to work upon prime numbers. SymPy is a python module which contains some really cool prime number related library functions. Given below is the list of these functions :
isprime(n): It tests if n is a prime number (True) or not (False).primerange(a, b): It generates a list of all prime numbers in the range [a, b).randprime(a, b): It returns a random prime number in the range [a, b).primepi(n): It returns the number of prime numbers less than or equal to n.prime(nth) : It returns the nth prime, with the primes indexed as prime(1) = 2. The nth prime is approximately n*log(n) and can never be larger than 2**n.prevprime(n): It returns the prev prime smaller than n.nextprime(n): It returns the next greater prime than n.sieve.primerange(a, b): It generates all prime numbers in the range [a, b), implemented as a dynamically growing sieve of Eratosthenes.
isprime(n): It tests if n is a prime number (True) or not (False).
primerange(a, b): It generates a list of all prime numbers in the range [a, b).
randprime(a, b): It returns a random prime number in the range [a, b).
primepi(n): It returns the number of prime numbers less than or equal to n.
prime(nth) : It returns the nth prime, with the primes indexed as prime(1) = 2. The nth prime is approximately n*log(n) and can never be larger than 2**n.
prevprime(n): It returns the prev prime smaller than n.
nextprime(n): It returns the next greater prime than n.
sieve.primerange(a, b): It generates all prime numbers in the range [a, b), implemented as a dynamically growing sieve of Eratosthenes.
Example:
Python3
# Library functions for primeimport sympy # Output : Trueprint(sympy.isprime(5)) # Output : [2, 3, 5, 7, 11, 13, 17, 19, 23,# 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,# 73, 79, 83, 89, 97]print(list(sympy.primerange(0, 100))) print(sympy.randprime(0, 100)) # Output : 83print(sympy.randprime(0, 100)) # Output : 41print(sympy.prime(3)) # Output : 5print(sympy.prevprime(50)) # Output : 47print(sympy.nextprime(50)) # Output : 53 # Output : [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,# 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,# 79, 83, 89, 97]print list(sympy.sieve.primerange(0, 100))
Reference : https://stackoverflow.com/questions/13326673/is-there-a-python-library-to-list-primesThis article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shubhamb836
Prime Number
SymPy
Mathematical
Python
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n20 Oct, 2020"
},
{
"code": null,
"e": 399,
"s": 53,
"text": "How to get prime numbers quickly in python using library functions?Library functions always make our code easy so here we are going to discuss some library function in python to work upon prime numbers. SymPy is a python module which contains some really cool prime number related library functions. Given below is the list of these functions : "
},
{
"code": null,
"e": 1089,
"s": 399,
"text": "isprime(n): It tests if n is a prime number (True) or not (False).primerange(a, b): It generates a list of all prime numbers in the range [a, b).randprime(a, b): It returns a random prime number in the range [a, b).primepi(n): It returns the number of prime numbers less than or equal to n.prime(nth) : It returns the nth prime, with the primes indexed as prime(1) = 2. The nth prime is approximately n*log(n) and can never be larger than 2**n.prevprime(n): It returns the prev prime smaller than n.nextprime(n): It returns the next greater prime than n.sieve.primerange(a, b): It generates all prime numbers in the range [a, b), implemented as a dynamically growing sieve of Eratosthenes."
},
{
"code": null,
"e": 1156,
"s": 1089,
"text": "isprime(n): It tests if n is a prime number (True) or not (False)."
},
{
"code": null,
"e": 1236,
"s": 1156,
"text": "primerange(a, b): It generates a list of all prime numbers in the range [a, b)."
},
{
"code": null,
"e": 1307,
"s": 1236,
"text": "randprime(a, b): It returns a random prime number in the range [a, b)."
},
{
"code": null,
"e": 1383,
"s": 1307,
"text": "primepi(n): It returns the number of prime numbers less than or equal to n."
},
{
"code": null,
"e": 1538,
"s": 1383,
"text": "prime(nth) : It returns the nth prime, with the primes indexed as prime(1) = 2. The nth prime is approximately n*log(n) and can never be larger than 2**n."
},
{
"code": null,
"e": 1594,
"s": 1538,
"text": "prevprime(n): It returns the prev prime smaller than n."
},
{
"code": null,
"e": 1650,
"s": 1594,
"text": "nextprime(n): It returns the next greater prime than n."
},
{
"code": null,
"e": 1786,
"s": 1650,
"text": "sieve.primerange(a, b): It generates all prime numbers in the range [a, b), implemented as a dynamically growing sieve of Eratosthenes."
},
{
"code": null,
"e": 1796,
"s": 1786,
"text": "Example: "
},
{
"code": null,
"e": 1804,
"s": 1796,
"text": "Python3"
},
{
"code": "# Library functions for primeimport sympy # Output : Trueprint(sympy.isprime(5)) # Output : [2, 3, 5, 7, 11, 13, 17, 19, 23,# 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,# 73, 79, 83, 89, 97]print(list(sympy.primerange(0, 100))) print(sympy.randprime(0, 100)) # Output : 83print(sympy.randprime(0, 100)) # Output : 41print(sympy.prime(3)) # Output : 5print(sympy.prevprime(50)) # Output : 47print(sympy.nextprime(50)) # Output : 53 # Output : [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,# 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,# 79, 83, 89, 97]print list(sympy.sieve.primerange(0, 100))",
"e": 2438,
"s": 1804,
"text": null
},
{
"code": null,
"e": 2971,
"s": 2438,
"text": "Reference : https://stackoverflow.com/questions/13326673/is-there-a-python-library-to-list-primesThis article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 2983,
"s": 2971,
"text": "shubhamb836"
},
{
"code": null,
"e": 2996,
"s": 2983,
"text": "Prime Number"
},
{
"code": null,
"e": 3002,
"s": 2996,
"text": "SymPy"
},
{
"code": null,
"e": 3015,
"s": 3002,
"text": "Mathematical"
},
{
"code": null,
"e": 3022,
"s": 3015,
"text": "Python"
},
{
"code": null,
"e": 3035,
"s": 3022,
"text": "Mathematical"
},
{
"code": null,
"e": 3048,
"s": 3035,
"text": "Prime Number"
},
{
"code": null,
"e": 3146,
"s": 3048,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3167,
"s": 3146,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 3181,
"s": 3167,
"text": "Prime Numbers"
},
{
"code": null,
"e": 3234,
"s": 3181,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 3271,
"s": 3234,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 3314,
"s": 3271,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 3342,
"s": 3314,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3392,
"s": 3342,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3414,
"s": 3392,
"text": "Python map() function"
}
] |
Python | Get elements till particular element in list | 28 Aug, 2019
Sometimes, while working with Python list, we can have a requirement in which we need to remove all the elements after a particular element, or, get all elements before a particular element. These both are similar problems and having a solution to it is always helpful. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using index() + list slicingThis problem can be solved using the combination of these functions. The index() can be used to find the index of desired element and list slicing can perform the remaining task of getting the elements.
# Python3 code to demonstrate working of# Get elements till particular element in list# using index() + list slicing # initialize listtest_list = [1, 4, 6, 8, 9, 10, 7] # printing original listprint("The original list is : " + str(test_list)) # declaring elements till which elements requiredN = 8 # Get elements till particular element in list# using index() + list slicingtemp = test_list.index(N)res = test_list[:temp] # printing resultprint("Elements till N in list are : " + str(res))
The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]
Method #2 : Using generatorThis task can also be performed using the generator function which uses yield to get the elements just till the required element and breaks the yields after that element.
# Python3 code to demonstrate working of# Get elements till particular element in list# using generator # helper function to perform taskdef print_ele(test_list, val): for ele in test_list: if ele == val: return yield ele # initialize listtest_list = [1, 4, 6, 8, 9, 10, 7] # printing original listprint("The original list is : " + str(test_list)) # declaring elements till which elements requiredN = 8 # Get elements till particular element in list# using generatorres = list(print_ele(test_list, N)) # printing resultprint("Elements till N in list are : " + str(res))
The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 362,
"s": 28,
"text": "Sometimes, while working with Python list, we can have a requirement in which we need to remove all the elements after a particular element, or, get all elements before a particular element. These both are similar problems and having a solution to it is always helpful. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 605,
"s": 362,
"text": "Method #1 : Using index() + list slicingThis problem can be solved using the combination of these functions. The index() can be used to find the index of desired element and list slicing can perform the remaining task of getting the elements."
},
{
"code": "# Python3 code to demonstrate working of# Get elements till particular element in list# using index() + list slicing # initialize listtest_list = [1, 4, 6, 8, 9, 10, 7] # printing original listprint(\"The original list is : \" + str(test_list)) # declaring elements till which elements requiredN = 8 # Get elements till particular element in list# using index() + list slicingtemp = test_list.index(N)res = test_list[:temp] # printing resultprint(\"Elements till N in list are : \" + str(res))",
"e": 1100,
"s": 605,
"text": null
},
{
"code": null,
"e": 1187,
"s": 1100,
"text": "The original list is : [1, 4, 6, 8, 9, 10, 7]\nElements till N in list are : [1, 4, 6]\n"
},
{
"code": null,
"e": 1387,
"s": 1189,
"text": "Method #2 : Using generatorThis task can also be performed using the generator function which uses yield to get the elements just till the required element and breaks the yields after that element."
},
{
"code": "# Python3 code to demonstrate working of# Get elements till particular element in list# using generator # helper function to perform taskdef print_ele(test_list, val): for ele in test_list: if ele == val: return yield ele # initialize listtest_list = [1, 4, 6, 8, 9, 10, 7] # printing original listprint(\"The original list is : \" + str(test_list)) # declaring elements till which elements requiredN = 8 # Get elements till particular element in list# using generatorres = list(print_ele(test_list, N)) # printing resultprint(\"Elements till N in list are : \" + str(res))",
"e": 1991,
"s": 1387,
"text": null
},
{
"code": null,
"e": 2078,
"s": 1991,
"text": "The original list is : [1, 4, 6, 8, 9, 10, 7]\nElements till N in list are : [1, 4, 6]\n"
},
{
"code": null,
"e": 2099,
"s": 2078,
"text": "Python list-programs"
},
{
"code": null,
"e": 2106,
"s": 2099,
"text": "Python"
},
{
"code": null,
"e": 2122,
"s": 2106,
"text": "Python Programs"
},
{
"code": null,
"e": 2220,
"s": 2122,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2238,
"s": 2220,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2280,
"s": 2238,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2315,
"s": 2280,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2341,
"s": 2315,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2373,
"s": 2341,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2416,
"s": 2373,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2438,
"s": 2416,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2477,
"s": 2438,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2515,
"s": 2477,
"text": "Python | Convert a list to dictionary"
}
] |
MySQL date format to convert dd.mm.yy to YYYY-MM-DD? | Use STR_TO_DATE() method from MySQL to convert. The syntax is as follows wherein we are using format specifiers. The format specifiers begin with %.
SELECT STR_TO_DATE(yourDateColumnName,'%d.%m.%Y') as anyVariableName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows.
mysql> create table ConvertIntoDateFormat
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> LoginDate varchar(30),
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.47 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into ConvertIntoDateFormat(LoginDate) values('11.01.2019');
Query OK, 1 row affected (0.10 sec)
mysql> insert into ConvertIntoDateFormat(LoginDate) values('10.04.2017');
Query OK, 1 row affected (0.16 sec)
mysql> insert into ConvertIntoDateFormat(LoginDate) values('21.10.2016');
Query OK, 1 row affected (0.12 sec)
mysql> insert into ConvertIntoDateFormat(LoginDate) values('26.09.2018');
Query OK, 1 row affected (0.14 sec)
mysql> insert into ConvertIntoDateFormat(LoginDate) values('25.12.2012');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement. The query is as follows−
mysql> select *from ConvertIntoDateFormat;
The following is the output.
+----+------------+
| Id | LoginDate |
+----+------------+
| 1 | 11.01.2019 |
| 2 | 10.04.2017 |
| 3 | 21.10.2016 |
| 4 | 26.09.2018 |
| 5 | 25.12.2012 |
+----+------------+
5 rows in set (0.00 sec)
The following is the query to format the date to YYYY-MM-DD.
mysql> select str_to_date(LoginDate,'%d.%m.%Y') as DateFormat from ConvertIntoDateFormat;
Here is the output.
+------------+
| DateFormat |
+------------+
| 2019-01-11 |
| 2017-04-10 |
| 2016-10-21 |
| 2018-09-26 |
| 2012-12-25 |
+------------+
5 rows in set (0.00 sec)
You can also use DATE_FORMAT() method for the same purpose. The query is as follows
mysql> select DATE_FORMAT(STR_TO_DATE(LoginDate,'%d.%m.%Y'), '%Y-%m-%d') as DateFormat from
-> ConvertIntoDateFormat;
The following is the output−
+------------+
| DateFormat |
+------------+
| 2019-01-11 |
| 2017-04-10 |
| 2016-10-21 |
| 2018-09-26 |
| 2012-12-25 |
+------------+
5 rows in set (0.00 sec) | [
{
"code": null,
"e": 1336,
"s": 1187,
"text": "Use STR_TO_DATE() method from MySQL to convert. The syntax is as follows wherein we are using format specifiers. The format specifiers begin with %."
},
{
"code": null,
"e": 1425,
"s": 1336,
"text": "SELECT STR_TO_DATE(yourDateColumnName,'%d.%m.%Y') as anyVariableName FROM yourTableName;"
},
{
"code": null,
"e": 1523,
"s": 1425,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows."
},
{
"code": null,
"e": 1708,
"s": 1523,
"text": "mysql> create table ConvertIntoDateFormat\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> LoginDate varchar(30),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.47 sec)"
},
{
"code": null,
"e": 1789,
"s": 1708,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2343,
"s": 1789,
"text": "mysql> insert into ConvertIntoDateFormat(LoginDate) values('11.01.2019');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into ConvertIntoDateFormat(LoginDate) values('10.04.2017');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into ConvertIntoDateFormat(LoginDate) values('21.10.2016');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into ConvertIntoDateFormat(LoginDate) values('26.09.2018');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into ConvertIntoDateFormat(LoginDate) values('25.12.2012');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 2427,
"s": 2343,
"text": "Display all records from the table using select statement. The query is as follows−"
},
{
"code": null,
"e": 2470,
"s": 2427,
"text": "mysql> select *from ConvertIntoDateFormat;"
},
{
"code": null,
"e": 2499,
"s": 2470,
"text": "The following is the output."
},
{
"code": null,
"e": 2704,
"s": 2499,
"text": "+----+------------+\n| Id | LoginDate |\n+----+------------+\n| 1 | 11.01.2019 |\n| 2 | 10.04.2017 |\n| 3 | 21.10.2016 |\n| 4 | 26.09.2018 |\n| 5 | 25.12.2012 |\n+----+------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2765,
"s": 2704,
"text": "The following is the query to format the date to YYYY-MM-DD."
},
{
"code": null,
"e": 2855,
"s": 2765,
"text": "mysql> select str_to_date(LoginDate,'%d.%m.%Y') as DateFormat from ConvertIntoDateFormat;"
},
{
"code": null,
"e": 2875,
"s": 2855,
"text": "Here is the output."
},
{
"code": null,
"e": 3035,
"s": 2875,
"text": "+------------+\n| DateFormat |\n+------------+\n| 2019-01-11 |\n| 2017-04-10 |\n| 2016-10-21 |\n| 2018-09-26 |\n| 2012-12-25 |\n+------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3119,
"s": 3035,
"text": "You can also use DATE_FORMAT() method for the same purpose. The query is as follows"
},
{
"code": null,
"e": 3240,
"s": 3119,
"text": "mysql> select DATE_FORMAT(STR_TO_DATE(LoginDate,'%d.%m.%Y'), '%Y-%m-%d') as DateFormat from\n -> ConvertIntoDateFormat;"
},
{
"code": null,
"e": 3269,
"s": 3240,
"text": "The following is the output−"
},
{
"code": null,
"e": 3429,
"s": 3269,
"text": "+------------+\n| DateFormat |\n+------------+\n| 2019-01-11 |\n| 2017-04-10 |\n| 2016-10-21 |\n| 2018-09-26 |\n| 2012-12-25 |\n+------------+\n5 rows in set (0.00 sec)"
}
] |
Problem with getline() after cin >> | 25 Feb, 2021
The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.
Program 1:
Below is the C++ program to illustrate the same:
C++
// C++ program for the above problem#include <iostream>using namespace std; // Driver Codeint main(){ int fav_no; string name; cout << "Type your favorite number: "; // The cin statement uses the // fav_no and leaves the \n // in the stream as garbage cin >> fav_no; cout << "Type your name : "; // getline() reads \n // and finish reading getline(cin, name); // In output only fav_no // will be displayed not // name cout << name << ", your favourite number is : " << fav_no; return 0;}
Output:
Explanation:
The solution to solve the above problem is to use something which extracts all white space characters after cin. std::ws in C++ to do the same thing. This is actually used with the “>>” operator on input streams.
Program 2:
Below is the C++ program to illustrate the solution for the above problem:
C++
// C++ program for the above solution#include <iostream>using namespace std; // Driver Codeint main(){ int fav_no; string name; cout << "Type your favourite number: "; cin >> fav_no; cout << "Type your name: "; // Usage of std::ws will extract // all the whitespace character getline(cin >> ws, name); cout << name << ", your favourite number is : " << fav_no; return 0;}
Output:
CPP-Basics
Technical Scripter 2020
C++
C++ Programs
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ program for hashing with chaining | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 367,
"s": 53,
"text": "The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage."
},
{
"code": null,
"e": 378,
"s": 367,
"text": "Program 1:"
},
{
"code": null,
"e": 427,
"s": 378,
"text": "Below is the C++ program to illustrate the same:"
},
{
"code": null,
"e": 431,
"s": 427,
"text": "C++"
},
{
"code": "// C++ program for the above problem#include <iostream>using namespace std; // Driver Codeint main(){ int fav_no; string name; cout << \"Type your favorite number: \"; // The cin statement uses the // fav_no and leaves the \\n // in the stream as garbage cin >> fav_no; cout << \"Type your name : \"; // getline() reads \\n // and finish reading getline(cin, name); // In output only fav_no // will be displayed not // name cout << name << \", your favourite number is : \" << fav_no; return 0;}",
"e": 996,
"s": 431,
"text": null
},
{
"code": null,
"e": 1004,
"s": 996,
"text": "Output:"
},
{
"code": null,
"e": 1017,
"s": 1004,
"text": "Explanation:"
},
{
"code": null,
"e": 1230,
"s": 1017,
"text": "The solution to solve the above problem is to use something which extracts all white space characters after cin. std::ws in C++ to do the same thing. This is actually used with the “>>” operator on input streams."
},
{
"code": null,
"e": 1241,
"s": 1230,
"text": "Program 2:"
},
{
"code": null,
"e": 1316,
"s": 1241,
"text": "Below is the C++ program to illustrate the solution for the above problem:"
},
{
"code": null,
"e": 1320,
"s": 1316,
"text": "C++"
},
{
"code": "// C++ program for the above solution#include <iostream>using namespace std; // Driver Codeint main(){ int fav_no; string name; cout << \"Type your favourite number: \"; cin >> fav_no; cout << \"Type your name: \"; // Usage of std::ws will extract // all the whitespace character getline(cin >> ws, name); cout << name << \", your favourite number is : \" << fav_no; return 0;}",
"e": 1746,
"s": 1320,
"text": null
},
{
"code": null,
"e": 1754,
"s": 1746,
"text": "Output:"
},
{
"code": null,
"e": 1765,
"s": 1754,
"text": "CPP-Basics"
},
{
"code": null,
"e": 1789,
"s": 1765,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1793,
"s": 1789,
"text": "C++"
},
{
"code": null,
"e": 1806,
"s": 1793,
"text": "C++ Programs"
},
{
"code": null,
"e": 1825,
"s": 1806,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1829,
"s": 1825,
"text": "CPP"
},
{
"code": null,
"e": 1927,
"s": 1829,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1951,
"s": 1927,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1971,
"s": 1951,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1996,
"s": 1971,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2029,
"s": 1996,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2073,
"s": 2029,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2108,
"s": 2073,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 2142,
"s": 2108,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 2186,
"s": 2142,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 2245,
"s": 2186,
"text": "How to return multiple values from a function in C or C++?"
}
] |
CSS | Styling Forms | 02 Jan, 2019
CSS form is used to create interactive form for user. It provides many ways to set the style.
There are many CSS properties available which can be used to create and style HTML forms to make them more interactive, some of which are listed below:
Attribute Selector: The attribute type of the input form can take a variety of form depending on user’s choice. It could be anything out of the possible types like text, search, url, tel, email, password, date pickers, number, checkbox, radio, file etc. User needs to specify type while creating a form.Example:<!DOCTYPE html><html> <head> <style> body{ background-color:green; } </style> </head> <body> <center> <b>Is Geeksforgeeks useful ?</b> <form> <input type="radio" name="useful" value="yes" checked> Yes <br> <input type="radio" name="useful" value="def_yes"> Definitely Yes </form> </center> </body></html> Output:Consider another example where the input type is simply a text:<!DOCTYPE html><html><head> <style> body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b> <br> <input type="text" name="info"><br> </form> </center></body></html> Output:
Example:
<!DOCTYPE html><html> <head> <style> body{ background-color:green; } </style> </head> <body> <center> <b>Is Geeksforgeeks useful ?</b> <form> <input type="radio" name="useful" value="yes" checked> Yes <br> <input type="radio" name="useful" value="def_yes"> Definitely Yes </form> </center> </body></html>
Output:Consider another example where the input type is simply a text:
<!DOCTYPE html><html><head> <style> body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b> <br> <input type="text" name="info"><br> </form> </center></body></html>
Output:
Styling the Width of Input: The width property is used to set the width of the input field. Consider the below example where the width is set to be 10% of the entire screen.<!DOCTYPE html><html><head> <style> input{ width:10%; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b> <br> <input type="text" name="info"><br> </form> </center></body></html> Output:
<!DOCTYPE html><html><head> <style> input{ width:10%; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b> <br> <input type="text" name="info"><br> </form> </center></body></html>
Output:
Add Padding in Inputs: The padding property is used to add spaces inside the text field. Consider the below example:<!DOCTYPE html><html><head> <style> input{ width:10%; padding: 12px; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b><br> <input type="text" name="info"><br> </form> </center></body></html> Output:
<!DOCTYPE html><html><head> <style> input{ width:10%; padding: 12px; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b><br> <input type="text" name="info"><br> </form> </center></body></html>
Output:
Set Margin for Inputs: The margin property is used to add space outside the input field. It is helpful when there are many inputs. Consider the example below with two inputs and observe the space (margin) between them.<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Mention two topics that you liked on Geeksforgeeks</b> <br> <input type="text" name="info"><br> <input type="text" name="info"><br> </form> </center></body></html> Output:
<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Mention two topics that you liked on Geeksforgeeks</b> <br> <input type="text" name="info"><br> <input type="text" name="info"><br> </form> </center></body></html>
Output:
Adding Border and Border-radius: The border property is used to bring change in the size and color of the border whereas border-radius property is used for adding rounded corners.Consider the below example where a 2px solid red border is created with a border radius of 4px.<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: 2px solid red; border-radius: 4px; } body{ background-color:green; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type="text" name="info"><br> <input type="text" name="info"><br> </form> </center></body></html> Output:Note: User can also have border at any particular side and remove others or have all borders of different color. Consider the below example where user want border only on top(blue color) and bottom(red color).<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: none; border-top: 3px solid blue; border-bottom: 3px solid red; } body{ background-color:green; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type="text" name="info"><br> <input type="text" name="info"><br> </form> </center></body></html> Output:
Consider the below example where a 2px solid red border is created with a border radius of 4px.
<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: 2px solid red; border-radius: 4px; } body{ background-color:green; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type="text" name="info"><br> <input type="text" name="info"><br> </form> </center></body></html>
Output:
Note: User can also have border at any particular side and remove others or have all borders of different color. Consider the below example where user want border only on top(blue color) and bottom(red color).
<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: none; border-top: 3px solid blue; border-bottom: 3px solid red; } body{ background-color:green; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type="text" name="info"><br> <input type="text" name="info"><br> </form> </center></body></html>
Output:
Adding Color to text and Background: The color property is used to change the color of the text in the input and the background-color property is used to change the color of the background of the input field.Consider the below example where color of text is black and background color is set to green.<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: none; background-color: green; color: black; } body{ background-color:white; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type="text" name="info"><br> <input type="text" name="info"><br> </form> </center></body></html> Output:
Consider the below example where color of text is black and background color is set to green.
<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: none; background-color: green; color: black; } body{ background-color:white; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type="text" name="info"><br> <input type="text" name="info"><br> </form> </center></body></html>
Output:
Focus Selector: When we click on the input field it gets an outline of blue color. You can change this behaviour by using :focus selector.Consider the below example where user wants a 3px solid red outline and green background when focused.<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; color: black; } input[type=text]:focus { border: 3px solid red; background-color: green; } body{ background-color:white; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type="text" name="info"><br> <input type="text" name="info"><br> </form> </center></body></html> Output:
Consider the below example where user wants a 3px solid red outline and green background when focused.
<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; color: black; } input[type=text]:focus { border: 3px solid red; background-color: green; } body{ background-color:white; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type="text" name="info"><br> <input type="text" name="info"><br> </form> </center></body></html>
Output:
Adding images in the Input form: The background-image property can be used to put an image inside the input form and it can be positioned using background-position property and user can also decide whether to repeat or not.Consider the example below with image in background with no-repeat mode.<!DOCTYPE html><html><head> <style> input{ width: 20%; background-image: url('search.png'); background-position: 10px 10px; background-repeat: no-repeat; padding: 12px 20px 12px 40px; } body{ background-color:white; } </style></head> <body> <center> <form> <b>Search on Geeksforgeeks</b><br> <input type="text" name="info" placeholder="Search.."><br> </form> </center></body></html> Output:
Consider the example below with image in background with no-repeat mode.
<!DOCTYPE html><html><head> <style> input{ width: 20%; background-image: url('search.png'); background-position: 10px 10px; background-repeat: no-repeat; padding: 12px 20px 12px 40px; } body{ background-color:white; } </style></head> <body> <center> <form> <b>Search on Geeksforgeeks</b><br> <input type="text" name="info" placeholder="Search.."><br> </form> </center></body></html>
Output:
Transition Property: The transition property can be used over the input field to bring change in the size of the field by specifying the relaxed width and focused width along with the time period for which operation will take place.Consider below example where relaxed input field width is 15% which when focused changes to 30% in 1 second.<!DOCTYPE html><html><head> <style> input{ width: 15%; -webkit-transition: width 1s ease-in-out; transition: width 1s ease-in-out; } input[type=text]:focus { width: 30%; border:4px solid blue; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Search on Geeksforgeeks</b><br> <input type="text" name="info" placeholder="Search.."><br> </form> </center></body></html> Output:When Relaxed-When focused-
Consider below example where relaxed input field width is 15% which when focused changes to 30% in 1 second.
<!DOCTYPE html><html><head> <style> input{ width: 15%; -webkit-transition: width 1s ease-in-out; transition: width 1s ease-in-out; } input[type=text]:focus { width: 30%; border:4px solid blue; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Search on Geeksforgeeks</b><br> <input type="text" name="info" placeholder="Search.."><br> </form> </center></body></html>
Output:When Relaxed-When focused-
CSS-Advanced
Picked
Technical Scripter 2018
CSS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jan, 2019"
},
{
"code": null,
"e": 148,
"s": 54,
"text": "CSS form is used to create interactive form for user. It provides many ways to set the style."
},
{
"code": null,
"e": 300,
"s": 148,
"text": "There are many CSS properties available which can be used to create and style HTML forms to make them more interactive, some of which are listed below:"
},
{
"code": null,
"e": 1490,
"s": 300,
"text": "Attribute Selector: The attribute type of the input form can take a variety of form depending on user’s choice. It could be anything out of the possible types like text, search, url, tel, email, password, date pickers, number, checkbox, radio, file etc. User needs to specify type while creating a form.Example:<!DOCTYPE html><html> <head> <style> body{ background-color:green; } </style> </head> <body> <center> <b>Is Geeksforgeeks useful ?</b> <form> <input type=\"radio\" name=\"useful\" value=\"yes\" checked> Yes <br> <input type=\"radio\" name=\"useful\" value=\"def_yes\"> Definitely Yes </form> </center> </body></html> Output:Consider another example where the input type is simply a text:<!DOCTYPE html><html><head> <style> body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b> <br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> Output:"
},
{
"code": null,
"e": 1499,
"s": 1490,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body{ background-color:green; } </style> </head> <body> <center> <b>Is Geeksforgeeks useful ?</b> <form> <input type=\"radio\" name=\"useful\" value=\"yes\" checked> Yes <br> <input type=\"radio\" name=\"useful\" value=\"def_yes\"> Definitely Yes </form> </center> </body></html> ",
"e": 1988,
"s": 1499,
"text": null
},
{
"code": null,
"e": 2059,
"s": 1988,
"text": "Output:Consider another example where the input type is simply a text:"
},
{
"code": "<!DOCTYPE html><html><head> <style> body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b> <br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> ",
"e": 2373,
"s": 2059,
"text": null
},
{
"code": null,
"e": 2381,
"s": 2373,
"text": "Output:"
},
{
"code": null,
"e": 2927,
"s": 2381,
"text": "Styling the Width of Input: The width property is used to set the width of the input field. Consider the below example where the width is set to be 10% of the entire screen.<!DOCTYPE html><html><head> <style> input{ width:10%; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b> <br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> Output:"
},
{
"code": "<!DOCTYPE html><html><head> <style> input{ width:10%; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b> <br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> ",
"e": 3293,
"s": 2927,
"text": null
},
{
"code": null,
"e": 3301,
"s": 3293,
"text": "Output:"
},
{
"code": null,
"e": 3820,
"s": 3301,
"text": "Add Padding in Inputs: The padding property is used to add spaces inside the text field. Consider the below example:<!DOCTYPE html><html><head> <style> input{ width:10%; padding: 12px; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> Output:"
},
{
"code": "<!DOCTYPE html><html><head> <style> input{ width:10%; padding: 12px; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Do you find Geeksforgeeks helpful?</b><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> ",
"e": 4216,
"s": 3820,
"text": null
},
{
"code": null,
"e": 4224,
"s": 4216,
"text": "Output:"
},
{
"code": null,
"e": 4898,
"s": 4224,
"text": "Set Margin for Inputs: The margin property is used to add space outside the input field. It is helpful when there are many inputs. Consider the example below with two inputs and observe the space (margin) between them.<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Mention two topics that you liked on Geeksforgeeks</b> <br> <input type=\"text\" name=\"info\"><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> Output:"
},
{
"code": "<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Mention two topics that you liked on Geeksforgeeks</b> <br> <input type=\"text\" name=\"info\"><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> ",
"e": 5347,
"s": 4898,
"text": null
},
{
"code": null,
"e": 5355,
"s": 5347,
"text": "Output:"
},
{
"code": null,
"e": 7047,
"s": 5355,
"text": "Adding Border and Border-radius: The border property is used to bring change in the size and color of the border whereas border-radius property is used for adding rounded corners.Consider the below example where a 2px solid red border is created with a border radius of 4px.<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: 2px solid red; border-radius: 4px; } body{ background-color:green; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type=\"text\" name=\"info\"><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> Output:Note: User can also have border at any particular side and remove others or have all borders of different color. Consider the below example where user want border only on top(blue color) and bottom(red color).<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: none; border-top: 3px solid blue; border-bottom: 3px solid red; } body{ background-color:green; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type=\"text\" name=\"info\"><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> Output:"
},
{
"code": null,
"e": 7143,
"s": 7047,
"text": "Consider the below example where a 2px solid red border is created with a border radius of 4px."
},
{
"code": "<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: 2px solid red; border-radius: 4px; } body{ background-color:green; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type=\"text\" name=\"info\"><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> ",
"e": 7721,
"s": 7143,
"text": null
},
{
"code": null,
"e": 7729,
"s": 7721,
"text": "Output:"
},
{
"code": null,
"e": 7939,
"s": 7729,
"text": "Note: User can also have border at any particular side and remove others or have all borders of different color. Consider the below example where user want border only on top(blue color) and bottom(red color)."
},
{
"code": "<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: none; border-top: 3px solid blue; border-bottom: 3px solid red; } body{ background-color:green; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type=\"text\" name=\"info\"><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> ",
"e": 8557,
"s": 7939,
"text": null
},
{
"code": null,
"e": 8565,
"s": 8557,
"text": "Output:"
},
{
"code": null,
"e": 9472,
"s": 8565,
"text": "Adding Color to text and Background: The color property is used to change the color of the text in the input and the background-color property is used to change the color of the background of the input field.Consider the below example where color of text is black and background color is set to green.<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: none; background-color: green; color: black; } body{ background-color:white; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type=\"text\" name=\"info\"><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> Output:"
},
{
"code": null,
"e": 9566,
"s": 9472,
"text": "Consider the below example where color of text is black and background color is set to green."
},
{
"code": "<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; border: none; background-color: green; color: black; } body{ background-color:white; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type=\"text\" name=\"info\"><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> ",
"e": 10165,
"s": 9566,
"text": null
},
{
"code": null,
"e": 10173,
"s": 10165,
"text": "Output:"
},
{
"code": null,
"e": 11035,
"s": 10173,
"text": "Focus Selector: When we click on the input field it gets an outline of blue color. You can change this behaviour by using :focus selector.Consider the below example where user wants a 3px solid red outline and green background when focused.<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; color: black; } input[type=text]:focus { border: 3px solid red; background-color: green; } body{ background-color:white; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type=\"text\" name=\"info\"><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> Output:"
},
{
"code": null,
"e": 11138,
"s": 11035,
"text": "Consider the below example where user wants a 3px solid red outline and green background when focused."
},
{
"code": "<!DOCTYPE html><html><head> <style> input{ width:10%; margin: 8px; color: black; } input[type=text]:focus { border: 3px solid red; background-color: green; } body{ background-color:white; } </style></head> <body> <center> <form> <b> Mention two topics that you liked on Geeksforgeeks </b> <br> <input type=\"text\" name=\"info\"><br> <input type=\"text\" name=\"info\"><br> </form> </center></body></html> ",
"e": 11753,
"s": 11138,
"text": null
},
{
"code": null,
"e": 11761,
"s": 11753,
"text": "Output:"
},
{
"code": null,
"e": 12604,
"s": 11761,
"text": "Adding images in the Input form: The background-image property can be used to put an image inside the input form and it can be positioned using background-position property and user can also decide whether to repeat or not.Consider the example below with image in background with no-repeat mode.<!DOCTYPE html><html><head> <style> input{ width: 20%; background-image: url('search.png'); background-position: 10px 10px; background-repeat: no-repeat; padding: 12px 20px 12px 40px; } body{ background-color:white; } </style></head> <body> <center> <form> <b>Search on Geeksforgeeks</b><br> <input type=\"text\" name=\"info\" placeholder=\"Search..\"><br> </form> </center></body></html> Output:"
},
{
"code": null,
"e": 12677,
"s": 12604,
"text": "Consider the example below with image in background with no-repeat mode."
},
{
"code": "<!DOCTYPE html><html><head> <style> input{ width: 20%; background-image: url('search.png'); background-position: 10px 10px; background-repeat: no-repeat; padding: 12px 20px 12px 40px; } body{ background-color:white; } </style></head> <body> <center> <form> <b>Search on Geeksforgeeks</b><br> <input type=\"text\" name=\"info\" placeholder=\"Search..\"><br> </form> </center></body></html> ",
"e": 13218,
"s": 12677,
"text": null
},
{
"code": null,
"e": 13226,
"s": 13218,
"text": "Output:"
},
{
"code": null,
"e": 14172,
"s": 13226,
"text": "Transition Property: The transition property can be used over the input field to bring change in the size of the field by specifying the relaxed width and focused width along with the time period for which operation will take place.Consider below example where relaxed input field width is 15% which when focused changes to 30% in 1 second.<!DOCTYPE html><html><head> <style> input{ width: 15%; -webkit-transition: width 1s ease-in-out; transition: width 1s ease-in-out; } input[type=text]:focus { width: 30%; border:4px solid blue; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Search on Geeksforgeeks</b><br> <input type=\"text\" name=\"info\" placeholder=\"Search..\"><br> </form> </center></body></html> Output:When Relaxed-When focused-"
},
{
"code": null,
"e": 14281,
"s": 14172,
"text": "Consider below example where relaxed input field width is 15% which when focused changes to 30% in 1 second."
},
{
"code": "<!DOCTYPE html><html><head> <style> input{ width: 15%; -webkit-transition: width 1s ease-in-out; transition: width 1s ease-in-out; } input[type=text]:focus { width: 30%; border:4px solid blue; } body{ background-color:green; } </style></head> <body> <center> <form> <b>Search on Geeksforgeeks</b><br> <input type=\"text\" name=\"info\" placeholder=\"Search..\"><br> </form> </center></body></html> ",
"e": 14854,
"s": 14281,
"text": null
},
{
"code": null,
"e": 14888,
"s": 14854,
"text": "Output:When Relaxed-When focused-"
},
{
"code": null,
"e": 14901,
"s": 14888,
"text": "CSS-Advanced"
},
{
"code": null,
"e": 14908,
"s": 14901,
"text": "Picked"
},
{
"code": null,
"e": 14932,
"s": 14908,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 14936,
"s": 14932,
"text": "CSS"
},
{
"code": null,
"e": 14955,
"s": 14936,
"text": "Technical Scripter"
},
{
"code": null,
"e": 14972,
"s": 14955,
"text": "Web Technologies"
},
{
"code": null,
"e": 15070,
"s": 14972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15118,
"s": 15070,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 15180,
"s": 15118,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 15230,
"s": 15180,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 15288,
"s": 15230,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 15338,
"s": 15288,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 15400,
"s": 15338,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 15433,
"s": 15400,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 15494,
"s": 15433,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 15544,
"s": 15494,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to read only the first line of a file with Python? | To read only the first line of a file, open the file in read mode and call readline method on the file object. For example,
f = open('my_file.txt', 'r')
line = f.readline()
print line
f.close()
The above code reads first line from my_file.txt and prints to stdout. A safer approach would be using the with open syntax to avoid file from not closeing in case of an exception:
with open('my_file.txt', 'r') as f:
print f.readline() | [
{
"code": null,
"e": 1311,
"s": 1187,
"text": "To read only the first line of a file, open the file in read mode and call readline method on the file object. For example,"
},
{
"code": null,
"e": 1381,
"s": 1311,
"text": "f = open('my_file.txt', 'r')\nline = f.readline()\nprint line\nf.close()"
},
{
"code": null,
"e": 1562,
"s": 1381,
"text": "The above code reads first line from my_file.txt and prints to stdout. A safer approach would be using the with open syntax to avoid file from not closeing in case of an exception:"
},
{
"code": null,
"e": 1621,
"s": 1562,
"text": "with open('my_file.txt', 'r') as f:\n print f.readline()"
}
] |
Python Program for KMP Algorithm for Pattern Searching | 08 Jun, 2022
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m. Examples:
Input: txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: Pattern found at index 10
Input: txt[] = "AABAACAADAABAABA"
pat[] = "AABA"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results.
Python3
# Python program for KMP Algorithmdef KMPSearch(pat, txt): M = len(pat) N = len(txt) # create lps[] that will hold the longest prefix suffix # values for pattern lps = [0]*M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps) i = 0 # index for txt[] while i < N: if pat[j] == txt[i]: i += 1 j += 1 if j == M: print ("Found pattern at index", str(i-j)) j = lps[j-1] # mismatch after j matches elif i < N and pat[j] != txt[i]: # Do not match lps[0..lps[j-1]] characters, # they will match anyway if j != 0: j = lps[j-1] else: i += 1 def computeLPSArray(pat, M, lps): len = 0 # length of the previous longest prefix suffix lps[0] # lps[0] is always 0 i = 1 # the loop calculates lps[i] for i = 1 to M-1 while i < M: if pat[i]== pat[len]: len += 1 lps[i] = len i += 1 else: # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if len != 0: len = lps[len-1] # Also, note that we do not increment i here else: lps[i] = 0 i += 1 txt = "ABABDABACDABABCABAB"pat = "ABABCABAB"KMPSearch(pat, txt) # This code is contributed by Bhavya Jain
Found pattern at index 10
Time Complexity: O(m+n)
Space Complexity: O(m)
Please refer complete article on KMP Algorithm for Pattern Searching for more details!
amartyaghoshgfg
chandramauliguptach
python searching-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to interchange first and last elements in a list
Appending to list in Python dictionary
Differences and Applications of List, Tuple, Set and Dictionary in Python
Appending a dictionary to a list in Python
Python Program to check Armstrong Number
Python | Difference between two dates (in minutes) using datetime.timedelta() method
Python | Remove spaces from a string
Python Program for Merge Sort
Python - Convert JSON to string
Python Program for simple interest | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 237,
"s": 52,
"text": "Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m. Examples: "
},
{
"code": null,
"e": 493,
"s": 237,
"text": "Input: txt[] = \"THIS IS A TEST TEXT\"\n pat[] = \"TEST\"\nOutput: Pattern found at index 10\n\nInput: txt[] = \"AABAACAADAABAABA\"\n pat[] = \"AABA\"\nOutput: Pattern found at index 0\n Pattern found at index 9\n Pattern found at index 12"
},
{
"code": null,
"e": 702,
"s": 495,
"text": "Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results. "
},
{
"code": null,
"e": 710,
"s": 702,
"text": "Python3"
},
{
"code": "# Python program for KMP Algorithmdef KMPSearch(pat, txt): M = len(pat) N = len(txt) # create lps[] that will hold the longest prefix suffix # values for pattern lps = [0]*M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps) i = 0 # index for txt[] while i < N: if pat[j] == txt[i]: i += 1 j += 1 if j == M: print (\"Found pattern at index\", str(i-j)) j = lps[j-1] # mismatch after j matches elif i < N and pat[j] != txt[i]: # Do not match lps[0..lps[j-1]] characters, # they will match anyway if j != 0: j = lps[j-1] else: i += 1 def computeLPSArray(pat, M, lps): len = 0 # length of the previous longest prefix suffix lps[0] # lps[0] is always 0 i = 1 # the loop calculates lps[i] for i = 1 to M-1 while i < M: if pat[i]== pat[len]: len += 1 lps[i] = len i += 1 else: # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if len != 0: len = lps[len-1] # Also, note that we do not increment i here else: lps[i] = 0 i += 1 txt = \"ABABDABACDABABCABAB\"pat = \"ABABCABAB\"KMPSearch(pat, txt) # This code is contributed by Bhavya Jain",
"e": 2196,
"s": 710,
"text": null
},
{
"code": null,
"e": 2222,
"s": 2196,
"text": "Found pattern at index 10"
},
{
"code": null,
"e": 2248,
"s": 2224,
"text": "Time Complexity: O(m+n)"
},
{
"code": null,
"e": 2271,
"s": 2248,
"text": "Space Complexity: O(m)"
},
{
"code": null,
"e": 2359,
"s": 2271,
"text": "Please refer complete article on KMP Algorithm for Pattern Searching for more details! "
},
{
"code": null,
"e": 2375,
"s": 2359,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 2395,
"s": 2375,
"text": "chandramauliguptach"
},
{
"code": null,
"e": 2422,
"s": 2395,
"text": "python searching-exercises"
},
{
"code": null,
"e": 2438,
"s": 2422,
"text": "Python Programs"
},
{
"code": null,
"e": 2536,
"s": 2438,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2600,
"s": 2536,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 2639,
"s": 2600,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 2713,
"s": 2639,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 2756,
"s": 2713,
"text": "Appending a dictionary to a list in Python"
},
{
"code": null,
"e": 2797,
"s": 2756,
"text": "Python Program to check Armstrong Number"
},
{
"code": null,
"e": 2882,
"s": 2797,
"text": "Python | Difference between two dates (in minutes) using datetime.timedelta() method"
},
{
"code": null,
"e": 2919,
"s": 2882,
"text": "Python | Remove spaces from a string"
},
{
"code": null,
"e": 2949,
"s": 2919,
"text": "Python Program for Merge Sort"
},
{
"code": null,
"e": 2981,
"s": 2949,
"text": "Python - Convert JSON to string"
}
] |
Queries for number of distinct elements in a subarray | 23 Mar, 2022
Given a array ‘a[]’ of size n and number of queries q. Each query can be represented by two integers l and r. Your task is to print the number of distinct integers in the subarray l to r. Given a[i] <= 106 Examples:
Input : a[] = {1, 1, 2, 1, 3}
q = 3
0 4
1 3
2 4
Output :3
2
3
In query 1, number of distinct integers
in a[0...4] is 3 (1, 2, 3)
In query 2, number of distinct integers
in a[1..3] is 2 (1, 2)
In query 3, number of distinct integers
in a[2..4] is 3 (1, 2, 3)
The idea is to use Binary Indexed Tree
Step 1 : Take an array last_visit of size 10^6 where last_visit[i] holds the rightmost index of the number i in the array a. Initialize this array as -1.Step 2 : Sort all the queries in ascending order of their right end r.Step 3 : Create a Binary Indexed Tree in an array bit[]. Start traversing the array ‘a’ and queries simultaneously and check if last_visit[a[i]] is -1 or not. If it is not, update the bit array with value -1 at the idx last_visit[a[i]].Step 4 : Set last_visit[a[i]] = i and update the bit array bit array with value 1 at idx i.Step 5 : Answer all the queries whose value of r is equal to i by querying the bit array. This can be easily done as queries are sorted.
Step 1 : Take an array last_visit of size 10^6 where last_visit[i] holds the rightmost index of the number i in the array a. Initialize this array as -1.
Step 2 : Sort all the queries in ascending order of their right end r.
Step 3 : Create a Binary Indexed Tree in an array bit[]. Start traversing the array ‘a’ and queries simultaneously and check if last_visit[a[i]] is -1 or not. If it is not, update the bit array with value -1 at the idx last_visit[a[i]].
Step 4 : Set last_visit[a[i]] = i and update the bit array bit array with value 1 at idx i.
Step 5 : Answer all the queries whose value of r is equal to i by querying the bit array. This can be easily done as queries are sorted.
C++
Java
Python3
Javascript
// C++ code to find number of distinct numbers// in a subarray#include<bits/stdc++.h>using namespace std; const int MAX = 1000001; // structure to store queriesstruct Query{ int l, r, idx;}; // cmp function to sort queries according to rbool cmp(Query x, Query y){ return x.r < y.r;} // updating the bit arrayvoid update(int idx, int val, int bit[], int n){ for (; idx <= n; idx += idx&-idx) bit[idx] += val;} // querying the bit arrayint query(int idx, int bit[], int n){ int sum = 0; for (; idx>0; idx-=idx&-idx) sum += bit[idx]; return sum;} void answeringQueries(int arr[], int n, Query queries[], int q){ // initialising bit array int bit[n+1]; memset(bit, 0, sizeof(bit)); // holds the rightmost index of any number // as numbers of a[i] are less than or equal to 10^6 int last_visit[MAX]; memset(last_visit, -1, sizeof(last_visit)); // answer for each query int ans[q]; int query_counter = 0; for (int i=0; i<n; i++) { // If last visit is not -1 update -1 at the // idx equal to last_visit[arr[i]] if (last_visit[arr[i]] !=-1) update (last_visit[arr[i]] + 1, -1, bit, n); // Setting last_visit[arr[i]] as i and updating // the bit array accordingly last_visit[arr[i]] = i; update(i + 1, 1, bit, n); // If i is equal to r of any query store answer // for that query in ans[] while (query_counter < q && queries[query_counter].r == i) { ans[queries[query_counter].idx] = query(queries[query_counter].r + 1, bit, n)- query(queries[query_counter].l, bit, n); query_counter++; } } // print answer for each query for (int i=0; i<q; i++) cout << ans[i] << endl;} // driver codeint main(){ int a[] = {1, 1, 2, 1, 3}; int n = sizeof(a)/sizeof(a[0]); Query queries[3]; queries[0].l = 0; queries[0].r = 4; queries[0].idx = 0; queries[1].l = 1; queries[1].r = 3; queries[1].idx = 1; queries[2].l = 2; queries[2].r = 4; queries[2].idx = 2; int q = sizeof(queries)/sizeof(queries[0]); sort(queries, queries+q, cmp); answeringQueries(a, n, queries, q); return 0;}
// Java code to find number of distinct numbers// in a subarrayimport java.io.*;import java.util.*; class GFG{ static int MAX = 1000001; // structure to store queries static class Query { int l, r, idx; } // updating the bit array static void update(int idx, int val, int bit[], int n) { for (; idx <= n; idx += idx & -idx) bit[idx] += val; } // querying the bit array static int query(int idx, int bit[], int n) { int sum = 0; for (; idx > 0; idx -= idx & -idx) sum += bit[idx]; return sum; } static void answeringQueries(int[] arr, int n, Query[] queries, int q) { // initialising bit array int[] bit = new int[n + 1]; Arrays.fill(bit, 0); // holds the rightmost index of any number // as numbers of a[i] are less than or equal to 10^6 int[] last_visit = new int[MAX]; Arrays.fill(last_visit, -1); // answer for each query int[] ans = new int[q]; int query_counter = 0; for (int i = 0; i < n; i++) { // If last visit is not -1 update -1 at the // idx equal to last_visit[arr[i]] if (last_visit[arr[i]] != -1) update(last_visit[arr[i]] + 1, -1, bit, n); // Setting last_visit[arr[i]] as i and updating // the bit array accordingly last_visit[arr[i]] = i; update(i + 1, 1, bit, n); // If i is equal to r of any query store answer // for that query in ans[] while (query_counter < q && queries[query_counter].r == i) { ans[queries[query_counter].idx] = query(queries[query_counter].r + 1, bit, n) - query(queries[query_counter].l, bit, n); query_counter++; } } // print answer for each query for (int i = 0; i < q; i++) System.out.println(ans[i]); } // Driver Code public static void main(String[] args) { int a[] = { 1, 1, 2, 1, 3 }; int n = a.length; Query[] queries = new Query[3]; for (int i = 0; i < 3; i++) queries[i] = new Query(); queries[0].l = 0; queries[0].r = 4; queries[0].idx = 0; queries[1].l = 1; queries[1].r = 3; queries[1].idx = 1; queries[2].l = 2; queries[2].r = 4; queries[2].idx = 2; int q = queries.length; Arrays.sort(queries, new Comparator<Query>() { public int compare(Query x, Query y) { if (x.r < y.r) return -1; else if (x.r == y.r) return 0; else return 1; } }); answeringQueries(a, n, queries, q); }} // This code is contributed by// sanjeev2552
# Python3 code to find number of# distinct numbers in a subarrayMAX = 1000001 # structure to store queriesclass Query: def __init__(self, l, r, idx): self.l = l self.r = r self.idx = idx # updating the bit arraydef update(idx, val, bit, n): while idx <= n: bit[idx] += val idx += idx & -idx # querying the bit arraydef query(idx, bit, n): summ = 0 while idx: summ += bit[idx] idx -= idx & -idx return summ def answeringQueries(arr, n, queries, q): # initialising bit array bit = [0] * (n + 1) # holds the rightmost index of # any number as numbers of a[i] # are less than or equal to 10^6 last_visit = [-1] * MAX # answer for each query ans = [0] * q query_counter = 0 for i in range(n): # If last visit is not -1 update -1 at the # idx equal to last_visit[arr[i]] if last_visit[arr[i]] != -1: update(last_visit[arr[i]] + 1, -1, bit, n) # Setting last_visit[arr[i]] as i and # updating the bit array accordingly last_visit[arr[i]] = i update(i + 1, 1, bit, n) # If i is equal to r of any query store answer # for that query in ans[] while query_counter < q and queries[query_counter].r == i: ans[queries[query_counter].idx] = \ query(queries[query_counter].r + 1, bit, n) - \ query(queries[query_counter].l, bit, n) query_counter += 1 # print answer for each query for i in range(q): print(ans[i]) # Driver Codeif __name__ == "__main__": a = [1, 1, 2, 1, 3] n = len(a) queries = [Query(0, 4, 0), Query(1, 3, 1), Query(2, 4, 2)] q = len(queries) queries.sort(key = lambda x: x.r) answeringQueries(a, n, queries, q) # This code is contributed by# sanjeev2552
<script> // JavaScript code to find number of// distinct numbers in a subarrayconst MAX = 1000001 // structure to store queriesclass Query{ constructor(l, r, idx){ this.l = l this.r = r this.idx = idx }} // updating the bit arrayfunction update(idx, val, bit, n){ while(idx <= n){ bit[idx] += val idx += idx & -idx }} // querying the bit arrayfunction query(idx, bit, n){ let summ = 0 while(idx){ summ += bit[idx] idx -= idx & -idx } return summ} function answeringQueries(arr, n, queries, q){ // initialising bit array let bit = new Array(n+1).fill(0) // holds the rightmost index of // any number as numbers of a[i] // are less than or equal to 10^6 let last_visit = new Array(MAX).fill(-1) // answer for each query let ans = new Array(q).fill(0); let query_counter = 0 for(let i=0;i<n;i++){ // If last visit is not -1 update -1 at the // idx equal to last_visit[arr[i]] if(last_visit[arr[i]] != -1) update(last_visit[arr[i]] + 1, -1, bit, n) // Setting last_visit[arr[i]] as i and // updating the bit array accordingly last_visit[arr[i]] = i update(i + 1, 1, bit, n) // If i is equal to r of any query store answer // for that query in ans[] while(query_counter < q && queries[query_counter].r == i){ ans[queries[query_counter].idx] = query(queries[query_counter].r + 1, bit, n) - query(queries[query_counter].l, bit, n) query_counter += 1 } } // print answer for each query for(let i=0;i<q;i++) document.write(ans[i],"</br>")} // Driver Code let a = [1, 1, 2, 1, 3]let n = a.lengthlet queries = [new Query(0, 4, 0),new Query(1, 3, 1),new Query(2, 4, 2)]let q = queries.length queries.sort((x,y) => x.r-y.r)answeringQueries(a, n, queries, q) // This code is contributed by shinjanpatra </script>
3
2
3
This article is contributed by Ayush Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sanjeev2552
shinjanpatra
array-range-queries
Binary Indexed Tree
Advanced Data Structure
Binary Indexed Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Agents in Artificial Intelligence
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Disjoint Set Data Structures
Difference between B tree and B+ tree
Insert Operation in B-Tree
Design a Chess Game
Red-Black Tree | Set 2 (Insert)
Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)
Largest Rectangular Area in a Histogram | Set 1 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 268,
"s": 52,
"text": "Given a array ‘a[]’ of size n and number of queries q. Each query can be represented by two integers l and r. Your task is to print the number of distinct integers in the subarray l to r. Given a[i] <= 106 Examples:"
},
{
"code": null,
"e": 576,
"s": 268,
"text": "Input : a[] = {1, 1, 2, 1, 3}\n q = 3\n 0 4\n 1 3\n 2 4\nOutput :3\n 2\n 3\nIn query 1, number of distinct integers\nin a[0...4] is 3 (1, 2, 3)\nIn query 2, number of distinct integers \nin a[1..3] is 2 (1, 2)\nIn query 3, number of distinct integers \nin a[2..4] is 3 (1, 2, 3)"
},
{
"code": null,
"e": 616,
"s": 576,
"text": "The idea is to use Binary Indexed Tree "
},
{
"code": null,
"e": 1303,
"s": 616,
"text": "Step 1 : Take an array last_visit of size 10^6 where last_visit[i] holds the rightmost index of the number i in the array a. Initialize this array as -1.Step 2 : Sort all the queries in ascending order of their right end r.Step 3 : Create a Binary Indexed Tree in an array bit[]. Start traversing the array ‘a’ and queries simultaneously and check if last_visit[a[i]] is -1 or not. If it is not, update the bit array with value -1 at the idx last_visit[a[i]].Step 4 : Set last_visit[a[i]] = i and update the bit array bit array with value 1 at idx i.Step 5 : Answer all the queries whose value of r is equal to i by querying the bit array. This can be easily done as queries are sorted."
},
{
"code": null,
"e": 1457,
"s": 1303,
"text": "Step 1 : Take an array last_visit of size 10^6 where last_visit[i] holds the rightmost index of the number i in the array a. Initialize this array as -1."
},
{
"code": null,
"e": 1528,
"s": 1457,
"text": "Step 2 : Sort all the queries in ascending order of their right end r."
},
{
"code": null,
"e": 1765,
"s": 1528,
"text": "Step 3 : Create a Binary Indexed Tree in an array bit[]. Start traversing the array ‘a’ and queries simultaneously and check if last_visit[a[i]] is -1 or not. If it is not, update the bit array with value -1 at the idx last_visit[a[i]]."
},
{
"code": null,
"e": 1857,
"s": 1765,
"text": "Step 4 : Set last_visit[a[i]] = i and update the bit array bit array with value 1 at idx i."
},
{
"code": null,
"e": 1994,
"s": 1857,
"text": "Step 5 : Answer all the queries whose value of r is equal to i by querying the bit array. This can be easily done as queries are sorted."
},
{
"code": null,
"e": 1998,
"s": 1994,
"text": "C++"
},
{
"code": null,
"e": 2003,
"s": 1998,
"text": "Java"
},
{
"code": null,
"e": 2011,
"s": 2003,
"text": "Python3"
},
{
"code": null,
"e": 2022,
"s": 2011,
"text": "Javascript"
},
{
"code": "// C++ code to find number of distinct numbers// in a subarray#include<bits/stdc++.h>using namespace std; const int MAX = 1000001; // structure to store queriesstruct Query{ int l, r, idx;}; // cmp function to sort queries according to rbool cmp(Query x, Query y){ return x.r < y.r;} // updating the bit arrayvoid update(int idx, int val, int bit[], int n){ for (; idx <= n; idx += idx&-idx) bit[idx] += val;} // querying the bit arrayint query(int idx, int bit[], int n){ int sum = 0; for (; idx>0; idx-=idx&-idx) sum += bit[idx]; return sum;} void answeringQueries(int arr[], int n, Query queries[], int q){ // initialising bit array int bit[n+1]; memset(bit, 0, sizeof(bit)); // holds the rightmost index of any number // as numbers of a[i] are less than or equal to 10^6 int last_visit[MAX]; memset(last_visit, -1, sizeof(last_visit)); // answer for each query int ans[q]; int query_counter = 0; for (int i=0; i<n; i++) { // If last visit is not -1 update -1 at the // idx equal to last_visit[arr[i]] if (last_visit[arr[i]] !=-1) update (last_visit[arr[i]] + 1, -1, bit, n); // Setting last_visit[arr[i]] as i and updating // the bit array accordingly last_visit[arr[i]] = i; update(i + 1, 1, bit, n); // If i is equal to r of any query store answer // for that query in ans[] while (query_counter < q && queries[query_counter].r == i) { ans[queries[query_counter].idx] = query(queries[query_counter].r + 1, bit, n)- query(queries[query_counter].l, bit, n); query_counter++; } } // print answer for each query for (int i=0; i<q; i++) cout << ans[i] << endl;} // driver codeint main(){ int a[] = {1, 1, 2, 1, 3}; int n = sizeof(a)/sizeof(a[0]); Query queries[3]; queries[0].l = 0; queries[0].r = 4; queries[0].idx = 0; queries[1].l = 1; queries[1].r = 3; queries[1].idx = 1; queries[2].l = 2; queries[2].r = 4; queries[2].idx = 2; int q = sizeof(queries)/sizeof(queries[0]); sort(queries, queries+q, cmp); answeringQueries(a, n, queries, q); return 0;}",
"e": 4273,
"s": 2022,
"text": null
},
{
"code": "// Java code to find number of distinct numbers// in a subarrayimport java.io.*;import java.util.*; class GFG{ static int MAX = 1000001; // structure to store queries static class Query { int l, r, idx; } // updating the bit array static void update(int idx, int val, int bit[], int n) { for (; idx <= n; idx += idx & -idx) bit[idx] += val; } // querying the bit array static int query(int idx, int bit[], int n) { int sum = 0; for (; idx > 0; idx -= idx & -idx) sum += bit[idx]; return sum; } static void answeringQueries(int[] arr, int n, Query[] queries, int q) { // initialising bit array int[] bit = new int[n + 1]; Arrays.fill(bit, 0); // holds the rightmost index of any number // as numbers of a[i] are less than or equal to 10^6 int[] last_visit = new int[MAX]; Arrays.fill(last_visit, -1); // answer for each query int[] ans = new int[q]; int query_counter = 0; for (int i = 0; i < n; i++) { // If last visit is not -1 update -1 at the // idx equal to last_visit[arr[i]] if (last_visit[arr[i]] != -1) update(last_visit[arr[i]] + 1, -1, bit, n); // Setting last_visit[arr[i]] as i and updating // the bit array accordingly last_visit[arr[i]] = i; update(i + 1, 1, bit, n); // If i is equal to r of any query store answer // for that query in ans[] while (query_counter < q && queries[query_counter].r == i) { ans[queries[query_counter].idx] = query(queries[query_counter].r + 1, bit, n) - query(queries[query_counter].l, bit, n); query_counter++; } } // print answer for each query for (int i = 0; i < q; i++) System.out.println(ans[i]); } // Driver Code public static void main(String[] args) { int a[] = { 1, 1, 2, 1, 3 }; int n = a.length; Query[] queries = new Query[3]; for (int i = 0; i < 3; i++) queries[i] = new Query(); queries[0].l = 0; queries[0].r = 4; queries[0].idx = 0; queries[1].l = 1; queries[1].r = 3; queries[1].idx = 1; queries[2].l = 2; queries[2].r = 4; queries[2].idx = 2; int q = queries.length; Arrays.sort(queries, new Comparator<Query>() { public int compare(Query x, Query y) { if (x.r < y.r) return -1; else if (x.r == y.r) return 0; else return 1; } }); answeringQueries(a, n, queries, q); }} // This code is contributed by// sanjeev2552",
"e": 7245,
"s": 4273,
"text": null
},
{
"code": "# Python3 code to find number of# distinct numbers in a subarrayMAX = 1000001 # structure to store queriesclass Query: def __init__(self, l, r, idx): self.l = l self.r = r self.idx = idx # updating the bit arraydef update(idx, val, bit, n): while idx <= n: bit[idx] += val idx += idx & -idx # querying the bit arraydef query(idx, bit, n): summ = 0 while idx: summ += bit[idx] idx -= idx & -idx return summ def answeringQueries(arr, n, queries, q): # initialising bit array bit = [0] * (n + 1) # holds the rightmost index of # any number as numbers of a[i] # are less than or equal to 10^6 last_visit = [-1] * MAX # answer for each query ans = [0] * q query_counter = 0 for i in range(n): # If last visit is not -1 update -1 at the # idx equal to last_visit[arr[i]] if last_visit[arr[i]] != -1: update(last_visit[arr[i]] + 1, -1, bit, n) # Setting last_visit[arr[i]] as i and # updating the bit array accordingly last_visit[arr[i]] = i update(i + 1, 1, bit, n) # If i is equal to r of any query store answer # for that query in ans[] while query_counter < q and queries[query_counter].r == i: ans[queries[query_counter].idx] = \\ query(queries[query_counter].r + 1, bit, n) - \\ query(queries[query_counter].l, bit, n) query_counter += 1 # print answer for each query for i in range(q): print(ans[i]) # Driver Codeif __name__ == \"__main__\": a = [1, 1, 2, 1, 3] n = len(a) queries = [Query(0, 4, 0), Query(1, 3, 1), Query(2, 4, 2)] q = len(queries) queries.sort(key = lambda x: x.r) answeringQueries(a, n, queries, q) # This code is contributed by# sanjeev2552",
"e": 9113,
"s": 7245,
"text": null
},
{
"code": "<script> // JavaScript code to find number of// distinct numbers in a subarrayconst MAX = 1000001 // structure to store queriesclass Query{ constructor(l, r, idx){ this.l = l this.r = r this.idx = idx }} // updating the bit arrayfunction update(idx, val, bit, n){ while(idx <= n){ bit[idx] += val idx += idx & -idx }} // querying the bit arrayfunction query(idx, bit, n){ let summ = 0 while(idx){ summ += bit[idx] idx -= idx & -idx } return summ} function answeringQueries(arr, n, queries, q){ // initialising bit array let bit = new Array(n+1).fill(0) // holds the rightmost index of // any number as numbers of a[i] // are less than or equal to 10^6 let last_visit = new Array(MAX).fill(-1) // answer for each query let ans = new Array(q).fill(0); let query_counter = 0 for(let i=0;i<n;i++){ // If last visit is not -1 update -1 at the // idx equal to last_visit[arr[i]] if(last_visit[arr[i]] != -1) update(last_visit[arr[i]] + 1, -1, bit, n) // Setting last_visit[arr[i]] as i and // updating the bit array accordingly last_visit[arr[i]] = i update(i + 1, 1, bit, n) // If i is equal to r of any query store answer // for that query in ans[] while(query_counter < q && queries[query_counter].r == i){ ans[queries[query_counter].idx] = query(queries[query_counter].r + 1, bit, n) - query(queries[query_counter].l, bit, n) query_counter += 1 } } // print answer for each query for(let i=0;i<q;i++) document.write(ans[i],\"</br>\")} // Driver Code let a = [1, 1, 2, 1, 3]let n = a.lengthlet queries = [new Query(0, 4, 0),new Query(1, 3, 1),new Query(2, 4, 2)]let q = queries.length queries.sort((x,y) => x.r-y.r)answeringQueries(a, n, queries, q) // This code is contributed by shinjanpatra </script>",
"e": 11049,
"s": 9113,
"text": null
},
{
"code": null,
"e": 11055,
"s": 11049,
"text": "3\n2\n3"
},
{
"code": null,
"e": 11473,
"s": 11055,
"text": "This article is contributed by Ayush Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 11485,
"s": 11473,
"text": "sanjeev2552"
},
{
"code": null,
"e": 11498,
"s": 11485,
"text": "shinjanpatra"
},
{
"code": null,
"e": 11518,
"s": 11498,
"text": "array-range-queries"
},
{
"code": null,
"e": 11538,
"s": 11518,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 11562,
"s": 11538,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 11582,
"s": 11562,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 11680,
"s": 11582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11714,
"s": 11680,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 11754,
"s": 11714,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 11782,
"s": 11754,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 11811,
"s": 11782,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 11849,
"s": 11811,
"text": "Difference between B tree and B+ tree"
},
{
"code": null,
"e": 11876,
"s": 11849,
"text": "Insert Operation in B-Tree"
},
{
"code": null,
"e": 11896,
"s": 11876,
"text": "Design a Chess Game"
},
{
"code": null,
"e": 11928,
"s": 11896,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 12008,
"s": 11928,
"text": "Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)"
}
] |
Using D3.js to create dynamic maps and visuals that show competing climate change scenarios for the 21st century | by Zach Alexander | Towards Data Science | As the Biden administration officially takes office over the next week, optimism emerges over a redirected effort towards combating climate change. Because of this, I thought it would be interesting to explore the potential effects of policy action (or inaction) on this issue over the next 80 years.
Recently, I worked on a full data visualization story comparing temperature-change projections for two competing climate change scenarios. The two scenarios (“A2” and “B1”) were developed by the IPCC at the beginning of the 21st century. These scenarios outline different levels of world-wide collaboration on this issue and its potential effects on carbon emissions. If you are interested in reading the full data story and interacting with its visualizations, feel free to head over to: zach-alexander.com/climate-change.
After writing this data story, I realized that it may be helpful to write a piece outlining the power of creating web visualizations for audiences. As a data science graduate student (and data engineer by profession), I’m often disappointed by the lack of follow-through (me included) on how we communicate conclusions of our analyses and data that we have worked so tirelessly to perfect. In the end, sometimes the algorithms or models we create can fall flat if they aren’t given context or communicated to audiences in a compelling way. Although there are a lot of data visualization platforms (PowerBI, Tableau, etc.) out there that can spin up quick charts and graphs, building out data stories on the web can take analyses to the next level.
In this write-up, I’ll take a piece of one of the visualizations I created for my data story and hope to provide a foundation of how to use Angular and D3.js to build an animated map that simulates a climate change model for the 21st century.
If you would like to follow along with the full code, you can pull from this repository. It’ll contain all of the code outlined below, including:
Merging and transforming csv data into jsons (python)
Running a local Angular application (Angular-cli)
Installing D3.js and loading json files into an Angular component (Angular)
Using D3.js to create a world map and animate it over 4 time intervals (Angular and Javascript)
If you find yourself wanting to build on the animation that we start in this article, you can pull additional code from my comprehensive data story on this topic.
Before diving into any of the website work, a crucial first step in developing any data visualization is to think about what you ultimately want to portray to your audience.
My goal: I wanted to visually show the change in land temperature (in degrees F) by country over the next 80 years based on an IPCC climate change scenario.
With this goal, I then set out to find a compelling dataset.
Fortunately, there are countless climate change datasets available for use, and this World Bank dataset containing ensemble data that projects changes in land temperature over the next century (based on global circulation models and IPCC climate change scenarios) was exactly what I was looking for.
Well, before we can tackle putting this data onto a webpage, we do have to think critically about what aspect of our data we’d like to present to our audience. Additionally, since D3.js works well with data formatted in JavaScript Object Notation (JSON) format, we’ll have to do some data transformation prior to building our visualization.
Since I would like to create a world map, we also are dealing with geographic coordinates, which take on an even more specific structure of json called “geojson”.
In short, geojson structure is an extension of the json format that is used specifically for encoding a variety of geographic data structures. When working with maps in D3.js, there are many built-in functions and processes that rely on your data being oriented in either geojson or topojson format. The difference between these two can be outlined in detail in this stackoverflow post. The format that we’ll be using, geojson, takes the structure below:
{ "type": "Feature", "geometry": { "type": "Point", "coordinates": [38.00,−97.00] }, "properties": { "name": "United States" }}
For this simple example above, we can see that this data when read into D3.js would draw a point (or dot) in the very center of the contiguous United States. The “geometry” mentioned is of type “point”, and the “coordinates” attached to the point are where the dot would be drawn on the web page. You can also attach specific properties to a point, such as a “name”, which can also be referenced by D3.js (we’ll see this come into play with our color palette later).
Although this is a simple example, you can imagine the “coordinates” getting much longer when you draw specific polygons (or shapes). Essentially, when working with polygons, you are taking a list of points that connect to one another. Each polygon has a set number of coordinates based on a particular projection, and these coordinates are then rendered onto the page. As an example of this in action, if we were to take a look at the polygon coordinates for the state of Nevada, you could find it below:
{ "type": "Feature", "properties": {"name": "Nevada"}, "geometry": { "type": "Polygon", "coordinates": [[[-117.027882,42.000709], [-114.04295,41.995232],[-114.048427,37.000263],[-114.048427,36.195153],[-114.152489,36.025367],[-114.251074,36.01989],[-114.371566,36.140383],[-114.738521,36.102045],[-114.678275,35.516012],[-114.596121,35.324319],[-114.574213,35.138103],[-114.634459,35.00118],[-115.85034,35.970598],[-116.540435,36.501861],[-117.498899,37.21934],[-118.71478,38.101128],[-120.001861,38.999346],[-119.996384,40.264519],[-120.001861,41.995232],[-118.698349,41.989755],[-117.027882,42.000709]]] }}
We can see that the “geometry” is much longer than our first example, and the “type” is now a polygon instead of “point”. The “coordinates” are listed based on the projection utilized, which would then render on the page.
With this new knowledge of geojsons, I devised a plan to take the csv files that have the climate change projections from Kaggle and ultimately transform them into json files for D3. Although a lot of data manipulation can be done right in JavaScript through many of D3s built-in functions (you can read csv data directly into JavaScript), I thought it would be more efficient to manipulate the data prior to loading it on the web page since the dataset is static (and won’t rely on access/connections to a third-party API). The upside of this is that it should make the code more efficient, our visualization more snappy, and cut down on the time needed to render maps and charts on page load.
To do this, I utilized python. You can find the entire jupyter notebook that documents my data transformation on Github.
In summary, after reading in the csv file from Kaggle, I first had to work through a fair amount of data aggregation for the various date ranges and model outputs. Then, I essentially took a public geojson file that had the polygons for all countries in the world, and merged the temperature data and other properties from the Kaggle csv files (utilizing the common identifier in the properties information) into each country’s properties. In the final chunk of code, I created a custom function to output the dataframes as json files:
# array of pandas dataframes with our various model data across the four time intervalsdataframes = [first20_med_a2, first20_med_b1, second20_med_a2, second20_med_b1, third20_med_a2, third20_med_b1, fourth20_med_a2, fourth20_med_b1]# empty array of json files that eventually will load in datajson_files = ['first20_med_a2.json', 'first20_med_b1.json', 'second20_med_a2.json', 'second20_med_b1.json', 'third20_med_a2.json', 'third20_med_b1.json', 'fourth20_med_a2.json', 'fourth20_med_b1.json']# custom function to take the pandas dataframes and store them in separate json filesdef createjsons(): for idx, d in enumerate(dataframes): for i in features: for index, row in d.iterrows(): if(row['Country'] == i['id']): i['Change_c'] = row['Change_c'] i['Change_f'] = row['Change_f'] i['Date_range'] = row['Date_range'] i['Percentile'] = row['Pctile'] i['Scenario'] = row['Type'] else: pass with open(json_files[idx], 'w') as outfile: json.dump(gj, outfile)createjsons()
The ultimate goal of this step was to create separate json files that stored the country name, change in temperature (in degrees C), change in temperature (in degrees F), the date range, the model calculation percentile, and the scenario type.
As we can see below, a country property in one of my final json files looks like this after our data tidying:
# I abbreviated the length of the coordinates to cut down on size of code block{ "type": "Feature", "id": "USA", "geometry": { "type": "MultiPolygon", "coordinates": [[[[-155.54211, 19.08348], [-155.68817, 18.91619], [-155.93665, 19.05939], [-155.90806, 19.33888], [-156.07347, 19.70294], [-156.02368, 19.81422], [-155.85008, 19.97729], [-155.91907, 20.17395], [-155.86108, 20.26721], [-155.78505, 20.2487], [-155.40214, 20.07975], [-155.22452, 19.99302], ...]]] }, "properties": { "name": "United States of America", "Change_c": 1.5040905413108334, "Change_f": 2.7073629743595, "Date_range": "2020-2040", "Percentile": "median", "Scenario": "a2" }}
Similar to our quick geojson examples above, we can see that we are utilizing many points to create our United States polygon, however I used python to merge in additional “properties” to be used later for my visualization. As we’ll see shortly, the change_f value will be used for our choropleth coloration.
With the json files ready to go, we can then start to imagine what our visualization will look like. From a user’s standpoint, we’ll want to show the change in land temperature over time, which we can do by reading in our json files over specific intervals of time — all of which are animated via D3.js.
Okay! Now that we have our data files ready to go, we can spin up a local single page application.
Depending on the JavaScript framework you’d like to use, you’ll need to download the command-line interface (cli) to launch a local server for development and a package manager.
For this example, the package manager we’ll use is npm. One of the easiest ways to install npm is to download node.js, which will also include npm in your installation. The instructions for this can be found here.
As our Javascript framework, we’ll use Angular. To make our operations simple, you can download the Angular cli to start the development server. The instructions can be found here, and consist of four lines.
Once you’ve downloaded node.js and Angular cli, you can open a VSCode terminal window (or any terminal window) and run the following:
// make sure npm is installed on your computer before running this:npm install -g @angular/cli
After this install, find a place on your computer where you want to store your application files, then run (changing “my-dream-app” to whatever you’d like your directory to be called):
ng new my-dream-app
This will take a minute or two to fully run, but in the end it will create a bunch of files that consist of your new Angular application and provide the directory structure needed for compilation. When the command is complete, you can then navigate to the new application folder and run “ng serve” to start the development server.
// change directories into your new angular applicationcd my-dream-app// start the development serverng serve
If all runs correctly, you should be able to compile your newly created Angular application and see this in your terminal:
I won’t go into more detail about how Angular works in order to keep this part brief, but if you are completely new to Angular, please read this excellent post to learn about basic app development. Additionally, the Angular documentation is very helpful for those that prefer to get more in the weeds.
With our Angular development server running, we can now start to build out our visualization. First, we’ll need to install the D3.js package from npm in order to be able to use the library in our application. For this visual, I decided to install version 4 of D3 (for various reasons). To do this, stop your development server in your terminal (ctrl + c) and run:
npm install d3v4
When this is complete, you can then restart the development server by running:
ng serve
You should then see the same “Compiled successfully” message as earlier. Next, we can add our json files to the “assets” directory inside of our application (folder structure below):
|- application-name |- src |- assets |- first20_med_a2.json |- second20_med_a2.json |- third20_med_a2.json |- fourth20_med_a2.json
You can find these json files already pre-made here. However, you you’d like, you can also utilize the python script from above.
If you are using Angular, because we are working with Typescript, you’ll likely also have to do a quick configuration to load the json files directly into the app.component.ts file. This article is a great summary of how to do this. Likely, you’ll just have to add the following line of bolded code to your tsconfig.json file:
{ "compileOnSave": false, "compilerOptions": { . . . "resolveJsonModule": true, . . . }}
With our json data stored inside of the application directory, the D3 library imported into our node_modules, and Angular ready to accept json files, we can start to see the power of data visualizations on the web!
To render one of our json files, we first need to ensure we are referencing it in our app.component.ts file (folder structure below):
|- application-name |- src |- app |- app.component.ts
Navigate to the app.component.ts file and import the json data into the component by adding the bolded code to your existing code code:
import { Component} from '@angular/core';import * as d3 from 'd3v4';// load the json file from the assets folder, give it a nameimport * as firstModel from '../assets/first20_med_a2.json';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent { // make sure to reference the correct structure firstModelData = firstModel['default']; ngOnInit() { // print the json data in the browser console console.log(this.firstModelData) }}
Save this file, return to your browser, and if all goes well, you should be able to see the json data printed to the console in development tools after the page refreshes:
We then need to remove the default html syntax in the app.component.html file and create a quick “div”. Navigate to the app.component.html file (folder structure below):
|- application-name |- src |- app |- app.component.html
Then, delete out all of the html code currently present, and add the following div:
<div class = "world-map"></div>
Now, with the json data reading into the component, we can start to write our D3.js functions. Navigate back to the app.component.ts file, and write the following bolded code inside of the AppComponent class:
export class AppComponent { firstModelData = firstModel['default']; ngOnInit() { console.log(this.firstModelData) } setMap(width, height, dataset) { const margin = {top: 10, right: 30, bottom: 10, left: 30}; width = width - margin.left - margin.right; height = height - margin.top - margin.bottom; const projection = d3.geoMercator() .rotate([-11, 0]) .scale(1) .translate([0, 0]); const path = d3.geoPath().projection(projection); const svg = d3.select('.world-map') .append('svg') .attr('viewBox', '0 0 1000 600') .attr('preserveAspectRatio', 'xMidYMid') .style('max-width', 1200) .style('margin', 'auto') .style('display', 'flex'); const b = path.bounds(datapull), s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0] [1]) / height), t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2]; projection.scale(s).translate(t); svg.selectAll('path') .data(datapull.features) .enter() .append('path') .attr('d', path) }}
In short, this code declares a function setMap() accepting three parameters of width, height, and our dataset. It then defines a margin and subtracts the margin pixels from all four sides of the canvas. Next, since we are using map coordinates, we have to define a map projection, rotating the map slightly so the easternmost part of Russia doesn’t make its way onto the left-side of our canvas, and setting our scale and translation. We then take this projection and map it onto our path, which will eventually draw our polygons based on our projection inputs and our defined dimensions of our canvas.
This then creates our first svg by selecting our blank div using the syntax, “d3.select(“.world-map”). By appending the svg to our existing div, we then set the dimensions and make it responsive by utilizing viewBox and preserveAspectRatio, and eventually set a max width of 1200px and centering the map on the page (if the viewport is larger than 1200px).
We then want to ensure that the scale and translation map on correctly, and the defined bounds of our canvas are correct, so variables s and t help define the bounds of our Mercator projection.
Finally, we select our newly appended svg, read in our geojson features, and draw the path on the page! In order for this to render on the page, we need to take our instantiated function and invoke it in ngOnInit() . Add this line of code into your app.component.ts file inside of the ngOnInit() function.
ngOnInit() { console.log(this.firstModelData) // add this line of code below to render your map: setMap(1000, 600, this.firstModelData)}
If all goes well, you should see something like this on your page:
Alright! Now we are getting somewhere! Unfortunately, though, our polygon fills are coming in black, and we’d like to create a choropleth coloration of each country based on the temperature change in degrees F. Remember when we merged that data into each country property using python? Well, now we can use the change_f value for each country to differentiate our fill colors!
To do this, we can add in the following code inside of our setMap() function (still in our app.component.ts file), and then add an attribute to our svg:
setMap(width, height, dataset) {...const color_domain = [2.5, 4, 7, 9, 10];const color_legend = d3.scaleThreshold<string>().range(['#fee5d9', '#fcbba1', '#fc9272', '#fb6a4a', '#de2d26', '#a50f15']).domain(color_domain);...svg.selectAll('path') .data(datapull.features) .enter() .append('path') .attr('d', path) .style('fill', function(d) { const value = d['Change_f']; if (value) { return color_legend(d['Change_f']); } else { return '#ccc'; }}) .style('stroke', '#fff') .style('stroke-width', '0.5')}
In short, we can use the d3.scaleThreshold() function in D3.js to help us create a choropleth color palette. I won’t go into a lot of detail about this for the sake of time, but you can read more about these scales here, if interested. Additionally, after adding the attribute to our path, I also made the polygon (country) outlines a bit thicker and gray.
If these additions are working correctly, you should see this rendered on your page:
If you’ve made it this far, you can definitely pat yourself on the back! The final step for this visualization is to animate it across different time intervals. If you remember from the beginning, our goal was to show the change in temperature for each country across four different time intervals:
2020 to 2040
2040 to 2060
2060 to 2080
and 2080 to 2100
As you can now see, we were able to create a static choropleth map with just one json file showing temperature changes between 2020 and 2040. However, to animate it across our other three time intervals, we want to load other json files into this function over a set time. D3.js makes this relatively easy.
First, we’ll have to load the rest of our json files into our app.component.ts file similar to the first one we did above. To do this, you can add the following lines of bolded code:
import { Component, OnInit } from '@angular/core';import * as d3 from 'd3';# load the rest of the json files from the assets folder, give it a nameimport * as firstModel from '../assets/first20_med_a2.json';import * as secondModel from '../assets/second20_med_a2.json';import * as thirdModel from '../assets/third20_med_a2.json';import * as fourthModel from '../assets/fourth20_med_a2.json';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {# make sure to reference the correct structurefirstModelData = firstModel['default'];secondModelData = secondModel['default'];thirdModelData = thirdModel['default'];fourthModelData = fourthModel['default'];jsons;...ngOnInit() {...}
Then, we need to store the json files in an array on page load. Therefore, we can add this into our ngOnInit() function:
ngOnInit() {...this.jsons = [this.firstModelData, this.secondModelData, this.thirdModelData, this.fourthModelData]...}
Now, in order for our animation to work, we have to create a new function below our setMap() function, called transitionMap():
transitionMap(json, i) { const svg = d3.select('.world-map'); const color_domain = [2.5, 4, 7, 9, 10]; const color_legend = d3.scaleThreshold<string>().range(['#fee5d9', '#fcbba1', '#fc9272', '#fb6a4a', '#de2d26', '#a50f15']).domain(color_domain);svg.selectAll('path') .data(json[i].features) .transition() .delay(100) .duration(1000) .style('fill', function(d) { const value = d['Change_f']; if (value) { return color_legend(d['Change_f']); } else { return '#ccc'; } })}
This function will take two arguments, our json and the iterator value that will serve as our index number for our json array. When the function is invoked, it’ll select our map svg, refresh the color pallete, and then redraw our map with the data referenced in the corresponding json. Because our .data() function is referencing json[i], we can cycle through the json array we just created and load each of json files in succession after a delay and a specific duration.
Now, we can set a time interval to define our “i” value by using the setInterval() function in Javascript. By adding the following code to the bottom of our ngOnInit() function, this process will start on page load:
ngOnInit() {... let time = 1; let interval = setInterval(() => { if (time <= 3) { this.transitionMap(this.jsons, time) time++; } else { clearInterval(interval); } }, 2000);}
If this works correctly, you should have a successfully animated choropleth map render on your page:
If you’ve made it all the way to the end, I’m sure you can start to imagine some additional items you can add to this visualization — including the four json files for the second climate change scenario.
For code to add buttons, sliders, legend, and additional data, you can go to my Github and pull more of my code!
In the end, the goal of this article was to walk through the process of building out a fairly complex map animation for the web. We tackled a few different items, from data tidying in python, to basic web development principles, and various visualization techniques. I hope that you enjoyed working with this dataset, and I encourage those with questions to reach out at any point.
Additionally, if you enjoyed this post, feel free to check out more of my stories where I discuss other topics I’m passionate about — i.e. data engineering, machine learning, and more!
You can also visit my website at zach-alexander.com to get in touch with questions! Thanks for reading! | [
{
"code": null,
"e": 473,
"s": 172,
"text": "As the Biden administration officially takes office over the next week, optimism emerges over a redirected effort towards combating climate change. Because of this, I thought it would be interesting to explore the potential effects of policy action (or inaction) on this issue over the next 80 years."
},
{
"code": null,
"e": 997,
"s": 473,
"text": "Recently, I worked on a full data visualization story comparing temperature-change projections for two competing climate change scenarios. The two scenarios (“A2” and “B1”) were developed by the IPCC at the beginning of the 21st century. These scenarios outline different levels of world-wide collaboration on this issue and its potential effects on carbon emissions. If you are interested in reading the full data story and interacting with its visualizations, feel free to head over to: zach-alexander.com/climate-change."
},
{
"code": null,
"e": 1745,
"s": 997,
"text": "After writing this data story, I realized that it may be helpful to write a piece outlining the power of creating web visualizations for audiences. As a data science graduate student (and data engineer by profession), I’m often disappointed by the lack of follow-through (me included) on how we communicate conclusions of our analyses and data that we have worked so tirelessly to perfect. In the end, sometimes the algorithms or models we create can fall flat if they aren’t given context or communicated to audiences in a compelling way. Although there are a lot of data visualization platforms (PowerBI, Tableau, etc.) out there that can spin up quick charts and graphs, building out data stories on the web can take analyses to the next level."
},
{
"code": null,
"e": 1988,
"s": 1745,
"text": "In this write-up, I’ll take a piece of one of the visualizations I created for my data story and hope to provide a foundation of how to use Angular and D3.js to build an animated map that simulates a climate change model for the 21st century."
},
{
"code": null,
"e": 2134,
"s": 1988,
"text": "If you would like to follow along with the full code, you can pull from this repository. It’ll contain all of the code outlined below, including:"
},
{
"code": null,
"e": 2188,
"s": 2134,
"text": "Merging and transforming csv data into jsons (python)"
},
{
"code": null,
"e": 2238,
"s": 2188,
"text": "Running a local Angular application (Angular-cli)"
},
{
"code": null,
"e": 2314,
"s": 2238,
"text": "Installing D3.js and loading json files into an Angular component (Angular)"
},
{
"code": null,
"e": 2410,
"s": 2314,
"text": "Using D3.js to create a world map and animate it over 4 time intervals (Angular and Javascript)"
},
{
"code": null,
"e": 2573,
"s": 2410,
"text": "If you find yourself wanting to build on the animation that we start in this article, you can pull additional code from my comprehensive data story on this topic."
},
{
"code": null,
"e": 2747,
"s": 2573,
"text": "Before diving into any of the website work, a crucial first step in developing any data visualization is to think about what you ultimately want to portray to your audience."
},
{
"code": null,
"e": 2904,
"s": 2747,
"text": "My goal: I wanted to visually show the change in land temperature (in degrees F) by country over the next 80 years based on an IPCC climate change scenario."
},
{
"code": null,
"e": 2965,
"s": 2904,
"text": "With this goal, I then set out to find a compelling dataset."
},
{
"code": null,
"e": 3265,
"s": 2965,
"text": "Fortunately, there are countless climate change datasets available for use, and this World Bank dataset containing ensemble data that projects changes in land temperature over the next century (based on global circulation models and IPCC climate change scenarios) was exactly what I was looking for."
},
{
"code": null,
"e": 3606,
"s": 3265,
"text": "Well, before we can tackle putting this data onto a webpage, we do have to think critically about what aspect of our data we’d like to present to our audience. Additionally, since D3.js works well with data formatted in JavaScript Object Notation (JSON) format, we’ll have to do some data transformation prior to building our visualization."
},
{
"code": null,
"e": 3769,
"s": 3606,
"text": "Since I would like to create a world map, we also are dealing with geographic coordinates, which take on an even more specific structure of json called “geojson”."
},
{
"code": null,
"e": 4224,
"s": 3769,
"text": "In short, geojson structure is an extension of the json format that is used specifically for encoding a variety of geographic data structures. When working with maps in D3.js, there are many built-in functions and processes that rely on your data being oriented in either geojson or topojson format. The difference between these two can be outlined in detail in this stackoverflow post. The format that we’ll be using, geojson, takes the structure below:"
},
{
"code": null,
"e": 4366,
"s": 4224,
"text": "{ \"type\": \"Feature\", \"geometry\": { \"type\": \"Point\", \"coordinates\": [38.00,−97.00] }, \"properties\": { \"name\": \"United States\" }}"
},
{
"code": null,
"e": 4833,
"s": 4366,
"text": "For this simple example above, we can see that this data when read into D3.js would draw a point (or dot) in the very center of the contiguous United States. The “geometry” mentioned is of type “point”, and the “coordinates” attached to the point are where the dot would be drawn on the web page. You can also attach specific properties to a point, such as a “name”, which can also be referenced by D3.js (we’ll see this come into play with our color palette later)."
},
{
"code": null,
"e": 5339,
"s": 4833,
"text": "Although this is a simple example, you can imagine the “coordinates” getting much longer when you draw specific polygons (or shapes). Essentially, when working with polygons, you are taking a list of points that connect to one another. Each polygon has a set number of coordinates based on a particular projection, and these coordinates are then rendered onto the page. As an example of this in action, if we were to take a look at the polygon coordinates for the state of Nevada, you could find it below:"
},
{
"code": null,
"e": 5971,
"s": 5339,
"text": "{ \"type\": \"Feature\", \"properties\": {\"name\": \"Nevada\"}, \"geometry\": { \"type\": \"Polygon\", \"coordinates\": [[[-117.027882,42.000709], [-114.04295,41.995232],[-114.048427,37.000263],[-114.048427,36.195153],[-114.152489,36.025367],[-114.251074,36.01989],[-114.371566,36.140383],[-114.738521,36.102045],[-114.678275,35.516012],[-114.596121,35.324319],[-114.574213,35.138103],[-114.634459,35.00118],[-115.85034,35.970598],[-116.540435,36.501861],[-117.498899,37.21934],[-118.71478,38.101128],[-120.001861,38.999346],[-119.996384,40.264519],[-120.001861,41.995232],[-118.698349,41.989755],[-117.027882,42.000709]]] }}"
},
{
"code": null,
"e": 6193,
"s": 5971,
"text": "We can see that the “geometry” is much longer than our first example, and the “type” is now a polygon instead of “point”. The “coordinates” are listed based on the projection utilized, which would then render on the page."
},
{
"code": null,
"e": 6888,
"s": 6193,
"text": "With this new knowledge of geojsons, I devised a plan to take the csv files that have the climate change projections from Kaggle and ultimately transform them into json files for D3. Although a lot of data manipulation can be done right in JavaScript through many of D3s built-in functions (you can read csv data directly into JavaScript), I thought it would be more efficient to manipulate the data prior to loading it on the web page since the dataset is static (and won’t rely on access/connections to a third-party API). The upside of this is that it should make the code more efficient, our visualization more snappy, and cut down on the time needed to render maps and charts on page load."
},
{
"code": null,
"e": 7009,
"s": 6888,
"text": "To do this, I utilized python. You can find the entire jupyter notebook that documents my data transformation on Github."
},
{
"code": null,
"e": 7545,
"s": 7009,
"text": "In summary, after reading in the csv file from Kaggle, I first had to work through a fair amount of data aggregation for the various date ranges and model outputs. Then, I essentially took a public geojson file that had the polygons for all countries in the world, and merged the temperature data and other properties from the Kaggle csv files (utilizing the common identifier in the properties information) into each country’s properties. In the final chunk of code, I created a custom function to output the dataframes as json files:"
},
{
"code": null,
"e": 8704,
"s": 7545,
"text": "# array of pandas dataframes with our various model data across the four time intervalsdataframes = [first20_med_a2, first20_med_b1, second20_med_a2, second20_med_b1, third20_med_a2, third20_med_b1, fourth20_med_a2, fourth20_med_b1]# empty array of json files that eventually will load in datajson_files = ['first20_med_a2.json', 'first20_med_b1.json', 'second20_med_a2.json', 'second20_med_b1.json', 'third20_med_a2.json', 'third20_med_b1.json', 'fourth20_med_a2.json', 'fourth20_med_b1.json']# custom function to take the pandas dataframes and store them in separate json filesdef createjsons(): for idx, d in enumerate(dataframes): for i in features: for index, row in d.iterrows(): if(row['Country'] == i['id']): i['Change_c'] = row['Change_c'] i['Change_f'] = row['Change_f'] i['Date_range'] = row['Date_range'] i['Percentile'] = row['Pctile'] i['Scenario'] = row['Type'] else: pass with open(json_files[idx], 'w') as outfile: json.dump(gj, outfile)createjsons()"
},
{
"code": null,
"e": 8948,
"s": 8704,
"text": "The ultimate goal of this step was to create separate json files that stored the country name, change in temperature (in degrees C), change in temperature (in degrees F), the date range, the model calculation percentile, and the scenario type."
},
{
"code": null,
"e": 9058,
"s": 8948,
"text": "As we can see below, a country property in one of my final json files looks like this after our data tidying:"
},
{
"code": null,
"e": 9771,
"s": 9058,
"text": "# I abbreviated the length of the coordinates to cut down on size of code block{ \"type\": \"Feature\", \"id\": \"USA\", \"geometry\": { \"type\": \"MultiPolygon\", \"coordinates\": [[[[-155.54211, 19.08348], [-155.68817, 18.91619], [-155.93665, 19.05939], [-155.90806, 19.33888], [-156.07347, 19.70294], [-156.02368, 19.81422], [-155.85008, 19.97729], [-155.91907, 20.17395], [-155.86108, 20.26721], [-155.78505, 20.2487], [-155.40214, 20.07975], [-155.22452, 19.99302], ...]]] }, \"properties\": { \"name\": \"United States of America\", \"Change_c\": 1.5040905413108334, \"Change_f\": 2.7073629743595, \"Date_range\": \"2020-2040\", \"Percentile\": \"median\", \"Scenario\": \"a2\" }}"
},
{
"code": null,
"e": 10080,
"s": 9771,
"text": "Similar to our quick geojson examples above, we can see that we are utilizing many points to create our United States polygon, however I used python to merge in additional “properties” to be used later for my visualization. As we’ll see shortly, the change_f value will be used for our choropleth coloration."
},
{
"code": null,
"e": 10384,
"s": 10080,
"text": "With the json files ready to go, we can then start to imagine what our visualization will look like. From a user’s standpoint, we’ll want to show the change in land temperature over time, which we can do by reading in our json files over specific intervals of time — all of which are animated via D3.js."
},
{
"code": null,
"e": 10483,
"s": 10384,
"text": "Okay! Now that we have our data files ready to go, we can spin up a local single page application."
},
{
"code": null,
"e": 10661,
"s": 10483,
"text": "Depending on the JavaScript framework you’d like to use, you’ll need to download the command-line interface (cli) to launch a local server for development and a package manager."
},
{
"code": null,
"e": 10875,
"s": 10661,
"text": "For this example, the package manager we’ll use is npm. One of the easiest ways to install npm is to download node.js, which will also include npm in your installation. The instructions for this can be found here."
},
{
"code": null,
"e": 11083,
"s": 10875,
"text": "As our Javascript framework, we’ll use Angular. To make our operations simple, you can download the Angular cli to start the development server. The instructions can be found here, and consist of four lines."
},
{
"code": null,
"e": 11217,
"s": 11083,
"text": "Once you’ve downloaded node.js and Angular cli, you can open a VSCode terminal window (or any terminal window) and run the following:"
},
{
"code": null,
"e": 11312,
"s": 11217,
"text": "// make sure npm is installed on your computer before running this:npm install -g @angular/cli"
},
{
"code": null,
"e": 11497,
"s": 11312,
"text": "After this install, find a place on your computer where you want to store your application files, then run (changing “my-dream-app” to whatever you’d like your directory to be called):"
},
{
"code": null,
"e": 11517,
"s": 11497,
"text": "ng new my-dream-app"
},
{
"code": null,
"e": 11848,
"s": 11517,
"text": "This will take a minute or two to fully run, but in the end it will create a bunch of files that consist of your new Angular application and provide the directory structure needed for compilation. When the command is complete, you can then navigate to the new application folder and run “ng serve” to start the development server."
},
{
"code": null,
"e": 11958,
"s": 11848,
"text": "// change directories into your new angular applicationcd my-dream-app// start the development serverng serve"
},
{
"code": null,
"e": 12081,
"s": 11958,
"text": "If all runs correctly, you should be able to compile your newly created Angular application and see this in your terminal:"
},
{
"code": null,
"e": 12383,
"s": 12081,
"text": "I won’t go into more detail about how Angular works in order to keep this part brief, but if you are completely new to Angular, please read this excellent post to learn about basic app development. Additionally, the Angular documentation is very helpful for those that prefer to get more in the weeds."
},
{
"code": null,
"e": 12747,
"s": 12383,
"text": "With our Angular development server running, we can now start to build out our visualization. First, we’ll need to install the D3.js package from npm in order to be able to use the library in our application. For this visual, I decided to install version 4 of D3 (for various reasons). To do this, stop your development server in your terminal (ctrl + c) and run:"
},
{
"code": null,
"e": 12764,
"s": 12747,
"text": "npm install d3v4"
},
{
"code": null,
"e": 12843,
"s": 12764,
"text": "When this is complete, you can then restart the development server by running:"
},
{
"code": null,
"e": 12852,
"s": 12843,
"text": "ng serve"
},
{
"code": null,
"e": 13035,
"s": 12852,
"text": "You should then see the same “Compiled successfully” message as earlier. Next, we can add our json files to the “assets” directory inside of our application (folder structure below):"
},
{
"code": null,
"e": 13200,
"s": 13035,
"text": "|- application-name |- src |- assets |- first20_med_a2.json |- second20_med_a2.json |- third20_med_a2.json |- fourth20_med_a2.json"
},
{
"code": null,
"e": 13329,
"s": 13200,
"text": "You can find these json files already pre-made here. However, you you’d like, you can also utilize the python script from above."
},
{
"code": null,
"e": 13656,
"s": 13329,
"text": "If you are using Angular, because we are working with Typescript, you’ll likely also have to do a quick configuration to load the json files directly into the app.component.ts file. This article is a great summary of how to do this. Likely, you’ll just have to add the following line of bolded code to your tsconfig.json file:"
},
{
"code": null,
"e": 13774,
"s": 13656,
"text": "{ \"compileOnSave\": false, \"compilerOptions\": { . . . \"resolveJsonModule\": true, . . . }}"
},
{
"code": null,
"e": 13989,
"s": 13774,
"text": "With our json data stored inside of the application directory, the D3 library imported into our node_modules, and Angular ready to accept json files, we can start to see the power of data visualizations on the web!"
},
{
"code": null,
"e": 14123,
"s": 13989,
"text": "To render one of our json files, we first need to ensure we are referencing it in our app.component.ts file (folder structure below):"
},
{
"code": null,
"e": 14190,
"s": 14123,
"text": "|- application-name |- src |- app |- app.component.ts"
},
{
"code": null,
"e": 14326,
"s": 14190,
"text": "Navigate to the app.component.ts file and import the json data into the component by adding the bolded code to your existing code code:"
},
{
"code": null,
"e": 14841,
"s": 14326,
"text": "import { Component} from '@angular/core';import * as d3 from 'd3v4';// load the json file from the assets folder, give it a nameimport * as firstModel from '../assets/first20_med_a2.json';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent { // make sure to reference the correct structure firstModelData = firstModel['default']; ngOnInit() { // print the json data in the browser console console.log(this.firstModelData) }}"
},
{
"code": null,
"e": 15013,
"s": 14841,
"text": "Save this file, return to your browser, and if all goes well, you should be able to see the json data printed to the console in development tools after the page refreshes:"
},
{
"code": null,
"e": 15183,
"s": 15013,
"text": "We then need to remove the default html syntax in the app.component.html file and create a quick “div”. Navigate to the app.component.html file (folder structure below):"
},
{
"code": null,
"e": 15252,
"s": 15183,
"text": "|- application-name |- src |- app |- app.component.html"
},
{
"code": null,
"e": 15336,
"s": 15252,
"text": "Then, delete out all of the html code currently present, and add the following div:"
},
{
"code": null,
"e": 15368,
"s": 15336,
"text": "<div class = \"world-map\"></div>"
},
{
"code": null,
"e": 15577,
"s": 15368,
"text": "Now, with the json data reading into the component, we can start to write our D3.js functions. Navigate back to the app.component.ts file, and write the following bolded code inside of the AppComponent class:"
},
{
"code": null,
"e": 16728,
"s": 15577,
"text": "export class AppComponent { firstModelData = firstModel['default']; ngOnInit() { console.log(this.firstModelData) } setMap(width, height, dataset) { const margin = {top: 10, right: 30, bottom: 10, left: 30}; width = width - margin.left - margin.right; height = height - margin.top - margin.bottom; const projection = d3.geoMercator() .rotate([-11, 0]) .scale(1) .translate([0, 0]); const path = d3.geoPath().projection(projection); const svg = d3.select('.world-map') .append('svg') .attr('viewBox', '0 0 1000 600') .attr('preserveAspectRatio', 'xMidYMid') .style('max-width', 1200) .style('margin', 'auto') .style('display', 'flex'); const b = path.bounds(datapull), s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0] [1]) / height), t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2]; projection.scale(s).translate(t); svg.selectAll('path') .data(datapull.features) .enter() .append('path') .attr('d', path) }}"
},
{
"code": null,
"e": 17331,
"s": 16728,
"text": "In short, this code declares a function setMap() accepting three parameters of width, height, and our dataset. It then defines a margin and subtracts the margin pixels from all four sides of the canvas. Next, since we are using map coordinates, we have to define a map projection, rotating the map slightly so the easternmost part of Russia doesn’t make its way onto the left-side of our canvas, and setting our scale and translation. We then take this projection and map it onto our path, which will eventually draw our polygons based on our projection inputs and our defined dimensions of our canvas."
},
{
"code": null,
"e": 17688,
"s": 17331,
"text": "This then creates our first svg by selecting our blank div using the syntax, “d3.select(“.world-map”). By appending the svg to our existing div, we then set the dimensions and make it responsive by utilizing viewBox and preserveAspectRatio, and eventually set a max width of 1200px and centering the map on the page (if the viewport is larger than 1200px)."
},
{
"code": null,
"e": 17882,
"s": 17688,
"text": "We then want to ensure that the scale and translation map on correctly, and the defined bounds of our canvas are correct, so variables s and t help define the bounds of our Mercator projection."
},
{
"code": null,
"e": 18188,
"s": 17882,
"text": "Finally, we select our newly appended svg, read in our geojson features, and draw the path on the page! In order for this to render on the page, we need to take our instantiated function and invoke it in ngOnInit() . Add this line of code into your app.component.ts file inside of the ngOnInit() function."
},
{
"code": null,
"e": 18334,
"s": 18188,
"text": "ngOnInit() { console.log(this.firstModelData) // add this line of code below to render your map: setMap(1000, 600, this.firstModelData)}"
},
{
"code": null,
"e": 18401,
"s": 18334,
"text": "If all goes well, you should see something like this on your page:"
},
{
"code": null,
"e": 18778,
"s": 18401,
"text": "Alright! Now we are getting somewhere! Unfortunately, though, our polygon fills are coming in black, and we’d like to create a choropleth coloration of each country based on the temperature change in degrees F. Remember when we merged that data into each country property using python? Well, now we can use the change_f value for each country to differentiate our fill colors!"
},
{
"code": null,
"e": 18931,
"s": 18778,
"text": "To do this, we can add in the following code inside of our setMap() function (still in our app.component.ts file), and then add an attribute to our svg:"
},
{
"code": null,
"e": 19508,
"s": 18931,
"text": "setMap(width, height, dataset) {...const color_domain = [2.5, 4, 7, 9, 10];const color_legend = d3.scaleThreshold<string>().range(['#fee5d9', '#fcbba1', '#fc9272', '#fb6a4a', '#de2d26', '#a50f15']).domain(color_domain);...svg.selectAll('path') .data(datapull.features) .enter() .append('path') .attr('d', path) .style('fill', function(d) { const value = d['Change_f']; if (value) { return color_legend(d['Change_f']); } else { return '#ccc'; }}) .style('stroke', '#fff') .style('stroke-width', '0.5')}"
},
{
"code": null,
"e": 19865,
"s": 19508,
"text": "In short, we can use the d3.scaleThreshold() function in D3.js to help us create a choropleth color palette. I won’t go into a lot of detail about this for the sake of time, but you can read more about these scales here, if interested. Additionally, after adding the attribute to our path, I also made the polygon (country) outlines a bit thicker and gray."
},
{
"code": null,
"e": 19950,
"s": 19865,
"text": "If these additions are working correctly, you should see this rendered on your page:"
},
{
"code": null,
"e": 20249,
"s": 19950,
"text": "If you’ve made it this far, you can definitely pat yourself on the back! The final step for this visualization is to animate it across different time intervals. If you remember from the beginning, our goal was to show the change in temperature for each country across four different time intervals:"
},
{
"code": null,
"e": 20262,
"s": 20249,
"text": "2020 to 2040"
},
{
"code": null,
"e": 20275,
"s": 20262,
"text": "2040 to 2060"
},
{
"code": null,
"e": 20288,
"s": 20275,
"text": "2060 to 2080"
},
{
"code": null,
"e": 20305,
"s": 20288,
"text": "and 2080 to 2100"
},
{
"code": null,
"e": 20612,
"s": 20305,
"text": "As you can now see, we were able to create a static choropleth map with just one json file showing temperature changes between 2020 and 2040. However, to animate it across our other three time intervals, we want to load other json files into this function over a set time. D3.js makes this relatively easy."
},
{
"code": null,
"e": 20795,
"s": 20612,
"text": "First, we’ll have to load the rest of our json files into our app.component.ts file similar to the first one we did above. To do this, you can add the following lines of bolded code:"
},
{
"code": null,
"e": 21557,
"s": 20795,
"text": "import { Component, OnInit } from '@angular/core';import * as d3 from 'd3';# load the rest of the json files from the assets folder, give it a nameimport * as firstModel from '../assets/first20_med_a2.json';import * as secondModel from '../assets/second20_med_a2.json';import * as thirdModel from '../assets/third20_med_a2.json';import * as fourthModel from '../assets/fourth20_med_a2.json';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {# make sure to reference the correct structurefirstModelData = firstModel['default'];secondModelData = secondModel['default'];thirdModelData = thirdModel['default'];fourthModelData = fourthModel['default'];jsons;...ngOnInit() {...}"
},
{
"code": null,
"e": 21678,
"s": 21557,
"text": "Then, we need to store the json files in an array on page load. Therefore, we can add this into our ngOnInit() function:"
},
{
"code": null,
"e": 21797,
"s": 21678,
"text": "ngOnInit() {...this.jsons = [this.firstModelData, this.secondModelData, this.thirdModelData, this.fourthModelData]...}"
},
{
"code": null,
"e": 21924,
"s": 21797,
"text": "Now, in order for our animation to work, we have to create a new function below our setMap() function, called transitionMap():"
},
{
"code": null,
"e": 22449,
"s": 21924,
"text": "transitionMap(json, i) { const svg = d3.select('.world-map'); const color_domain = [2.5, 4, 7, 9, 10]; const color_legend = d3.scaleThreshold<string>().range(['#fee5d9', '#fcbba1', '#fc9272', '#fb6a4a', '#de2d26', '#a50f15']).domain(color_domain);svg.selectAll('path') .data(json[i].features) .transition() .delay(100) .duration(1000) .style('fill', function(d) { const value = d['Change_f']; if (value) { return color_legend(d['Change_f']); } else { return '#ccc'; } })}"
},
{
"code": null,
"e": 22921,
"s": 22449,
"text": "This function will take two arguments, our json and the iterator value that will serve as our index number for our json array. When the function is invoked, it’ll select our map svg, refresh the color pallete, and then redraw our map with the data referenced in the corresponding json. Because our .data() function is referencing json[i], we can cycle through the json array we just created and load each of json files in succession after a delay and a specific duration."
},
{
"code": null,
"e": 23137,
"s": 22921,
"text": "Now, we can set a time interval to define our “i” value by using the setInterval() function in Javascript. By adding the following code to the bottom of our ngOnInit() function, this process will start on page load:"
},
{
"code": null,
"e": 23347,
"s": 23137,
"text": "ngOnInit() {... let time = 1; let interval = setInterval(() => { if (time <= 3) { this.transitionMap(this.jsons, time) time++; } else { clearInterval(interval); } }, 2000);}"
},
{
"code": null,
"e": 23448,
"s": 23347,
"text": "If this works correctly, you should have a successfully animated choropleth map render on your page:"
},
{
"code": null,
"e": 23652,
"s": 23448,
"text": "If you’ve made it all the way to the end, I’m sure you can start to imagine some additional items you can add to this visualization — including the four json files for the second climate change scenario."
},
{
"code": null,
"e": 23765,
"s": 23652,
"text": "For code to add buttons, sliders, legend, and additional data, you can go to my Github and pull more of my code!"
},
{
"code": null,
"e": 24147,
"s": 23765,
"text": "In the end, the goal of this article was to walk through the process of building out a fairly complex map animation for the web. We tackled a few different items, from data tidying in python, to basic web development principles, and various visualization techniques. I hope that you enjoyed working with this dataset, and I encourage those with questions to reach out at any point."
},
{
"code": null,
"e": 24332,
"s": 24147,
"text": "Additionally, if you enjoyed this post, feel free to check out more of my stories where I discuss other topics I’m passionate about — i.e. data engineering, machine learning, and more!"
}
] |
Impala - Limit Clause | The limit clause in Impala is used to restrict the number of rows of a resultset to a desired number, i.e., the resultset of the query does not hold the records beyond the specified limit.
Following is the syntax of the Limit clause in Impala.
select * from table_name order by id limit numerical_expression;
Assume we have a table named customers in the database my_db and its contents are as follows −
[quickstart.cloudera:21000] > select * from customers;
Query: select * from customers
+----+----------+-----+-----------+--------+
| id | name | age | address | salary |
+----+----------+-----+-----------+--------+
| 3 | kaushik | 23 | Kota | 30000 |
| 6 | Komal | 22 | MP | 32000 |
| 1 | Ramesh | 32 | Ahmedabad | 20000 |
| 5 | Hardik | 27 | Bhopal | 40000 |
| 2 | Khilan | 25 | Delhi | 15000 |
| 8 | ram | 22 | vizag | 31000 |
| 9 | robert | 23 | banglore | 28000 |
| 7 | ram | 25 | chennai | 23000 |
| 4 | Chaitali | 25 | Mumbai | 35000 |
+----+----------+-----+-----------+--------+
Fetched 9 row(s) in 0.51s
You can arrange the records in the table in the ascending order of their id’s using the order by clause as shown below.
[quickstart.cloudera:21000] > select * from customers order by id;
Query: select * from customers order by id
+----+----------+-----+-----------+--------+
| id | name | age | address | salary |
+----+----------+-----+-----------+--------+
| 1 | Ramesh | 32 | Ahmedabad | 20000 |
| 2 | Khilan | 25 | Delhi | 15000 |
| 3 | kaushik | 23 | Kota | 30000 |
| 4 | Chaitali | 25 | Mumbai | 35000 |
| 5 | Hardik | 27 | Bhopal | 40000 |
| 6 | Komal | 22 | MP | 32000 |
| 7 | ram | 25 | chennai | 23000 |
| 8 | ram | 22 | vizag | 31000 |
| 9 | robert | 23 | banglore | 28000 |
+----+----------+-----+-----------+--------+
Fetched 9 row(s) in 0.54s
Now, using the limit clause, you can restrict the number of records of the output to 4, using the limit clause as shown below.
[quickstart.cloudera:21000] > select * from customers order by id limit 4;
On executing, the above query gives the following output.
Query: select * from customers order by id limit 4
+----+----------+-----+-----------+--------+
| id | name | age | address | salary |
+----+----------+-----+-----------+--------+
| 1 | Ramesh | 32 | Ahmedabad | 20000 |
| 2 | Khilan | 25 | Delhi | 15000 |
| 3 | kaushik | 23 | Kota | 30000 |
| 4 | Chaitali | 25 | Mumbai | 35000 |
+----+----------+-----+-----------+--------+
Fetched 4 row(s) in 0.64s
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2474,
"s": 2285,
"text": "The limit clause in Impala is used to restrict the number of rows of a resultset to a desired number, i.e., the resultset of the query does not hold the records beyond the specified limit."
},
{
"code": null,
"e": 2529,
"s": 2474,
"text": "Following is the syntax of the Limit clause in Impala."
},
{
"code": null,
"e": 2595,
"s": 2529,
"text": "select * from table_name order by id limit numerical_expression;\n"
},
{
"code": null,
"e": 2690,
"s": 2595,
"text": "Assume we have a table named customers in the database my_db and its contents are as follows −"
},
{
"code": null,
"e": 3403,
"s": 2690,
"text": "[quickstart.cloudera:21000] > select * from customers; \nQuery: select * from customers \n+----+----------+-----+-----------+--------+ \n| id | name | age | address | salary | \n+----+----------+-----+-----------+--------+ \n| 3 | kaushik | 23 | Kota | 30000 | \n| 6 | Komal | 22 | MP | 32000 | \n| 1 | Ramesh | 32 | Ahmedabad | 20000 | \n| 5 | Hardik | 27 | Bhopal | 40000 | \n| 2 | Khilan | 25 | Delhi | 15000 | \n| 8 | ram | 22 | vizag | 31000 | \n| 9 | robert | 23 | banglore | 28000 | \n| 7 | ram | 25 | chennai | 23000 | \n| 4 | Chaitali | 25 | Mumbai | 35000 | \n+----+----------+-----+-----------+--------+ \nFetched 9 row(s) in 0.51s\n"
},
{
"code": null,
"e": 3523,
"s": 3403,
"text": "You can arrange the records in the table in the ascending order of their id’s using the order by clause as shown below."
},
{
"code": null,
"e": 4259,
"s": 3523,
"text": "[quickstart.cloudera:21000] > select * from customers order by id; \nQuery: select * from customers order by id \n+----+----------+-----+-----------+--------+ \n| id | name | age | address | salary | \n+----+----------+-----+-----------+--------+ \n| 1 | Ramesh | 32 | Ahmedabad | 20000 | \n| 2 | Khilan | 25 | Delhi | 15000 | \n| 3 | kaushik | 23 | Kota | 30000 | \n| 4 | Chaitali | 25 | Mumbai | 35000 | \n| 5 | Hardik | 27 | Bhopal | 40000 | \n| 6 | Komal | 22 | MP | 32000 | \n| 7 | ram | 25 | chennai | 23000 | \n| 8 | ram | 22 | vizag | 31000 |\n| 9 | robert | 23 | banglore | 28000 | \n+----+----------+-----+-----------+--------+ \nFetched 9 row(s) in 0.54s\n"
},
{
"code": null,
"e": 4386,
"s": 4259,
"text": "Now, using the limit clause, you can restrict the number of records of the output to 4, using the limit clause as shown below."
},
{
"code": null,
"e": 4462,
"s": 4386,
"text": "[quickstart.cloudera:21000] > select * from customers order by id limit 4;\n"
},
{
"code": null,
"e": 4520,
"s": 4462,
"text": "On executing, the above query gives the following output."
},
{
"code": null,
"e": 4966,
"s": 4520,
"text": "Query: select * from customers order by id limit 4 \n+----+----------+-----+-----------+--------+ \n| id | name | age | address | salary | \n+----+----------+-----+-----------+--------+ \n| 1 | Ramesh | 32 | Ahmedabad | 20000 | \n| 2 | Khilan | 25 | Delhi | 15000 |\n| 3 | kaushik | 23 | Kota | 30000 | \n| 4 | Chaitali | 25 | Mumbai | 35000 | \n+----+----------+-----+-----------+--------+ \nFetched 4 row(s) in 0.64s\n"
},
{
"code": null,
"e": 4973,
"s": 4966,
"text": " Print"
},
{
"code": null,
"e": 4984,
"s": 4973,
"text": " Add Notes"
}
] |
Program to create grade calculator in Python | In Academics it is a common requirement to find the grades of students after an assessment. In this article we will create a Python program which will assign the grades based on the grading criteria. Will call it A grade calculator.
Below is the grading criteria we have chosen for the program.
score >= 90 : "O"
score >= 80 : "A+"
score >= 70 : "A"
score >= 60 : "B+"
score >= 50 : "B"
score >= 40 : "C"
Initialize variables and array to hold the student details including the marks obtained by individual subjects.
Initialize variables and array to hold the student details including the marks obtained by individual subjects.
Define a function to accept input values on the screen and store them in the above variables.
Define a function to accept input values on the screen and store them in the above variables.
Design a for loop to add the marks obtained in individual subjects.
Design a for loop to add the marks obtained in individual subjects.
Using if and elif condition design the calculator which will define the range of the marks obtained by the student and categorize the result into specific grade.
Using if and elif condition design the calculator which will define the range of the marks obtained by the student and categorize the result into specific grade.
Finally define a function which will run the above functions in a specific sequence.
Finally define a function which will run the above functions in a specific sequence.
Run the program and input the values.
Run the program and input the values.
Below is the grading program as per the above approach. When we run the program it asks for various inputs. On feeding the require input, we get the final result.
class grade_calculator:
def __init__(self):
self.__roll_number = 0
self._Name = ""
self.__marks_obtained = []
self.__total_marks = 0
self.__percentage = 0
self.__grade = ""
self.__result = ""
def setgrade_calculator(self):
self.__roll_number = int(input("Enter Roll Number: "))
self.__Name = input("Enter Name: ")
print("Enter 5 subjects marks: ")
for n in range(5):
self.__marks_obtained.append(int(input("Subject " + str(n + 1) + ": ")))
def Total(self):
for i in self.__marks_obtained:
self.__total_marks += i
def Percentage(self):
self.__percentage = self.__total_marks / 5
def calculateGrade(self):
if self.__percentage >= 90:
self.__grade = "0"
elif self.__percentage >= 80:
self.__grade = "A+"
elif self.__percentage >= 70:
self.__grade = "A"
elif self.__percentage >= 60:
self.__grade = "B+"
elif self.__percentage >= 50:
self.__grade = "B"
elif self.__percentage >= 40:
self.__grade = "C"
else:
self.__grade = "F"
def Result(self):
count = 0
for x in self.__marks_obtained:
if x >= 40:
count += 1
if count == 5:
self.__result = "PASS"
elif count >= 3:
self.__result = "COMP."
else:
self.__result = "FAIL"
def showgrade_calculator(self):
self.Total()
self.Percentage()
self.calculateGrade()
self.Result()
print(self.__roll_number, "\t", self.__Name, "\t", self.__total_marks, "\t", self.__percentage, "\t", self.__grade, "\t",
self.__result)
def main():
gc = grade_calculator()
gc.setgrade_calculator()
gc.showgrade_calculator()
if __name__ == "__main__":
main()
Running the above code gives us the following result −
Enter Roll Number: 3
Enter Name: raj
Enter 5 subjects marks:
Subject 1: 86
Subject 2: 75
Subject 3: 69
Subject 4: 55
Subject 5: 92
3 Kumar 377 75.4 A PASS | [
{
"code": null,
"e": 1295,
"s": 1062,
"text": "In Academics it is a common requirement to find the grades of students after an assessment. In this article we will create a Python program which will assign the grades based on the grading criteria. Will call it A grade calculator."
},
{
"code": null,
"e": 1357,
"s": 1295,
"text": "Below is the grading criteria we have chosen for the program."
},
{
"code": null,
"e": 1467,
"s": 1357,
"text": "score >= 90 : \"O\"\nscore >= 80 : \"A+\"\nscore >= 70 : \"A\"\nscore >= 60 : \"B+\"\nscore >= 50 : \"B\"\nscore >= 40 : \"C\""
},
{
"code": null,
"e": 1579,
"s": 1467,
"text": "Initialize variables and array to hold the student details including the marks obtained by individual subjects."
},
{
"code": null,
"e": 1691,
"s": 1579,
"text": "Initialize variables and array to hold the student details including the marks obtained by individual subjects."
},
{
"code": null,
"e": 1785,
"s": 1691,
"text": "Define a function to accept input values on the screen and store them in the above variables."
},
{
"code": null,
"e": 1879,
"s": 1785,
"text": "Define a function to accept input values on the screen and store them in the above variables."
},
{
"code": null,
"e": 1947,
"s": 1879,
"text": "Design a for loop to add the marks obtained in individual subjects."
},
{
"code": null,
"e": 2015,
"s": 1947,
"text": "Design a for loop to add the marks obtained in individual subjects."
},
{
"code": null,
"e": 2177,
"s": 2015,
"text": "Using if and elif condition design the calculator which will define the range of the marks obtained by the student and categorize the result into specific grade."
},
{
"code": null,
"e": 2339,
"s": 2177,
"text": "Using if and elif condition design the calculator which will define the range of the marks obtained by the student and categorize the result into specific grade."
},
{
"code": null,
"e": 2424,
"s": 2339,
"text": "Finally define a function which will run the above functions in a specific sequence."
},
{
"code": null,
"e": 2509,
"s": 2424,
"text": "Finally define a function which will run the above functions in a specific sequence."
},
{
"code": null,
"e": 2547,
"s": 2509,
"text": "Run the program and input the values."
},
{
"code": null,
"e": 2585,
"s": 2547,
"text": "Run the program and input the values."
},
{
"code": null,
"e": 2748,
"s": 2585,
"text": "Below is the grading program as per the above approach. When we run the program it asks for various inputs. On feeding the require input, we get the final result."
},
{
"code": null,
"e": 4579,
"s": 2748,
"text": "class grade_calculator:\n def __init__(self):\n self.__roll_number = 0\n self._Name = \"\"\n self.__marks_obtained = []\n self.__total_marks = 0\n self.__percentage = 0\n self.__grade = \"\"\n self.__result = \"\"\n def setgrade_calculator(self):\n self.__roll_number = int(input(\"Enter Roll Number: \"))\n self.__Name = input(\"Enter Name: \")\n print(\"Enter 5 subjects marks: \")\n for n in range(5):\n self.__marks_obtained.append(int(input(\"Subject \" + str(n + 1) + \": \")))\n def Total(self):\n for i in self.__marks_obtained:\n self.__total_marks += i\n def Percentage(self):\n self.__percentage = self.__total_marks / 5\n def calculateGrade(self):\n if self.__percentage >= 90:\n self.__grade = \"0\"\n elif self.__percentage >= 80:\n self.__grade = \"A+\"\n elif self.__percentage >= 70:\n self.__grade = \"A\"\n elif self.__percentage >= 60:\n self.__grade = \"B+\"\n elif self.__percentage >= 50:\n self.__grade = \"B\"\n elif self.__percentage >= 40:\n self.__grade = \"C\"\n else:\n self.__grade = \"F\"\n def Result(self):\n count = 0\n for x in self.__marks_obtained:\n if x >= 40:\n count += 1\n if count == 5:\n self.__result = \"PASS\"\n elif count >= 3:\n self.__result = \"COMP.\"\n else:\n self.__result = \"FAIL\"\n def showgrade_calculator(self):\n self.Total()\n self.Percentage()\n self.calculateGrade()\n self.Result()\n print(self.__roll_number, \"\\t\", self.__Name, \"\\t\", self.__total_marks, \"\\t\", self.__percentage, \"\\t\", self.__grade, \"\\t\",\n self.__result)\ndef main():\n gc = grade_calculator()\n gc.setgrade_calculator()\n gc.showgrade_calculator()\nif __name__ == \"__main__\":\n main()"
},
{
"code": null,
"e": 4634,
"s": 4579,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 4804,
"s": 4634,
"text": "Enter Roll Number: 3\nEnter Name: raj\nEnter 5 subjects marks:\nSubject 1: 86\nSubject 2: 75\nSubject 3: 69\nSubject 4: 55\nSubject 5: 92\n3 Kumar 377 75.4 A PASS"
}
] |
Plot a multicolored line based on a condition in Python Matplotlib | To plot a multicolored line based on a condition in Python Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create y data points using numpy.
Create y data points using numpy.
Make l and u data points to differentiate the colors.
Make l and u data points to differentiate the colors.
Plot the u and l data points using plot() method, with different colors.
Plot the u and l data points using plot() method, with different colors.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
y = np.sin(np.linspace(-10, 10, 100))
u = y.copy()
l = y.copy()
u[u <= 0] = np.nan
l[l >= 0] = np.nan
plt.plot(u, color='red')
plt.plot(l, color='blue')
plt.show() | [
{
"code": null,
"e": 1167,
"s": 1062,
"text": "To plot a multicolored line based on a condition in Python Matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1243,
"s": 1167,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1319,
"s": 1243,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1353,
"s": 1319,
"text": "Create y data points using numpy."
},
{
"code": null,
"e": 1387,
"s": 1353,
"text": "Create y data points using numpy."
},
{
"code": null,
"e": 1441,
"s": 1387,
"text": "Make l and u data points to differentiate the colors."
},
{
"code": null,
"e": 1495,
"s": 1441,
"text": "Make l and u data points to differentiate the colors."
},
{
"code": null,
"e": 1568,
"s": 1495,
"text": "Plot the u and l data points using plot() method, with different colors."
},
{
"code": null,
"e": 1641,
"s": 1568,
"text": "Plot the u and l data points using plot() method, with different colors."
},
{
"code": null,
"e": 1683,
"s": 1641,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1725,
"s": 1683,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2033,
"s": 1725,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ny = np.sin(np.linspace(-10, 10, 100))\n\nu = y.copy()\nl = y.copy()\n\nu[u <= 0] = np.nan\nl[l >= 0] = np.nan\n\nplt.plot(u, color='red')\nplt.plot(l, color='blue')\n\nplt.show()"
}
] |
Tryit Editor v3.7 | Tryit: Using align-items: center | [] |
Find inverse of matrix in MATLAB - GeeksforGeeks | 28 Apr, 2021
Inverse function in MATLAB is used to find the inverse of a matrix. Suppose A is a matrix and B is the inverse of a then A*B will be an identity matrix. This function computes the inverse of a square matrix. This is used while solving linear equations. We can compute the inverse of a matrix by passing it to inv().
Syntax:
inv(A)
Parameters:
It takes a matrix as parameter.
Returns:
It returns a matrix which is inverse of input matrix.
Below are some examples which depict how to compute the inverse of a matrix in MATLAB.
Example 1: This example takes a 3×3 matrix as input and computes its inverse using inv() function.
Matlab
% Defining matrixA = [1 2 0; 3 1 4; 5 6 7] % Getting inverse matrixinv(A)
Output:
Example 2: Here is another example that takes a 2×2 matrix as input and computes its inverse.
Matlab
% Defining matrixA = [1 2; 3 1] % Getting inverse matrixinv(A)
Output:
Example 3: This example uses a singular matrix and tries to find its inverse. It will show a warning that the matrix is a singular matrix. Different versions of MATLAB gave a different value of inverse for singular matrix. This is due to the different versions of Math Kernel Library used in different versions of MATLAB.
Matlab
% Defining matrixA = [2 4 6;2 0 2;6 8 14] % Getting inverse matrixinv(A)
Output:
warning: matrix singular to machine precision, rcond = 1.34572e-17
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Boundary Extraction of image using MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Laplacian of Gaussian Filter in MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
Differential or Derivatives in MATLAB
MATLAB Syntax
How to Remove Salt and Pepper Noise from Image Using MATLAB?
How to Normalize a Histogram in MATLAB?
Laplace Transform in MATLAB | [
{
"code": null,
"e": 24580,
"s": 24552,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 24896,
"s": 24580,
"text": "Inverse function in MATLAB is used to find the inverse of a matrix. Suppose A is a matrix and B is the inverse of a then A*B will be an identity matrix. This function computes the inverse of a square matrix. This is used while solving linear equations. We can compute the inverse of a matrix by passing it to inv()."
},
{
"code": null,
"e": 24904,
"s": 24896,
"text": "Syntax:"
},
{
"code": null,
"e": 24911,
"s": 24904,
"text": "inv(A)"
},
{
"code": null,
"e": 24923,
"s": 24911,
"text": "Parameters:"
},
{
"code": null,
"e": 24955,
"s": 24923,
"text": "It takes a matrix as parameter."
},
{
"code": null,
"e": 24964,
"s": 24955,
"text": "Returns:"
},
{
"code": null,
"e": 25018,
"s": 24964,
"text": "It returns a matrix which is inverse of input matrix."
},
{
"code": null,
"e": 25105,
"s": 25018,
"text": "Below are some examples which depict how to compute the inverse of a matrix in MATLAB."
},
{
"code": null,
"e": 25204,
"s": 25105,
"text": "Example 1: This example takes a 3×3 matrix as input and computes its inverse using inv() function."
},
{
"code": null,
"e": 25211,
"s": 25204,
"text": "Matlab"
},
{
"code": "% Defining matrixA = [1 2 0; 3 1 4; 5 6 7] % Getting inverse matrixinv(A)",
"e": 25286,
"s": 25211,
"text": null
},
{
"code": null,
"e": 25294,
"s": 25286,
"text": "Output:"
},
{
"code": null,
"e": 25388,
"s": 25294,
"text": "Example 2: Here is another example that takes a 2×2 matrix as input and computes its inverse."
},
{
"code": null,
"e": 25395,
"s": 25388,
"text": "Matlab"
},
{
"code": "% Defining matrixA = [1 2; 3 1] % Getting inverse matrixinv(A)",
"e": 25459,
"s": 25395,
"text": null
},
{
"code": null,
"e": 25467,
"s": 25459,
"text": "Output:"
},
{
"code": null,
"e": 25789,
"s": 25467,
"text": "Example 3: This example uses a singular matrix and tries to find its inverse. It will show a warning that the matrix is a singular matrix. Different versions of MATLAB gave a different value of inverse for singular matrix. This is due to the different versions of Math Kernel Library used in different versions of MATLAB."
},
{
"code": null,
"e": 25796,
"s": 25789,
"text": "Matlab"
},
{
"code": "% Defining matrixA = [2 4 6;2 0 2;6 8 14] % Getting inverse matrixinv(A)",
"e": 25870,
"s": 25796,
"text": null
},
{
"code": null,
"e": 25878,
"s": 25870,
"text": "Output:"
},
{
"code": null,
"e": 25945,
"s": 25878,
"text": "warning: matrix singular to machine precision, rcond = 1.34572e-17"
},
{
"code": null,
"e": 25952,
"s": 25945,
"text": "Picked"
},
{
"code": null,
"e": 25959,
"s": 25952,
"text": "MATLAB"
},
{
"code": null,
"e": 26057,
"s": 25959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26066,
"s": 26057,
"text": "Comments"
},
{
"code": null,
"e": 26079,
"s": 26066,
"text": "Old Comments"
},
{
"code": null,
"e": 26121,
"s": 26079,
"text": "Boundary Extraction of image using MATLAB"
},
{
"code": null,
"e": 26194,
"s": 26121,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 26233,
"s": 26194,
"text": "Laplacian of Gaussian Filter in MATLAB"
},
{
"code": null,
"e": 26293,
"s": 26233,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 26358,
"s": 26293,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 26396,
"s": 26358,
"text": "Differential or Derivatives in MATLAB"
},
{
"code": null,
"e": 26410,
"s": 26396,
"text": "MATLAB Syntax"
},
{
"code": null,
"e": 26471,
"s": 26410,
"text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?"
},
{
"code": null,
"e": 26511,
"s": 26471,
"text": "How to Normalize a Histogram in MATLAB?"
}
] |
HTML - Phrase Tags | The phrase tags have been desicolgned for specific purposes, though they are displayed in a similar way as other basic tags like <b>, <i>, <pre>, and <tt>, you have seen in previous chapter. This chapter will take you through all the important phrase tags, so let's start seeing them one by one.
Anything that appears within <em>...</em> element is displayed as emphasized text.
<!DOCTYPE html>
<html>
<head>
<title>Emphasized Text Example</title>
</head>
<body>
<p>The following word uses an <em>emphasized</em> typeface.</p>
</body>
</html>
This will produce the following result −
The following word uses an emphasized typeface.
Anything that appears with-in <mark>...</mark> element, is displayed as marked with yellow ink.
<!DOCTYPE html>
<html>
<head>
<title>Marked Text Example</title>
</head>
<body>
<p>The following word has been <mark>marked</mark> with yellow</p>
</body>
</html>
This will produce the following result −
The following word has been marked with yellow
Anything that appears within <strong>...</strong> element is displayed as important text.
<!DOCTYPE html>
<html>
<head>
<title>Strong Text Example</title>
</head>
<body>
<p>The following word uses a <strong>strong</strong> typeface.</p>
</body>
</html>
This will produce the following result −
The following word uses a strong typeface.
You can abbreviate a text by putting it inside opening <abbr> and closing </abbr> tags. If present, the title attribute must contain this full description and nothing else.
<!DOCTYPE html>
<html>
<head>
<title>Text Abbreviation</title>
</head>
<body>
<p>My best friend's name is <abbr title = "Abhishek">Abhy</abbr>.</p>
</body>
</html>
This will produce the following result −
My best friend's name is Abhy.
The <acronym> element allows you to indicate that the text between <acronym> and </acronym> tags is an acronym.
At present, the major browsers do not change the appearance of the content of the <acronym> element.
<!DOCTYPE html>
<html>
<head>
<title>Acronym Example</title>
</head>
<body>
<p>This chapter covers marking up text in <acronym>XHTML</acronym>.</p>
</body>
</html>
This will produce the following result −
This chapter covers marking up text in XHTML.
The <bdo>...</bdo> element stands for Bi-Directional Override and it is used to override the current text direction.
<!DOCTYPE html>
<html>
<head>
<title>Text Direction Example</title>
</head>
<body>
<p>This text will go left to right.</p>
<p><bdo dir = "rtl">This text will go right to left.</bdo></p>
</body>
</html>
This will produce the following result −
This text will go left to right.
This text will go right to left.
The <dfn>...</dfn> element (or HTML Definition Element) allows you to specify that you are introducing a special term. It's usage is similar to italic words in the midst of a paragraph.
Typically, you would use the <dfn> element the first time you introduce a key term. Most recent browsers render the content of a <dfn> element in an italic font.
<!DOCTYPE html>
<html>
<head>
<title>Special Terms Example</title>
</head>
<body>
<p>The following word is a <dfn>special</dfn> term.</p>
</body>
</html>
This will produce the following result −
The following word is a special term.
When you want to quote a passage from another source, you should put it in between <blockquote>...</blockquote> tags.
Text inside a <blockquote> element is usually indented from the left and right edges of the surrounding text, and sometimes uses an italicized font.
<!DOCTYPE html>
<html>
<head>
<title>Blockquote Example</title>
</head>
<body>
<p>The following description of XHTML is taken from the W3C Web site:</p>
<blockquote>XHTML 1.0 is the W3C's first Recommendation for XHTML,following on
from earlier work on HTML 4.01, HTML 4.0, HTML 3.2 and HTML 2.0.</blockquote>
</body>
</html>
This will produce the following result −
The following description of XHTML is taken from the W3C Web site:
The <q>...</q> element is used when you want to add a double quote within a sentence.
<!DOCTYPE html>
<html>
<head>
<title>Double Quote Example</title>
</head>
<body>
<p>Amit is in Spain, <q>I think I am wrong</q>.</p>
</body>
</html>
This will produce the following result −
Amit is in Spain, I think I am wrong.
If you are quoting a text, you can indicate the source placing it between an opening <cite> tag and closing </cite> tag
As you would expect in a print publication, the content of the <cite> element is rendered in italicized text by default.
<!DOCTYPE html>
<html>
<head>
<title>Citations Example</title>
</head>
<body>
<p>This HTML tutorial is derived from <cite>W3 Standard for HTML</cite>.</p>
</body>
</html>
This will produce the following result −
This HTML tutorial is derived from W3 Standard for HTML.
Any programming code to appear on a Web page should be placed inside <code>...</code> tags. Usually the content of the <code> element is presented in a monospaced font, just like the code in most programming books.
<!DOCTYPE html>
<html>
<head>
<title>Computer Code Example</title>
</head>
<body>
<p>Regular text. <code>This is code.</code> Regular text.</p>
</body>
</html>
This will produce the following result −
Regular text. This is code. Regular text.
When you are talking about computers, if you want to tell a reader to enter some text, you can use the <kbd>...</kbd> element to indicate what should be typed in, as in this example.
<!DOCTYPE html>
<html>
<head>
<title>Keyboard Text Example</title>
</head>
<body>
<p>Regular text. <kbd>This is inside kbd element</kbd> Regular text.</p>
</body>
</html>
This will produce the following result −
Regular text. This is inside kbd element Regular text.
This element is usually used in conjunction with the <pre> and <code> elements to indicate that the content of that element is a variable.
<!DOCTYPE html>
<html>
<head>
<title>Variable Text Example</title>
</head>
<body>
<p><code>document.write("<var>user-name</var>")</code></p>
</body>
</html>
This will produce the following result −
document.write("user-name")
The <samp>...</samp> element indicates sample output from a program, and script etc. Again, it is mainly used when documenting programming or coding concepts.
<!DOCTYPE html>
<html>
<head>
<title>Program Output Example</title>
</head>
<body>
<p>Result produced by the program is <samp>Hello World!</samp></p>
</body>
</html>
This will produce the following result −
Result produced by the program is Hello World!
The <address>...</address> element is used to contain any address.
<!DOCTYPE html>
<html>
<head>
<title>Address Example</title>
</head>
<body>
<address>388A, Road No 22, Jubilee Hills - Hyderabad</address>
</body>
</html>
This will produce the following result −
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2670,
"s": 2374,
"text": "The phrase tags have been desicolgned for specific purposes, though they are displayed in a similar way as other basic tags like <b>, <i>, <pre>, and <tt>, you have seen in previous chapter. This chapter will take you through all the important phrase tags, so let's start seeing them one by one."
},
{
"code": null,
"e": 2753,
"s": 2670,
"text": "Anything that appears within <em>...</em> element is displayed as emphasized text."
},
{
"code": null,
"e": 2946,
"s": 2753,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Emphasized Text Example</title>\n </head>\n\t\n <body>\n <p>The following word uses an <em>emphasized</em> typeface.</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 2987,
"s": 2946,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3035,
"s": 2987,
"text": "The following word uses an emphasized typeface."
},
{
"code": null,
"e": 3131,
"s": 3035,
"text": "Anything that appears with-in <mark>...</mark> element, is displayed as marked with yellow ink."
},
{
"code": null,
"e": 3323,
"s": 3131,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Marked Text Example</title>\n </head>\n\t\n <body>\n <p>The following word has been <mark>marked</mark> with yellow</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 3364,
"s": 3323,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3411,
"s": 3364,
"text": "The following word has been marked with yellow"
},
{
"code": null,
"e": 3501,
"s": 3411,
"text": "Anything that appears within <strong>...</strong> element is displayed as important text."
},
{
"code": null,
"e": 3693,
"s": 3501,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Strong Text Example</title>\n </head>\n\t\n <body>\n <p>The following word uses a <strong>strong</strong> typeface.</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 3734,
"s": 3693,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3777,
"s": 3734,
"text": "The following word uses a strong typeface."
},
{
"code": null,
"e": 3950,
"s": 3777,
"text": "You can abbreviate a text by putting it inside opening <abbr> and closing </abbr> tags. If present, the title attribute must contain this full description and nothing else."
},
{
"code": null,
"e": 4144,
"s": 3950,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Text Abbreviation</title>\n </head>\n\t\n <body>\n <p>My best friend's name is <abbr title = \"Abhishek\">Abhy</abbr>.</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 4185,
"s": 4144,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4217,
"s": 4185,
"text": "My best friend's name is Abhy."
},
{
"code": null,
"e": 4329,
"s": 4217,
"text": "The <acronym> element allows you to indicate that the text between <acronym> and </acronym> tags is an acronym."
},
{
"code": null,
"e": 4430,
"s": 4329,
"text": "At present, the major browsers do not change the appearance of the content of the <acronym> element."
},
{
"code": null,
"e": 4623,
"s": 4430,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Acronym Example</title>\n </head>\n\t\n <body>\n <p>This chapter covers marking up text in <acronym>XHTML</acronym>.</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 4664,
"s": 4623,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4710,
"s": 4664,
"text": "This chapter covers marking up text in XHTML."
},
{
"code": null,
"e": 4827,
"s": 4710,
"text": "The <bdo>...</bdo> element stands for Bi-Directional Override and it is used to override the current text direction."
},
{
"code": null,
"e": 5062,
"s": 4827,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Text Direction Example</title>\n </head>\n\n <body>\n <p>This text will go left to right.</p>\n <p><bdo dir = \"rtl\">This text will go right to left.</bdo></p>\n </body>\n\n</html>"
},
{
"code": null,
"e": 5103,
"s": 5062,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 5136,
"s": 5103,
"text": "This text will go left to right."
},
{
"code": null,
"e": 5169,
"s": 5136,
"text": "This text will go right to left."
},
{
"code": null,
"e": 5355,
"s": 5169,
"text": "The <dfn>...</dfn> element (or HTML Definition Element) allows you to specify that you are introducing a special term. It's usage is similar to italic words in the midst of a paragraph."
},
{
"code": null,
"e": 5517,
"s": 5355,
"text": "Typically, you would use the <dfn> element the first time you introduce a key term. Most recent browsers render the content of a <dfn> element in an italic font."
},
{
"code": null,
"e": 5700,
"s": 5517,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Special Terms Example</title>\n </head>\n\t\n <body>\n <p>The following word is a <dfn>special</dfn> term.</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 5741,
"s": 5700,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 5779,
"s": 5741,
"text": "The following word is a special term."
},
{
"code": null,
"e": 5897,
"s": 5779,
"text": "When you want to quote a passage from another source, you should put it in between <blockquote>...</blockquote> tags."
},
{
"code": null,
"e": 6046,
"s": 5897,
"text": "Text inside a <blockquote> element is usually indented from the left and right edges of the surrounding text, and sometimes uses an italicized font."
},
{
"code": null,
"e": 6418,
"s": 6046,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Blockquote Example</title>\n </head>\n\t\n <body>\n <p>The following description of XHTML is taken from the W3C Web site:</p>\n\n <blockquote>XHTML 1.0 is the W3C's first Recommendation for XHTML,following on \n from earlier work on HTML 4.01, HTML 4.0, HTML 3.2 and HTML 2.0.</blockquote>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 6459,
"s": 6418,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 6526,
"s": 6459,
"text": "The following description of XHTML is taken from the W3C Web site:"
},
{
"code": null,
"e": 6612,
"s": 6526,
"text": "The <q>...</q> element is used when you want to add a double quote within a sentence."
},
{
"code": null,
"e": 6790,
"s": 6612,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Double Quote Example</title>\n </head>\n\t\n <body>\n <p>Amit is in Spain, <q>I think I am wrong</q>.</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 6831,
"s": 6790,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 6869,
"s": 6831,
"text": "Amit is in Spain, I think I am wrong."
},
{
"code": null,
"e": 6989,
"s": 6869,
"text": "If you are quoting a text, you can indicate the source placing it between an opening <cite> tag and closing </cite> tag"
},
{
"code": null,
"e": 7110,
"s": 6989,
"text": "As you would expect in a print publication, the content of the <cite> element is rendered in italicized text by default."
},
{
"code": null,
"e": 7317,
"s": 7110,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <title>Citations Example</title>\n </head>\n \n <body>\n <p>This HTML tutorial is derived from <cite>W3 Standard for HTML</cite>.</p>\n </body>\n \n</html>"
},
{
"code": null,
"e": 7358,
"s": 7317,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 7415,
"s": 7358,
"text": "This HTML tutorial is derived from W3 Standard for HTML."
},
{
"code": null,
"e": 7630,
"s": 7415,
"text": "Any programming code to appear on a Web page should be placed inside <code>...</code> tags. Usually the content of the <code> element is presented in a monospaced font, just like the code in most programming books."
},
{
"code": null,
"e": 7826,
"s": 7630,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <title>Computer Code Example</title>\n </head>\n \n <body>\n <p>Regular text. <code>This is code.</code> Regular text.</p>\n </body>\n \n</html>"
},
{
"code": null,
"e": 7867,
"s": 7826,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 7909,
"s": 7867,
"text": "Regular text. This is code. Regular text."
},
{
"code": null,
"e": 8092,
"s": 7909,
"text": "When you are talking about computers, if you want to tell a reader to enter some text, you can use the <kbd>...</kbd> element to indicate what should be typed in, as in this example."
},
{
"code": null,
"e": 8299,
"s": 8092,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <title>Keyboard Text Example</title>\n </head>\n \n <body>\n <p>Regular text. <kbd>This is inside kbd element</kbd> Regular text.</p>\n </body>\n \n</html>"
},
{
"code": null,
"e": 8340,
"s": 8299,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 8395,
"s": 8340,
"text": "Regular text. This is inside kbd element Regular text."
},
{
"code": null,
"e": 8534,
"s": 8395,
"text": "This element is usually used in conjunction with the <pre> and <code> elements to indicate that the content of that element is a variable."
},
{
"code": null,
"e": 8727,
"s": 8534,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <title>Variable Text Example</title>\n </head>\n \n <body>\n <p><code>document.write(\"<var>user-name</var>\")</code></p>\n </body>\n \n</html>"
},
{
"code": null,
"e": 8768,
"s": 8727,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 8796,
"s": 8768,
"text": "document.write(\"user-name\")"
},
{
"code": null,
"e": 8955,
"s": 8796,
"text": "The <samp>...</samp> element indicates sample output from a program, and script etc. Again, it is mainly used when documenting programming or coding concepts."
},
{
"code": null,
"e": 9157,
"s": 8955,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <title>Program Output Example</title>\n </head>\n \n <body>\n <p>Result produced by the program is <samp>Hello World!</samp></p>\n </body>\n \n</html>"
},
{
"code": null,
"e": 9198,
"s": 9157,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 9245,
"s": 9198,
"text": "Result produced by the program is Hello World!"
},
{
"code": null,
"e": 9312,
"s": 9245,
"text": "The <address>...</address> element is used to contain any address."
},
{
"code": null,
"e": 9504,
"s": 9312,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <title>Address Example</title>\n </head>\n \n <body>\n <address>388A, Road No 22, Jubilee Hills - Hyderabad</address>\n </body>\n \n</html>"
},
{
"code": null,
"e": 9545,
"s": 9504,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 9578,
"s": 9545,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9592,
"s": 9578,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9627,
"s": 9592,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9641,
"s": 9627,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9676,
"s": 9641,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9693,
"s": 9676,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9728,
"s": 9693,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9759,
"s": 9728,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 9792,
"s": 9759,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9823,
"s": 9792,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 9858,
"s": 9823,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9889,
"s": 9858,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 9896,
"s": 9889,
"text": " Print"
},
{
"code": null,
"e": 9907,
"s": 9896,
"text": " Add Notes"
}
] |
ASP.NET - Server Side | We have studied the page life cycle and how a page contains various controls. The page itself is instantiated as a control object. All web forms are basically instances of the ASP.NET Page class. The page class has the following extremely useful properties that correspond to intrinsic objects:
Session
Application
Cache
Request
Response
Server
User
Trace
We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request object, and the Response object.
The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform various jobs.
The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET.
The following table provides a list of the properties:
The following table provides a list of some important methods:
The request object is an instance of the System.Web.HttpRequest class. It represents the values and properties of the HTTP request that makes the page loading into the browser.
The information presented by this object is wrapped by the higher level abstractions (the web control model). However, this object helps in checking some information such as the client browser and cookies.
The following table provides some noteworthy properties of the Request object:
The following table provides a list of some important methods:
The Response object represents the server's response to the client request. It is an instance of the System.Web.HttpResponse class.
In ASP.NET, the response object does not play any vital role in sending HTML text to the client, because the server-side controls have nested, object oriented methods for rendering themselves.
However, the HttpResponse object still provides some important functionalities, like the cookie feature and the Redirect() method. The Response.Redirect() method allows transferring the user to another page, inside as well as outside the application. It requires a round trip.
The following table provides some noteworthy properties of the Response object:
The following table provides a list of some important methods:
The following simple example has a text box control where the user can enter name, a button to send the information to the server, and a label control to display the URL of the client computer.
The content file:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="server_side._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter your name:
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
<br />
<asp:Label ID="Label1" runat="server"/>
</div>
</form>
</body>
</html>
The code behind Button1_Click:
protected void Button1_Click(object sender, EventArgs e) {
if (!String.IsNullOrEmpty(TextBox1.Text)) {
// Access the HttpServerUtility methods through
// the intrinsic Server object.
Label1.Text = "Welcome, " + Server.HtmlEncode(TextBox1.Text) + ". <br/> The url is " + Server.UrlEncode(Request.Url.ToString())
}
}
Run the page to see the following result:
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2642,
"s": 2347,
"text": "We have studied the page life cycle and how a page contains various controls. The page itself is instantiated as a control object. All web forms are basically instances of the ASP.NET Page class. The page class has the following extremely useful properties that correspond to intrinsic objects:"
},
{
"code": null,
"e": 2650,
"s": 2642,
"text": "Session"
},
{
"code": null,
"e": 2662,
"s": 2650,
"text": "Application"
},
{
"code": null,
"e": 2668,
"s": 2662,
"text": "Cache"
},
{
"code": null,
"e": 2676,
"s": 2668,
"text": "Request"
},
{
"code": null,
"e": 2685,
"s": 2676,
"text": "Response"
},
{
"code": null,
"e": 2692,
"s": 2685,
"text": "Server"
},
{
"code": null,
"e": 2697,
"s": 2692,
"text": "User"
},
{
"code": null,
"e": 2703,
"s": 2697,
"text": "Trace"
},
{
"code": null,
"e": 2851,
"s": 2703,
"text": "We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request object, and the Response object."
},
{
"code": null,
"e": 3032,
"s": 2851,
"text": "The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform various jobs."
},
{
"code": null,
"e": 3159,
"s": 3032,
"text": "The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET."
},
{
"code": null,
"e": 3214,
"s": 3159,
"text": "The following table provides a list of the properties:"
},
{
"code": null,
"e": 3277,
"s": 3214,
"text": "The following table provides a list of some important methods:"
},
{
"code": null,
"e": 3454,
"s": 3277,
"text": "The request object is an instance of the System.Web.HttpRequest class. It represents the values and properties of the HTTP request that makes the page loading into the browser."
},
{
"code": null,
"e": 3660,
"s": 3454,
"text": "The information presented by this object is wrapped by the higher level abstractions (the web control model). However, this object helps in checking some information such as the client browser and cookies."
},
{
"code": null,
"e": 3739,
"s": 3660,
"text": "The following table provides some noteworthy properties of the Request object:"
},
{
"code": null,
"e": 3802,
"s": 3739,
"text": "The following table provides a list of some important methods:"
},
{
"code": null,
"e": 3934,
"s": 3802,
"text": "The Response object represents the server's response to the client request. It is an instance of the System.Web.HttpResponse class."
},
{
"code": null,
"e": 4127,
"s": 3934,
"text": "In ASP.NET, the response object does not play any vital role in sending HTML text to the client, because the server-side controls have nested, object oriented methods for rendering themselves."
},
{
"code": null,
"e": 4404,
"s": 4127,
"text": "However, the HttpResponse object still provides some important functionalities, like the cookie feature and the Redirect() method. The Response.Redirect() method allows transferring the user to another page, inside as well as outside the application. It requires a round trip."
},
{
"code": null,
"e": 4484,
"s": 4404,
"text": "The following table provides some noteworthy properties of the Response object:"
},
{
"code": null,
"e": 4547,
"s": 4484,
"text": "The following table provides a list of some important methods:"
},
{
"code": null,
"e": 4741,
"s": 4547,
"text": "The following simple example has a text box control where the user can enter name, a button to send the information to the server, and a label control to display the URL of the client computer."
},
{
"code": null,
"e": 4759,
"s": 4741,
"text": "The content file:"
},
{
"code": null,
"e": 5534,
"s": 4759,
"text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" \n Inherits=\"server_side._Default\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n\n <head runat=\"server\">\n <title>Untitled Page</title>\n </head>\n \n <body>\n <form id=\"form1\" runat=\"server\">\n <div>\n \n Enter your name:\n <br />\n <asp:TextBox ID=\"TextBox1\" runat=\"server\"></asp:TextBox>\n <asp:Button ID=\"Button1\" runat=\"server\" OnClick=\"Button1_Click\" Text=\"Submit\" />\n <br />\n <asp:Label ID=\"Label1\" runat=\"server\"/>\n\n </div>\n </form>\n </body>\n \n</html>"
},
{
"code": null,
"e": 5565,
"s": 5534,
"text": "The code behind Button1_Click:"
},
{
"code": null,
"e": 5909,
"s": 5565,
"text": "protected void Button1_Click(object sender, EventArgs e) {\n\n if (!String.IsNullOrEmpty(TextBox1.Text)) {\n \n // Access the HttpServerUtility methods through\n // the intrinsic Server object.\n Label1.Text = \"Welcome, \" + Server.HtmlEncode(TextBox1.Text) + \". <br/> The url is \" + Server.UrlEncode(Request.Url.ToString())\n }\n}"
},
{
"code": null,
"e": 5951,
"s": 5909,
"text": "Run the page to see the following result:"
},
{
"code": null,
"e": 5986,
"s": 5951,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6000,
"s": 5986,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6035,
"s": 6000,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6058,
"s": 6035,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6092,
"s": 6058,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 6112,
"s": 6092,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6147,
"s": 6112,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6164,
"s": 6147,
"text": " University Code"
},
{
"code": null,
"e": 6199,
"s": 6164,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6216,
"s": 6199,
"text": " University Code"
},
{
"code": null,
"e": 6250,
"s": 6216,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6265,
"s": 6250,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 6272,
"s": 6265,
"text": " Print"
},
{
"code": null,
"e": 6283,
"s": 6272,
"text": " Add Notes"
}
] |
Change the order of index of a series in Pandas - GeeksforGeeks | 06 Jan, 2022
Suppose we want to change the order of the index of series, then we have to use the Series.reindex() Method of pandas module for performing this task.
Series, which is a 1-D labeled array capable of holding any data.
Syntax: pandas.Series(data, index, dtype, copy)
Parameters:
data takes ndarrys, list, constants.
index values.
dtypes for data types.
Copy data, default is False.
For knowing more about the pandas Series click here.
Series.reindex() Method is used for changing the data on the basis of indexes.
Syntax: Series.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None)
For knowing more about the pandas Series.reindex() method click here.
Let’s create a series:
Python3
# import required libraryimport pandas as pdimport numpy as np # create numpy arraydata = np.array(["Android dev", "content writing", "competitive coding"])#create a seriestotal_series = pd.Series(data, index = [1, 2, 3]) # show the seriestotal_series
Output:
Series
Example 1:
Python3
# import required libraryimport pandas as pdimport numpy as np # create numpy arraydata = np.array(["Android dev", "content writing", "competitive coding"])# create a seriestotal_series = pd.Series(data, index = [1, 2, 3])# reindexing of seriestotal_series = total_series.reindex(index = [3, 2, 1])# show the seriestotal_series
Output:
Example 2:
Python3
# import required libraryimport pandas as pdimport numpy as np # create numpy arraydata = np.array(["Android dev", "content writing", "competitive coding"])# create a seriestotal_series = pd.Series(data, index = [1, 2, 3])# reindexing of seriestotal_series = total_series.reindex([2, 3, 1]) # show the seriestotal_series
Output:
adnanirshad158
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.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Split string into list of characters | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 24443,
"s": 24292,
"text": "Suppose we want to change the order of the index of series, then we have to use the Series.reindex() Method of pandas module for performing this task."
},
{
"code": null,
"e": 24509,
"s": 24443,
"text": "Series, which is a 1-D labeled array capable of holding any data."
},
{
"code": null,
"e": 24558,
"s": 24509,
"text": "Syntax: pandas.Series(data, index, dtype, copy) "
},
{
"code": null,
"e": 24570,
"s": 24558,
"text": "Parameters:"
},
{
"code": null,
"e": 24607,
"s": 24570,
"text": "data takes ndarrys, list, constants."
},
{
"code": null,
"e": 24621,
"s": 24607,
"text": "index values."
},
{
"code": null,
"e": 24644,
"s": 24621,
"text": "dtypes for data types."
},
{
"code": null,
"e": 24673,
"s": 24644,
"text": "Copy data, default is False."
},
{
"code": null,
"e": 24726,
"s": 24673,
"text": "For knowing more about the pandas Series click here."
},
{
"code": null,
"e": 24805,
"s": 24726,
"text": "Series.reindex() Method is used for changing the data on the basis of indexes."
},
{
"code": null,
"e": 24959,
"s": 24805,
"text": "Syntax: Series.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None) "
},
{
"code": null,
"e": 25029,
"s": 24959,
"text": "For knowing more about the pandas Series.reindex() method click here."
},
{
"code": null,
"e": 25052,
"s": 25029,
"text": "Let’s create a series:"
},
{
"code": null,
"e": 25060,
"s": 25052,
"text": "Python3"
},
{
"code": "# import required libraryimport pandas as pdimport numpy as np # create numpy arraydata = np.array([\"Android dev\", \"content writing\", \"competitive coding\"])#create a seriestotal_series = pd.Series(data, index = [1, 2, 3]) # show the seriestotal_series",
"e": 25368,
"s": 25060,
"text": null
},
{
"code": null,
"e": 25376,
"s": 25368,
"text": "Output:"
},
{
"code": null,
"e": 25383,
"s": 25376,
"text": "Series"
},
{
"code": null,
"e": 25395,
"s": 25383,
"text": "Example 1: "
},
{
"code": null,
"e": 25403,
"s": 25395,
"text": "Python3"
},
{
"code": "# import required libraryimport pandas as pdimport numpy as np # create numpy arraydata = np.array([\"Android dev\", \"content writing\", \"competitive coding\"])# create a seriestotal_series = pd.Series(data, index = [1, 2, 3])# reindexing of seriestotal_series = total_series.reindex(index = [3, 2, 1])# show the seriestotal_series",
"e": 25822,
"s": 25403,
"text": null
},
{
"code": null,
"e": 25831,
"s": 25822,
"text": "Output: "
},
{
"code": null,
"e": 25843,
"s": 25831,
"text": "Example 2: "
},
{
"code": null,
"e": 25851,
"s": 25843,
"text": "Python3"
},
{
"code": "# import required libraryimport pandas as pdimport numpy as np # create numpy arraydata = np.array([\"Android dev\", \"content writing\", \"competitive coding\"])# create a seriestotal_series = pd.Series(data, index = [1, 2, 3])# reindexing of seriestotal_series = total_series.reindex([2, 3, 1]) # show the seriestotal_series",
"e": 26228,
"s": 25851,
"text": null
},
{
"code": null,
"e": 26236,
"s": 26228,
"text": "Output:"
},
{
"code": null,
"e": 26253,
"s": 26238,
"text": "adnanirshad158"
},
{
"code": null,
"e": 26274,
"s": 26253,
"text": "Python pandas-series"
},
{
"code": null,
"e": 26303,
"s": 26274,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 26317,
"s": 26303,
"text": "Python-pandas"
},
{
"code": null,
"e": 26324,
"s": 26317,
"text": "Python"
},
{
"code": null,
"e": 26422,
"s": 26324,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26454,
"s": 26422,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26510,
"s": 26454,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26552,
"s": 26510,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26594,
"s": 26552,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26649,
"s": 26594,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26671,
"s": 26649,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26710,
"s": 26671,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26741,
"s": 26710,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26770,
"s": 26741,
"text": "Create a directory in Python"
}
] |
How to take input in Python? | Programs are written to solve a specific problem of a user. Thus, the program must be such which can interact with the user. This means that a program must take input from the user and perform the task accordingly on the input which user provides.
The method to take input is different for different datatypes. We’ll discuss how to take input for various datatypes as well as how to take array input from the user.
The input() method is used to take string input from the user.The user can enter numeric value as well but it will be treated as a string. The program can contain any logic or operation to be performed on the string entered by the user ,but in example, we’ll simply print the string which the user enters.
print("Enter a string")
a=input()
print("The string entered by user is",a)
Enter a string
TutorialsPoint
The string entered by user is TutorialsPoint
The above example upon execution, prints the message “Enter a string” on the output screen and lets the user enter something. When input() function executes, the program flow will be stopped until the user gives some input. After entering the string, the second print statement executes.
The integer input can be taken by just type casting the input received into input(). Thus, for taking integer input, we use int(input()) . Only numerical values can be entered by the user, else it throws an error.
print("Enter a number")
a=int(input())
print("The number entered by user is",a)
Enter a number
10
The number entered by user is 10
The float input can be taken by type casting input received in input() .We’ll use float(input()) to take float input. The user can enter integer or float values but the value will be treated as float.
print("Enter a number")
a=float(input())
print("The number entered by user is",a)
Enter a number
2.5
The number entered by user is 2.5
We may at times, need to take an array as input from the user. There is no separate syntax for taking array input.
print("Enter no. of elements")
a=int(input())
print("Enter",a,"integer elements")
array=[]
for i in range(a):
array.append(int(input()))
print("Array entered by user is",array)
Enter no. of elements
5
Enter 5 integer elements
1
2
3
4
5
Array entered by user is [1, 2, 3, 4, 5]
In the above example, the size of the array is taken as input from the user. Then the array is declared and using for loop, we take further elements input from the user and append those in the array.
For taking string array input, we can use input() instead of int(input()) inside for loop. | [
{
"code": null,
"e": 1310,
"s": 1062,
"text": "Programs are written to solve a specific problem of a user. Thus, the program must be such which can interact with the user. This means that a program must take input from the user and perform the task accordingly on the input which user provides."
},
{
"code": null,
"e": 1477,
"s": 1310,
"text": "The method to take input is different for different datatypes. We’ll discuss how to take input for various datatypes as well as how to take array input from the user."
},
{
"code": null,
"e": 1783,
"s": 1477,
"text": "The input() method is used to take string input from the user.The user can enter numeric value as well but it will be treated as a string. The program can contain any logic or operation to be performed on the string entered by the user ,but in example, we’ll simply print the string which the user enters."
},
{
"code": null,
"e": 1858,
"s": 1783,
"text": "print(\"Enter a string\")\na=input()\nprint(\"The string entered by user is\",a)"
},
{
"code": null,
"e": 1933,
"s": 1858,
"text": "Enter a string\nTutorialsPoint\nThe string entered by user is TutorialsPoint"
},
{
"code": null,
"e": 2221,
"s": 1933,
"text": "The above example upon execution, prints the message “Enter a string” on the output screen and lets the user enter something. When input() function executes, the program flow will be stopped until the user gives some input. After entering the string, the second print statement executes."
},
{
"code": null,
"e": 2435,
"s": 2221,
"text": "The integer input can be taken by just type casting the input received into input(). Thus, for taking integer input, we use int(input()) . Only numerical values can be entered by the user, else it throws an error."
},
{
"code": null,
"e": 2515,
"s": 2435,
"text": "print(\"Enter a number\")\na=int(input())\nprint(\"The number entered by user is\",a)"
},
{
"code": null,
"e": 2566,
"s": 2515,
"text": "Enter a number\n10\nThe number entered by user is 10"
},
{
"code": null,
"e": 2767,
"s": 2566,
"text": "The float input can be taken by type casting input received in input() .We’ll use float(input()) to take float input. The user can enter integer or float values but the value will be treated as float."
},
{
"code": null,
"e": 2849,
"s": 2767,
"text": "print(\"Enter a number\")\na=float(input())\nprint(\"The number entered by user is\",a)"
},
{
"code": null,
"e": 2902,
"s": 2849,
"text": "Enter a number\n2.5\nThe number entered by user is 2.5"
},
{
"code": null,
"e": 3017,
"s": 2902,
"text": "We may at times, need to take an array as input from the user. There is no separate syntax for taking array input."
},
{
"code": null,
"e": 3197,
"s": 3017,
"text": "print(\"Enter no. of elements\")\na=int(input())\nprint(\"Enter\",a,\"integer elements\")\narray=[]\nfor i in range(a):\n array.append(int(input()))\nprint(\"Array entered by user is\",array)"
},
{
"code": null,
"e": 3297,
"s": 3197,
"text": "Enter no. of elements\n5\nEnter 5 integer elements\n1\n2\n3\n4\n5\nArray entered by user is [1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 3497,
"s": 3297,
"text": "In the above example, the size of the array is taken as input from the user. Then the array is declared and using for loop, we take further elements input from the user and append those in the array."
},
{
"code": null,
"e": 3588,
"s": 3497,
"text": "For taking string array input, we can use input() instead of int(input()) inside for loop."
}
] |
Left Join with Pandas Data Frames in Python | by Sergei Izrailev | Towards Data Science | A tutorial on how to properly flag the source of null values in the result of a left join.
Merging Pandas data frames is covered extensively in a StackOverflow article Pandas Merging 101. However, my experience of grading data science take-home tests leads me to believe that left joins remain to be a challenge for many people. In this post, I show how to properly handle cases when the right table (data frame) in a Pandas left join contains nulls.
Let’s consider a scenario where we have a table transactions containing transactions performed by some users and a table users containing some user properties, for example, their favorite color. We want to annotate the transactions with the users’ properties. Here are the data frames:
import numpy as npimport pandas as pdnp.random.seed(0)# transactionsleft_df = pd.DataFrame({'transaction_id': ['A', 'B', 'C', 'D'], 'user_id': ['Peter', 'John', 'John', 'Anna'], 'value': np.random.randn(4), })# usersright_df = pd.DataFrame({'user_id': ['Paul', 'Mary', 'John', 'Anna'], 'favorite_color': ['blue', 'blue', 'red', np.NaN], })
Note that Peter is not in the users table and Anna doesn’t have a favorite color.
>>> left_df transaction_id user_id value0 A Peter 1.8675581 B John -0.9772782 C John 0.9500883 D Anna -0.151357>>> right_df user_id favorite_color0 Paul blue1 Mary blue2 John red3 Anna NaN
Adding the user’s favorite color to the transaction table seems straightforward using a left join on the user id:
>>> left_df.merge(right_df, on='user_id', how='left') transaction_id user_id value favorite_color0 A Peter 1.867558 NaN1 B John -0.977278 red2 C John 0.950088 red3 D Anna -0.151357 NaN
We see that Peter and Anna have NaNs in the favorite_color column. However, the missing values are there for two different reasons: Peter’s record didn’t have a match in the users table, while Anna didn’t have a value for the favorite color. In some cases, this subtle difference is important. For example, it can be critical to understanding the data during initial exploration and to improving data quality.
Here are two simple methods to track the differences in why a value is missing in the result of a left join. The first is provided directly by the merge function through theindicator parameter. When set toTrue, the resulting data frame has an additional column _merge:
>>> left_df.merge(right_df, on='user_id', how='left', indicator=True) transaction_id user_id value favorite_color _merge0 A Peter 1.867558 NaN left_only1 B John -0.977278 red both2 C John 0.950088 red both3 D Anna -0.151357 NaN both
The second method is related to how it would be done in the SQL world and explicitly adds a column representing the user_id in the right table. We note that if the join columns in the two tables have different names, both columns appear in the resulting data frame, so we rename the user_id column in the users table before merging.
>>> left_df.merge(right_df.rename({'user_id': 'user_id_r'}, axis=1), left_on='user_id', right_on='user_id_r', how='left') transaction_id user_id value user_id_r favorite_color0 A Peter 1.867558 NaN NaN1 B John -0.977278 John red2 C John 0.950088 John red3 D Anna -0.151357 Anna NaN
An equivalent SQL query is
select t.transaction_id , t.user_id , t.value , u.user_id as user_id_r , u.favorite_colorfrom transactions t left join users u on t.user_id = u.user_id;
In conclusion, adding an extra column that indicates whether there was a match in the Pandas left join allows us to subsequently treat the missing values for the favorite color differently depending on whether the user was known but didn’t have a favorite color or the user was missing from the users table.
This post first appeared on the Life Around Data blog. Photo by Ilona Froehlich on Unsplash. | [
{
"code": null,
"e": 263,
"s": 172,
"text": "A tutorial on how to properly flag the source of null values in the result of a left join."
},
{
"code": null,
"e": 623,
"s": 263,
"text": "Merging Pandas data frames is covered extensively in a StackOverflow article Pandas Merging 101. However, my experience of grading data science take-home tests leads me to believe that left joins remain to be a challenge for many people. In this post, I show how to properly handle cases when the right table (data frame) in a Pandas left join contains nulls."
},
{
"code": null,
"e": 909,
"s": 623,
"text": "Let’s consider a scenario where we have a table transactions containing transactions performed by some users and a table users containing some user properties, for example, their favorite color. We want to annotate the transactions with the users’ properties. Here are the data frames:"
},
{
"code": null,
"e": 1439,
"s": 909,
"text": "import numpy as npimport pandas as pdnp.random.seed(0)# transactionsleft_df = pd.DataFrame({'transaction_id': ['A', 'B', 'C', 'D'], 'user_id': ['Peter', 'John', 'John', 'Anna'], 'value': np.random.randn(4), })# usersright_df = pd.DataFrame({'user_id': ['Paul', 'Mary', 'John', 'Anna'], 'favorite_color': ['blue', 'blue', 'red', np.NaN], })"
},
{
"code": null,
"e": 1521,
"s": 1439,
"text": "Note that Peter is not in the users table and Anna doesn’t have a favorite color."
},
{
"code": null,
"e": 1835,
"s": 1521,
"text": ">>> left_df transaction_id user_id value0 A Peter 1.8675581 B John -0.9772782 C John 0.9500883 D Anna -0.151357>>> right_df user_id favorite_color0 Paul blue1 Mary blue2 John red3 Anna NaN"
},
{
"code": null,
"e": 1949,
"s": 1835,
"text": "Adding the user’s favorite color to the transaction table seems straightforward using a left join on the user id:"
},
{
"code": null,
"e": 2248,
"s": 1949,
"text": ">>> left_df.merge(right_df, on='user_id', how='left') transaction_id user_id value favorite_color0 A Peter 1.867558 NaN1 B John -0.977278 red2 C John 0.950088 red3 D Anna -0.151357 NaN"
},
{
"code": null,
"e": 2658,
"s": 2248,
"text": "We see that Peter and Anna have NaNs in the favorite_color column. However, the missing values are there for two different reasons: Peter’s record didn’t have a match in the users table, while Anna didn’t have a value for the favorite color. In some cases, this subtle difference is important. For example, it can be critical to understanding the data during initial exploration and to improving data quality."
},
{
"code": null,
"e": 2927,
"s": 2658,
"text": "Here are two simple methods to track the differences in why a value is missing in the result of a left join. The first is provided directly by the merge function through theindicator parameter. When set toTrue, the resulting data frame has an additional column _merge:"
},
{
"code": null,
"e": 3297,
"s": 2927,
"text": ">>> left_df.merge(right_df, on='user_id', how='left', indicator=True) transaction_id user_id value favorite_color _merge0 A Peter 1.867558 NaN left_only1 B John -0.977278 red both2 C John 0.950088 red both3 D Anna -0.151357 NaN both"
},
{
"code": null,
"e": 3630,
"s": 3297,
"text": "The second method is related to how it would be done in the SQL world and explicitly adds a column representing the user_id in the right table. We note that if the join columns in the two tables have different names, both columns appear in the resulting data frame, so we rename the user_id column in the users table before merging."
},
{
"code": null,
"e": 4061,
"s": 3630,
"text": ">>> left_df.merge(right_df.rename({'user_id': 'user_id_r'}, axis=1), left_on='user_id', right_on='user_id_r', how='left') transaction_id user_id value user_id_r favorite_color0 A Peter 1.867558 NaN NaN1 B John -0.977278 John red2 C John 0.950088 John red3 D Anna -0.151357 Anna NaN"
},
{
"code": null,
"e": 4088,
"s": 4061,
"text": "An equivalent SQL query is"
},
{
"code": null,
"e": 4268,
"s": 4088,
"text": "select t.transaction_id , t.user_id , t.value , u.user_id as user_id_r , u.favorite_colorfrom transactions t left join users u on t.user_id = u.user_id;"
},
{
"code": null,
"e": 4576,
"s": 4268,
"text": "In conclusion, adding an extra column that indicates whether there was a match in the Pandas left join allows us to subsequently treat the missing values for the favorite color differently depending on whether the user was known but didn’t have a favorite color or the user was missing from the users table."
}
] |
A Data Science/Big Data Laboratory — part 1 of 4: Raspberry Pi or VMs cluster — OS and communication | by Pier Taranti | Towards Data Science | This text can be used to support the installation in any Ubuntu 20.04 server clusters, and this is the beauty of well-designed layered software. Furthermore, if you have more nodes, you can distribute the software as you like. The text assumes you know Linux command line, including ssh, vim, and nano.
I do not recommend starting with less than three Raspberries since you need to set the communication, and both Zookeeper and Kafka requires an odd number of nodes. If you are trying a single node this guide may be used. Still, the performance is likely to be disappointing in a Raspberry — for single node I suggest a virtual machine with a reasonable amount of RAM and processor.
Due to size, I had to divide the tutorial into four parts
Part 1: Introduction, Operational System and Networking
Part 2: Hadoop and Spark
Part 3: PostgreSQL and Hive
Part 4: Kafka, Zookeeper, and Conclusion
All configuration files are available at [1]:
github.com
Disclaimer: This text is offered to everyone for free to use at your own risk. I took care in citing all my sources, but if you feel that something is missed, please send me a note. Since different software versions may behaviour in a distinct way due to their dependencies, I suggest using the same versions I used in your first try.
Training or studying data science or business intelligence is usually a solitary task. You can attend an MBA or do curses on-line, but consolidating knowledge requires practising and experimenting.
For some technologies, this is simple. Python and R can be easily installed on an average computer. However, an overall experiment will require several tools integrated — from the data acquisition to the reporting/visualisation.
And these tools... what can I say ... I do not like to not understanding the tool I am using. I am an old guy who learned the Basic language with 12yo in 1987. I played with Z80 loading programs from an audiotape player, and in the 90’s I administrated Novell networks and used Linux only some years after the Minix — and no, I am not a museum curator. I learned Fortran, Pascal, C, Java... and now R and Python. And I want to train pipelines and analysis in near to real environment — this gets me back to the tools. I feel the need for not only having the environment to train but to really understand this environment.
On the environment, I am talking about the Apache supported solutions (with some friends): Hadoop, Spark, Hive, Postgres, Kafka and so on, installed on a cluster. On your desktop, you are likely to use Anaconda and Rstudio (sorry Anaconda, but I prefer stand-alone Rstudio).
This is my dream lab, and I went for it.
Big Data environment requires a distributed solution in the real world — scalability is a prime requirement. Thus, learning how to configure the environment seams important to me. I did not go for cloud-based solutions — I want full control and no restrictions on the “personal lab”.
Firstly, I have installed the full solution in my notebook, using three virtual machines (Ubuntu 20.04 over VirtualBox). It worked, but there were some drawbacks — performance and networking. Worst — I move my laptop from home to work and back, and using this kind of “virtual network” was not acceptable there.
I was to buy a robust station to virtualise a cluster for my lab when I decided to give a try to Raspberry. The new Raspberry Pi 4 is available up to 4GB of RAM. It is not a Ferrari, but I only needed a small car to have fan and do the work. I read some texts about how to assemble clusters with Raspberry, for the Hadoop + Spark solution — and they succeeded with a PI 3.
Then I decided to assemble my own cluster with three Raspberry Pi.
I am happy with the result; it works, and its performance allows me to conduct the experiments. I would recommend this for students.
This first part will lead you in assembling the physical cluster, installing the Ubuntu server 20.04, and setting the environment for cluster
3 or more Raspberry Pi 4 4GB
1 switch gigabit (10/100/1000)
USB-C cables for power up the Pi
Micro SD cards for your Raspberries
Ethernet Cables for networking
Power supply (I am using a charger with 3 USB 3A ports)
The acrylic mount for the cluster
Raspberry Pi 4 has wifi and gigabit ethernet. I opted by a cabled network for the cluster communication, using the gigabit switch. I am also using the wifi for remote access. Thus, you should use cables cat 6.
I bought 128GB SD cards because I want to play with data. However, one of the cards was not delivered, and I started with a 16GB card in for the second raspberry (node pi2), and it worked. Buying good quality SD cards with high read/write speed is essential for the cluster performance. Raspberry has some expansion boards that allows you to use 2.5 HD, SSD SATA or NVME. I did not install it, but you can easily mount a NAS or a data storage area.
I spent a lot of hours configuring the cluster, it was almost three weeks discovering issues and returning to zero. I am not a sadistic seeking for others to suffer the same, then I decided to publish this guide, and I hope you enjoy it.
I used these excellent guides as a reference, with a focus in the first [2, 3, 4]:
dev.to
medium.com
developer.ibm.com
However, even following the tutorials, I found many issues and pitfalls. Some of the problems can be related to different software versions.
In order to help you when reading this text, and myself if I need to reinstall, I saved all config files in a similar folder structure as the one existent in the raspberries — use with caution (IPs, server names, and so on, can be different for you). All files are in the final version, with distributed versions of Hadoop, Hive, Zookeeper and Kafka (Spark and Postgres are installed in single nodes).
First of all, you should assemble the physical stuff in the cluster support, less the SD cards. Do not be eager to start with parts all over your desk; this is prone to short circuits, and you will lose your material.
My notebook runs Windows 10 — and I did not forget the dark side (Linux) — I have some Linux virtual machines ready to choose and use. But I will refer to Windows supporting software when describing the tutorial. If you are a Linux-only geek, I am sure you know how to get the job done with your tools (and it is usually easier in Linux).
The best tool for creating the micro SD card with the Ubuntu server is the Raspberry Pi Imager [5]. The tool is available for Windows, Ubuntu and Mac, and can be downloaded from:
www.raspberrypi.org
This utility will burn your initial OS system in pristine version.
Advice: I tried to use that cheap microSD to SD adaptor that usually arrives with the micro SD card in the notebook SD slot. It was very slow, and I changed to a micro-SD to USB adaptor and used in the USB 3.0 port. Much better.
Raspberry Pi 4 has AMR64 architecture — previous versions were AMR32. Thus, any Linux 32/64 should install fine. In my first attempts, I used the Raspbian (only 32bit version available) — but I had issues with the Hadoop installation. After that, I decided using the Ubuntu 64bit version (recommended by Ubuntu for Pi 4).
Insert your SD and start the Raspberry Pi Imager and format it (I always format before any OS installation). Install the Ubuntu server 20.04 64bit. Do the same for all your PI Micro SD cards.
The Ubuntu 20.04 server comes in minimal version, set to connect ethernet network by DHCP.
Note — if you reinsert the micro SD card in your laptop card reader before installing it in the Raspberry, you will have access to the installation config files. In theory, you can set you initial users and network configuration. The network configuration file follows the netplan standard for yaml files. However, I tried some times and did not work properly, and I decided to do it as usual, through an ssh connection or using a keyboard and monitor.
Note — Ubuntu comes with vim and nano editors installed. I am used to vim, but the highlight schema of colours makes reading difficult — even with glasses! I used nano. The shortcuts are displayed in the bottom of the nano interface.
This is a cluster — networking is paramount. All this tutorial assumes you have a home network with a router/gateway.
You will need access to the OS to configure your network. You can do it in two different ways: the simpler one is buying an adaptor from micro-HDMI to HDMI, wired keyboard and plug in your Raspberry one by one. You will have direct access with the initial username/password.
The default user/password is ubuntu/ubuntu, and you will be asked to change the password in the first login. I changed passwords to ‘raspberry’. This is a lab, avoid using your true passwords in the cluster.
The second way to initially connect the Raspberries is to rely on your DHCP and connecting the Pi on your cabled network (ethernet), again one by one.
When accessing your router management page, you will have access to the connected devices, and the Raspberry will appear as “ubuntu”. Take note of the IP address for the remote connection.
I did it by ssh since my wired keyboard did not arrive on time. Power up only one Raspberry at the time, configure its network, hostname, hosts and user and turn it down. This will facilitate the identification of the dynamic IP for the initial connection with ssh.
When you power up a Pi 4, you will see red and green led blinking near the micro SD. Red led is power and green shows it is accessing your secondary memory (the micro SD).
All my Pi have the same configuration for user/password and files location. This makes it easier to manage the cluster.
Like I wrote before, I decided to set up ethernet and wifi. I did it in this way because my cluster is not directly linked to my router. I have a wifi network extender, TP-Link RE200, which offers one ethernet port 10/100, but offers 2.4GHz + 5.0GHz over the air. Thus, my solution is having the switch gigabit only for intra-cluster communication and for the remote access I use wifi. Anyway, I have the ethernet from the extender (RE200) connected to the switch to ensure a second route to the cluster — just in case.
Ubuntu server 20.04 uses netplan for network configuration. As a resume, you produce a well-formatted text file and ask the system to parse and process files with yaml suffix in /etc/netplan folder. Netplan will then change your network settings accordingly.
Important — indentation must have 4 spaces. I struggled when editing before realising this.
You will find the following file to edit:
/etc/netplan/50-cloud-init.yaml
I was lazy and only edited it, but you can opt by changing its suffix to avoid netplan to read it and creating a new one.
Note — after losing connection with my Pi in some installations, which forced me to reinstall the system (I had no USB keyboard), I opted for first configure wifi and restart. After ensuring the wifi is ok, I changed the ethernet from DHCP to static IP.
You can copy my file and edit accordingly:
/etc/netplan 50-cloud-init.yaml
After editing the file, you need to confirm the changes:
ubuntu@ubuntu:/etc/netplan$ sudo netplan apply
You need to adapt the file to your environment. Usually, you will need only to decide on IPs for the cluster, change the router IP (gateway) and configure wifi (name and password). I have 2 wifi networks (2.4G + 5G).
To make my life easier, I kept it simple:
Hostname IP (Ethernet) IP(wifi) pi1 192.168.1.11 192.162.1.21pi2 192.168.1.12 192.162.1.22pi3 192.168.1.13 192.162.1.23
Note — be sure to remove the range you have chosen from the range your router can use for DHCP connections.
Once you have stable network connections, you can start the real configuration. Keep in mind the cluster uses network connections, the access rights must be all ok between the Raspberries, or your distributed services will fail.
My cluster architecture is as presented in the image:
You will create the same user in all nodes, with sudo access:
Note — do not use the low-level useradd command!
sudo adduser pi sudo passwd piNew password:Retype new password:passwd: password updated successfullysudo usermod -aG sudo pi sudo usermod -aG admin pi
The usermod commands ensures the sudo access.
Login as pi, and update your system!
sudo apt updatesudo apt upgrade
You will find useful installing the net-tools package! It comes with the netstat, and we will after use it to check active services (ports) in the nodes:
sudo apt-get install net-tools
I have installed a light graphical interface (xfce4) with a web-browser (chromium)and remote desktop access (xrdp). However, this is not really needed, and I am considering removing it. But if you are a GUI guy, you may like it:
In order to enable the remote desktop access, you need to:
Install xfce4 and xrdp:
Sudo apt-get install xfce4sudo apt-get install xrdp
and create the file
create the file /home/pi/.xsession
echo xfce4-session > /home/pi/.xsession
and edit the file
/etc/xrdp/startwm.sh
sudo nano /etc/xrdp/startwm.sh
adding the following at the end, after the last line:
startxfce4
Restart services:
sudo service xrdp restart
The xcfe4 web browser was broken. I installed the chromium:
sudo apt-get install chromium-browser
Just in case, install extFat support (this may help with pen drivers):
sudo apt install exfat-fuse
After restarting you should be able to remotely connect from any windows machine using remote desktop.
You need to update the hostname and also the host files in /etc. See the examples in GitHub.
Note — remove from host file the reference to localhost 127.0.01.
/etc/hosts
On the hostnames, I suggest you stay with pi1, pi2, pi3, ... piX. This because all my config files consider these hostnames. Otherwise, you will need much care of editing it.
/etc/hostname
This was an Achilles heel:
Hadoop is compiled and runs well on Java8. I have looked for it, but I did not find a build from Java Hotspot 8 or Oracle Java 8 for the AMR64 architecture. After some experiments, I decided in favour of the OpenJDK8, already available in Ubuntu repositories and well maintained (I hope so).
You can find information on Hadoop and Java support in [6]:
cwiki.apache.org
To install java:
sudo apt-get install openjdk-8-jdk
This is my version:
pi@p2:~$ java -versionopenjdk version "1.8.0_252"OpenJDK Runtime Environment (build 1.8.0_252-8u252-b09-1ubuntu1-b09)OpenJDK 64-Bit Server VM (build 25.252-b09, mixed mode)
Edit the file (see GitHub):
/home/pi/.ssh/config
To create shortcuts for ssh
Generate public/private rsa key pair for user pi in all cluster nodes:
Commands and outputs, you should expect:
pi@pi1:~$ ssh-keygen -t rsaGenerating public/private rsa key pair.Enter file in which to save the key (/home/pi/.ssh/id_rsa):Enter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in /home/pi/.ssh/id_rsaYour public key has been saved in /home/pi/.ssh/id_rsa.pubThe key fingerprint is:SHA256:mKDvp5u/AsK5CxUUYdkFNSM+rSI4S4aQJR7Wd1AcPZU pi@pi1The key's randomart image is:+---[RSA 3072]----+|.oB=o=Ooo ... ||o*oo.+ = o E ||o.. = o . ||+ o + o ||*o= . o S ||+B.o ||o.... ||.. .... || .. =*o. |
Copy the public keys to the authorized keys list:
cat .ssh/id_rsa.pub >> .ssh/authorized_keys
And copy to all nodes:
cat ~/.ssh/id_rsa.pub | ssh pi2 'cat >> .ssh/authorized_keys'cat ~/.ssh/id_rsa.pub | ssh pi3 'cat >> .ssh/authorized_keys'
Note — you should do this process in each cluster node. In the end, all nodes will have all public keys in their lists. This is important — not having the key would prevent machine-to-machine communication after.
Note — I included my ssh/authorized_keys in the GitHub as an example. Obviously, you cannot use it because it will not work. You need to make your keyring.
The referenced tutorials recommend disabling the password-based authentication mainly because of security issues. I decided against their advice since I want to have easy access to the nodes using traditional password-based access.
If you would like to explore this option, check the two first tutorials referenced at the start of this text. If you would like to explore this option check the two first tutorials referenced at the start of this text.
Create functions to help you on the cluster management, by adding the following on the following file:
/home/pi/.bashrc
run the command:
source /home/pi/.bashrc
You must do it in all nodes. Use scp to copy between nodes if you prefer. If using WinSCP remote access you would be able to copy and paste — but using scp in command line is quicker, and you should learn to do it.
Note — The original tutorials do not have the clustercmd-sudo. I included it since I experimented issues with commands requiring superuser access.
Note — these functions assume the node’s hostnames are pi1, pi2, pi3 pi4..., and that all of it has a user/password pi/pi. These assumptions are also made in Hadoop/Spark/Zookeeper/Kafka/Postgres configuration. If you have chosen different names, then you will need to check every line with care.
Usually, I synchronize all my machines with a time server in UTC. In a cluster, this is even more important.
pi@p2:~$ clustercmd dateFri May 29 21:09:59 UTC 2020Fri May 29 21:09:57 UTC 2020Fri May 29 21:10:02 UTC 2020
Ok, I cheated. My cluster is already synchronised, and I inserted the time difference editing. But your cluster may have differences.
Run the following command:
clustercmd-sudo apt install htpdate -yclustercmd-sudo htpdate -a -l www.pool.ntp.org
The later command uses the htpdate to synchronised the nodes’ clocks with the www.pool.ntp.org.
towardsdatascience.com
[1] P. G. Taranti. https://github.com/ptaranti/RaspberryPiCluster
[2] A. W. Watson. Building a Raspberry Pi Hadoop / Spark Cluster (2019)
[3] W. H. Liang. Build Raspberry Pi Hadoop/Spark Cluster from scratch (2019)
[4] A. Verdugo. Building a Hadoop cluster with Raspberry Pi: Installing, configuring and testing a distributed storage and processing cluster with single-board computers (2017)
[5] G. Hollingworth. Introducing Raspberry Pi Imager, our new imaging utility (2020)
[6] A. Ajisaka. Hadoop Java Versions (2020) | [
{
"code": null,
"e": 475,
"s": 172,
"text": "This text can be used to support the installation in any Ubuntu 20.04 server clusters, and this is the beauty of well-designed layered software. Furthermore, if you have more nodes, you can distribute the software as you like. The text assumes you know Linux command line, including ssh, vim, and nano."
},
{
"code": null,
"e": 856,
"s": 475,
"text": "I do not recommend starting with less than three Raspberries since you need to set the communication, and both Zookeeper and Kafka requires an odd number of nodes. If you are trying a single node this guide may be used. Still, the performance is likely to be disappointing in a Raspberry — for single node I suggest a virtual machine with a reasonable amount of RAM and processor."
},
{
"code": null,
"e": 914,
"s": 856,
"text": "Due to size, I had to divide the tutorial into four parts"
},
{
"code": null,
"e": 970,
"s": 914,
"text": "Part 1: Introduction, Operational System and Networking"
},
{
"code": null,
"e": 995,
"s": 970,
"text": "Part 2: Hadoop and Spark"
},
{
"code": null,
"e": 1023,
"s": 995,
"text": "Part 3: PostgreSQL and Hive"
},
{
"code": null,
"e": 1064,
"s": 1023,
"text": "Part 4: Kafka, Zookeeper, and Conclusion"
},
{
"code": null,
"e": 1110,
"s": 1064,
"text": "All configuration files are available at [1]:"
},
{
"code": null,
"e": 1121,
"s": 1110,
"text": "github.com"
},
{
"code": null,
"e": 1456,
"s": 1121,
"text": "Disclaimer: This text is offered to everyone for free to use at your own risk. I took care in citing all my sources, but if you feel that something is missed, please send me a note. Since different software versions may behaviour in a distinct way due to their dependencies, I suggest using the same versions I used in your first try."
},
{
"code": null,
"e": 1654,
"s": 1456,
"text": "Training or studying data science or business intelligence is usually a solitary task. You can attend an MBA or do curses on-line, but consolidating knowledge requires practising and experimenting."
},
{
"code": null,
"e": 1883,
"s": 1654,
"text": "For some technologies, this is simple. Python and R can be easily installed on an average computer. However, an overall experiment will require several tools integrated — from the data acquisition to the reporting/visualisation."
},
{
"code": null,
"e": 2505,
"s": 1883,
"text": "And these tools... what can I say ... I do not like to not understanding the tool I am using. I am an old guy who learned the Basic language with 12yo in 1987. I played with Z80 loading programs from an audiotape player, and in the 90’s I administrated Novell networks and used Linux only some years after the Minix — and no, I am not a museum curator. I learned Fortran, Pascal, C, Java... and now R and Python. And I want to train pipelines and analysis in near to real environment — this gets me back to the tools. I feel the need for not only having the environment to train but to really understand this environment."
},
{
"code": null,
"e": 2780,
"s": 2505,
"text": "On the environment, I am talking about the Apache supported solutions (with some friends): Hadoop, Spark, Hive, Postgres, Kafka and so on, installed on a cluster. On your desktop, you are likely to use Anaconda and Rstudio (sorry Anaconda, but I prefer stand-alone Rstudio)."
},
{
"code": null,
"e": 2821,
"s": 2780,
"text": "This is my dream lab, and I went for it."
},
{
"code": null,
"e": 3105,
"s": 2821,
"text": "Big Data environment requires a distributed solution in the real world — scalability is a prime requirement. Thus, learning how to configure the environment seams important to me. I did not go for cloud-based solutions — I want full control and no restrictions on the “personal lab”."
},
{
"code": null,
"e": 3417,
"s": 3105,
"text": "Firstly, I have installed the full solution in my notebook, using three virtual machines (Ubuntu 20.04 over VirtualBox). It worked, but there were some drawbacks — performance and networking. Worst — I move my laptop from home to work and back, and using this kind of “virtual network” was not acceptable there."
},
{
"code": null,
"e": 3790,
"s": 3417,
"text": "I was to buy a robust station to virtualise a cluster for my lab when I decided to give a try to Raspberry. The new Raspberry Pi 4 is available up to 4GB of RAM. It is not a Ferrari, but I only needed a small car to have fan and do the work. I read some texts about how to assemble clusters with Raspberry, for the Hadoop + Spark solution — and they succeeded with a PI 3."
},
{
"code": null,
"e": 3857,
"s": 3790,
"text": "Then I decided to assemble my own cluster with three Raspberry Pi."
},
{
"code": null,
"e": 3990,
"s": 3857,
"text": "I am happy with the result; it works, and its performance allows me to conduct the experiments. I would recommend this for students."
},
{
"code": null,
"e": 4132,
"s": 3990,
"text": "This first part will lead you in assembling the physical cluster, installing the Ubuntu server 20.04, and setting the environment for cluster"
},
{
"code": null,
"e": 4161,
"s": 4132,
"text": "3 or more Raspberry Pi 4 4GB"
},
{
"code": null,
"e": 4192,
"s": 4161,
"text": "1 switch gigabit (10/100/1000)"
},
{
"code": null,
"e": 4225,
"s": 4192,
"text": "USB-C cables for power up the Pi"
},
{
"code": null,
"e": 4261,
"s": 4225,
"text": "Micro SD cards for your Raspberries"
},
{
"code": null,
"e": 4292,
"s": 4261,
"text": "Ethernet Cables for networking"
},
{
"code": null,
"e": 4348,
"s": 4292,
"text": "Power supply (I am using a charger with 3 USB 3A ports)"
},
{
"code": null,
"e": 4382,
"s": 4348,
"text": "The acrylic mount for the cluster"
},
{
"code": null,
"e": 4592,
"s": 4382,
"text": "Raspberry Pi 4 has wifi and gigabit ethernet. I opted by a cabled network for the cluster communication, using the gigabit switch. I am also using the wifi for remote access. Thus, you should use cables cat 6."
},
{
"code": null,
"e": 5041,
"s": 4592,
"text": "I bought 128GB SD cards because I want to play with data. However, one of the cards was not delivered, and I started with a 16GB card in for the second raspberry (node pi2), and it worked. Buying good quality SD cards with high read/write speed is essential for the cluster performance. Raspberry has some expansion boards that allows you to use 2.5 HD, SSD SATA or NVME. I did not install it, but you can easily mount a NAS or a data storage area."
},
{
"code": null,
"e": 5279,
"s": 5041,
"text": "I spent a lot of hours configuring the cluster, it was almost three weeks discovering issues and returning to zero. I am not a sadistic seeking for others to suffer the same, then I decided to publish this guide, and I hope you enjoy it."
},
{
"code": null,
"e": 5362,
"s": 5279,
"text": "I used these excellent guides as a reference, with a focus in the first [2, 3, 4]:"
},
{
"code": null,
"e": 5369,
"s": 5362,
"text": "dev.to"
},
{
"code": null,
"e": 5380,
"s": 5369,
"text": "medium.com"
},
{
"code": null,
"e": 5398,
"s": 5380,
"text": "developer.ibm.com"
},
{
"code": null,
"e": 5539,
"s": 5398,
"text": "However, even following the tutorials, I found many issues and pitfalls. Some of the problems can be related to different software versions."
},
{
"code": null,
"e": 5941,
"s": 5539,
"text": "In order to help you when reading this text, and myself if I need to reinstall, I saved all config files in a similar folder structure as the one existent in the raspberries — use with caution (IPs, server names, and so on, can be different for you). All files are in the final version, with distributed versions of Hadoop, Hive, Zookeeper and Kafka (Spark and Postgres are installed in single nodes)."
},
{
"code": null,
"e": 6159,
"s": 5941,
"text": "First of all, you should assemble the physical stuff in the cluster support, less the SD cards. Do not be eager to start with parts all over your desk; this is prone to short circuits, and you will lose your material."
},
{
"code": null,
"e": 6498,
"s": 6159,
"text": "My notebook runs Windows 10 — and I did not forget the dark side (Linux) — I have some Linux virtual machines ready to choose and use. But I will refer to Windows supporting software when describing the tutorial. If you are a Linux-only geek, I am sure you know how to get the job done with your tools (and it is usually easier in Linux)."
},
{
"code": null,
"e": 6677,
"s": 6498,
"text": "The best tool for creating the micro SD card with the Ubuntu server is the Raspberry Pi Imager [5]. The tool is available for Windows, Ubuntu and Mac, and can be downloaded from:"
},
{
"code": null,
"e": 6697,
"s": 6677,
"text": "www.raspberrypi.org"
},
{
"code": null,
"e": 6764,
"s": 6697,
"text": "This utility will burn your initial OS system in pristine version."
},
{
"code": null,
"e": 6993,
"s": 6764,
"text": "Advice: I tried to use that cheap microSD to SD adaptor that usually arrives with the micro SD card in the notebook SD slot. It was very slow, and I changed to a micro-SD to USB adaptor and used in the USB 3.0 port. Much better."
},
{
"code": null,
"e": 7315,
"s": 6993,
"text": "Raspberry Pi 4 has AMR64 architecture — previous versions were AMR32. Thus, any Linux 32/64 should install fine. In my first attempts, I used the Raspbian (only 32bit version available) — but I had issues with the Hadoop installation. After that, I decided using the Ubuntu 64bit version (recommended by Ubuntu for Pi 4)."
},
{
"code": null,
"e": 7507,
"s": 7315,
"text": "Insert your SD and start the Raspberry Pi Imager and format it (I always format before any OS installation). Install the Ubuntu server 20.04 64bit. Do the same for all your PI Micro SD cards."
},
{
"code": null,
"e": 7598,
"s": 7507,
"text": "The Ubuntu 20.04 server comes in minimal version, set to connect ethernet network by DHCP."
},
{
"code": null,
"e": 8051,
"s": 7598,
"text": "Note — if you reinsert the micro SD card in your laptop card reader before installing it in the Raspberry, you will have access to the installation config files. In theory, you can set you initial users and network configuration. The network configuration file follows the netplan standard for yaml files. However, I tried some times and did not work properly, and I decided to do it as usual, through an ssh connection or using a keyboard and monitor."
},
{
"code": null,
"e": 8285,
"s": 8051,
"text": "Note — Ubuntu comes with vim and nano editors installed. I am used to vim, but the highlight schema of colours makes reading difficult — even with glasses! I used nano. The shortcuts are displayed in the bottom of the nano interface."
},
{
"code": null,
"e": 8403,
"s": 8285,
"text": "This is a cluster — networking is paramount. All this tutorial assumes you have a home network with a router/gateway."
},
{
"code": null,
"e": 8678,
"s": 8403,
"text": "You will need access to the OS to configure your network. You can do it in two different ways: the simpler one is buying an adaptor from micro-HDMI to HDMI, wired keyboard and plug in your Raspberry one by one. You will have direct access with the initial username/password."
},
{
"code": null,
"e": 8886,
"s": 8678,
"text": "The default user/password is ubuntu/ubuntu, and you will be asked to change the password in the first login. I changed passwords to ‘raspberry’. This is a lab, avoid using your true passwords in the cluster."
},
{
"code": null,
"e": 9037,
"s": 8886,
"text": "The second way to initially connect the Raspberries is to rely on your DHCP and connecting the Pi on your cabled network (ethernet), again one by one."
},
{
"code": null,
"e": 9226,
"s": 9037,
"text": "When accessing your router management page, you will have access to the connected devices, and the Raspberry will appear as “ubuntu”. Take note of the IP address for the remote connection."
},
{
"code": null,
"e": 9492,
"s": 9226,
"text": "I did it by ssh since my wired keyboard did not arrive on time. Power up only one Raspberry at the time, configure its network, hostname, hosts and user and turn it down. This will facilitate the identification of the dynamic IP for the initial connection with ssh."
},
{
"code": null,
"e": 9664,
"s": 9492,
"text": "When you power up a Pi 4, you will see red and green led blinking near the micro SD. Red led is power and green shows it is accessing your secondary memory (the micro SD)."
},
{
"code": null,
"e": 9784,
"s": 9664,
"text": "All my Pi have the same configuration for user/password and files location. This makes it easier to manage the cluster."
},
{
"code": null,
"e": 10304,
"s": 9784,
"text": "Like I wrote before, I decided to set up ethernet and wifi. I did it in this way because my cluster is not directly linked to my router. I have a wifi network extender, TP-Link RE200, which offers one ethernet port 10/100, but offers 2.4GHz + 5.0GHz over the air. Thus, my solution is having the switch gigabit only for intra-cluster communication and for the remote access I use wifi. Anyway, I have the ethernet from the extender (RE200) connected to the switch to ensure a second route to the cluster — just in case."
},
{
"code": null,
"e": 10563,
"s": 10304,
"text": "Ubuntu server 20.04 uses netplan for network configuration. As a resume, you produce a well-formatted text file and ask the system to parse and process files with yaml suffix in /etc/netplan folder. Netplan will then change your network settings accordingly."
},
{
"code": null,
"e": 10655,
"s": 10563,
"text": "Important — indentation must have 4 spaces. I struggled when editing before realising this."
},
{
"code": null,
"e": 10697,
"s": 10655,
"text": "You will find the following file to edit:"
},
{
"code": null,
"e": 10729,
"s": 10697,
"text": "/etc/netplan/50-cloud-init.yaml"
},
{
"code": null,
"e": 10851,
"s": 10729,
"text": "I was lazy and only edited it, but you can opt by changing its suffix to avoid netplan to read it and creating a new one."
},
{
"code": null,
"e": 11105,
"s": 10851,
"text": "Note — after losing connection with my Pi in some installations, which forced me to reinstall the system (I had no USB keyboard), I opted for first configure wifi and restart. After ensuring the wifi is ok, I changed the ethernet from DHCP to static IP."
},
{
"code": null,
"e": 11148,
"s": 11105,
"text": "You can copy my file and edit accordingly:"
},
{
"code": null,
"e": 11180,
"s": 11148,
"text": "/etc/netplan 50-cloud-init.yaml"
},
{
"code": null,
"e": 11237,
"s": 11180,
"text": "After editing the file, you need to confirm the changes:"
},
{
"code": null,
"e": 11284,
"s": 11237,
"text": "ubuntu@ubuntu:/etc/netplan$ sudo netplan apply"
},
{
"code": null,
"e": 11501,
"s": 11284,
"text": "You need to adapt the file to your environment. Usually, you will need only to decide on IPs for the cluster, change the router IP (gateway) and configure wifi (name and password). I have 2 wifi networks (2.4G + 5G)."
},
{
"code": null,
"e": 11543,
"s": 11501,
"text": "To make my life easier, I kept it simple:"
},
{
"code": null,
"e": 11706,
"s": 11543,
"text": "Hostname IP (Ethernet) IP(wifi) pi1 192.168.1.11 192.162.1.21pi2 192.168.1.12 192.162.1.22pi3 192.168.1.13 192.162.1.23"
},
{
"code": null,
"e": 11814,
"s": 11706,
"text": "Note — be sure to remove the range you have chosen from the range your router can use for DHCP connections."
},
{
"code": null,
"e": 12043,
"s": 11814,
"text": "Once you have stable network connections, you can start the real configuration. Keep in mind the cluster uses network connections, the access rights must be all ok between the Raspberries, or your distributed services will fail."
},
{
"code": null,
"e": 12097,
"s": 12043,
"text": "My cluster architecture is as presented in the image:"
},
{
"code": null,
"e": 12159,
"s": 12097,
"text": "You will create the same user in all nodes, with sudo access:"
},
{
"code": null,
"e": 12208,
"s": 12159,
"text": "Note — do not use the low-level useradd command!"
},
{
"code": null,
"e": 12360,
"s": 12208,
"text": "sudo adduser pi sudo passwd piNew password:Retype new password:passwd: password updated successfullysudo usermod -aG sudo pi sudo usermod -aG admin pi"
},
{
"code": null,
"e": 12406,
"s": 12360,
"text": "The usermod commands ensures the sudo access."
},
{
"code": null,
"e": 12443,
"s": 12406,
"text": "Login as pi, and update your system!"
},
{
"code": null,
"e": 12475,
"s": 12443,
"text": "sudo apt updatesudo apt upgrade"
},
{
"code": null,
"e": 12629,
"s": 12475,
"text": "You will find useful installing the net-tools package! It comes with the netstat, and we will after use it to check active services (ports) in the nodes:"
},
{
"code": null,
"e": 12660,
"s": 12629,
"text": "sudo apt-get install net-tools"
},
{
"code": null,
"e": 12889,
"s": 12660,
"text": "I have installed a light graphical interface (xfce4) with a web-browser (chromium)and remote desktop access (xrdp). However, this is not really needed, and I am considering removing it. But if you are a GUI guy, you may like it:"
},
{
"code": null,
"e": 12948,
"s": 12889,
"text": "In order to enable the remote desktop access, you need to:"
},
{
"code": null,
"e": 12972,
"s": 12948,
"text": "Install xfce4 and xrdp:"
},
{
"code": null,
"e": 13024,
"s": 12972,
"text": "Sudo apt-get install xfce4sudo apt-get install xrdp"
},
{
"code": null,
"e": 13044,
"s": 13024,
"text": "and create the file"
},
{
"code": null,
"e": 13079,
"s": 13044,
"text": "create the file /home/pi/.xsession"
},
{
"code": null,
"e": 13119,
"s": 13079,
"text": "echo xfce4-session > /home/pi/.xsession"
},
{
"code": null,
"e": 13137,
"s": 13119,
"text": "and edit the file"
},
{
"code": null,
"e": 13158,
"s": 13137,
"text": "/etc/xrdp/startwm.sh"
},
{
"code": null,
"e": 13189,
"s": 13158,
"text": "sudo nano /etc/xrdp/startwm.sh"
},
{
"code": null,
"e": 13243,
"s": 13189,
"text": "adding the following at the end, after the last line:"
},
{
"code": null,
"e": 13254,
"s": 13243,
"text": "startxfce4"
},
{
"code": null,
"e": 13272,
"s": 13254,
"text": "Restart services:"
},
{
"code": null,
"e": 13298,
"s": 13272,
"text": "sudo service xrdp restart"
},
{
"code": null,
"e": 13358,
"s": 13298,
"text": "The xcfe4 web browser was broken. I installed the chromium:"
},
{
"code": null,
"e": 13396,
"s": 13358,
"text": "sudo apt-get install chromium-browser"
},
{
"code": null,
"e": 13467,
"s": 13396,
"text": "Just in case, install extFat support (this may help with pen drivers):"
},
{
"code": null,
"e": 13495,
"s": 13467,
"text": "sudo apt install exfat-fuse"
},
{
"code": null,
"e": 13598,
"s": 13495,
"text": "After restarting you should be able to remotely connect from any windows machine using remote desktop."
},
{
"code": null,
"e": 13691,
"s": 13598,
"text": "You need to update the hostname and also the host files in /etc. See the examples in GitHub."
},
{
"code": null,
"e": 13757,
"s": 13691,
"text": "Note — remove from host file the reference to localhost 127.0.01."
},
{
"code": null,
"e": 13768,
"s": 13757,
"text": "/etc/hosts"
},
{
"code": null,
"e": 13943,
"s": 13768,
"text": "On the hostnames, I suggest you stay with pi1, pi2, pi3, ... piX. This because all my config files consider these hostnames. Otherwise, you will need much care of editing it."
},
{
"code": null,
"e": 13957,
"s": 13943,
"text": "/etc/hostname"
},
{
"code": null,
"e": 13984,
"s": 13957,
"text": "This was an Achilles heel:"
},
{
"code": null,
"e": 14276,
"s": 13984,
"text": "Hadoop is compiled and runs well on Java8. I have looked for it, but I did not find a build from Java Hotspot 8 or Oracle Java 8 for the AMR64 architecture. After some experiments, I decided in favour of the OpenJDK8, already available in Ubuntu repositories and well maintained (I hope so)."
},
{
"code": null,
"e": 14336,
"s": 14276,
"text": "You can find information on Hadoop and Java support in [6]:"
},
{
"code": null,
"e": 14353,
"s": 14336,
"text": "cwiki.apache.org"
},
{
"code": null,
"e": 14370,
"s": 14353,
"text": "To install java:"
},
{
"code": null,
"e": 14405,
"s": 14370,
"text": "sudo apt-get install openjdk-8-jdk"
},
{
"code": null,
"e": 14425,
"s": 14405,
"text": "This is my version:"
},
{
"code": null,
"e": 14598,
"s": 14425,
"text": "pi@p2:~$ java -versionopenjdk version \"1.8.0_252\"OpenJDK Runtime Environment (build 1.8.0_252-8u252-b09-1ubuntu1-b09)OpenJDK 64-Bit Server VM (build 25.252-b09, mixed mode)"
},
{
"code": null,
"e": 14626,
"s": 14598,
"text": "Edit the file (see GitHub):"
},
{
"code": null,
"e": 14647,
"s": 14626,
"text": "/home/pi/.ssh/config"
},
{
"code": null,
"e": 14675,
"s": 14647,
"text": "To create shortcuts for ssh"
},
{
"code": null,
"e": 14746,
"s": 14675,
"text": "Generate public/private rsa key pair for user pi in all cluster nodes:"
},
{
"code": null,
"e": 14787,
"s": 14746,
"text": "Commands and outputs, you should expect:"
},
{
"code": null,
"e": 15399,
"s": 14787,
"text": "pi@pi1:~$ ssh-keygen -t rsaGenerating public/private rsa key pair.Enter file in which to save the key (/home/pi/.ssh/id_rsa):Enter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in /home/pi/.ssh/id_rsaYour public key has been saved in /home/pi/.ssh/id_rsa.pubThe key fingerprint is:SHA256:mKDvp5u/AsK5CxUUYdkFNSM+rSI4S4aQJR7Wd1AcPZU pi@pi1The key's randomart image is:+---[RSA 3072]----+|.oB=o=Ooo ... ||o*oo.+ = o E ||o.. = o . ||+ o + o ||*o= . o S ||+B.o ||o.... ||.. .... || .. =*o. |"
},
{
"code": null,
"e": 15449,
"s": 15399,
"text": "Copy the public keys to the authorized keys list:"
},
{
"code": null,
"e": 15494,
"s": 15449,
"text": "cat .ssh/id_rsa.pub >> .ssh/authorized_keys"
},
{
"code": null,
"e": 15517,
"s": 15494,
"text": "And copy to all nodes:"
},
{
"code": null,
"e": 15640,
"s": 15517,
"text": "cat ~/.ssh/id_rsa.pub | ssh pi2 'cat >> .ssh/authorized_keys'cat ~/.ssh/id_rsa.pub | ssh pi3 'cat >> .ssh/authorized_keys'"
},
{
"code": null,
"e": 15853,
"s": 15640,
"text": "Note — you should do this process in each cluster node. In the end, all nodes will have all public keys in their lists. This is important — not having the key would prevent machine-to-machine communication after."
},
{
"code": null,
"e": 16009,
"s": 15853,
"text": "Note — I included my ssh/authorized_keys in the GitHub as an example. Obviously, you cannot use it because it will not work. You need to make your keyring."
},
{
"code": null,
"e": 16241,
"s": 16009,
"text": "The referenced tutorials recommend disabling the password-based authentication mainly because of security issues. I decided against their advice since I want to have easy access to the nodes using traditional password-based access."
},
{
"code": null,
"e": 16460,
"s": 16241,
"text": "If you would like to explore this option, check the two first tutorials referenced at the start of this text. If you would like to explore this option check the two first tutorials referenced at the start of this text."
},
{
"code": null,
"e": 16563,
"s": 16460,
"text": "Create functions to help you on the cluster management, by adding the following on the following file:"
},
{
"code": null,
"e": 16580,
"s": 16563,
"text": "/home/pi/.bashrc"
},
{
"code": null,
"e": 16597,
"s": 16580,
"text": "run the command:"
},
{
"code": null,
"e": 16621,
"s": 16597,
"text": "source /home/pi/.bashrc"
},
{
"code": null,
"e": 16836,
"s": 16621,
"text": "You must do it in all nodes. Use scp to copy between nodes if you prefer. If using WinSCP remote access you would be able to copy and paste — but using scp in command line is quicker, and you should learn to do it."
},
{
"code": null,
"e": 16983,
"s": 16836,
"text": "Note — The original tutorials do not have the clustercmd-sudo. I included it since I experimented issues with commands requiring superuser access."
},
{
"code": null,
"e": 17280,
"s": 16983,
"text": "Note — these functions assume the node’s hostnames are pi1, pi2, pi3 pi4..., and that all of it has a user/password pi/pi. These assumptions are also made in Hadoop/Spark/Zookeeper/Kafka/Postgres configuration. If you have chosen different names, then you will need to check every line with care."
},
{
"code": null,
"e": 17389,
"s": 17280,
"text": "Usually, I synchronize all my machines with a time server in UTC. In a cluster, this is even more important."
},
{
"code": null,
"e": 17498,
"s": 17389,
"text": "pi@p2:~$ clustercmd dateFri May 29 21:09:59 UTC 2020Fri May 29 21:09:57 UTC 2020Fri May 29 21:10:02 UTC 2020"
},
{
"code": null,
"e": 17632,
"s": 17498,
"text": "Ok, I cheated. My cluster is already synchronised, and I inserted the time difference editing. But your cluster may have differences."
},
{
"code": null,
"e": 17659,
"s": 17632,
"text": "Run the following command:"
},
{
"code": null,
"e": 17744,
"s": 17659,
"text": "clustercmd-sudo apt install htpdate -yclustercmd-sudo htpdate -a -l www.pool.ntp.org"
},
{
"code": null,
"e": 17840,
"s": 17744,
"text": "The later command uses the htpdate to synchronised the nodes’ clocks with the www.pool.ntp.org."
},
{
"code": null,
"e": 17863,
"s": 17840,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 17929,
"s": 17863,
"text": "[1] P. G. Taranti. https://github.com/ptaranti/RaspberryPiCluster"
},
{
"code": null,
"e": 18001,
"s": 17929,
"text": "[2] A. W. Watson. Building a Raspberry Pi Hadoop / Spark Cluster (2019)"
},
{
"code": null,
"e": 18078,
"s": 18001,
"text": "[3] W. H. Liang. Build Raspberry Pi Hadoop/Spark Cluster from scratch (2019)"
},
{
"code": null,
"e": 18255,
"s": 18078,
"text": "[4] A. Verdugo. Building a Hadoop cluster with Raspberry Pi: Installing, configuring and testing a distributed storage and processing cluster with single-board computers (2017)"
},
{
"code": null,
"e": 18340,
"s": 18255,
"text": "[5] G. Hollingworth. Introducing Raspberry Pi Imager, our new imaging utility (2020)"
}
] |
iText - Drawing an Arc | In this chapter, we will see how to draw an arc on a PDF document using iText library.
You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor.
To draw an arc on a PdfDocument, instantiate the PdfCanvas class of the package com.itextpdf.kernel.pdf.canvas and create an arc using the arc() method of this class.
Following are the steps to draw an arc on a PDF document.
The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created.
Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below.
// Creating a PdfWriter
String dest = "C:/itextExamples/drawingArc.pdf";
PdfWriter writer = new PdfWriter(dest);
When the object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified.
The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor.
Instantiate the PdfDocument class by passing the PdfWriter object to its constructor, as shown below.
// Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(writer);
Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class.
The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument.
Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps as shown below.
// Creating a Document
Document document = new Document(pdfDoc);
Create a new PdfPage class using the addNewPage() method of the PdfDocument class.
Instantiate the PdfCanvas object of the package com.itextpdf.kernel.pdf.canvas by passing the above created PdfPage object to the constructor of this class, as shown below.
// Creating a new page
PdfPage pdfPage = pdfDoc.addNewPage();
// Creating a PdfCanvas object
PdfCanvas canvas = new PdfCanvas(pdfPage);
Draw the arc using the arc() method of the Canvas class and fill it using the fill() method, as shown below.
// Drawing an arc
canvas.arc(50, 50, 300, 545, 0, 360);
// Filling the arc
canvas.fill();
Close the document using the close() method of the Document class, as shown below.
// Closing the document
document.close();
The following Java program demonstrates how to draw an arc in a PDF document using the iText library.
It creates a PDF document with the name drawingArc.pdf, draws an arc in it, and saves it in the path C:/itextExamples/
Save this code in a file with the name DrawingArc.java.
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
public class DrawingArc {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/drawingArc.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a new page
PdfPage pdfPage = pdfDoc.addNewPage();
// Creating a PdfCanvas object
PdfCanvas canvas = new PdfCanvas(pdfPage);
// Drawing an arc
canvas.arc(50, 50, 300, 545, 0, 360);
// Filling the arc
canvas.fill();
// Closing the document
doc.close();
System.out.println("Object drawn on pdf successfully");
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac DrawingArc.java
java DrawingArc
Upon execution, the above program creates a PDF document, displaying the following message.
Object drawn on pdf successfully
If you verify the specified path, you can find the created PDF document, as shown below.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2455,
"s": 2368,
"text": "In this chapter, we will see how to draw an arc on a PDF document using iText library."
},
{
"code": null,
"e": 2634,
"s": 2455,
"text": "You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor."
},
{
"code": null,
"e": 2801,
"s": 2634,
"text": "To draw an arc on a PdfDocument, instantiate the PdfCanvas class of the package com.itextpdf.kernel.pdf.canvas and create an arc using the arc() method of this class."
},
{
"code": null,
"e": 2859,
"s": 2801,
"text": "Following are the steps to draw an arc on a PDF document."
},
{
"code": null,
"e": 3088,
"s": 2859,
"text": "The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created."
},
{
"code": null,
"e": 3237,
"s": 3088,
"text": "Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below."
},
{
"code": null,
"e": 3354,
"s": 3237,
"text": "// Creating a PdfWriter \nString dest = \"C:/itextExamples/drawingArc.pdf\"; \nPdfWriter writer = new PdfWriter(dest); \n"
},
{
"code": null,
"e": 3495,
"s": 3354,
"text": "When the object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified."
},
{
"code": null,
"e": 3747,
"s": 3495,
"text": "The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor."
},
{
"code": null,
"e": 3849,
"s": 3747,
"text": "Instantiate the PdfDocument class by passing the PdfWriter object to its constructor, as shown below."
},
{
"code": null,
"e": 3925,
"s": 3849,
"text": "// Creating a PdfDocument \nPdfDocument pdfDoc = new PdfDocument(writer); \n"
},
{
"code": null,
"e": 4096,
"s": 3925,
"text": "Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class."
},
{
"code": null,
"e": 4290,
"s": 4096,
"text": "The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument."
},
{
"code": null,
"e": 4414,
"s": 4290,
"text": "Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps as shown below."
},
{
"code": null,
"e": 4484,
"s": 4414,
"text": "// Creating a Document \nDocument document = new Document(pdfDoc); \n"
},
{
"code": null,
"e": 4567,
"s": 4484,
"text": "Create a new PdfPage class using the addNewPage() method of the PdfDocument class."
},
{
"code": null,
"e": 4740,
"s": 4567,
"text": "Instantiate the PdfCanvas object of the package com.itextpdf.kernel.pdf.canvas by passing the above created PdfPage object to the constructor of this class, as shown below."
},
{
"code": null,
"e": 4892,
"s": 4740,
"text": "// Creating a new page \nPdfPage pdfPage = pdfDoc.addNewPage(); \n\n// Creating a PdfCanvas object \nPdfCanvas canvas = new PdfCanvas(pdfPage); \n"
},
{
"code": null,
"e": 5001,
"s": 4892,
"text": "Draw the arc using the arc() method of the Canvas class and fill it using the fill() method, as shown below."
},
{
"code": null,
"e": 5099,
"s": 5001,
"text": "// Drawing an arc \ncanvas.arc(50, 50, 300, 545, 0, 360); \n\n// Filling the arc \ncanvas.fill(); \n"
},
{
"code": null,
"e": 5182,
"s": 5099,
"text": "Close the document using the close() method of the Document class, as shown below."
},
{
"code": null,
"e": 5226,
"s": 5182,
"text": "// Closing the document \ndocument.close();\n"
},
{
"code": null,
"e": 5328,
"s": 5226,
"text": "The following Java program demonstrates how to draw an arc in a PDF document using the iText library."
},
{
"code": null,
"e": 5447,
"s": 5328,
"text": "It creates a PDF document with the name drawingArc.pdf, draws an arc in it, and saves it in the path C:/itextExamples/"
},
{
"code": null,
"e": 5503,
"s": 5447,
"text": "Save this code in a file with the name DrawingArc.java."
},
{
"code": null,
"e": 6590,
"s": 5503,
"text": "import com.itextpdf.kernel.color.Color; \nimport com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfPage; \nimport com.itextpdf.kernel.pdf.PdfWriter; \nimport com.itextpdf.kernel.pdf.canvas.PdfCanvas; \nimport com.itextpdf.layout.Document; \n\npublic class DrawingArc {\n public static void main(String args[]) throws Exception {\n // Creating a PdfWriter\n String dest = \"C:/itextExamples/drawingArc.pdf\";\n PdfWriter writer = new PdfWriter(dest); \n\n // Creating a PdfDocument object\n PdfDocument pdfDoc = new PdfDocument(writer);\n\n // Creating a Document object\n Document doc = new Document(pdfDoc);\n\n // Creating a new page\n PdfPage pdfPage = pdfDoc.addNewPage();\n\n // Creating a PdfCanvas object\n PdfCanvas canvas = new PdfCanvas(pdfPage);\n\n // Drawing an arc\n canvas.arc(50, 50, 300, 545, 0, 360);\n\n // Filling the arc\n canvas.fill(); \n\n // Closing the document\n doc.close();\n \n System.out.println(\"Object drawn on pdf successfully\"); \n } \n} "
},
{
"code": null,
"e": 6685,
"s": 6590,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 6725,
"s": 6685,
"text": "javac DrawingArc.java \njava DrawingArc\n"
},
{
"code": null,
"e": 6817,
"s": 6725,
"text": "Upon execution, the above program creates a PDF document, displaying the following message."
},
{
"code": null,
"e": 6852,
"s": 6817,
"text": "Object drawn on pdf successfully \n"
},
{
"code": null,
"e": 6941,
"s": 6852,
"text": "If you verify the specified path, you can find the created PDF document, as shown below."
},
{
"code": null,
"e": 6948,
"s": 6941,
"text": " Print"
},
{
"code": null,
"e": 6959,
"s": 6948,
"text": " Add Notes"
}
] |
Decision Trees for Online Shopping Analysis | by Chathuranga Siriwardhana | Towards Data Science | Nowadays there is a trend to use online shopping solutions like Amazon, eBay, AliExpress. These websites provide a platform for the sellers to sell their products to a large number of customers. Since many delivery services are connected with these online shopping platforms, customers from different countries buy products. Unlike the traditional shops, the ratings and the good-name is directly represented on the shopping platform for each seller. Therefore the sellers have let the customers return their bought items if they don’t like the product or there is any defect of the item. Some sellers refund the whole amount if the customers complain that the items are not delivered within the promised period. Some customers are misusing these facilities and fraud to the sellers. Therefore, the sellers on the online shopping platforms experience a huge loss of profits. Let’s discuss how we can spot these types of customers by developing a simple Machine Learning model; a Decision Tree.
Have a look at this medium post on Decision Trees if you are not familiar with them. For a quick recap, a decision tree is a model in machine learning which includes the conditions on which we are categorizing the data (for labelling problem). As an example, think about a simple situation where a man is happy is the weather is sunny or he is on vacation. This scenario is modelled below. Note that you can use weather and vacation status to predict the man’s happiness with this model.
I obtained a dataset containing details of an online shopping platform from a data analytics company when I was competing on a Datathon (Data Hackathon). The dataset is encoded such that customer details and seller details won’t be exposed. However, the dataset included plenty of data (in an encoded manner) on the sellers, customers and the products. One of the main tasks of the datathon mentioned above was to find the item returning patterns. This includes the often returning customer attributes, months of the year, often returning item details and seller details. The full dataset includes complete data of one year. Have a look at the dataset schema to get an understanding of the dataset.
The dataset was very huge. Even if it contained data of one year, the size was approximately 25GB. It was written as 4 .csv files(One file per quarter of the year). Even with a computer which has a 16GB memory and an SSD hard drive, the files were too hard to handle. Therefore, pandas python package was used to read the dataset in chunks.
chunks = pd.read_csv('dataset/DataSet01.csv', chunksize=1000000)for chunk in chunks: df = chunk ## Perform task on dataframe; df
Note that the chunksize parameter indicates that only 1000000 records from the given .csv file are read. When preprocessing the data, training machine learning models (here decision trees) and testing models, we can perform those tasks per chunk.
As for preprocessing, the records with missing attributes were ignored since there were millions of records with necessary attributes. A subset of given attributes was selected for item returning analysis by observing the correlations with returns. Have a look at this GitHub repository for more details and code on correlation analysis. Finally, the following attributes were selected by correlation analysis and domain knowledge.
selected_atributes = [‘ONLINE_STORE_CATEGORY’, ‘SIZE_CDE’, ‘CLOR_CDE’, ‘SELLING_PRICE’, ‘PRODUCT_CLASS_02’, ‘FMALE_IND’, ‘MRYD_IND’, ‘BRAND_CODE’, ‘EDUC_LVL_NBR’, ‘MRYD’, ‘AGE’, ‘2017_M7_PURCHASE_AMT’, ‘2017_M7_RETURNED_AMT’,’PRODUCT_CLASS_01', ‘PRODUCT_CLASS_02’]
Note: that these attributes include the category of the item, size, colour, gender, age and marital status of the customer, past months purchased and returned values, education level and, etc.
Let’s build our decision tree model using sklearn’s DecisionTreeClassifier.
from sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn import metrics# load selected attributes and return indication as X and yX = df[selected_atributes]y = df.RETURN_INDICATION## Split dataset into training set and test setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% testmodel = DecisionTreeClassifier()# train the modelmodel= model.fit(X_train,y_train)# testing the modely_pred = model.predict(X_test)# Accuracy calculationprint("Accuracy:", metrics.accuracy_score(y_test, y_pred))
Keeping all the hyperparameters default, I obtained an accuracy of 89%. You can also change the hyperparameters of the decision tree by changing the parameters mentioned in the official documentation.
Now, we have built our decision tree, we want to see the conditions(decisions) on which the customer record is categorized as a returning or not. Decision Tree visualization is a great way of understanding these conditions. Let’s use plot_tree option in sklern.tree to generate the tree.
tree.plot_tree(model, max_depth=5, filled=True)
Note that max_depth=5 indicates that visualize first 5 depth levels of the tree. Our tree is a very complex one. Therefore it can take a huge amount of time and memory to plot the full tree.
You can use the option sklearn.tree.export.export_text to export the tree in text. This way, the full tree can be generated easily.
from sklearn.tree.export import export_textr = export_text(model)print(r)
Go to the GitHub repository to see the generated plot and text structure of the decision tree.
You can use pickle to save the model.
pickle.dump(clf, open('finalized_model.sav', 'wb'))
As well as to load the model from the dumped file.
loaded_model = pickle.load(open('finalized_model.sav', 'rb'))
To classify a given customer record as returning or non-returning, we can use the predict method in the sklearn tree model. Note that you first have to load the same attributes in the same order as you did in the model building step. Let’s predict for the testing data as we split our dataset into training and testing sets.
y_pred_loaded = loaded_model.predict(X_test)
This will return a list of predictions (Item returning indication) which can be compared with the actual returning indication to evaluate our model.
print(“Accuracy:”, metrics.accuracy_score(y_test, y_pred_loaded))>>> 0.96
More importantly, we can use this model to predict some unseen data. As introduced in the Online shopping items returning problem sub-section, the dataset has 4 .csv files. We have used the 1st file to train our model. Let’s use the 4th file to predict the return indication. Note that we are using pandas to load data in chunks.
selected_atributes= ['ONLINE_STORE_CATEGORY', 'SIZE_CDE', 'CLOR_CDE', 'SELLING_PRICE', 'PRODUCT_CLASS_02', 'FMALE_IND', 'MRYD_IND', 'BRAND_CODE', 'EDUC_LVL_NBR', 'MRYD', 'AGE', '2017_M7_PURCHASE_AMT', '2017_M7_RETURNED_AMT','PRODUCT_CLASS_01', 'PRODUCT_CLASS_02']chunks = pd.read_csv('dataset/DataSet04.csv',chunksize=1000000)i = 0for chunk in chunks: i = i +1 if(i>10): break df = chunk# load features and target seperately X_test = df[selected_atributes] y_test = df.RETURN_INDICATION y_pred = loaded_model.predict(X_test) print("Accuracy for chunk ", i, metrics.accuracy_score(y_test, y_pred))>>> Accuracy for chunk 1 0.865241>>> Accuracy for chunk 2 0.860326>>> Accuracy for chunk 3 0.859471>>> Accuracy for chunk 4 0.853036>>> Accuracy for chunk 5 0.852454>>> Accuracy for chunk 6 0.859550>>> Accuracy for chunk 7 0.869302>>> Accuracy for chunk 8 0.866371>>> Accuracy for chunk 9 0.867436>>> Accuracy for chunk 10 0.89067
In the testing step, we got a 96% accuracy. However, this will result in mid-80s accuracies. This is because the model has been overfitted to the seasonal variations in the first quarter of the year. (Recall that we only trained our model using the 1st .csv file of 4 files) Therefore, it doesn’t capture the seasonal variations in the last quarter of the year. However, having trained the model using all the 4 .csv files may resolve this issue. You can still load the data in small chunks from all the 4 .csv files and train the model.
Check out the code at this GitHub repository. Hope you find the article useful. | [
{
"code": null,
"e": 1166,
"s": 172,
"text": "Nowadays there is a trend to use online shopping solutions like Amazon, eBay, AliExpress. These websites provide a platform for the sellers to sell their products to a large number of customers. Since many delivery services are connected with these online shopping platforms, customers from different countries buy products. Unlike the traditional shops, the ratings and the good-name is directly represented on the shopping platform for each seller. Therefore the sellers have let the customers return their bought items if they don’t like the product or there is any defect of the item. Some sellers refund the whole amount if the customers complain that the items are not delivered within the promised period. Some customers are misusing these facilities and fraud to the sellers. Therefore, the sellers on the online shopping platforms experience a huge loss of profits. Let’s discuss how we can spot these types of customers by developing a simple Machine Learning model; a Decision Tree."
},
{
"code": null,
"e": 1654,
"s": 1166,
"text": "Have a look at this medium post on Decision Trees if you are not familiar with them. For a quick recap, a decision tree is a model in machine learning which includes the conditions on which we are categorizing the data (for labelling problem). As an example, think about a simple situation where a man is happy is the weather is sunny or he is on vacation. This scenario is modelled below. Note that you can use weather and vacation status to predict the man’s happiness with this model."
},
{
"code": null,
"e": 2353,
"s": 1654,
"text": "I obtained a dataset containing details of an online shopping platform from a data analytics company when I was competing on a Datathon (Data Hackathon). The dataset is encoded such that customer details and seller details won’t be exposed. However, the dataset included plenty of data (in an encoded manner) on the sellers, customers and the products. One of the main tasks of the datathon mentioned above was to find the item returning patterns. This includes the often returning customer attributes, months of the year, often returning item details and seller details. The full dataset includes complete data of one year. Have a look at the dataset schema to get an understanding of the dataset."
},
{
"code": null,
"e": 2694,
"s": 2353,
"text": "The dataset was very huge. Even if it contained data of one year, the size was approximately 25GB. It was written as 4 .csv files(One file per quarter of the year). Even with a computer which has a 16GB memory and an SSD hard drive, the files were too hard to handle. Therefore, pandas python package was used to read the dataset in chunks."
},
{
"code": null,
"e": 2829,
"s": 2694,
"text": "chunks = pd.read_csv('dataset/DataSet01.csv', chunksize=1000000)for chunk in chunks: df = chunk ## Perform task on dataframe; df"
},
{
"code": null,
"e": 3076,
"s": 2829,
"text": "Note that the chunksize parameter indicates that only 1000000 records from the given .csv file are read. When preprocessing the data, training machine learning models (here decision trees) and testing models, we can perform those tasks per chunk."
},
{
"code": null,
"e": 3508,
"s": 3076,
"text": "As for preprocessing, the records with missing attributes were ignored since there were millions of records with necessary attributes. A subset of given attributes was selected for item returning analysis by observing the correlations with returns. Have a look at this GitHub repository for more details and code on correlation analysis. Finally, the following attributes were selected by correlation analysis and domain knowledge."
},
{
"code": null,
"e": 3773,
"s": 3508,
"text": "selected_atributes = [‘ONLINE_STORE_CATEGORY’, ‘SIZE_CDE’, ‘CLOR_CDE’, ‘SELLING_PRICE’, ‘PRODUCT_CLASS_02’, ‘FMALE_IND’, ‘MRYD_IND’, ‘BRAND_CODE’, ‘EDUC_LVL_NBR’, ‘MRYD’, ‘AGE’, ‘2017_M7_PURCHASE_AMT’, ‘2017_M7_RETURNED_AMT’,’PRODUCT_CLASS_01', ‘PRODUCT_CLASS_02’]"
},
{
"code": null,
"e": 3966,
"s": 3773,
"text": "Note: that these attributes include the category of the item, size, colour, gender, age and marital status of the customer, past months purchased and returned values, education level and, etc."
},
{
"code": null,
"e": 4042,
"s": 3966,
"text": "Let’s build our decision tree model using sklearn’s DecisionTreeClassifier."
},
{
"code": null,
"e": 4652,
"s": 4042,
"text": "from sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn import metrics# load selected attributes and return indication as X and yX = df[selected_atributes]y = df.RETURN_INDICATION## Split dataset into training set and test setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% testmodel = DecisionTreeClassifier()# train the modelmodel= model.fit(X_train,y_train)# testing the modely_pred = model.predict(X_test)# Accuracy calculationprint(\"Accuracy:\", metrics.accuracy_score(y_test, y_pred))"
},
{
"code": null,
"e": 4853,
"s": 4652,
"text": "Keeping all the hyperparameters default, I obtained an accuracy of 89%. You can also change the hyperparameters of the decision tree by changing the parameters mentioned in the official documentation."
},
{
"code": null,
"e": 5141,
"s": 4853,
"text": "Now, we have built our decision tree, we want to see the conditions(decisions) on which the customer record is categorized as a returning or not. Decision Tree visualization is a great way of understanding these conditions. Let’s use plot_tree option in sklern.tree to generate the tree."
},
{
"code": null,
"e": 5189,
"s": 5141,
"text": "tree.plot_tree(model, max_depth=5, filled=True)"
},
{
"code": null,
"e": 5380,
"s": 5189,
"text": "Note that max_depth=5 indicates that visualize first 5 depth levels of the tree. Our tree is a very complex one. Therefore it can take a huge amount of time and memory to plot the full tree."
},
{
"code": null,
"e": 5512,
"s": 5380,
"text": "You can use the option sklearn.tree.export.export_text to export the tree in text. This way, the full tree can be generated easily."
},
{
"code": null,
"e": 5586,
"s": 5512,
"text": "from sklearn.tree.export import export_textr = export_text(model)print(r)"
},
{
"code": null,
"e": 5681,
"s": 5586,
"text": "Go to the GitHub repository to see the generated plot and text structure of the decision tree."
},
{
"code": null,
"e": 5719,
"s": 5681,
"text": "You can use pickle to save the model."
},
{
"code": null,
"e": 5771,
"s": 5719,
"text": "pickle.dump(clf, open('finalized_model.sav', 'wb'))"
},
{
"code": null,
"e": 5822,
"s": 5771,
"text": "As well as to load the model from the dumped file."
},
{
"code": null,
"e": 5884,
"s": 5822,
"text": "loaded_model = pickle.load(open('finalized_model.sav', 'rb'))"
},
{
"code": null,
"e": 6209,
"s": 5884,
"text": "To classify a given customer record as returning or non-returning, we can use the predict method in the sklearn tree model. Note that you first have to load the same attributes in the same order as you did in the model building step. Let’s predict for the testing data as we split our dataset into training and testing sets."
},
{
"code": null,
"e": 6254,
"s": 6209,
"text": "y_pred_loaded = loaded_model.predict(X_test)"
},
{
"code": null,
"e": 6403,
"s": 6254,
"text": "This will return a list of predictions (Item returning indication) which can be compared with the actual returning indication to evaluate our model."
},
{
"code": null,
"e": 6477,
"s": 6403,
"text": "print(“Accuracy:”, metrics.accuracy_score(y_test, y_pred_loaded))>>> 0.96"
},
{
"code": null,
"e": 6807,
"s": 6477,
"text": "More importantly, we can use this model to predict some unseen data. As introduced in the Online shopping items returning problem sub-section, the dataset has 4 .csv files. We have used the 1st file to train our model. Let’s use the 4th file to predict the return indication. Note that we are using pandas to load data in chunks."
},
{
"code": null,
"e": 7780,
"s": 6807,
"text": "selected_atributes= ['ONLINE_STORE_CATEGORY', 'SIZE_CDE', 'CLOR_CDE', 'SELLING_PRICE', 'PRODUCT_CLASS_02', 'FMALE_IND', 'MRYD_IND', 'BRAND_CODE', 'EDUC_LVL_NBR', 'MRYD', 'AGE', '2017_M7_PURCHASE_AMT', '2017_M7_RETURNED_AMT','PRODUCT_CLASS_01', 'PRODUCT_CLASS_02']chunks = pd.read_csv('dataset/DataSet04.csv',chunksize=1000000)i = 0for chunk in chunks: i = i +1 if(i>10): break df = chunk# load features and target seperately X_test = df[selected_atributes] y_test = df.RETURN_INDICATION y_pred = loaded_model.predict(X_test) print(\"Accuracy for chunk \", i, metrics.accuracy_score(y_test, y_pred))>>> Accuracy for chunk 1 0.865241>>> Accuracy for chunk 2 0.860326>>> Accuracy for chunk 3 0.859471>>> Accuracy for chunk 4 0.853036>>> Accuracy for chunk 5 0.852454>>> Accuracy for chunk 6 0.859550>>> Accuracy for chunk 7 0.869302>>> Accuracy for chunk 8 0.866371>>> Accuracy for chunk 9 0.867436>>> Accuracy for chunk 10 0.89067"
},
{
"code": null,
"e": 8318,
"s": 7780,
"text": "In the testing step, we got a 96% accuracy. However, this will result in mid-80s accuracies. This is because the model has been overfitted to the seasonal variations in the first quarter of the year. (Recall that we only trained our model using the 1st .csv file of 4 files) Therefore, it doesn’t capture the seasonal variations in the last quarter of the year. However, having trained the model using all the 4 .csv files may resolve this issue. You can still load the data in small chunks from all the 4 .csv files and train the model."
}
] |
Java Examples - Exception Methods | How to handle the exception methods ?
This example shows how to handle the exception methods by using System.err.println() method of System class.
public class NewClass {
public static void main(String[] args) {
try {
throw new Exception("My Exception");
} catch (Exception e) {
System.err.println("Caught Exception");
System.err.println("getMessage():" + e.getMessage());
System.err.println("getLocalizedMessage():" + e.getLocalizedMessage());
System.err.println("toString():" + e);
System.err.println("printStackTrace():");
e.printStackTrace();
}
}
}
The above code sample will produce the following result.
Caught Exception
getMassage(): My Exception
gatLocalisedMessage(): My Exception
toString():java.lang.Exception: My Exception
print StackTrace():
java.lang.Exception: My Exception
at ExceptionMethods.main(ExceptionMeyhods.java:12)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2106,
"s": 2068,
"text": "How to handle the exception methods ?"
},
{
"code": null,
"e": 2215,
"s": 2106,
"text": "This example shows how to handle the exception methods by using System.err.println() method of System class."
},
{
"code": null,
"e": 2708,
"s": 2215,
"text": "public class NewClass {\n public static void main(String[] args) {\n try {\n throw new Exception(\"My Exception\");\n } catch (Exception e) {\n System.err.println(\"Caught Exception\");\n System.err.println(\"getMessage():\" + e.getMessage());\n System.err.println(\"getLocalizedMessage():\" + e.getLocalizedMessage());\n System.err.println(\"toString():\" + e);\n System.err.println(\"printStackTrace():\");\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2765,
"s": 2708,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3002,
"s": 2765,
"text": "Caught Exception\ngetMassage(): My Exception\ngatLocalisedMessage(): My Exception\ntoString():java.lang.Exception: My Exception\nprint StackTrace():\n java.lang.Exception: My Exception\n at ExceptionMethods.main(ExceptionMeyhods.java:12)\n"
},
{
"code": null,
"e": 3009,
"s": 3002,
"text": " Print"
},
{
"code": null,
"e": 3020,
"s": 3009,
"text": " Add Notes"
}
] |
C++ Algorithm Library - count_if() Function | The C++ function std::algorithm::count_if() returns the number of occurrences of value from range that satisfies condition.
Following is the declaration for std::algorithm::count_if() function form std::algorithm header.
template <class InputIterator, class Predicate>
typename iterator_traits<InputIterator>::difference_type
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
first − Input iterators to the initial positions of the searched sequence.
first − Input iterators to the initial positions of the searched sequence.
last − Input iterators to the final positions of the searched sequence.
last − Input iterators to the final positions of the searched sequence.
pred − Unary predicate which takes an argument and returns bool.
pred − Unary predicate which takes an argument and returns bool.
Returns the number of elements in the range for which pred returns true.
Throws an exception if either predicate or an operation on an iterator throws exception.
Please note that invalid parameters cause undefined behavior.
Linear in the distance between first to last.
The following example shows the usage of std::algorithm::count_if() function.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool predicate(int n) {
return (n > 3);
}
int main(void) {
vector<int> v = {1, 2, 3, 4, 5};
int cnt;
cnt = count_if(v.begin(), v.end(), predicate);
cout << "There are " << cnt << " numbers are greater that 3." << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
There are 2 numbers are greater that 3.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2727,
"s": 2603,
"text": "The C++ function std::algorithm::count_if() returns the number of occurrences of value from range that satisfies condition."
},
{
"code": null,
"e": 2824,
"s": 2727,
"text": "Following is the declaration for std::algorithm::count_if() function form std::algorithm header."
},
{
"code": null,
"e": 3003,
"s": 2824,
"text": "template <class InputIterator, class Predicate>\ntypename iterator_traits<InputIterator>::difference_type\ncount_if (InputIterator first, InputIterator last, UnaryPredicate pred);\n"
},
{
"code": null,
"e": 3078,
"s": 3003,
"text": "first − Input iterators to the initial positions of the searched sequence."
},
{
"code": null,
"e": 3153,
"s": 3078,
"text": "first − Input iterators to the initial positions of the searched sequence."
},
{
"code": null,
"e": 3225,
"s": 3153,
"text": "last − Input iterators to the final positions of the searched sequence."
},
{
"code": null,
"e": 3297,
"s": 3225,
"text": "last − Input iterators to the final positions of the searched sequence."
},
{
"code": null,
"e": 3362,
"s": 3297,
"text": "pred − Unary predicate which takes an argument and returns bool."
},
{
"code": null,
"e": 3427,
"s": 3362,
"text": "pred − Unary predicate which takes an argument and returns bool."
},
{
"code": null,
"e": 3500,
"s": 3427,
"text": "Returns the number of elements in the range for which pred returns true."
},
{
"code": null,
"e": 3589,
"s": 3500,
"text": "Throws an exception if either predicate or an operation on an iterator throws exception."
},
{
"code": null,
"e": 3651,
"s": 3589,
"text": "Please note that invalid parameters cause undefined behavior."
},
{
"code": null,
"e": 3697,
"s": 3651,
"text": "Linear in the distance between first to last."
},
{
"code": null,
"e": 3775,
"s": 3697,
"text": "The following example shows the usage of std::algorithm::count_if() function."
},
{
"code": null,
"e": 4110,
"s": 3775,
"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nbool predicate(int n) {\n return (n > 3);\n}\n\nint main(void) {\n vector<int> v = {1, 2, 3, 4, 5};\n int cnt;\n\n cnt = count_if(v.begin(), v.end(), predicate);\n\n cout << \"There are \" << cnt << \" numbers are greater that 3.\" << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 4193,
"s": 4110,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 4234,
"s": 4193,
"text": "There are 2 numbers are greater that 3.\n"
},
{
"code": null,
"e": 4241,
"s": 4234,
"text": " Print"
},
{
"code": null,
"e": 4252,
"s": 4241,
"text": " Add Notes"
}
] |
How to create a JLabel with an image icon in Java? | Let us create a label with image icon −
JLabel label = new JLabel("SUBJECT ");
label.setIcon(new ImageIcon("E:\\new.png"));
Now, create another component −
JTextArea text = new JTextArea();
text.setText("Add subject here...");
Align the components with GridBagLayout −
panel.setLayout(new GridBagLayout());
The following is an example to center a label with an image icon −
package my;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Demo Frame");
JPanel panel = new JPanel();
JLabel label = new JLabel("SUBJECT ");
label.setIcon(new ImageIcon("E:\\new.png"));
JTextArea text = new JTextArea();
text.setText("Add subject here...");
panel.setLayout(new GridBagLayout());
panel.add(label);
panel.add(text);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(500, 300);
frame.setVisible(true);
}
} | [
{
"code": null,
"e": 1102,
"s": 1062,
"text": "Let us create a label with image icon −"
},
{
"code": null,
"e": 1186,
"s": 1102,
"text": "JLabel label = new JLabel(\"SUBJECT \");\nlabel.setIcon(new ImageIcon(\"E:\\\\new.png\"));"
},
{
"code": null,
"e": 1218,
"s": 1186,
"text": "Now, create another component −"
},
{
"code": null,
"e": 1289,
"s": 1218,
"text": "JTextArea text = new JTextArea();\ntext.setText(\"Add subject here...\");"
},
{
"code": null,
"e": 1331,
"s": 1289,
"text": "Align the components with GridBagLayout −"
},
{
"code": null,
"e": 1369,
"s": 1331,
"text": "panel.setLayout(new GridBagLayout());"
},
{
"code": null,
"e": 1436,
"s": 1369,
"text": "The following is an example to center a label with an image icon −"
},
{
"code": null,
"e": 2344,
"s": 1436,
"text": "package my;\nimport java.awt.GridBagLayout;\nimport javax.swing.BorderFactory;\nimport javax.swing.ImageIcon;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JTextArea;\nimport javax.swing.WindowConstants;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Demo Frame\");\n JPanel panel = new JPanel();\n JLabel label = new JLabel(\"SUBJECT \");\n label.setIcon(new ImageIcon(\"E:\\\\new.png\"));\n JTextArea text = new JTextArea();\n text.setText(\"Add subject here...\");\n panel.setLayout(new GridBagLayout());\n panel.add(label);\n panel.add(text);\n panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));\n frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n frame.add(panel);\n frame.setSize(500, 300);\n frame.setVisible(true);\n }\n}"
}
] |
Sass - Number Operations | SASS allows for mathematical operations such as addition, subtraction, multiplication and division. You cannot use incompatible units such as px * px or while adding number with px and em leads to produce invalid CSS. Therefore, SASS will display an error if you use invalid units in CSS. SASS supports relational operators like <, >, <=, >= and equality operators = =, !=.
SASS allows division operation (/) on numbers as we do in normal CSS. You can use division (/) operation in three situations.
If the value is stored in a variable or returned by function.
If the value is stored in a variable or returned by function.
If parentheses are outside the list and value is inside, the value will be surrounded by parentheses.
If parentheses are outside the list and value is inside, the value will be surrounded by parentheses.
If value is a part of arithmetic expression.
If value is a part of arithmetic expression.
Using SASS, you can perform some operations such as subtraction of numbers (10px - 5px), negating a number (-5), unary negation operator (-$myval) or using identifier (font-size). In some of the cases, these are useful like −
you can use spaces both sides of - when performing subtraction of numbers
you can use spaces both sides of - when performing subtraction of numbers
you can use space before the - , but not after the negative number or a unary negation
you can use space before the - , but not after the negative number or a unary negation
you can enclose the unary negation within parentheses separated by space (5px (-$myval))
you can enclose the unary negation within parentheses separated by space (5px (-$myval))
Examples are −
It can used in identifier such as font-size and SASS allows only valid identifiers.
It can used in identifier such as font-size and SASS allows only valid identifiers.
It can be used with two numbers without space i.e, 10-5 is similar to 10 - 5.
It can be used with two numbers without space i.e, 10-5 is similar to 10 - 5.
It can be used as beginning of a negative number (-5).
It can be used as beginning of a negative number (-5).
It can be used without considering space such as 5 -$myval is similar to 5 - $myval.
It can be used without considering space such as 5 -$myval is similar to 5 - $myval.
It can be used as unary negation operator (-$myval).
It can be used as unary negation operator (-$myval).
The following example demonstrates the use of number operations in the SCSS file −
<html>
<head>
<title>Number Operations</title>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<p class = "para1">SASS stands for Syntactically Awesome Stylesheet..</p>
<h2>Hello...Welcome to Sass</h2>
<h3>Hello...Welcome to Sass</h3>
<p class = "para2">Hello...Welcome to Sass</p>
</div>
</body>
</html>
Next, create file style.scss.
$size: 25px;
h2{
font-size: $size + 5;
}
h3{
font-size: $size / 5;
}
.para1 {
font-size: $size * 1.5;
}
.para2 {
font-size: $size - 10;
}
You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −
sass --watch C:\ruby\lib\sass\style.scss:style.css
Next, execute the above command; it will create the style.css file automatically with the following code −
h2 {
font-size: 30px;
}
h3 {
font-size: 5px;
}
.para1 {
font-size: 37.5px;
}
.para2 {
font-size: 15px;
}
Let us carry out the following steps to see how the above given code works −
Save the above given html code in number_operations.html file.
Save the above given html code in number_operations.html file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.
50 Lectures
5.5 hours
Code And Create
124 Lectures
30 hours
Juan Galvan
162 Lectures
31.5 hours
Yossef Ayman Zedan
167 Lectures
45.5 hours
Muslim Helalee
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2226,
"s": 1852,
"text": "SASS allows for mathematical operations such as addition, subtraction, multiplication and division. You cannot use incompatible units such as px * px or while adding number with px and em leads to produce invalid CSS. Therefore, SASS will display an error if you use invalid units in CSS. SASS supports relational operators like <, >, <=, >= and equality operators = =, !=."
},
{
"code": null,
"e": 2352,
"s": 2226,
"text": "SASS allows division operation (/) on numbers as we do in normal CSS. You can use division (/) operation in three situations."
},
{
"code": null,
"e": 2414,
"s": 2352,
"text": "If the value is stored in a variable or returned by function."
},
{
"code": null,
"e": 2476,
"s": 2414,
"text": "If the value is stored in a variable or returned by function."
},
{
"code": null,
"e": 2578,
"s": 2476,
"text": "If parentheses are outside the list and value is inside, the value will be surrounded by parentheses."
},
{
"code": null,
"e": 2680,
"s": 2578,
"text": "If parentheses are outside the list and value is inside, the value will be surrounded by parentheses."
},
{
"code": null,
"e": 2725,
"s": 2680,
"text": "If value is a part of arithmetic expression."
},
{
"code": null,
"e": 2770,
"s": 2725,
"text": "If value is a part of arithmetic expression."
},
{
"code": null,
"e": 2996,
"s": 2770,
"text": "Using SASS, you can perform some operations such as subtraction of numbers (10px - 5px), negating a number (-5), unary negation operator (-$myval) or using identifier (font-size). In some of the cases, these are useful like −"
},
{
"code": null,
"e": 3070,
"s": 2996,
"text": "you can use spaces both sides of - when performing subtraction of numbers"
},
{
"code": null,
"e": 3144,
"s": 3070,
"text": "you can use spaces both sides of - when performing subtraction of numbers"
},
{
"code": null,
"e": 3231,
"s": 3144,
"text": "you can use space before the - , but not after the negative number or a unary negation"
},
{
"code": null,
"e": 3318,
"s": 3231,
"text": "you can use space before the - , but not after the negative number or a unary negation"
},
{
"code": null,
"e": 3407,
"s": 3318,
"text": "you can enclose the unary negation within parentheses separated by space (5px (-$myval))"
},
{
"code": null,
"e": 3496,
"s": 3407,
"text": "you can enclose the unary negation within parentheses separated by space (5px (-$myval))"
},
{
"code": null,
"e": 3511,
"s": 3496,
"text": "Examples are −"
},
{
"code": null,
"e": 3595,
"s": 3511,
"text": "It can used in identifier such as font-size and SASS allows only valid identifiers."
},
{
"code": null,
"e": 3679,
"s": 3595,
"text": "It can used in identifier such as font-size and SASS allows only valid identifiers."
},
{
"code": null,
"e": 3757,
"s": 3679,
"text": "It can be used with two numbers without space i.e, 10-5 is similar to 10 - 5."
},
{
"code": null,
"e": 3835,
"s": 3757,
"text": "It can be used with two numbers without space i.e, 10-5 is similar to 10 - 5."
},
{
"code": null,
"e": 3890,
"s": 3835,
"text": "It can be used as beginning of a negative number (-5)."
},
{
"code": null,
"e": 3945,
"s": 3890,
"text": "It can be used as beginning of a negative number (-5)."
},
{
"code": null,
"e": 4030,
"s": 3945,
"text": "It can be used without considering space such as 5 -$myval is similar to 5 - $myval."
},
{
"code": null,
"e": 4115,
"s": 4030,
"text": "It can be used without considering space such as 5 -$myval is similar to 5 - $myval."
},
{
"code": null,
"e": 4168,
"s": 4115,
"text": "It can be used as unary negation operator (-$myval)."
},
{
"code": null,
"e": 4221,
"s": 4168,
"text": "It can be used as unary negation operator (-$myval)."
},
{
"code": null,
"e": 4304,
"s": 4221,
"text": "The following example demonstrates the use of number operations in the SCSS file −"
},
{
"code": null,
"e": 5048,
"s": 4304,
"text": "<html>\n <head>\n <title>Number Operations</title>\n <link rel = \"stylesheet\" type = \"text/css\" href = \"style.css\" />\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"></script>\n </head>\n\n <body>\n <div class = \"container\">\n <p class = \"para1\">SASS stands for Syntactically Awesome Stylesheet..</p>\n <h2>Hello...Welcome to Sass</h2>\n <h3>Hello...Welcome to Sass</h3>\n <p class = \"para2\">Hello...Welcome to Sass</p>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 5078,
"s": 5048,
"text": "Next, create file style.scss."
},
{
"code": null,
"e": 5232,
"s": 5078,
"text": "$size: 25px;\n\nh2{\n font-size: $size + 5;\n}\n\nh3{\n font-size: $size / 5;\n}\n\n.para1 {\n font-size: $size * 1.5;\n}\n\n.para2 {\n font-size: $size - 10;\n}"
},
{
"code": null,
"e": 5348,
"s": 5232,
"text": "You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −"
},
{
"code": null,
"e": 5400,
"s": 5348,
"text": "sass --watch C:\\ruby\\lib\\sass\\style.scss:style.css\n"
},
{
"code": null,
"e": 5507,
"s": 5400,
"text": "Next, execute the above command; it will create the style.css file automatically with the following code −"
},
{
"code": null,
"e": 5626,
"s": 5507,
"text": "h2 {\n font-size: 30px;\n}\n\nh3 {\n font-size: 5px;\n}\n\n.para1 {\n font-size: 37.5px;\n}\n\n.para2 {\n font-size: 15px;\n}"
},
{
"code": null,
"e": 5703,
"s": 5626,
"text": "Let us carry out the following steps to see how the above given code works −"
},
{
"code": null,
"e": 5766,
"s": 5703,
"text": "Save the above given html code in number_operations.html file."
},
{
"code": null,
"e": 5829,
"s": 5766,
"text": "Save the above given html code in number_operations.html file."
},
{
"code": null,
"e": 5902,
"s": 5829,
"text": "Open this HTML file in a browser, an output is displayed as shown below."
},
{
"code": null,
"e": 5975,
"s": 5902,
"text": "Open this HTML file in a browser, an output is displayed as shown below."
},
{
"code": null,
"e": 6010,
"s": 5975,
"text": "\n 50 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6027,
"s": 6010,
"text": " Code And Create"
},
{
"code": null,
"e": 6062,
"s": 6027,
"text": "\n 124 Lectures \n 30 hours \n"
},
{
"code": null,
"e": 6075,
"s": 6062,
"text": " Juan Galvan"
},
{
"code": null,
"e": 6112,
"s": 6075,
"text": "\n 162 Lectures \n 31.5 hours \n"
},
{
"code": null,
"e": 6132,
"s": 6112,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 6169,
"s": 6132,
"text": "\n 167 Lectures \n 45.5 hours \n"
},
{
"code": null,
"e": 6185,
"s": 6169,
"text": " Muslim Helalee"
},
{
"code": null,
"e": 6192,
"s": 6185,
"text": " Print"
},
{
"code": null,
"e": 6203,
"s": 6192,
"text": " Add Notes"
}
] |
IntStream average() method in Java | The average() method of the IntStream class in Java returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty. It gets the average of the elements of the stream.
The syntax is as follows
OptionalDouble average()
Here, OptionalDouble is a container object which may or may not contain a double value.
Create an IntStream with some elements
IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);
Now, get the average of the elements of the stream
OptionalDouble res = intStream.average();
The following is an example to implement IntStream average() method in Java. The isPresent() method of the OptionalDouble class returns true if the value is present
Live Demo
import java.util.*;
import java.util.stream.IntStream;
public class Demo {
public static void main(String[] args) {
IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);
OptionalDouble res = intStream.average();
System.out.println("Average of the elements of the stream...");
if (res.isPresent()) {
System.out.println(res.getAsDouble());
} else {
System.out.println("Nothing!");
}
}
}
Average of the elements of the stream...
47.75 | [
{
"code": null,
"e": 1296,
"s": 1062,
"text": "The average() method of the IntStream class in Java returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty. It gets the average of the elements of the stream."
},
{
"code": null,
"e": 1321,
"s": 1296,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 1346,
"s": 1321,
"text": "OptionalDouble average()"
},
{
"code": null,
"e": 1434,
"s": 1346,
"text": "Here, OptionalDouble is a container object which may or may not contain a double value."
},
{
"code": null,
"e": 1473,
"s": 1434,
"text": "Create an IntStream with some elements"
},
{
"code": null,
"e": 1541,
"s": 1473,
"text": "IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);"
},
{
"code": null,
"e": 1592,
"s": 1541,
"text": "Now, get the average of the elements of the stream"
},
{
"code": null,
"e": 1634,
"s": 1592,
"text": "OptionalDouble res = intStream.average();"
},
{
"code": null,
"e": 1799,
"s": 1634,
"text": "The following is an example to implement IntStream average() method in Java. The isPresent() method of the OptionalDouble class returns true if the value is present"
},
{
"code": null,
"e": 1810,
"s": 1799,
"text": " Live Demo"
},
{
"code": null,
"e": 2269,
"s": 1810,
"text": "import java.util.*;\nimport java.util.stream.IntStream;\npublic class Demo {\n public static void main(String[] args) {\n IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);\n OptionalDouble res = intStream.average();\n System.out.println(\"Average of the elements of the stream...\");\n if (res.isPresent()) {\n System.out.println(res.getAsDouble());\n } else {\n System.out.println(\"Nothing!\");\n }\n }\n}"
},
{
"code": null,
"e": 2316,
"s": 2269,
"text": "Average of the elements of the stream...\n47.75"
}
] |
JavaFX - 2D Shapes Polyline | A Polyline is same as a polygon except that a polyline is not closed in the end. Or, continuous line composed of one or more line segments.
In short, we can say a polygon is an open figure formed by coplanar line segments.
n JavaFX, a Polyline is represented by a class named Polygon. This class belongs to the package javafx.scene.shape..
By instantiating this class, you can create polyline node in JavaFX. You need to pass the x, y coordinates of the points by which the polyline should be defined in the form of a double array.
You can pass the double array as a parameter of the constructor of this class as shown below −
Polyline polyline = new Polyline(doubleArray);
Or, by using the getPoints() method as follows −
polyline.getPoints().addAll(new Double[]{List of XY coordinates separated by commas });
To Draw a Polyline in JavaFX, follow the steps given below.
Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows.
public class ClassName extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
}
}
You can create a line in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape. You can instantiate this class as follows.
//Creating an object of the class Polyline
Polyline polyline = new Polyline();
Specify a double array holding the XY coordinates of the points of the required polyline (hexagon in this example) separated by commas. You can do this by using the getPoints() method of the Polyline class as shown in the following code block.
//Adding coordinates to the hexagon
polyline.getPoints().addAll(new Double[]{
200.0, 50.0,
400.0, 50.0,
450.0, 150.0,
400.0, 250.0,
200.0, 250.0,
150.0, 150.0,
});
In the start() method create a group object by instantiating the class named Group, which belongs to the package javafx.scene.
Pass the Polyline (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −
Group root = new Group(polyline);
Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class pass the Group object (root) that was created in the previous step.
In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.
Scene scene = new Scene(group ,600, 300);
You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class as a parameter.
Using the primaryStage object, set the title of the scene as Sample Application as follows.
primaryStage.setTitle("Sample Application");
You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using the following method.
primaryStage.setScene(scene);
Display the contents of the scene using the method named show() of the Stage class as follows.
primaryStage.show();
Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.
public static void main(String args[]){
launch(args);
}
Following is a program which generates a polyline using JavaFX. Save this code in a file with the name PolylineExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.Polyline
public class PolylineExample extends Application {
@Override
public void start(Stage stage) {
//Creating a polyline
Polyline polyline = new Polyline();
//Adding coordinates to the polygon
polyline.getPoints().addAll(new Double[]{
200.0, 50.0,
400.0, 50.0,
450.0, 150.0,
400.0, 250.0,
200.0, 250.0,
150.0, 150.0,
});
//Creating a Group object
Group root = new Group(polyline);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Drawing a Polyline");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac PolylineExample.java
java PolylineExample
On executing, the above program generates a JavaFX window displaying a polyline as shown below.
33 Lectures
7.5 hours
Syed Raza
64 Lectures
12.5 hours
Emenwa Global, Ejike IfeanyiChukwu
20 Lectures
4 hours
Emenwa Global, Ejike IfeanyiChukwu
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2040,
"s": 1900,
"text": "A Polyline is same as a polygon except that a polyline is not closed in the end. Or, continuous line composed of one or more line segments."
},
{
"code": null,
"e": 2123,
"s": 2040,
"text": "In short, we can say a polygon is an open figure formed by coplanar line segments."
},
{
"code": null,
"e": 2240,
"s": 2123,
"text": "n JavaFX, a Polyline is represented by a class named Polygon. This class belongs to the package javafx.scene.shape.."
},
{
"code": null,
"e": 2432,
"s": 2240,
"text": "By instantiating this class, you can create polyline node in JavaFX. You need to pass the x, y coordinates of the points by which the polyline should be defined in the form of a double array."
},
{
"code": null,
"e": 2527,
"s": 2432,
"text": "You can pass the double array as a parameter of the constructor of this class as shown below −"
},
{
"code": null,
"e": 2575,
"s": 2527,
"text": "Polyline polyline = new Polyline(doubleArray);\n"
},
{
"code": null,
"e": 2624,
"s": 2575,
"text": "Or, by using the getPoints() method as follows −"
},
{
"code": null,
"e": 2714,
"s": 2624,
"text": "polyline.getPoints().addAll(new Double[]{List of XY coordinates separated by commas }); \n"
},
{
"code": null,
"e": 2774,
"s": 2714,
"text": "To Draw a Polyline in JavaFX, follow the steps given below."
},
{
"code": null,
"e": 2921,
"s": 2774,
"text": "Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows."
},
{
"code": null,
"e": 3059,
"s": 2921,
"text": "public class ClassName extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception {\n } \n} "
},
{
"code": null,
"e": 3219,
"s": 3059,
"text": "You can create a line in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape. You can instantiate this class as follows."
},
{
"code": null,
"e": 3300,
"s": 3219,
"text": "//Creating an object of the class Polyline \nPolyline polyline = new Polyline();\n"
},
{
"code": null,
"e": 3544,
"s": 3300,
"text": "Specify a double array holding the XY coordinates of the points of the required polyline (hexagon in this example) separated by commas. You can do this by using the getPoints() method of the Polyline class as shown in the following code block."
},
{
"code": null,
"e": 3769,
"s": 3544,
"text": "//Adding coordinates to the hexagon \npolyline.getPoints().addAll(new Double[]{ \n 200.0, 50.0, \n 400.0, 50.0, \n 450.0, 150.0, \n 400.0, 250.0, \n 200.0, 250.0, \n 150.0, 150.0, \n}); "
},
{
"code": null,
"e": 3896,
"s": 3769,
"text": "In the start() method create a group object by instantiating the class named Group, which belongs to the package javafx.scene."
},
{
"code": null,
"e": 4058,
"s": 3896,
"text": "Pass the Polyline (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −"
},
{
"code": null,
"e": 4093,
"s": 4058,
"text": "Group root = new Group(polyline);\n"
},
{
"code": null,
"e": 4272,
"s": 4093,
"text": "Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class pass the Group object (root) that was created in the previous step."
},
{
"code": null,
"e": 4441,
"s": 4272,
"text": "In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows."
},
{
"code": null,
"e": 4484,
"s": 4441,
"text": "Scene scene = new Scene(group ,600, 300);\n"
},
{
"code": null,
"e": 4673,
"s": 4484,
"text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class as a parameter."
},
{
"code": null,
"e": 4765,
"s": 4673,
"text": "Using the primaryStage object, set the title of the scene as Sample Application as follows."
},
{
"code": null,
"e": 4811,
"s": 4765,
"text": "primaryStage.setTitle(\"Sample Application\");\n"
},
{
"code": null,
"e": 4985,
"s": 4811,
"text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using the following method."
},
{
"code": null,
"e": 5016,
"s": 4985,
"text": "primaryStage.setScene(scene);\n"
},
{
"code": null,
"e": 5111,
"s": 5016,
"text": "Display the contents of the scene using the method named show() of the Stage class as follows."
},
{
"code": null,
"e": 5133,
"s": 5111,
"text": "primaryStage.show();\n"
},
{
"code": null,
"e": 5259,
"s": 5133,
"text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows."
},
{
"code": null,
"e": 5327,
"s": 5259,
"text": "public static void main(String args[]){ \n launch(args); \n}"
},
{
"code": null,
"e": 5452,
"s": 5327,
"text": "Following is a program which generates a polyline using JavaFX. Save this code in a file with the name PolylineExample.java."
},
{
"code": null,
"e": 6583,
"s": 5452,
"text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.stage.Stage; \nimport javafx.scene.shape.Polyline\n\npublic class PolylineExample extends Application { \n @Override \n public void start(Stage stage) { \n //Creating a polyline \n Polyline polyline = new Polyline(); \n \n //Adding coordinates to the polygon \n polyline.getPoints().addAll(new Double[]{ \n 200.0, 50.0, \n 400.0, 50.0, \n 450.0, 150.0, \n 400.0, 250.0, \n 200.0, 250.0, \n 150.0, 150.0, \n }); \n \n //Creating a Group object \n Group root = new Group(polyline); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Drawing a Polyline\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}"
},
{
"code": null,
"e": 6677,
"s": 6583,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 6727,
"s": 6677,
"text": "javac PolylineExample.java \njava PolylineExample\n"
},
{
"code": null,
"e": 6823,
"s": 6727,
"text": "On executing, the above program generates a JavaFX window displaying a polyline as shown below."
},
{
"code": null,
"e": 6858,
"s": 6823,
"text": "\n 33 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6869,
"s": 6858,
"text": " Syed Raza"
},
{
"code": null,
"e": 6905,
"s": 6869,
"text": "\n 64 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 6941,
"s": 6905,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 6974,
"s": 6941,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7010,
"s": 6974,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 7017,
"s": 7010,
"text": " Print"
},
{
"code": null,
"e": 7028,
"s": 7017,
"text": " Add Notes"
}
] |
Spring MVC - Xml View Resolver Example | The XmlViewResolver is used to resolve the view names using view beans defined in xml file. The following example shows how to use the XmlViewResolver using Spring Web MVC framework.
<bean class = "org.springframework.web.servlet.view.XmlViewResolver">
<property name = "location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
<bean id = "hello"
class = "org.springframework.web.servlet.view.JstlView">
<property name = "url" value = "/WEB-INF/jsp/hello.jsp" />
</bean>
For example, using the above configuration, if URI −
/hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the view.xml.
/hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the view.xml.
To start with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.XmlViewResolver">
<property name = "location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
</beans>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id = "hello"
class = "org.springframework.web.servlet.view.JstlView">
<property name = "url" value = "/WEB-INF/jsp/hello.jsp" />
</bean>
</beans>
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in Tomcat's webapps folder.
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try to access the URL − http://localhost:8080/HelloWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2974,
"s": 2791,
"text": "The XmlViewResolver is used to resolve the view names using view beans defined in xml file. The following example shows how to use the XmlViewResolver using Spring Web MVC framework."
},
{
"code": null,
"e": 3139,
"s": 2974,
"text": "<bean class = \"org.springframework.web.servlet.view.XmlViewResolver\">\n <property name = \"location\">\n <value>/WEB-INF/views.xml</value>\n </property>\n</bean>"
},
{
"code": null,
"e": 3288,
"s": 3139,
"text": "<bean id = \"hello\"\n class = \"org.springframework.web.servlet.view.JstlView\">\n <property name = \"url\" value = \"/WEB-INF/jsp/hello.jsp\" />\n</bean>"
},
{
"code": null,
"e": 3341,
"s": 3288,
"text": "For example, using the above configuration, if URI −"
},
{
"code": null,
"e": 3461,
"s": 3341,
"text": "/hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the view.xml."
},
{
"code": null,
"e": 3581,
"s": 3461,
"text": "/hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the view.xml."
},
{
"code": null,
"e": 3752,
"s": 3581,
"text": "To start with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework."
},
{
"code": null,
"e": 4259,
"s": 3752,
"text": "package com.tutorialspoint;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.ui.ModelMap;\n\n@Controller\n@RequestMapping(\"/hello\")\npublic class HelloController{\n \n @RequestMapping(method = RequestMethod.GET)\n public String printHello(ModelMap model) {\n model.addAttribute(\"message\", \"Hello Spring MVC Framework!\");\n\n return \"hello\";\n }\n\n}"
},
{
"code": null,
"e": 4973,
"s": 4259,
"text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n\n <context:component-scan base-package = \"com.tutorialspoint\" />\n\n <bean class = \"org.springframework.web.servlet.view.XmlViewResolver\">\n <property name = \"location\">\n <value>/WEB-INF/views.xml</value>\n </property>\n </bean>\n</beans>"
},
{
"code": null,
"e": 5601,
"s": 4973,
"text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n\n <bean id = \"hello\"\n class = \"org.springframework.web.servlet.view.JstlView\">\n <property name = \"url\" value = \"/WEB-INF/jsp/hello.jsp\" />\n </bean>\n</beans>"
},
{
"code": null,
"e": 5772,
"s": 5601,
"text": "<%@ page contentType = \"text/html; charset = UTF-8\" %>\n<html>\n <head>\n <title>Hello World</title>\n </head>\n <body>\n <h2>${message}</h2>\n </body>\n</html>"
},
{
"code": null,
"e": 5982,
"s": 5772,
"text": "Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in Tomcat's webapps folder."
},
{
"code": null,
"e": 6268,
"s": 5982,
"text": "Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try to access the URL − http://localhost:8080/HelloWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen."
},
{
"code": null,
"e": 6275,
"s": 6268,
"text": " Print"
},
{
"code": null,
"e": 6286,
"s": 6275,
"text": " Add Notes"
}
] |
Image Enhancement Techniques using OpenCV and Python | by Ashish Bansal | Towards Data Science | In this blog post, I would like to demonstrate how one can enhance the quality and extract meaningful information from a low resolution /blurred image/low contrast using image processing.
Let's begin the process :
I have a sample image of an LPG Cylinder which is taken from the warehouse running on a conveyor belt. My objective is to find out the Batch no of LPG Cylinder so that I could update how many LPG Cylinders have been tested for quality check.
Step 1: Import the necessary libraries
import cv2import numpy as npimport matplotlib.pyplot as plt
Step 2: Load the image and display the sample image.
img= cv2.imread('cylinder1.png')img1=cv2.imread('cylinder.png')images=np.concatenate(img(img,img1),axis=1)cv2.imshow("Images",images)cv2.waitKey(0)cv2.destroyAllWindows()
As you can see that the contrast of the image is very poor. We could hardly recognize the batch number. This is a common problem in the warehouse where the lightning conditions are inappropriate. Further will discuss Contrast Limited Adaptive Histogram Equalization and try to experiment with different algorithms on the data set.
Step 3: Convert the images into a grayscale image
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)gray_img1=cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
Step 4: Now we find out the histograms of the grayscale image and look for the distribution of intensities.
hist=cv2.calcHist(gray_img,[0],None,[256],[0,256])hist1=cv2.calcHist(gray_img1,[0],None,[256],[0,256])plt.subplot(121)plt.title("Image1")plt.xlabel('bins')plt.ylabel("No of pixels")plt.plot(hist)plt.subplot(122)plt.title("Image2")plt.xlabel('bins')plt.ylabel("No of pixels")plt.plot(hist1)plt.show()
Step 5: Now we will use cv2.equalizeHist() function with the purpose of equalizing the contrast of a given grayscale image. cv2.equalizeHist() function normalises the brightness and also increases the contrast.
gray_img_eqhist=cv2.equalizeHist(gray_img)gray_img1_eqhist=cv2.equalizeHist(gray_img1)hist=cv2.calcHist(gray_img_eqhist,[0],None,[256],[0,256])hist1=cv2.calcHist(gray_img1_eqhist,[0],None,[256],[0,256])plt.subplot(121)plt.plot(hist)plt.subplot(122)plt.plot(hist1)plt.show()
Step 6: Display the Gray Scale Histogram equalized images
eqhist_images=np.concatenate((gray_img_eqhist,gray_img1_eqhist),axis=1)cv2.imshow("Images",eqhist_images)cv2.waitKey(0)cv2.destroyAllWindows()
Let's drill down further with CLAHE
Step 7 :
Contrast Limited Adaptive Histogram Equalization
This algorithm can be applied to improve the contrast of the images. This algorithm works by creating several histograms of the image and uses all of these histograms to redistribute the lightness of the image.CLAHE can be applied to greyscale as well as colour images. There are 2 parameters to tune.
clip limit which sets the threshold for contrast limiting. The default value is 40tileGridsize which sets the number of titles in the row and column. While applying CLAHE image is divided into small blocks called tiles (8*8) in order to perform calculations.
clip limit which sets the threshold for contrast limiting. The default value is 40
tileGridsize which sets the number of titles in the row and column. While applying CLAHE image is divided into small blocks called tiles (8*8) in order to perform calculations.
clahe=cv2.createCLAHE(clipLimit=40)gray_img_clahe=clahe.apply(gray_img_eqhist)gray_img1_clahe=clahe.apply(gray_img1_eqhist)images=np.concatenate((gray_img_clahe,gray_img1_clahe),axis=1)cv2.imshow("Images",images)cv2.waitKey(0)cv2.destroyAllWindows()
Step 8:
Thresholding Techniques
Thresholding is a simple, yet effective method for image partitioning into a foreground and background. The simplest thresholding methods replace each pixel in the source image with a black pixel if the pixel intensity is less than some predefined constant(the threshold value)or a white pixel if the pixel intensity is greater than the threshold value. Different types of Thresholding are:-
cv2.THRESH_BINARY
cv2.THRESH_BINARY_INV
cv2.THRESH_TRUNC
cv2.THRESH_TOZERO
cv2.THRESH_TOZERO_INV
cv2.THRESH_OTSU
cv2.THRESH_TRIANGLE
Try changing the threshold and max_val to obtain different results.
th=80max_val=255ret, o1 = cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_BINARY)cv2.putText(o1,"Thresh_Binary",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)ret, o2 = cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_BINARY_INV)cv2.putText(o2,"Thresh_Binary_inv",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)ret, o3 = cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_TOZERO)cv2.putText(o3,"Thresh_Tozero",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)ret, o4 = cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_TOZERO_INV)cv2.putText(o4,"Thresh_Tozero_inv",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)ret, o5 = cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_TRUNC)cv2.putText(o5,"Thresh_trunc",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)ret ,o6= cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_OTSU)cv2.putText(o6,"Thresh_OSTU",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)final=np.concatenate((o1,o2,o3),axis=1)final1=np.concatenate((o4,o5,o6),axis=1)cv2.imwrite("Image1.jpg",final)cv2.imwrite("Image2.jpg",final1)
Step 9: Adaptive Thresholding
In the previous section, we have applied cv2.threshold() using a global threshold value. As we could see, the obtained results were not very good due to the different illumination conditions in the different areas of the image. In these cases, you can try adaptive thresholding. In OpenCV, the adaptive thresholding is performed by the cv2.adapativeThreshold() function
This function applies an adaptive threshold to the src array (8bit singlechannel image). The maxValue parameter sets the value for the pixels in the dst image for which the condition is satisfied. The adaptiveMethod parameter sets the adaptive thresholding algorithm to use .
cv2.ADAPTIVE_THRESH_MEAN_C: The T(x, y) threshold value is calculated as the mean of the blockSize x blockSize neighbourhood of (x, y) minus the C parameter. cv2.ADAPTIVE_THRESH_GAUSSIAN_C: The T(x, y) threshold value is calculated as the weighted sum of the blockSize x blockSize neighbourhood of (x, y) minus the C parameter.
The blockSize parameter sets the size of the neighbourhood area used to calculate a threshold value for the pixel, and it can take the values 3, 5, 7,... and so forth.
The C parameter is just a constant subtracted from the means or weighted means (depending on the adaptive method set by the adaptiveMethod parameter). Commonly, this value is positive, but it can be zero or negative.
gray_image = cv2.imread('cylinder1.png',0)gray_image1 = cv2.imread('cylinder.png',0)thresh1 = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)thresh2 = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 31, 3)thresh3 = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 13, 5)thresh4 = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 4)thresh11 = cv2.adaptiveThreshold(gray_image1, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)thresh21 = cv2.adaptiveThreshold(gray_image1, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 31, 5)thresh31 = cv2.adaptiveThreshold(gray_image1, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21,5 )thresh41 = cv2.adaptiveThreshold(gray_image1, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 5)final=np.concatenate((thresh1,thresh2,thresh3,thresh4),axis=1)final1=np.concatenate((thresh11,thresh21,thresh31,thresh41),axis=1)cv2.imwrite('rect.jpg',final)cv2.imwrite('rect1.jpg',final1)
Step 10:
OTSU Binarization
Otsu’s binarization algorithm, which is a good approach when dealing with bimodal images. A bimodal image can be characterized by its histogram containing two peaks. Otsu’s algorithm automatically calculates the optimal threshold value that separates both peaks by maximizing the variance between two classes of pixels. Equivalently, the optimal threshold value minimizes the intraclass variance. Otsu’s binarization algorithm is a statistical method, because it relies on statistical information derived from the histogram (for example, mean, variance, or entropy)
gray_image = cv2.imread('cylinder1.png',0)gray_image1 = cv2.imread('cylinder.png',0)ret,thresh1 = cv2.threshold(gray_image,0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)ret,thresh2 = cv2.threshold(gray_image1,0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)cv2.imwrite('rect.jpeg',np.concatenate((thresh1,thresh2),axis=1))
Now we have clearly recognized the batch no from a low contrast image . Hope you find this blog informative and interesting.
Thank you !!
Stay Tuned for my next blog...
You can visit my previous blog on below links
Follow me on my Youtube Channel
https://www.youtube.com/channel/UCSp0BoeXI_EK2W0GzG7TxEw
Connect with me here:
Linkedin: https://www.linkedin.com/in/ashishban...
Github: https://github.com/Ashishb21
Medium: https://medium.com/@ashishb21
Website: http://techplanetai.com/
Email : [email protected] , [email protected] | [
{
"code": null,
"e": 360,
"s": 172,
"text": "In this blog post, I would like to demonstrate how one can enhance the quality and extract meaningful information from a low resolution /blurred image/low contrast using image processing."
},
{
"code": null,
"e": 386,
"s": 360,
"text": "Let's begin the process :"
},
{
"code": null,
"e": 628,
"s": 386,
"text": "I have a sample image of an LPG Cylinder which is taken from the warehouse running on a conveyor belt. My objective is to find out the Batch no of LPG Cylinder so that I could update how many LPG Cylinders have been tested for quality check."
},
{
"code": null,
"e": 667,
"s": 628,
"text": "Step 1: Import the necessary libraries"
},
{
"code": null,
"e": 727,
"s": 667,
"text": "import cv2import numpy as npimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 780,
"s": 727,
"text": "Step 2: Load the image and display the sample image."
},
{
"code": null,
"e": 951,
"s": 780,
"text": "img= cv2.imread('cylinder1.png')img1=cv2.imread('cylinder.png')images=np.concatenate(img(img,img1),axis=1)cv2.imshow(\"Images\",images)cv2.waitKey(0)cv2.destroyAllWindows()"
},
{
"code": null,
"e": 1282,
"s": 951,
"text": "As you can see that the contrast of the image is very poor. We could hardly recognize the batch number. This is a common problem in the warehouse where the lightning conditions are inappropriate. Further will discuss Contrast Limited Adaptive Histogram Equalization and try to experiment with different algorithms on the data set."
},
{
"code": null,
"e": 1332,
"s": 1282,
"text": "Step 3: Convert the images into a grayscale image"
},
{
"code": null,
"e": 1425,
"s": 1332,
"text": "gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)gray_img1=cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)"
},
{
"code": null,
"e": 1533,
"s": 1425,
"text": "Step 4: Now we find out the histograms of the grayscale image and look for the distribution of intensities."
},
{
"code": null,
"e": 1833,
"s": 1533,
"text": "hist=cv2.calcHist(gray_img,[0],None,[256],[0,256])hist1=cv2.calcHist(gray_img1,[0],None,[256],[0,256])plt.subplot(121)plt.title(\"Image1\")plt.xlabel('bins')plt.ylabel(\"No of pixels\")plt.plot(hist)plt.subplot(122)plt.title(\"Image2\")plt.xlabel('bins')plt.ylabel(\"No of pixels\")plt.plot(hist1)plt.show()"
},
{
"code": null,
"e": 2044,
"s": 1833,
"text": "Step 5: Now we will use cv2.equalizeHist() function with the purpose of equalizing the contrast of a given grayscale image. cv2.equalizeHist() function normalises the brightness and also increases the contrast."
},
{
"code": null,
"e": 2318,
"s": 2044,
"text": "gray_img_eqhist=cv2.equalizeHist(gray_img)gray_img1_eqhist=cv2.equalizeHist(gray_img1)hist=cv2.calcHist(gray_img_eqhist,[0],None,[256],[0,256])hist1=cv2.calcHist(gray_img1_eqhist,[0],None,[256],[0,256])plt.subplot(121)plt.plot(hist)plt.subplot(122)plt.plot(hist1)plt.show()"
},
{
"code": null,
"e": 2376,
"s": 2318,
"text": "Step 6: Display the Gray Scale Histogram equalized images"
},
{
"code": null,
"e": 2519,
"s": 2376,
"text": "eqhist_images=np.concatenate((gray_img_eqhist,gray_img1_eqhist),axis=1)cv2.imshow(\"Images\",eqhist_images)cv2.waitKey(0)cv2.destroyAllWindows()"
},
{
"code": null,
"e": 2555,
"s": 2519,
"text": "Let's drill down further with CLAHE"
},
{
"code": null,
"e": 2564,
"s": 2555,
"text": "Step 7 :"
},
{
"code": null,
"e": 2613,
"s": 2564,
"text": "Contrast Limited Adaptive Histogram Equalization"
},
{
"code": null,
"e": 2915,
"s": 2613,
"text": "This algorithm can be applied to improve the contrast of the images. This algorithm works by creating several histograms of the image and uses all of these histograms to redistribute the lightness of the image.CLAHE can be applied to greyscale as well as colour images. There are 2 parameters to tune."
},
{
"code": null,
"e": 3174,
"s": 2915,
"text": "clip limit which sets the threshold for contrast limiting. The default value is 40tileGridsize which sets the number of titles in the row and column. While applying CLAHE image is divided into small blocks called tiles (8*8) in order to perform calculations."
},
{
"code": null,
"e": 3257,
"s": 3174,
"text": "clip limit which sets the threshold for contrast limiting. The default value is 40"
},
{
"code": null,
"e": 3434,
"s": 3257,
"text": "tileGridsize which sets the number of titles in the row and column. While applying CLAHE image is divided into small blocks called tiles (8*8) in order to perform calculations."
},
{
"code": null,
"e": 3684,
"s": 3434,
"text": "clahe=cv2.createCLAHE(clipLimit=40)gray_img_clahe=clahe.apply(gray_img_eqhist)gray_img1_clahe=clahe.apply(gray_img1_eqhist)images=np.concatenate((gray_img_clahe,gray_img1_clahe),axis=1)cv2.imshow(\"Images\",images)cv2.waitKey(0)cv2.destroyAllWindows()"
},
{
"code": null,
"e": 3692,
"s": 3684,
"text": "Step 8:"
},
{
"code": null,
"e": 3716,
"s": 3692,
"text": "Thresholding Techniques"
},
{
"code": null,
"e": 4108,
"s": 3716,
"text": "Thresholding is a simple, yet effective method for image partitioning into a foreground and background. The simplest thresholding methods replace each pixel in the source image with a black pixel if the pixel intensity is less than some predefined constant(the threshold value)or a white pixel if the pixel intensity is greater than the threshold value. Different types of Thresholding are:-"
},
{
"code": null,
"e": 4126,
"s": 4108,
"text": "cv2.THRESH_BINARY"
},
{
"code": null,
"e": 4148,
"s": 4126,
"text": "cv2.THRESH_BINARY_INV"
},
{
"code": null,
"e": 4165,
"s": 4148,
"text": "cv2.THRESH_TRUNC"
},
{
"code": null,
"e": 4183,
"s": 4165,
"text": "cv2.THRESH_TOZERO"
},
{
"code": null,
"e": 4205,
"s": 4183,
"text": "cv2.THRESH_TOZERO_INV"
},
{
"code": null,
"e": 4221,
"s": 4205,
"text": "cv2.THRESH_OTSU"
},
{
"code": null,
"e": 4241,
"s": 4221,
"text": "cv2.THRESH_TRIANGLE"
},
{
"code": null,
"e": 4309,
"s": 4241,
"text": "Try changing the threshold and max_val to obtain different results."
},
{
"code": null,
"e": 5475,
"s": 4309,
"text": "th=80max_val=255ret, o1 = cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_BINARY)cv2.putText(o1,\"Thresh_Binary\",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)ret, o2 = cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_BINARY_INV)cv2.putText(o2,\"Thresh_Binary_inv\",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)ret, o3 = cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_TOZERO)cv2.putText(o3,\"Thresh_Tozero\",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)ret, o4 = cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_TOZERO_INV)cv2.putText(o4,\"Thresh_Tozero_inv\",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)ret, o5 = cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_TRUNC)cv2.putText(o5,\"Thresh_trunc\",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)ret ,o6= cv2.threshold(gray_img_clahe, th, max_val, cv2.THRESH_OTSU)cv2.putText(o6,\"Thresh_OSTU\",(40,100),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),3,cv2.LINE_AA)final=np.concatenate((o1,o2,o3),axis=1)final1=np.concatenate((o4,o5,o6),axis=1)cv2.imwrite(\"Image1.jpg\",final)cv2.imwrite(\"Image2.jpg\",final1)"
},
{
"code": null,
"e": 5505,
"s": 5475,
"text": "Step 9: Adaptive Thresholding"
},
{
"code": null,
"e": 5875,
"s": 5505,
"text": "In the previous section, we have applied cv2.threshold() using a global threshold value. As we could see, the obtained results were not very good due to the different illumination conditions in the different areas of the image. In these cases, you can try adaptive thresholding. In OpenCV, the adaptive thresholding is performed by the cv2.adapativeThreshold() function"
},
{
"code": null,
"e": 6153,
"s": 5875,
"text": "This function applies an adaptive threshold to the src array (8bit singlechannel image). The maxValue parameter sets the value for the pixels in the dst image for which the condition is satisfied. The adaptiveMethod parameter sets the adaptive thresholding algorithm to use ."
},
{
"code": null,
"e": 6481,
"s": 6153,
"text": "cv2.ADAPTIVE_THRESH_MEAN_C: The T(x, y) threshold value is calculated as the mean of the blockSize x blockSize neighbourhood of (x, y) minus the C parameter. cv2.ADAPTIVE_THRESH_GAUSSIAN_C: The T(x, y) threshold value is calculated as the weighted sum of the blockSize x blockSize neighbourhood of (x, y) minus the C parameter."
},
{
"code": null,
"e": 6649,
"s": 6481,
"text": "The blockSize parameter sets the size of the neighbourhood area used to calculate a threshold value for the pixel, and it can take the values 3, 5, 7,... and so forth."
},
{
"code": null,
"e": 6866,
"s": 6649,
"text": "The C parameter is just a constant subtracted from the means or weighted means (depending on the adaptive method set by the adaptiveMethod parameter). Commonly, this value is positive, but it can be zero or negative."
},
{
"code": null,
"e": 7980,
"s": 6866,
"text": "gray_image = cv2.imread('cylinder1.png',0)gray_image1 = cv2.imread('cylinder.png',0)thresh1 = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)thresh2 = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 31, 3)thresh3 = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 13, 5)thresh4 = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 4)thresh11 = cv2.adaptiveThreshold(gray_image1, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)thresh21 = cv2.adaptiveThreshold(gray_image1, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 31, 5)thresh31 = cv2.adaptiveThreshold(gray_image1, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21,5 )thresh41 = cv2.adaptiveThreshold(gray_image1, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 5)final=np.concatenate((thresh1,thresh2,thresh3,thresh4),axis=1)final1=np.concatenate((thresh11,thresh21,thresh31,thresh41),axis=1)cv2.imwrite('rect.jpg',final)cv2.imwrite('rect1.jpg',final1)"
},
{
"code": null,
"e": 7989,
"s": 7980,
"text": "Step 10:"
},
{
"code": null,
"e": 8007,
"s": 7989,
"text": "OTSU Binarization"
},
{
"code": null,
"e": 8574,
"s": 8007,
"text": "Otsu’s binarization algorithm, which is a good approach when dealing with bimodal images. A bimodal image can be characterized by its histogram containing two peaks. Otsu’s algorithm automatically calculates the optimal threshold value that separates both peaks by maximizing the variance between two classes of pixels. Equivalently, the optimal threshold value minimizes the intraclass variance. Otsu’s binarization algorithm is a statistical method, because it relies on statistical information derived from the histogram (for example, mean, variance, or entropy)"
},
{
"code": null,
"e": 8889,
"s": 8574,
"text": "gray_image = cv2.imread('cylinder1.png',0)gray_image1 = cv2.imread('cylinder.png',0)ret,thresh1 = cv2.threshold(gray_image,0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)ret,thresh2 = cv2.threshold(gray_image1,0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)cv2.imwrite('rect.jpeg',np.concatenate((thresh1,thresh2),axis=1))"
},
{
"code": null,
"e": 9014,
"s": 8889,
"text": "Now we have clearly recognized the batch no from a low contrast image . Hope you find this blog informative and interesting."
},
{
"code": null,
"e": 9027,
"s": 9014,
"text": "Thank you !!"
},
{
"code": null,
"e": 9058,
"s": 9027,
"text": "Stay Tuned for my next blog..."
},
{
"code": null,
"e": 9104,
"s": 9058,
"text": "You can visit my previous blog on below links"
},
{
"code": null,
"e": 9136,
"s": 9104,
"text": "Follow me on my Youtube Channel"
},
{
"code": null,
"e": 9193,
"s": 9136,
"text": "https://www.youtube.com/channel/UCSp0BoeXI_EK2W0GzG7TxEw"
},
{
"code": null,
"e": 9215,
"s": 9193,
"text": "Connect with me here:"
},
{
"code": null,
"e": 9266,
"s": 9215,
"text": "Linkedin: https://www.linkedin.com/in/ashishban..."
},
{
"code": null,
"e": 9303,
"s": 9266,
"text": "Github: https://github.com/Ashishb21"
},
{
"code": null,
"e": 9341,
"s": 9303,
"text": "Medium: https://medium.com/@ashishb21"
},
{
"code": null,
"e": 9375,
"s": 9341,
"text": "Website: http://techplanetai.com/"
}
] |
Calculate the Weighted Mean in R Programming - weighted.mean() Function - GeeksforGeeks | 23 Jun, 2020
weighted.mean() function in R Language is used to compute the weighted arithmetic mean of input vector values.
Syntax: weighted.mean(x, weights)
Parameters:x: data input vectorweights: It is weight of input data.
Returns: weighted mean of given values
Example 1:
# Create example datax1 <- c(1, 2, 7, 5, 3, 2, 5, 4) # Create example weights w1 <- c(7, 5, 3, 5, 7, 1, 3, 7) # Apply weighted.mean() functionweighted.mean(x1, w1)
Output:
[1] 3.394737
Example 2:
# Create example datax1 <- c(1, 2, 7, 5, 3, 2, 5, 4) # Create example weights w1 <- c(7, 5, 3, 8, 7, 1, 3, 7) # Create vector with NA# Extend weights vectorx2 <- c(x1, NA) w2 <- c(w1, 3) weighted.mean(x2, w2) # Remove missing valuesweighted.mean(x2, w2, na.rm = TRUE)
Output:
[1] NA
[1] 3.512195
R Math-Function
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?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n23 Jun, 2020"
},
{
"code": null,
"e": 24962,
"s": 24851,
"text": "weighted.mean() function in R Language is used to compute the weighted arithmetic mean of input vector values."
},
{
"code": null,
"e": 24996,
"s": 24962,
"text": "Syntax: weighted.mean(x, weights)"
},
{
"code": null,
"e": 25064,
"s": 24996,
"text": "Parameters:x: data input vectorweights: It is weight of input data."
},
{
"code": null,
"e": 25103,
"s": 25064,
"text": "Returns: weighted mean of given values"
},
{
"code": null,
"e": 25114,
"s": 25103,
"text": "Example 1:"
},
{
"code": "# Create example datax1 <- c(1, 2, 7, 5, 3, 2, 5, 4) # Create example weights w1 <- c(7, 5, 3, 5, 7, 1, 3, 7) # Apply weighted.mean() functionweighted.mean(x1, w1)",
"e": 25319,
"s": 25114,
"text": null
},
{
"code": null,
"e": 25327,
"s": 25319,
"text": "Output:"
},
{
"code": null,
"e": 25341,
"s": 25327,
"text": "[1] 3.394737\n"
},
{
"code": null,
"e": 25352,
"s": 25341,
"text": "Example 2:"
},
{
"code": "# Create example datax1 <- c(1, 2, 7, 5, 3, 2, 5, 4) # Create example weights w1 <- c(7, 5, 3, 8, 7, 1, 3, 7) # Create vector with NA# Extend weights vectorx2 <- c(x1, NA) w2 <- c(w1, 3) weighted.mean(x2, w2) # Remove missing valuesweighted.mean(x2, w2, na.rm = TRUE) ",
"e": 25741,
"s": 25352,
"text": null
},
{
"code": null,
"e": 25749,
"s": 25741,
"text": "Output:"
},
{
"code": null,
"e": 25770,
"s": 25749,
"text": "[1] NA\n[1] 3.512195\n"
},
{
"code": null,
"e": 25786,
"s": 25770,
"text": "R Math-Function"
},
{
"code": null,
"e": 25797,
"s": 25786,
"text": "R Language"
},
{
"code": null,
"e": 25895,
"s": 25797,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25904,
"s": 25895,
"text": "Comments"
},
{
"code": null,
"e": 25917,
"s": 25904,
"text": "Old Comments"
},
{
"code": null,
"e": 25969,
"s": 25917,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26007,
"s": 25969,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26042,
"s": 26007,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26100,
"s": 26042,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 26149,
"s": 26100,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 26192,
"s": 26149,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 26242,
"s": 26192,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 26259,
"s": 26242,
"text": "R - if statement"
},
{
"code": null,
"e": 26296,
"s": 26259,
"text": "How to import an Excel File into R ?"
}
] |
Sorting Lists in Python. How to use sort() and sorted() to sort... | by Luay Matalka | Towards Data Science | In this tutorial, we will look at how to sort lists using sort() and sorted() based on different criteria in python.
There are two ways to sort a list. We can either use the sort() method or the sorted() function. The sort() method is a list method and thus can only be used on lists. The sorted() function works on any iterable.
The sort() method is a list method that modifies the list in-place and returns None. In other words, the sort() method modifies or changes the list it is called on, and does not create a new list.
The sort() method has two optional parameters: the key parameter and reverse parameter. The key parameter takes in a function that takes a single argument and returns a key to use for sorting. By default, the sort() method will sort a list of numbers by their values and a list of strings alphabetically. The reverse parameter accepts a boolean value of True or False. The default value for reverse is False, meaning it sorts in ascending order. To sort in descending order, we would set reverse=True. These parameters will make much more sense as we look at some examples below.
Let’s say that we have a list of numbers and we want to sort it in ascending order.
num_list = [1,-5,3,-9,25,10]num_list.sort()print(num_list)# [-9,-5,1,3,10,25]
So we have a list of numbers, or num_list. We call the sort() method on this list. Notice how we didn’t pass in a value for the key parameter. Thus, it just sorted this list of numbers by their actual values. And since we didn’t set reverse = True, it sorted in ascending order. The sort() method modified our num_list.
What if we want to sort our list based on the absolute values of the numbers? That is when we would need to use the key parameter. The key parameter takes in a function that takes a single argument and returns a key to use for sorting.
num_list = [1,-5,3,-9,25,10]def absolute_value(num): return abs(num)num_list.sort(key = absolute_value)print(num_list) # [1,3,-5,-9,10,25]
We defined a function, absolute_value, that takes in a number and returns its absolute value. We then passed this function in as the argument for the key parameter of the sort() method. Thus, it runs each element or number of num_list through the absolute value function before it makes the comparison. As a result, the absolute values of the numbers are used to sort this list in ascending order (since reverse is set to False by default).
We could have passed in a lambda expression instead for the key parameter as follows:
num_list.sort(key = lambda num: abs(num))
For more information about lambda functions:
towardsdatascience.com
Remember that the sort() method returns None. Thus, if we set the output, or return value, of the sort() method to a new variable, we get None as follows:
new_list = num_list.sort(key = absolute_value)print(new_list)# None
Instead of writing our own absolute_value function as we did above, we could have just passed in the python built-in abs() function for the key parameter as follows:
num_list.sort(key = abs)
towardsdatascience.com
The sorted() function can accept three parameters: the iterable, the key, and reverse. In other words, the sort() method only works on lists, but the sorted() function can work on any iterable, such as lists, tuples, dictionaries, and others. However, unlike the sort() method which returns None and modifies the original list, the sorted() function returns a new list while leaving the original object unchanged.
Let’s sort num_list again using the absolute values but using the sorted() function instead:
num_list = [1,-5,3,-9,25,10]new_list = sorted(num_list, key = abs)print(new_list) # [1,3,-5,-9,10,25]print(num_list)# [1,-5,3,-9,25,10]
We pass in the iterable, num_list, to the sorted() function, along with the built-in abs function to the key parameter. We set the output of the sorted() function to a new variable, new_list. Note how num_list is unaltered since the sorted() function does not modify the iterable it acts on.
Note: No matter what iterable is passed in to the sorted() function, it always returns a list.
Let’s say that we have a list of tuples. Each element of the list is a tuple that contains three elements: the name, age, and salary.
list_of_tuples = [ ('john', 27, 45000), ('jane', 25, 65000), ('beth', 31, 70000)]
We can sort this list alphabetically, by age, or by salary. We can specify which we want to use with the key parameter.
To sort by age, we can use the following code:
sorted_age_list = sorted(list_of_tuples, key = lambda person: person[1])print(sorted_age_list) # [('jane', 25, 65000), ('john', 27, 45000), ('beth', 31, 70000)]
Each element of the list_of_tuples is passed in to the lambda function as the person parameter. The element at index 1 of each tuple is returned. That is the value that is used to sort the list, which is the age.
To sort the name alphabetically, we can do so without passing a key at all since by default the first element of each tuple is what is compared (and remember, by default, strings are sorted alphabetically):
sorted_name_list = sorted(list_of_tuples)print(sorted_name_list) # [('beth', 31, 70000), ('jane', 25, 65000), ('john', 27, 45000)]
However, we can specify that we want to sort by the first element of each tuple as follows:
sorted_name_list = sorted(list_of_tuples, key = lambda person: person[0])print(sorted_name_list) # [('beth', 31, 70000), ('jane', 25, 65000), ('john', 27, 45000)]
Remember that we can assign a lambda expression to a variable (similar to using the def keyword to define a function). Thus, we can organize the lambda expressions based on the criteria they use to sort the list:
name = lambda person: person[0]age = lambda person: person[1]salary = lambda person: person[2]# sort by namesorted(list_of_tuples, key = name)# sort by agesorted(list_of_tuples, key = age)# sort by salarysorted(list_of_tuples, key = salary)
towardsdatascience.com
In this tutorial, we compared the sort() method and sorted() function when sorting a list based on different criteria. We learned how the sort() method modifies the original list, and the sorted() function returns a new list. | [
{
"code": null,
"e": 164,
"s": 47,
"text": "In this tutorial, we will look at how to sort lists using sort() and sorted() based on different criteria in python."
},
{
"code": null,
"e": 377,
"s": 164,
"text": "There are two ways to sort a list. We can either use the sort() method or the sorted() function. The sort() method is a list method and thus can only be used on lists. The sorted() function works on any iterable."
},
{
"code": null,
"e": 574,
"s": 377,
"text": "The sort() method is a list method that modifies the list in-place and returns None. In other words, the sort() method modifies or changes the list it is called on, and does not create a new list."
},
{
"code": null,
"e": 1154,
"s": 574,
"text": "The sort() method has two optional parameters: the key parameter and reverse parameter. The key parameter takes in a function that takes a single argument and returns a key to use for sorting. By default, the sort() method will sort a list of numbers by their values and a list of strings alphabetically. The reverse parameter accepts a boolean value of True or False. The default value for reverse is False, meaning it sorts in ascending order. To sort in descending order, we would set reverse=True. These parameters will make much more sense as we look at some examples below."
},
{
"code": null,
"e": 1238,
"s": 1154,
"text": "Let’s say that we have a list of numbers and we want to sort it in ascending order."
},
{
"code": null,
"e": 1316,
"s": 1238,
"text": "num_list = [1,-5,3,-9,25,10]num_list.sort()print(num_list)# [-9,-5,1,3,10,25]"
},
{
"code": null,
"e": 1636,
"s": 1316,
"text": "So we have a list of numbers, or num_list. We call the sort() method on this list. Notice how we didn’t pass in a value for the key parameter. Thus, it just sorted this list of numbers by their actual values. And since we didn’t set reverse = True, it sorted in ascending order. The sort() method modified our num_list."
},
{
"code": null,
"e": 1872,
"s": 1636,
"text": "What if we want to sort our list based on the absolute values of the numbers? That is when we would need to use the key parameter. The key parameter takes in a function that takes a single argument and returns a key to use for sorting."
},
{
"code": null,
"e": 2014,
"s": 1872,
"text": "num_list = [1,-5,3,-9,25,10]def absolute_value(num): return abs(num)num_list.sort(key = absolute_value)print(num_list) # [1,3,-5,-9,10,25]"
},
{
"code": null,
"e": 2455,
"s": 2014,
"text": "We defined a function, absolute_value, that takes in a number and returns its absolute value. We then passed this function in as the argument for the key parameter of the sort() method. Thus, it runs each element or number of num_list through the absolute value function before it makes the comparison. As a result, the absolute values of the numbers are used to sort this list in ascending order (since reverse is set to False by default)."
},
{
"code": null,
"e": 2541,
"s": 2455,
"text": "We could have passed in a lambda expression instead for the key parameter as follows:"
},
{
"code": null,
"e": 2583,
"s": 2541,
"text": "num_list.sort(key = lambda num: abs(num))"
},
{
"code": null,
"e": 2628,
"s": 2583,
"text": "For more information about lambda functions:"
},
{
"code": null,
"e": 2651,
"s": 2628,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2806,
"s": 2651,
"text": "Remember that the sort() method returns None. Thus, if we set the output, or return value, of the sort() method to a new variable, we get None as follows:"
},
{
"code": null,
"e": 2874,
"s": 2806,
"text": "new_list = num_list.sort(key = absolute_value)print(new_list)# None"
},
{
"code": null,
"e": 3040,
"s": 2874,
"text": "Instead of writing our own absolute_value function as we did above, we could have just passed in the python built-in abs() function for the key parameter as follows:"
},
{
"code": null,
"e": 3065,
"s": 3040,
"text": "num_list.sort(key = abs)"
},
{
"code": null,
"e": 3088,
"s": 3065,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3502,
"s": 3088,
"text": "The sorted() function can accept three parameters: the iterable, the key, and reverse. In other words, the sort() method only works on lists, but the sorted() function can work on any iterable, such as lists, tuples, dictionaries, and others. However, unlike the sort() method which returns None and modifies the original list, the sorted() function returns a new list while leaving the original object unchanged."
},
{
"code": null,
"e": 3595,
"s": 3502,
"text": "Let’s sort num_list again using the absolute values but using the sorted() function instead:"
},
{
"code": null,
"e": 3731,
"s": 3595,
"text": "num_list = [1,-5,3,-9,25,10]new_list = sorted(num_list, key = abs)print(new_list) # [1,3,-5,-9,10,25]print(num_list)# [1,-5,3,-9,25,10]"
},
{
"code": null,
"e": 4023,
"s": 3731,
"text": "We pass in the iterable, num_list, to the sorted() function, along with the built-in abs function to the key parameter. We set the output of the sorted() function to a new variable, new_list. Note how num_list is unaltered since the sorted() function does not modify the iterable it acts on."
},
{
"code": null,
"e": 4118,
"s": 4023,
"text": "Note: No matter what iterable is passed in to the sorted() function, it always returns a list."
},
{
"code": null,
"e": 4252,
"s": 4118,
"text": "Let’s say that we have a list of tuples. Each element of the list is a tuple that contains three elements: the name, age, and salary."
},
{
"code": null,
"e": 4343,
"s": 4252,
"text": "list_of_tuples = [ ('john', 27, 45000), ('jane', 25, 65000), ('beth', 31, 70000)]"
},
{
"code": null,
"e": 4463,
"s": 4343,
"text": "We can sort this list alphabetically, by age, or by salary. We can specify which we want to use with the key parameter."
},
{
"code": null,
"e": 4510,
"s": 4463,
"text": "To sort by age, we can use the following code:"
},
{
"code": null,
"e": 4671,
"s": 4510,
"text": "sorted_age_list = sorted(list_of_tuples, key = lambda person: person[1])print(sorted_age_list) # [('jane', 25, 65000), ('john', 27, 45000), ('beth', 31, 70000)]"
},
{
"code": null,
"e": 4884,
"s": 4671,
"text": "Each element of the list_of_tuples is passed in to the lambda function as the person parameter. The element at index 1 of each tuple is returned. That is the value that is used to sort the list, which is the age."
},
{
"code": null,
"e": 5091,
"s": 4884,
"text": "To sort the name alphabetically, we can do so without passing a key at all since by default the first element of each tuple is what is compared (and remember, by default, strings are sorted alphabetically):"
},
{
"code": null,
"e": 5222,
"s": 5091,
"text": "sorted_name_list = sorted(list_of_tuples)print(sorted_name_list) # [('beth', 31, 70000), ('jane', 25, 65000), ('john', 27, 45000)]"
},
{
"code": null,
"e": 5314,
"s": 5222,
"text": "However, we can specify that we want to sort by the first element of each tuple as follows:"
},
{
"code": null,
"e": 5477,
"s": 5314,
"text": "sorted_name_list = sorted(list_of_tuples, key = lambda person: person[0])print(sorted_name_list) # [('beth', 31, 70000), ('jane', 25, 65000), ('john', 27, 45000)]"
},
{
"code": null,
"e": 5690,
"s": 5477,
"text": "Remember that we can assign a lambda expression to a variable (similar to using the def keyword to define a function). Thus, we can organize the lambda expressions based on the criteria they use to sort the list:"
},
{
"code": null,
"e": 5931,
"s": 5690,
"text": "name = lambda person: person[0]age = lambda person: person[1]salary = lambda person: person[2]# sort by namesorted(list_of_tuples, key = name)# sort by agesorted(list_of_tuples, key = age)# sort by salarysorted(list_of_tuples, key = salary)"
},
{
"code": null,
"e": 5954,
"s": 5931,
"text": "towardsdatascience.com"
}
] |
std::oct , std::dec and std::hex in C++ - GeeksforGeeks | 24 Nov, 2017
This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base
std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in octal base when this flag is set.
std::hex : When basefield is set to hex, integer values inserted into the stream are expressed in hexadecimal base (i.e., radix 16). For input streams, extracted values are also expected to be expressed in hexadecimal base when this flag is set.
The basefield format flag can take decimal values (each with its own manipulator). This is an I/O manipulator. It may be called with an expression such as out << std::oct, std::hex or std ::dec for any out of type std::basic_ostream or with an expressionSyntax :
ios_base& hex (ios_base& str);
str :
Stream object whose basefield format flag is affected.
Return value :
Return the augmented string parsed in the base decimal to base octal
Examples:
Input :
54
Output :
oct - 66
dec - 54
hex - 36
// CPP program to illustrate// std::oct, std::hex, std::dec#include <iostream> // std::cout, std::dec, std::hex, std::oct int main(){ int n = 54; std::cout << std::oct << "oct - " << n << '\n'; std::cout << std::dec << "dec - " << n << '\n'; std::cout << std::hex << "hex - " << n << '\n'; return 0;}
Output:
oct - 66
dec - 54
hex - 36
CPP-Library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Pure Virtual Functions and Abstract Classes in C++ | [
{
"code": null,
"e": 25479,
"s": 25451,
"text": "\n24 Nov, 2017"
},
{
"code": null,
"e": 25626,
"s": 25479,
"text": "This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base"
},
{
"code": null,
"e": 25861,
"s": 25626,
"text": "std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in octal base when this flag is set."
},
{
"code": null,
"e": 26107,
"s": 25861,
"text": "std::hex : When basefield is set to hex, integer values inserted into the stream are expressed in hexadecimal base (i.e., radix 16). For input streams, extracted values are also expected to be expressed in hexadecimal base when this flag is set."
},
{
"code": null,
"e": 26370,
"s": 26107,
"text": "The basefield format flag can take decimal values (each with its own manipulator). This is an I/O manipulator. It may be called with an expression such as out << std::oct, std::hex or std ::dec for any out of type std::basic_ostream or with an expressionSyntax :"
},
{
"code": null,
"e": 26549,
"s": 26370,
"text": "ios_base& hex (ios_base& str);\nstr :\n Stream object whose basefield format flag is affected.\n Return value :\nReturn the augmented string parsed in the base decimal to base octal\n"
},
{
"code": null,
"e": 26559,
"s": 26549,
"text": "Examples:"
},
{
"code": null,
"e": 26608,
"s": 26559,
"text": "Input : \n54\nOutput :\noct - 66\ndec - 54\nhex - 36\n"
},
{
"code": "// CPP program to illustrate// std::oct, std::hex, std::dec#include <iostream> // std::cout, std::dec, std::hex, std::oct int main(){ int n = 54; std::cout << std::oct << \"oct - \" << n << '\\n'; std::cout << std::dec << \"dec - \" << n << '\\n'; std::cout << std::hex << \"hex - \" << n << '\\n'; return 0;}",
"e": 26925,
"s": 26608,
"text": null
},
{
"code": null,
"e": 26933,
"s": 26925,
"text": "Output:"
},
{
"code": null,
"e": 26961,
"s": 26933,
"text": "oct - 66\ndec - 54\nhex - 36\n"
},
{
"code": null,
"e": 26973,
"s": 26961,
"text": "CPP-Library"
},
{
"code": null,
"e": 26977,
"s": 26973,
"text": "STL"
},
{
"code": null,
"e": 26981,
"s": 26977,
"text": "C++"
},
{
"code": null,
"e": 26985,
"s": 26981,
"text": "STL"
},
{
"code": null,
"e": 26989,
"s": 26985,
"text": "CPP"
},
{
"code": null,
"e": 27087,
"s": 26989,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27115,
"s": 27087,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27135,
"s": 27115,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27168,
"s": 27135,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27192,
"s": 27168,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27217,
"s": 27192,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27241,
"s": 27217,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 27285,
"s": 27241,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27338,
"s": 27285,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 27374,
"s": 27338,
"text": "Convert string to char array in C++"
}
] |
Check whether a given number is even or odd in PL/SQL - GeeksforGeeks | 02 Jul, 2018
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Examples:
Input: 2
Output: even
Input: 5
Output: odd
The approach is to divide the given number by 2 and if the remainder is 0 then the given number is even else odd.
Below is the required implementation:
DECLARE -- Declare variable n, s, r, len -- and m of datatype number n NUMBER := 1634; r NUMBER;BEGIN -- Calculating modulo r := MOD(n, 2); IF r = 0 THEN dbms_output.Put_line('Even'); ELSE dbms_output.Put_line('Odd'); END IF;END;--End program
Output:
Even
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 25649,
"s": 25621,
"text": "\n02 Jul, 2018"
},
{
"code": null,
"e": 25893,
"s": 25649,
"text": "Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations."
},
{
"code": null,
"e": 25903,
"s": 25893,
"text": "Examples:"
},
{
"code": null,
"e": 25949,
"s": 25903,
"text": "Input: 2 \nOutput: even\n\nInput: 5\nOutput: odd\n"
},
{
"code": null,
"e": 26063,
"s": 25949,
"text": "The approach is to divide the given number by 2 and if the remainder is 0 then the given number is even else odd."
},
{
"code": null,
"e": 26101,
"s": 26063,
"text": "Below is the required implementation:"
},
{
"code": "DECLARE -- Declare variable n, s, r, len -- and m of datatype number n NUMBER := 1634; r NUMBER;BEGIN -- Calculating modulo r := MOD(n, 2); IF r = 0 THEN dbms_output.Put_line('Even'); ELSE dbms_output.Put_line('Odd'); END IF;END;--End program ",
"e": 26384,
"s": 26101,
"text": null
},
{
"code": null,
"e": 26392,
"s": 26384,
"text": "Output:"
},
{
"code": null,
"e": 26398,
"s": 26392,
"text": "Even\n"
},
{
"code": null,
"e": 26409,
"s": 26398,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 26413,
"s": 26409,
"text": "SQL"
},
{
"code": null,
"e": 26417,
"s": 26413,
"text": "SQL"
},
{
"code": null,
"e": 26515,
"s": 26417,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26581,
"s": 26515,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26638,
"s": 26581,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 26670,
"s": 26638,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26685,
"s": 26670,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 26763,
"s": 26685,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26799,
"s": 26763,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 26816,
"s": 26799,
"text": "SQL using Python"
},
{
"code": null,
"e": 26882,
"s": 26816,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 26944,
"s": 26882,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
Subsets and Splits