title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Python | Safe access nested dictionary keys | 14 May, 2020
Sometimes, while working with Python we can have a problem in which we need to get the 2nd degree key of dictionary i.e the nested key. This type of problem is common in case of web development, especially with the advent of NoSQL databases. Let’s discuss certain ways to safely get the nested available key in dictionary.
Method #1 : Using nested get()
This method is used to solve this particular problem, we just take advantage of the functionality of get() to check and assign in absence of value to achieve this particular task. Just returns non-error None if any key is not present.
# Python3 code to demonstrate working of# Safe access nested dictionary key# Using nested get() # initializing dictionarytest_dict = {'Gfg' : {'is' : 'best'}} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # using nested get()# Safe access nested dictionary keyres = test_dict.get('Gfg', {}).get('is') # printing resultprint("The nested safely accessed value is : " + str(res))
The original dictionary is : {'Gfg': {'is': 'best'}}
The nested safely accessed value is : best
Method #2 : Using reduce() + lambda
The combination of above functions can be used to perform this particular task. It just checks using lambda function for the available keys. The plus of this method is that more than 1 key can be queried at once i.e more nested level keys, but the negative is that it does only work with Python2.
# Python code to demonstrate working of# Safe access nested dictionary key# Using reduce() + lambda # initializing dictionarytest_dict = {'Gfg' : {'is' : 'best'}} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # using reduce() + lambda# Safe access nested dictionary keykeys = ['Gfg', 'is']res = reduce(lambda val, key: val.get(key) if val else None, keys, test_dict) # printing resultprint("The nested safely accessed value is : " + str(res))
The original dictionary is : {'Gfg': {'is': 'best'}}
The nested safely accessed value is : best
Python dictionary-programs
Python-nested-dictionary
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 May, 2020"
},
{
"code": null,
"e": 351,
"s": 28,
"text": "Sometimes, while working with Python we can have a problem in which we need to get the 2nd degree key of dictionary i.e the nested key. This type of problem is common in case of web development, especially with the advent of NoSQL databases. Let’s discuss certain ways to safely get the nested available key in dictionary."
},
{
"code": null,
"e": 382,
"s": 351,
"text": "Method #1 : Using nested get()"
},
{
"code": null,
"e": 617,
"s": 382,
"text": "This method is used to solve this particular problem, we just take advantage of the functionality of get() to check and assign in absence of value to achieve this particular task. Just returns non-error None if any key is not present."
},
{
"code": "# Python3 code to demonstrate working of# Safe access nested dictionary key# Using nested get() # initializing dictionarytest_dict = {'Gfg' : {'is' : 'best'}} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # using nested get()# Safe access nested dictionary keyres = test_dict.get('Gfg', {}).get('is') # printing resultprint(\"The nested safely accessed value is : \" + str(res))",
"e": 1039,
"s": 617,
"text": null
},
{
"code": null,
"e": 1137,
"s": 1039,
"text": "The original dictionary is : {'Gfg': {'is': 'best'}}\nThe nested safely accessed value is : best\n"
},
{
"code": null,
"e": 1175,
"s": 1139,
"text": "Method #2 : Using reduce() + lambda"
},
{
"code": null,
"e": 1472,
"s": 1175,
"text": "The combination of above functions can be used to perform this particular task. It just checks using lambda function for the available keys. The plus of this method is that more than 1 key can be queried at once i.e more nested level keys, but the negative is that it does only work with Python2."
},
{
"code": "# Python code to demonstrate working of# Safe access nested dictionary key# Using reduce() + lambda # initializing dictionarytest_dict = {'Gfg' : {'is' : 'best'}} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # using reduce() + lambda# Safe access nested dictionary keykeys = ['Gfg', 'is']res = reduce(lambda val, key: val.get(key) if val else None, keys, test_dict) # printing resultprint(\"The nested safely accessed value is : \" + str(res))",
"e": 1960,
"s": 1472,
"text": null
},
{
"code": null,
"e": 2058,
"s": 1960,
"text": "The original dictionary is : {'Gfg': {'is': 'best'}}\nThe nested safely accessed value is : best\n"
},
{
"code": null,
"e": 2085,
"s": 2058,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2110,
"s": 2085,
"text": "Python-nested-dictionary"
},
{
"code": null,
"e": 2117,
"s": 2110,
"text": "Python"
},
{
"code": null,
"e": 2133,
"s": 2117,
"text": "Python Programs"
},
{
"code": null,
"e": 2231,
"s": 2133,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2263,
"s": 2231,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2290,
"s": 2263,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2321,
"s": 2290,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2342,
"s": 2321,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2398,
"s": 2342,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2420,
"s": 2398,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2459,
"s": 2420,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2497,
"s": 2459,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2546,
"s": 2497,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Calling a non-member function inside a class in C++ - GeeksforGeeks | 11 Oct, 2021
Member Function: It is a function that can be declared as members of a class. It is usually declared inside the class definition and works on data members of the same class. It can have access to private, public, and protected data members of the same class. This function is declared as shown below:
C++
// Given Classclass memberdemo {private: { public: { void check(); } // Member Function trial::void check(); }}
Non-member Function: The function which is declared outside the class is known as the non-member function of that class. Below is the difference between the two:
The member function can appear outside of the class body (for instance, in the implementation file). But, this approach is followed, the member function must be qualified by the name of its class. This is to identify that that function is a member of a particular class. But a non-member function always appears outside of a class.
Another difference between member functions and non-member functions is how they are called (or invoked) in the main routine.
Program 1:
C++
// C++ to illustrate the above concepts#include <iostream>using namespace std; class A { int a; public: // Member function void memberfn(int x) { a = x; cout << "Member function inside" << " class declared\n"; } // Member function but definition // outside the class void memberfn2();}; // Member function declared with// scope resolution operatorvoid A::memberfn2(){ cout << "Member function but declared " << " outside the class\n";} // Non-member functionvoid nonmemberfn(){ cout << "Non-member function\n";} // Driver Codeint main(){ // Object of class A A obj; // Calling Member Function obj.memberfn(5); obj.memberfn2(); // Calling Non-Member Function nonmemberfn(); return 0;}
Member function inside class declared
Member function but declared outside the class
Non-member function
Explanation: From the above program, there are three types of cases:
A member function is declared and defined in the class and called using the object of the class.
A member function is declared in the class but defined outside the class and is called using the object of the class.
A non-member function that is declared outside the class but called a normal function inside the main function.
Now, the question here arises whether it is possible to call a non-member function inside a member function in a program or not. The answer is YES. Below is the program to illustrate how to call a non-member function inside a member function:
Program 2:
C++
// C++ program to illustrate the// above approach#include <bits/stdc++.h>using namespace std; // Function to find the factorial// of the number Nint fact(int n){ if (n == 0 || n == 1) return 1; else return n * fact(n - 1);} // Class Examplesclass example { int x; public: void set(int x) { this->x = x; } // Calling the non-member function // inside the function of class int find() { return fact(x); }}; // Driver Codeint main(){ // Object of the class example obj; obj.set(5); // Calling the member function cout << obj.find(); return 0;}
120
Explanation: A non-member function can be called inside a member function but the condition is that the non-member function must be declared before the member function. In the above example, the same approach is followed and it becomes possible to invoke a non-member function thus the answer is the factorial of 5 i.e. 120.
C++-Class and Object
CPP-Functions
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Polymorphism in C++
Sorting a vector in C++
Header files in C/C++ and its uses
C++ Program for QuickSort
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
CSV file management using C++ | [
{
"code": null,
"e": 24044,
"s": 24016,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 24345,
"s": 24044,
"text": "Member Function: It is a function that can be declared as members of a class. It is usually declared inside the class definition and works on data members of the same class. It can have access to private, public, and protected data members of the same class. This function is declared as shown below:"
},
{
"code": null,
"e": 24349,
"s": 24345,
"text": "C++"
},
{
"code": "// Given Classclass memberdemo {private: { public: { void check(); } // Member Function trial::void check(); }}",
"e": 24511,
"s": 24349,
"text": null
},
{
"code": null,
"e": 24673,
"s": 24511,
"text": "Non-member Function: The function which is declared outside the class is known as the non-member function of that class. Below is the difference between the two:"
},
{
"code": null,
"e": 25005,
"s": 24673,
"text": "The member function can appear outside of the class body (for instance, in the implementation file). But, this approach is followed, the member function must be qualified by the name of its class. This is to identify that that function is a member of a particular class. But a non-member function always appears outside of a class."
},
{
"code": null,
"e": 25131,
"s": 25005,
"text": "Another difference between member functions and non-member functions is how they are called (or invoked) in the main routine."
},
{
"code": null,
"e": 25142,
"s": 25131,
"text": "Program 1:"
},
{
"code": null,
"e": 25146,
"s": 25142,
"text": "C++"
},
{
"code": "// C++ to illustrate the above concepts#include <iostream>using namespace std; class A { int a; public: // Member function void memberfn(int x) { a = x; cout << \"Member function inside\" << \" class declared\\n\"; } // Member function but definition // outside the class void memberfn2();}; // Member function declared with// scope resolution operatorvoid A::memberfn2(){ cout << \"Member function but declared \" << \" outside the class\\n\";} // Non-member functionvoid nonmemberfn(){ cout << \"Non-member function\\n\";} // Driver Codeint main(){ // Object of class A A obj; // Calling Member Function obj.memberfn(5); obj.memberfn2(); // Calling Non-Member Function nonmemberfn(); return 0;}",
"e": 25931,
"s": 25146,
"text": null
},
{
"code": null,
"e": 26038,
"s": 25931,
"text": "Member function inside class declared\nMember function but declared outside the class\nNon-member function\n"
},
{
"code": null,
"e": 26107,
"s": 26038,
"text": "Explanation: From the above program, there are three types of cases:"
},
{
"code": null,
"e": 26204,
"s": 26107,
"text": "A member function is declared and defined in the class and called using the object of the class."
},
{
"code": null,
"e": 26322,
"s": 26204,
"text": "A member function is declared in the class but defined outside the class and is called using the object of the class."
},
{
"code": null,
"e": 26434,
"s": 26322,
"text": "A non-member function that is declared outside the class but called a normal function inside the main function."
},
{
"code": null,
"e": 26677,
"s": 26434,
"text": "Now, the question here arises whether it is possible to call a non-member function inside a member function in a program or not. The answer is YES. Below is the program to illustrate how to call a non-member function inside a member function:"
},
{
"code": null,
"e": 26688,
"s": 26677,
"text": "Program 2:"
},
{
"code": null,
"e": 26692,
"s": 26688,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// above approach#include <bits/stdc++.h>using namespace std; // Function to find the factorial// of the number Nint fact(int n){ if (n == 0 || n == 1) return 1; else return n * fact(n - 1);} // Class Examplesclass example { int x; public: void set(int x) { this->x = x; } // Calling the non-member function // inside the function of class int find() { return fact(x); }}; // Driver Codeint main(){ // Object of the class example obj; obj.set(5); // Calling the member function cout << obj.find(); return 0;}",
"e": 27298,
"s": 26692,
"text": null
},
{
"code": null,
"e": 27303,
"s": 27298,
"text": "120\n"
},
{
"code": null,
"e": 27628,
"s": 27303,
"text": "Explanation: A non-member function can be called inside a member function but the condition is that the non-member function must be declared before the member function. In the above example, the same approach is followed and it becomes possible to invoke a non-member function thus the answer is the factorial of 5 i.e. 120."
},
{
"code": null,
"e": 27649,
"s": 27628,
"text": "C++-Class and Object"
},
{
"code": null,
"e": 27663,
"s": 27649,
"text": "CPP-Functions"
},
{
"code": null,
"e": 27667,
"s": 27663,
"text": "C++"
},
{
"code": null,
"e": 27680,
"s": 27667,
"text": "C++ Programs"
},
{
"code": null,
"e": 27684,
"s": 27680,
"text": "CPP"
},
{
"code": null,
"e": 27782,
"s": 27684,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27791,
"s": 27782,
"text": "Comments"
},
{
"code": null,
"e": 27804,
"s": 27791,
"text": "Old Comments"
},
{
"code": null,
"e": 27825,
"s": 27804,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 27853,
"s": 27825,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27886,
"s": 27853,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27906,
"s": 27886,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27930,
"s": 27906,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27965,
"s": 27930,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 27991,
"s": 27965,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 28035,
"s": 27991,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 28094,
"s": 28035,
"text": "How to return multiple values from a function in C or C++?"
}
] |
SQL query to check SAP HANA system version | Other option to check the version of SAP HANA database-
Select * from "SYS"."M_DATABASE";
Go to SQL editor and run the above command.
Go to Result tab and you can see the version of your SAP HANA system. | [
{
"code": null,
"e": 1118,
"s": 1062,
"text": "Other option to check the version of SAP HANA database-"
},
{
"code": null,
"e": 1152,
"s": 1118,
"text": "Select * from \"SYS\".\"M_DATABASE\";"
},
{
"code": null,
"e": 1196,
"s": 1152,
"text": "Go to SQL editor and run the above command."
},
{
"code": null,
"e": 1266,
"s": 1196,
"text": "Go to Result tab and you can see the version of your SAP HANA system."
}
] |
What is fopen() and open() in Linux? | The key difference between the fopen() and the open() function in the Linux operating system is that the open() function is a low-level call, where the fopen() when called simply calls the open() function in the background and it returns a Filepointer directly.
The call to the open() function includes invoking several other functions and the behaviour of the entire process is mentioned below as a reference to understand the open() function better.
Consider the code shown below −
int sys_open(const char *filename, int flags, int mode) {
char *tmp = getname(filename);
int fd = get_unused_fd();
struct file *f = filp_open(tmp, flags, mode);
fd_install(fd, f);
putname(tmp);
return fd;
}
The above code can also be found inside the fs/open.c file on your linux machine.
Now, as we can see there are many functions that gets called from this function, like the first of them is the function named getname() in which we pass the filename as an argument and the code of the getname() function looks something like this −
#define __getname() kmem_cache_alloc(names_cachep, SLAB_KERNEL)
#define putname(name) kmem_cache_free(names_cachep, (void *)(name))
char *getname(const char *filename) {
char *tmp = __getname(); /* allocate some memory */
strncpy_from_user(tmp, filename, PATH_MAX + 1);
return tmp;
}
The above code can be found inside the fs/namei.c file and its main use is to copy the file name from the user space and pass it to the kernel space. Then after the getname() function we have the get_unused_fd() function which returns us an unused file descriptor, which is nothing but an integer index into a growable list of currently opened files. The code of the get_unused_fd() function looks something like this −
int get_unused_fd(void) {
struct files_struct *files = current->files;
int fd = find_next_zero_bit(files->open_fds, files->max_fdset, files->next_fd);
FD_SET(fd, files->open_fds); /* in use now */
files->next_fd = fd + 1;
return fd;
}
Now we have the filp_open() function that has the following implementation −
struct file *filp_open(const char *filename, int flags, int mode) {
struct nameidata nd;
open_namei(filename, flags, mode, &nd);
return dentry_open(nd.dentry, nd.mnt, flags);
}
The above function plays two key roles, first, it uses the filesystem to look up the inode which corresponds to the filename of path that was passed in. Next, if creates a struct file with all the essential information about the inode and then returns the file.
Now, the next function in the call stack is the fd_install() function which can be found in the include/linux/file.h file. It is used to store the information returned by the function filp_open(). The code for the fd_install() function is shown below −
void fd_install(unsigned int fd, struct file *file) {
struct files_struct *files = current->files;
files->fd[fd] = file;
}
Then we have the store() function that stores the struct that was returned from the filp_open() function and then installs that struct into the process’s list of open files.
The next step is to free the allocated block of kernel-controlled memory. Finally, it returns the file descriptor, which can then be passed to other C functions like close(), write(), etc. | [
{
"code": null,
"e": 1324,
"s": 1062,
"text": "The key difference between the fopen() and the open() function in the Linux operating system is that the open() function is a low-level call, where the fopen() when called simply calls the open() function in the background and it returns a Filepointer directly."
},
{
"code": null,
"e": 1514,
"s": 1324,
"text": "The call to the open() function includes invoking several other functions and the behaviour of the entire process is mentioned below as a reference to understand the open() function better."
},
{
"code": null,
"e": 1546,
"s": 1514,
"text": "Consider the code shown below −"
},
{
"code": null,
"e": 1771,
"s": 1546,
"text": "int sys_open(const char *filename, int flags, int mode) {\n char *tmp = getname(filename);\n int fd = get_unused_fd();\n struct file *f = filp_open(tmp, flags, mode);\n fd_install(fd, f);\n putname(tmp);\n return fd;\n}"
},
{
"code": null,
"e": 1853,
"s": 1771,
"text": "The above code can also be found inside the fs/open.c file on your linux machine."
},
{
"code": null,
"e": 2101,
"s": 1853,
"text": "Now, as we can see there are many functions that gets called from this function, like the first of them is the function named getname() in which we pass the filename as an argument and the code of the getname() function looks something like this −"
},
{
"code": null,
"e": 2395,
"s": 2101,
"text": "#define __getname() kmem_cache_alloc(names_cachep, SLAB_KERNEL)\n#define putname(name) kmem_cache_free(names_cachep, (void *)(name))\n\nchar *getname(const char *filename) {\n char *tmp = __getname(); /* allocate some memory */\n strncpy_from_user(tmp, filename, PATH_MAX + 1);\n return tmp;\n}"
},
{
"code": null,
"e": 2815,
"s": 2395,
"text": "The above code can be found inside the fs/namei.c file and its main use is to copy the file name from the user space and pass it to the kernel space. Then after the getname() function we have the get_unused_fd() function which returns us an unused file descriptor, which is nothing but an integer index into a growable list of currently opened files. The code of the get_unused_fd() function looks something like this −"
},
{
"code": null,
"e": 3065,
"s": 2815,
"text": "int get_unused_fd(void) {\n struct files_struct *files = current->files;\n int fd = find_next_zero_bit(files->open_fds, files->max_fdset, files->next_fd);\n FD_SET(fd, files->open_fds); /* in use now */\n files->next_fd = fd + 1;\n return fd;\n}"
},
{
"code": null,
"e": 3142,
"s": 3065,
"text": "Now we have the filp_open() function that has the following implementation −"
},
{
"code": null,
"e": 3328,
"s": 3142,
"text": "struct file *filp_open(const char *filename, int flags, int mode) {\n struct nameidata nd;\n open_namei(filename, flags, mode, &nd);\n return dentry_open(nd.dentry, nd.mnt, flags);\n}"
},
{
"code": null,
"e": 3590,
"s": 3328,
"text": "The above function plays two key roles, first, it uses the filesystem to look up the inode which corresponds to the filename of path that was passed in. Next, if creates a struct file with all the essential information about the inode and then returns the file."
},
{
"code": null,
"e": 3843,
"s": 3590,
"text": "Now, the next function in the call stack is the fd_install() function which can be found in the include/linux/file.h file. It is used to store the information returned by the function filp_open(). The code for the fd_install() function is shown below −"
},
{
"code": null,
"e": 3972,
"s": 3843,
"text": "void fd_install(unsigned int fd, struct file *file) {\n struct files_struct *files = current->files;\n files->fd[fd] = file;\n}"
},
{
"code": null,
"e": 4146,
"s": 3972,
"text": "Then we have the store() function that stores the struct that was returned from the filp_open() function and then installs that struct into the process’s list of open files."
},
{
"code": null,
"e": 4335,
"s": 4146,
"text": "The next step is to free the allocated block of kernel-controlled memory. Finally, it returns the file descriptor, which can then be passed to other C functions like close(), write(), etc."
}
] |
Financial Question Answering with Jina and BERT — Part 2 | Towards Data Science | Part 1 — Learn how to use the neural search framework, Jina, to build a Financial Question Answering (QA) search application with the FiQA dataset, PyTorch, and Hugging Face transformers.
Part 2 — Learn how evaluate and improve your Financial QA search results with Jina
In the previous tutorial we learned how to build a production-ready Financial Question Answering search application with Jina and BERT. In order to improve our application and retrieve meaningful answers, evaluating the search results is essential for tuning the parameters of the system. For example, it can help us decide which pre-trained model to choose for the encoder, the maximum sequence length, and the type of Ranker we want to use.
Recall that Jina provides us the building blocks that enable us to create a search application. Therefore, instead of implementing the evaluation metrics by ourselves, we can use Jina’s Evaluator, a type of Executor.
So far, we have already seen some of the Executors: Encoder, Indexer, and Ranker. Each of these Executors is responsible for the logic of their corresponding functionalities. As the name suggests the Evaluator will contain the logic of our evaluation metrics. We have also learned how to design an Index and Query Flow, which are pipelines for indexing and searching the answer passages.
To evaluate the search results, we will need to create an evaluation pipeline, the Evaluation Flow, for us to use in our Financial QA search application.
In this tutorial we will learn how to add the evaluation pipeline in our Financial QA system by designing a Flow to evaluate the search results with Precision and Mean Reciprocal Rank (MRR).
We will evaluate the search results before and after reranking with FinBERT-QA. Here is overview of the Evaluation Flow:
If you are coming from the previous tutorial, you will need to make some small changes to app.py, FinBertQARanker/__init__.py , and FinBertQARanker/tests/test_finbertqaranker.py. Joan Fontanals Martinez and I have added some helper functions and batching in the Ranker to help speed up the process.
Instead of pointing out the changes, I have made a new template to simplify the workflow and also show those of you who are already familiar with Jina how to implement the evaluation mode.
Clone project template:
git clone https://github.com/yuanbit/jina-financial-qa-evaluator-template.git
Make sure the requirements are installed and you have downloaded the data and model.
You can find the final code of this tutorial here.
Let us walk through the Evaluation Flow step-by-step.
Our working directory will be jina-financial-qa-evaluator-template/. In the dataset/ folder you should have the following files:
For this tutorial we will need:
sample_test_set.pickle: a sample test set with 50 questions and ground truth answers
qid_to_text.pickle: a dictionary to map the question ids to question text
If you want to use the complete test set from FinBERT-QA, test_set.pickle, which has 333 questions and ground truth answers, you can simply change the path.
The test set that we will be working with in this tutorial is a pickle file, sample_test_set.pickle. It is a list of lists in the form [[question id, [ground truth answer ids]]], where each element contains the question id and a list of ground truth answer ids. Here is a slice from the test set:
[[14, [398960]], [458, [263485, 218858]], [502, [498631, 549435, 181678]], [712, [212810, 580479, 527433, 28356, 97582, 129965, 273307]],...]
Next, similar to defining our Document for indexing the answer passages, we will create two Documents containing the data of the questions and the ground truth answers.
Recall in our Index Flow, when we defined our data in index_generator function we included the answer passage ids (docids) in the Document. Therefore, after indexing, these answer ids are stored in the index and they are important because they are part of the search results during query time. Thus, we only need to define the Ground truth Document with the ground truth answer ids for each query and compare these answer ids with the answer ids of the matches.
Let’s add a Python generator under the load_pickle function to define our test set for evaluation. For each Document, we will map the corresponding question and from the test set to the actual text.
Similar to the Query Flow, we will pass our two Documents into the Encoder Pod from pods/encode.yml. The Driver will pass the question text to the Encoder to transform it into an embedding and the same Driver will add the embedding to the Query Document. The only difference this time is that we are passing two Documents into the Encoder Pod and the Ground truth Document is immutable and stays unchanged through the Flow.
In flows/ lets create a file to configure our Evaluation Flow called evaluate.yml and add the Encoder Pod as follows:
The output of the Encoder will contain the Query Document with the embeddings of the questions and the Ground truth Document stays unchanged as shown in Figure 4.
Next, the Indexer Pod from pods/doc.yml will search for the answers with the most similar embeddings and the Driver of the Indexer will add a list of top-k answer matches to the Query Document. The Ground truth Document remains unchanged.
Let’s add the doc_indexer to flows/evaluate.yml as follows:
The output of the Indexer will contain the Query Document with the answer matches and their corresponding information and the Ground truth Document.
Since I mentioned in the beginning that we will evaluate the search results both before and after reranking, you might think that now we will add the following sequence:
Evaluator for the match resultsRankerEvaluator for the reranked results
Evaluator for the match results
Ranker
Evaluator for the reranked results
However, since evaluation serves to improve the results of our search system, it is not an actual component of the final application. You can think of it as a tool that provide us information on which part of the system needs improvement.
Having the goal to allow us to inspect any part of the pipeline and enabling us to evaluate at arbitrary places in the Flow, we can use Jina Flow API’s inspect feature to attach the Evaluator Pods to the main pipeline so that the evaluations will not block messages to the other components of the pipeline.
For example, without the inspect mode, we would have a sequential design mentioned above. With the inspect mode, after retrieving the answer matches from the Indexer, the Documents will be sent to an Evaluator and the Ranker in parallel. Consequently the Ranker won’t have to wait for the initial answer matches to be evaluated before it can output the reranked answer matches!
The benefit of this design in our QA system is that the Evaluator can perform evaluations without blocking the progress of the Flow because it is independent from the other components of the pipeline. You can think of the Evaluator as a side task running in parallel with the Flow. As a result, we can evaluate with minimal impact to the performance of the Flow.
You can refer to this article to learn more about the design of the evaluation mode and the inspect feature.
Let’s take a closer look at the evaluation part of the Flow:
In Figure 6, we can see that the evaluate_matching Pod, which is the Evaluator responsible for evaluating the answer matches is working in parallel with the Ranker and theevaluate_ranking Pod, the Evaluator responsible for evaluating the reranked answer matches.
gather_inspect is used to accumulate the evaluation results for each query. Furthermore, the auxiliary Pods shown before and after the Ranker are constructions that allow the the Evaluation Flow to have the connections of the Pods in the same way as if the Query Flow would not have the Evaluators, so that the performance of retrieving and reranking the answer matches would only be affected minimally.
Previously, we used an Encoder and Indexer from Jina Hub, an open-registry for hosting Executors via container images. We can again take advantage of Jina Hub and simply use the Precision and the Reciprocal Rank Pods that are already available!
Now let’s take a look at the Matching and Ranking Evaluators:
After the Indexer Pod outputs the Query Document with the matches, one workflow will involve the Matching Evaluator, which is responsible for computing the the precision and reciprocal rank of the answer matches (without reranking).
The Driver of the Matching Evaluator Pod interprets both the Query and Ground truth Document and passes the answer match ids and the desired ground truth answer ids per query to the Matching Evaluator, which computes the precision and reciprocal rank values as shown in Figure 7.
Now, let’s create our Matching Evaluator. In the folder pods/, and create a file called evaluate_matching.yml. We will add the following to the file:
PrecisionEvaluator and ReciprocalRankEvaluator are the Evaluators for precision and reciprocal rank from Jina Hub. We specify eval_at: 10 to evaluate the top-10 answer matches. We also indicate the name for each component, which we will use later in the Evaluation Flow.
You might be wondering from the last tutorial why we don’t we need to specify the Driver in pods/encode.yml and pods/doc.yml since the Peas in the Pods require both components. This is because the Drivers for these two Pods are are commonly used and are already included by default. However, since we want to use two Evaluators of our choice (Precision and Reciprocal Rank) from Jina Hub, we need to specify the Driver for each Evaluator, namely RankEvaluateDriver.
Next, let us add this Pod to the Evaluation Flow. In flows/evaluate.yml add evaluate_matching as follows:
Here we indicate method: inspect because we are using the inspect feature from the Flow API to inspect the performance of our application in the middle of the Flow.
The Driver of the Matching Evaluator will add the evaluation results of the answer matches to the Query Document for each query as shown in Figure 8.
Well done! We have successfully implemented the first Evaluator. Let us look at how to evaluate the reranked search results next.
Another workflow after the Indexer Pod involves the Ranking Evaluator, which is responsible for computing the precision and reciprocal rank of the reranked answer matches using FinBERT-QA. The construction of the Ranking Evaluator Pod is similar to the Matching Evaluator Pod, the only difference is that we are passing the reordered match ids to the Ranking Evaluator as show in Figure 9.
Let’s create our Ranking Evaluator. In the folder pods/, create a file called evaluate_ranking.yml. We will add the following to the file:
Notice that this is almost identical to evaluate_matching.yml except for the naming conventions.
In the previous tutorial we learned how to build a custom Ranker. We need to build the docker image for this Ranker in order to use it as a Pod in our Flow.
Note: you will need to rebuild this image even if you have built it in the previous tutorial because batching has been added.
Make sure you have the Jina Hub extension installed:
pip install “jina[hub]”
In the working directory type:
jina hub build FinBertQARanker/ — pull — test-uses — timeout-ready 60000
You should get a message indicating you have successfully built the image with its tag name. Depending the current Jina release. Make sure to change the tag name accordingly when using it as a Pod.
Next, let us add the Ranker and Evaluate Ranking Pod to the Evaluation Flow in flows/evaluate.yml:
The Indexer Pod will pass the Query Document with the answer matches and the Ground truth ids to the Ranker containing FinBERT-QA. Then the Ranker Pod will output the Query Document with the reordered answer match ids and the Ground truth Document, which will both be passed to the Ranking Evaluator. The output shown in Figure 10, would be the same as the Matching Evaluator, with the difference of the evaluation values computed from the reordered answer matches.
Great job! We have just finished the design of the Evaluation Flow. Next let us see how to use it in our search application.
Similar to the index function, in app.py let’s add an evaluate function after evaluate_generator, which will load the Evaluation Flow from flows/evaluate.yml and pass the input Query and Ground truth Documents from evaluate_generator to the Flow. We set our top-k=10 to evaluate precision@10 and reciprocal-rank@10.
Since we want to compute the average precision@10 and mean-reciprocal-rank@10 across all queries in the test set, we will write a function, print_average_evaluations , to compute the average of the evaluation values
The final evaluation values will be stored in the Query Document, like the print_resp function, we can write a function to print out the evaluation response by looping through the evaluations in our Query Document, d.evaluations and printing out the values for each Evaluator:
Hooray! 🎉🎉🎉 We have just implemented an evaluation mode in our Financial QA search engine! We can now run:
python app.py evaluate
As this tutorial is for educational purposes, we only indexed a portion of the answer passages and used a small sample test set. Therefore, the results cannot be compared to the results from FinBERT-QA. Feel free to index the entire answer collection and evaluate on the complete test set and share your results!
You will see the individual questions being evaluated and printed. Here is an example for question id: 1281.
Evaluations for QID:1282 Matching-Precision@10: 0.10000000149011612 Matching-ReciprocalRank@10: 1.0 Ranking-Precision@10: 0.10000000149011612 Ranking-ReciprocalRank@10: 0.125
At the end you will see the average evaluation results:
Average Evaluation Results Matching-Precision@10: 0.056000000834465026 Matching-ReciprocalRank@10: 0.225 Ranking-Precision@10: 0.056000000834465026 Ranking-ReciprocalRank@10: 0.118555556088686
In this tutorial, I introduced the evaluation feature in Jina and demonstrated how we can design an Evaluation Flow for our Financial QA search application. We learned how to use the inspect mode to create our Evaluator Pods and that it benefits our application by minimizing the impact of evaluation to the performance of the pipeline.
Be sure to check out Jina’s Github page to learn more and get started on building your own deep-learning-powered search applications!
Slack channel — a communication platform for developers to discuss Jina
Community newsletter — subscribe to the latest update, release and event news of Jina
LinkedIn — get to know Jina AI as a company and find job opportunities
Twitter — follow and interact with Jina AI using hashtag #JinaSearch
Company — know more about Jina AI and their commitment to open-source!
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. | [
{
"code": null,
"e": 360,
"s": 172,
"text": "Part 1 — Learn how to use the neural search framework, Jina, to build a Financial Question Answering (QA) search application with the FiQA dataset, PyTorch, and Hugging Face transformers."
},
{
"code": null,
"e": 443,
"s": 360,
"text": "Part 2 — Learn how evaluate and improve your Financial QA search results with Jina"
},
{
"code": null,
"e": 886,
"s": 443,
"text": "In the previous tutorial we learned how to build a production-ready Financial Question Answering search application with Jina and BERT. In order to improve our application and retrieve meaningful answers, evaluating the search results is essential for tuning the parameters of the system. For example, it can help us decide which pre-trained model to choose for the encoder, the maximum sequence length, and the type of Ranker we want to use."
},
{
"code": null,
"e": 1103,
"s": 886,
"text": "Recall that Jina provides us the building blocks that enable us to create a search application. Therefore, instead of implementing the evaluation metrics by ourselves, we can use Jina’s Evaluator, a type of Executor."
},
{
"code": null,
"e": 1491,
"s": 1103,
"text": "So far, we have already seen some of the Executors: Encoder, Indexer, and Ranker. Each of these Executors is responsible for the logic of their corresponding functionalities. As the name suggests the Evaluator will contain the logic of our evaluation metrics. We have also learned how to design an Index and Query Flow, which are pipelines for indexing and searching the answer passages."
},
{
"code": null,
"e": 1645,
"s": 1491,
"text": "To evaluate the search results, we will need to create an evaluation pipeline, the Evaluation Flow, for us to use in our Financial QA search application."
},
{
"code": null,
"e": 1836,
"s": 1645,
"text": "In this tutorial we will learn how to add the evaluation pipeline in our Financial QA system by designing a Flow to evaluate the search results with Precision and Mean Reciprocal Rank (MRR)."
},
{
"code": null,
"e": 1957,
"s": 1836,
"text": "We will evaluate the search results before and after reranking with FinBERT-QA. Here is overview of the Evaluation Flow:"
},
{
"code": null,
"e": 2256,
"s": 1957,
"text": "If you are coming from the previous tutorial, you will need to make some small changes to app.py, FinBertQARanker/__init__.py , and FinBertQARanker/tests/test_finbertqaranker.py. Joan Fontanals Martinez and I have added some helper functions and batching in the Ranker to help speed up the process."
},
{
"code": null,
"e": 2445,
"s": 2256,
"text": "Instead of pointing out the changes, I have made a new template to simplify the workflow and also show those of you who are already familiar with Jina how to implement the evaluation mode."
},
{
"code": null,
"e": 2469,
"s": 2445,
"text": "Clone project template:"
},
{
"code": null,
"e": 2547,
"s": 2469,
"text": "git clone https://github.com/yuanbit/jina-financial-qa-evaluator-template.git"
},
{
"code": null,
"e": 2632,
"s": 2547,
"text": "Make sure the requirements are installed and you have downloaded the data and model."
},
{
"code": null,
"e": 2683,
"s": 2632,
"text": "You can find the final code of this tutorial here."
},
{
"code": null,
"e": 2737,
"s": 2683,
"text": "Let us walk through the Evaluation Flow step-by-step."
},
{
"code": null,
"e": 2866,
"s": 2737,
"text": "Our working directory will be jina-financial-qa-evaluator-template/. In the dataset/ folder you should have the following files:"
},
{
"code": null,
"e": 2898,
"s": 2866,
"text": "For this tutorial we will need:"
},
{
"code": null,
"e": 2983,
"s": 2898,
"text": "sample_test_set.pickle: a sample test set with 50 questions and ground truth answers"
},
{
"code": null,
"e": 3057,
"s": 2983,
"text": "qid_to_text.pickle: a dictionary to map the question ids to question text"
},
{
"code": null,
"e": 3214,
"s": 3057,
"text": "If you want to use the complete test set from FinBERT-QA, test_set.pickle, which has 333 questions and ground truth answers, you can simply change the path."
},
{
"code": null,
"e": 3511,
"s": 3214,
"text": "The test set that we will be working with in this tutorial is a pickle file, sample_test_set.pickle. It is a list of lists in the form [[question id, [ground truth answer ids]]], where each element contains the question id and a list of ground truth answer ids. Here is a slice from the test set:"
},
{
"code": null,
"e": 3653,
"s": 3511,
"text": "[[14, [398960]], [458, [263485, 218858]], [502, [498631, 549435, 181678]], [712, [212810, 580479, 527433, 28356, 97582, 129965, 273307]],...]"
},
{
"code": null,
"e": 3822,
"s": 3653,
"text": "Next, similar to defining our Document for indexing the answer passages, we will create two Documents containing the data of the questions and the ground truth answers."
},
{
"code": null,
"e": 4284,
"s": 3822,
"text": "Recall in our Index Flow, when we defined our data in index_generator function we included the answer passage ids (docids) in the Document. Therefore, after indexing, these answer ids are stored in the index and they are important because they are part of the search results during query time. Thus, we only need to define the Ground truth Document with the ground truth answer ids for each query and compare these answer ids with the answer ids of the matches."
},
{
"code": null,
"e": 4483,
"s": 4284,
"text": "Let’s add a Python generator under the load_pickle function to define our test set for evaluation. For each Document, we will map the corresponding question and from the test set to the actual text."
},
{
"code": null,
"e": 4907,
"s": 4483,
"text": "Similar to the Query Flow, we will pass our two Documents into the Encoder Pod from pods/encode.yml. The Driver will pass the question text to the Encoder to transform it into an embedding and the same Driver will add the embedding to the Query Document. The only difference this time is that we are passing two Documents into the Encoder Pod and the Ground truth Document is immutable and stays unchanged through the Flow."
},
{
"code": null,
"e": 5025,
"s": 4907,
"text": "In flows/ lets create a file to configure our Evaluation Flow called evaluate.yml and add the Encoder Pod as follows:"
},
{
"code": null,
"e": 5188,
"s": 5025,
"text": "The output of the Encoder will contain the Query Document with the embeddings of the questions and the Ground truth Document stays unchanged as shown in Figure 4."
},
{
"code": null,
"e": 5427,
"s": 5188,
"text": "Next, the Indexer Pod from pods/doc.yml will search for the answers with the most similar embeddings and the Driver of the Indexer will add a list of top-k answer matches to the Query Document. The Ground truth Document remains unchanged."
},
{
"code": null,
"e": 5487,
"s": 5427,
"text": "Let’s add the doc_indexer to flows/evaluate.yml as follows:"
},
{
"code": null,
"e": 5636,
"s": 5487,
"text": "The output of the Indexer will contain the Query Document with the answer matches and their corresponding information and the Ground truth Document."
},
{
"code": null,
"e": 5806,
"s": 5636,
"text": "Since I mentioned in the beginning that we will evaluate the search results both before and after reranking, you might think that now we will add the following sequence:"
},
{
"code": null,
"e": 5878,
"s": 5806,
"text": "Evaluator for the match resultsRankerEvaluator for the reranked results"
},
{
"code": null,
"e": 5910,
"s": 5878,
"text": "Evaluator for the match results"
},
{
"code": null,
"e": 5917,
"s": 5910,
"text": "Ranker"
},
{
"code": null,
"e": 5952,
"s": 5917,
"text": "Evaluator for the reranked results"
},
{
"code": null,
"e": 6191,
"s": 5952,
"text": "However, since evaluation serves to improve the results of our search system, it is not an actual component of the final application. You can think of it as a tool that provide us information on which part of the system needs improvement."
},
{
"code": null,
"e": 6498,
"s": 6191,
"text": "Having the goal to allow us to inspect any part of the pipeline and enabling us to evaluate at arbitrary places in the Flow, we can use Jina Flow API’s inspect feature to attach the Evaluator Pods to the main pipeline so that the evaluations will not block messages to the other components of the pipeline."
},
{
"code": null,
"e": 6876,
"s": 6498,
"text": "For example, without the inspect mode, we would have a sequential design mentioned above. With the inspect mode, after retrieving the answer matches from the Indexer, the Documents will be sent to an Evaluator and the Ranker in parallel. Consequently the Ranker won’t have to wait for the initial answer matches to be evaluated before it can output the reranked answer matches!"
},
{
"code": null,
"e": 7239,
"s": 6876,
"text": "The benefit of this design in our QA system is that the Evaluator can perform evaluations without blocking the progress of the Flow because it is independent from the other components of the pipeline. You can think of the Evaluator as a side task running in parallel with the Flow. As a result, we can evaluate with minimal impact to the performance of the Flow."
},
{
"code": null,
"e": 7348,
"s": 7239,
"text": "You can refer to this article to learn more about the design of the evaluation mode and the inspect feature."
},
{
"code": null,
"e": 7409,
"s": 7348,
"text": "Let’s take a closer look at the evaluation part of the Flow:"
},
{
"code": null,
"e": 7672,
"s": 7409,
"text": "In Figure 6, we can see that the evaluate_matching Pod, which is the Evaluator responsible for evaluating the answer matches is working in parallel with the Ranker and theevaluate_ranking Pod, the Evaluator responsible for evaluating the reranked answer matches."
},
{
"code": null,
"e": 8076,
"s": 7672,
"text": "gather_inspect is used to accumulate the evaluation results for each query. Furthermore, the auxiliary Pods shown before and after the Ranker are constructions that allow the the Evaluation Flow to have the connections of the Pods in the same way as if the Query Flow would not have the Evaluators, so that the performance of retrieving and reranking the answer matches would only be affected minimally."
},
{
"code": null,
"e": 8321,
"s": 8076,
"text": "Previously, we used an Encoder and Indexer from Jina Hub, an open-registry for hosting Executors via container images. We can again take advantage of Jina Hub and simply use the Precision and the Reciprocal Rank Pods that are already available!"
},
{
"code": null,
"e": 8383,
"s": 8321,
"text": "Now let’s take a look at the Matching and Ranking Evaluators:"
},
{
"code": null,
"e": 8616,
"s": 8383,
"text": "After the Indexer Pod outputs the Query Document with the matches, one workflow will involve the Matching Evaluator, which is responsible for computing the the precision and reciprocal rank of the answer matches (without reranking)."
},
{
"code": null,
"e": 8896,
"s": 8616,
"text": "The Driver of the Matching Evaluator Pod interprets both the Query and Ground truth Document and passes the answer match ids and the desired ground truth answer ids per query to the Matching Evaluator, which computes the precision and reciprocal rank values as shown in Figure 7."
},
{
"code": null,
"e": 9046,
"s": 8896,
"text": "Now, let’s create our Matching Evaluator. In the folder pods/, and create a file called evaluate_matching.yml. We will add the following to the file:"
},
{
"code": null,
"e": 9317,
"s": 9046,
"text": "PrecisionEvaluator and ReciprocalRankEvaluator are the Evaluators for precision and reciprocal rank from Jina Hub. We specify eval_at: 10 to evaluate the top-10 answer matches. We also indicate the name for each component, which we will use later in the Evaluation Flow."
},
{
"code": null,
"e": 9783,
"s": 9317,
"text": "You might be wondering from the last tutorial why we don’t we need to specify the Driver in pods/encode.yml and pods/doc.yml since the Peas in the Pods require both components. This is because the Drivers for these two Pods are are commonly used and are already included by default. However, since we want to use two Evaluators of our choice (Precision and Reciprocal Rank) from Jina Hub, we need to specify the Driver for each Evaluator, namely RankEvaluateDriver."
},
{
"code": null,
"e": 9889,
"s": 9783,
"text": "Next, let us add this Pod to the Evaluation Flow. In flows/evaluate.yml add evaluate_matching as follows:"
},
{
"code": null,
"e": 10054,
"s": 9889,
"text": "Here we indicate method: inspect because we are using the inspect feature from the Flow API to inspect the performance of our application in the middle of the Flow."
},
{
"code": null,
"e": 10204,
"s": 10054,
"text": "The Driver of the Matching Evaluator will add the evaluation results of the answer matches to the Query Document for each query as shown in Figure 8."
},
{
"code": null,
"e": 10334,
"s": 10204,
"text": "Well done! We have successfully implemented the first Evaluator. Let us look at how to evaluate the reranked search results next."
},
{
"code": null,
"e": 10724,
"s": 10334,
"text": "Another workflow after the Indexer Pod involves the Ranking Evaluator, which is responsible for computing the precision and reciprocal rank of the reranked answer matches using FinBERT-QA. The construction of the Ranking Evaluator Pod is similar to the Matching Evaluator Pod, the only difference is that we are passing the reordered match ids to the Ranking Evaluator as show in Figure 9."
},
{
"code": null,
"e": 10863,
"s": 10724,
"text": "Let’s create our Ranking Evaluator. In the folder pods/, create a file called evaluate_ranking.yml. We will add the following to the file:"
},
{
"code": null,
"e": 10960,
"s": 10863,
"text": "Notice that this is almost identical to evaluate_matching.yml except for the naming conventions."
},
{
"code": null,
"e": 11117,
"s": 10960,
"text": "In the previous tutorial we learned how to build a custom Ranker. We need to build the docker image for this Ranker in order to use it as a Pod in our Flow."
},
{
"code": null,
"e": 11243,
"s": 11117,
"text": "Note: you will need to rebuild this image even if you have built it in the previous tutorial because batching has been added."
},
{
"code": null,
"e": 11296,
"s": 11243,
"text": "Make sure you have the Jina Hub extension installed:"
},
{
"code": null,
"e": 11320,
"s": 11296,
"text": "pip install “jina[hub]”"
},
{
"code": null,
"e": 11351,
"s": 11320,
"text": "In the working directory type:"
},
{
"code": null,
"e": 11424,
"s": 11351,
"text": "jina hub build FinBertQARanker/ — pull — test-uses — timeout-ready 60000"
},
{
"code": null,
"e": 11622,
"s": 11424,
"text": "You should get a message indicating you have successfully built the image with its tag name. Depending the current Jina release. Make sure to change the tag name accordingly when using it as a Pod."
},
{
"code": null,
"e": 11721,
"s": 11622,
"text": "Next, let us add the Ranker and Evaluate Ranking Pod to the Evaluation Flow in flows/evaluate.yml:"
},
{
"code": null,
"e": 12187,
"s": 11721,
"text": "The Indexer Pod will pass the Query Document with the answer matches and the Ground truth ids to the Ranker containing FinBERT-QA. Then the Ranker Pod will output the Query Document with the reordered answer match ids and the Ground truth Document, which will both be passed to the Ranking Evaluator. The output shown in Figure 10, would be the same as the Matching Evaluator, with the difference of the evaluation values computed from the reordered answer matches."
},
{
"code": null,
"e": 12312,
"s": 12187,
"text": "Great job! We have just finished the design of the Evaluation Flow. Next let us see how to use it in our search application."
},
{
"code": null,
"e": 12628,
"s": 12312,
"text": "Similar to the index function, in app.py let’s add an evaluate function after evaluate_generator, which will load the Evaluation Flow from flows/evaluate.yml and pass the input Query and Ground truth Documents from evaluate_generator to the Flow. We set our top-k=10 to evaluate precision@10 and reciprocal-rank@10."
},
{
"code": null,
"e": 12844,
"s": 12628,
"text": "Since we want to compute the average precision@10 and mean-reciprocal-rank@10 across all queries in the test set, we will write a function, print_average_evaluations , to compute the average of the evaluation values"
},
{
"code": null,
"e": 13121,
"s": 12844,
"text": "The final evaluation values will be stored in the Query Document, like the print_resp function, we can write a function to print out the evaluation response by looping through the evaluations in our Query Document, d.evaluations and printing out the values for each Evaluator:"
},
{
"code": null,
"e": 13228,
"s": 13121,
"text": "Hooray! 🎉🎉🎉 We have just implemented an evaluation mode in our Financial QA search engine! We can now run:"
},
{
"code": null,
"e": 13251,
"s": 13228,
"text": "python app.py evaluate"
},
{
"code": null,
"e": 13564,
"s": 13251,
"text": "As this tutorial is for educational purposes, we only indexed a portion of the answer passages and used a small sample test set. Therefore, the results cannot be compared to the results from FinBERT-QA. Feel free to index the entire answer collection and evaluate on the complete test set and share your results!"
},
{
"code": null,
"e": 13673,
"s": 13564,
"text": "You will see the individual questions being evaluated and printed. Here is an example for question id: 1281."
},
{
"code": null,
"e": 13864,
"s": 13673,
"text": "Evaluations for QID:1282 Matching-Precision@10: 0.10000000149011612 Matching-ReciprocalRank@10: 1.0 Ranking-Precision@10: 0.10000000149011612 Ranking-ReciprocalRank@10: 0.125"
},
{
"code": null,
"e": 13920,
"s": 13864,
"text": "At the end you will see the average evaluation results:"
},
{
"code": null,
"e": 14129,
"s": 13920,
"text": "Average Evaluation Results Matching-Precision@10: 0.056000000834465026 Matching-ReciprocalRank@10: 0.225 Ranking-Precision@10: 0.056000000834465026 Ranking-ReciprocalRank@10: 0.118555556088686"
},
{
"code": null,
"e": 14466,
"s": 14129,
"text": "In this tutorial, I introduced the evaluation feature in Jina and demonstrated how we can design an Evaluation Flow for our Financial QA search application. We learned how to use the inspect mode to create our Evaluator Pods and that it benefits our application by minimizing the impact of evaluation to the performance of the pipeline."
},
{
"code": null,
"e": 14600,
"s": 14466,
"text": "Be sure to check out Jina’s Github page to learn more and get started on building your own deep-learning-powered search applications!"
},
{
"code": null,
"e": 14672,
"s": 14600,
"text": "Slack channel — a communication platform for developers to discuss Jina"
},
{
"code": null,
"e": 14758,
"s": 14672,
"text": "Community newsletter — subscribe to the latest update, release and event news of Jina"
},
{
"code": null,
"e": 14829,
"s": 14758,
"text": "LinkedIn — get to know Jina AI as a company and find job opportunities"
},
{
"code": null,
"e": 14898,
"s": 14829,
"text": "Twitter — follow and interact with Jina AI using hashtag #JinaSearch"
},
{
"code": null,
"e": 14969,
"s": 14898,
"text": "Company — know more about Jina AI and their commitment to open-source!"
}
] |
Python - Check if a file or directory exists - GeeksforGeeks | 06 May, 2021
Sometimes the need to check whether a directory or file exists or not becomes important because maybe you want to prevent overwriting to the already existing file, or maybe you want to make sure that the file is available or not before loading it. There are various ways to check that a file or directory already exists or not. They are –
Using os.path.exists()
Using os.path.isfile()
Using os.path.isdir()
Using pathlib.Path.exists()
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is a submodule of OS module in Python used for common path name manipulation.Note: To know more about the OS module click here.os.path.exists() method in Python is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not.
Syntax: os.path.exists(path)Parameter: path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.Return Type: This method returns a Boolean value of class bool. This method returns True if path exists otherwise returns False.
Example:
Python3
# Python program to explain os.path.exists() method # importing os module import os # Specify pathpath = '/usr/local/bin/' # Check whether the specified# path exists or notisExist = os.path.exists(path)print(isExist) # Specify pathpath = '/home/User/Desktop/file.txt' # Check whether the specified# path exists or notisExist = os.path.exists(path)print(isExist)
Output:
True
False
os.path.isfile() method in Python is used to check whether the specified path is an existing regular file or not.
Syntax: os.path.isfile(path)Parameter: path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.Return Type: This method returns a Boolean value of class bool. This method returns True if specified path is an existing regular file, otherwise returns False.
Example:
Python3
# Python program to explain os.path.isfile() method # importing os module import os # Pathpath = 'C:/Users/gfg/Desktop/file.txt' # Check whether the # specified path is # an existing fileisFile = os.path.isfile(path)print(isFile) # Pathpath = '/home/User/Desktop/' # Check whether the # specified path is # an existing fileisFile = os.path.isfile(path)print(isFile)
Output:
True
False
os.path.isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows a symbolic link, which means if the specified path is a symbolic link pointing to a directory then the method will return True.
Syntax: os.path.isdir(path)Parameter: path: A path-like object representing a file system path.Return Type: This method returns a Boolean value of class bool. This method returns True if specified path is an existing directory, otherwise returns False.
Example:
Python3
# Python program to explain os.path.isdir() method # importing os.path module import os.path # Pathpath = '/home/User/Documents/file.txt' # Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir) # Pathpath = '/home/User/Documents/' # Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir)
Output:
False
True
Example: If the specified path is a symbolic link.
Python3
# Python program to explain os.path.isdir() method # importing os.path module import os.path # Create a directory# (in current working directory)dirname = "GeeksForGeeks"os.mkdir(dirname) # Create a symbolic link# pointing to above directorysymlink_path = "/home/User/Desktop/gfg"os.symlink(dirname, symlink_path) path = dirname # Now, Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir) path = symlink_path # Check whether the # specified path (which is a# symbolic link ) is an# existing directory or notisdir = os.path.isdir(path)print(isdir)
Output:
True
True
Pathlib module in Python provides various classes representing file system paths with semantics appropriate for different operating systems. This module comes under Python’s standard utility modules. Path classes in Pathlib module are divided into pure paths and concrete paths. Pure paths provide only computational operations but do not provides I/O operations, while concrete paths inherit from pure paths provides computational as well as I/O operations.Note: To know more about pathlib module click here.pathlib.Path.exists() method is used to check whether the given path points to an existing file or directory or not.
Syntax: pathlib.Path.exists(path)Parameter: path: A path-like object representing a file system path.Return Type: This method returns a Boolean value of class bool. This method returns True if path exists otherwise returns False.
Example:
Python3
# Import Path classfrom pathlib import Path # Pathpath = '/home/gfg/Desktop' # Instantiate the Path classobj = Path(path) # Check if path points to # an existing file or directory print(obj.exists())
Output:
True
aman chourasiya
Python file-handling-programs
Python OS-path-module
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24188,
"s": 24160,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 24529,
"s": 24188,
"text": "Sometimes the need to check whether a directory or file exists or not becomes important because maybe you want to prevent overwriting to the already existing file, or maybe you want to make sure that the file is available or not before loading it. There are various ways to check that a file or directory already exists or not. They are – "
},
{
"code": null,
"e": 24553,
"s": 24529,
"text": "Using os.path.exists() "
},
{
"code": null,
"e": 24577,
"s": 24553,
"text": "Using os.path.isfile() "
},
{
"code": null,
"e": 24600,
"s": 24577,
"text": "Using os.path.isdir() "
},
{
"code": null,
"e": 24630,
"s": 24600,
"text": "Using pathlib.Path.exists() "
},
{
"code": null,
"e": 25190,
"s": 24632,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is a submodule of OS module in Python used for common path name manipulation.Note: To know more about the OS module click here.os.path.exists() method in Python is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not. "
},
{
"code": null,
"e": 25492,
"s": 25190,
"text": "Syntax: os.path.exists(path)Parameter: path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.Return Type: This method returns a Boolean value of class bool. This method returns True if path exists otherwise returns False. "
},
{
"code": null,
"e": 25502,
"s": 25492,
"text": "Example: "
},
{
"code": null,
"e": 25510,
"s": 25502,
"text": "Python3"
},
{
"code": "# Python program to explain os.path.exists() method # importing os module import os # Specify pathpath = '/usr/local/bin/' # Check whether the specified# path exists or notisExist = os.path.exists(path)print(isExist) # Specify pathpath = '/home/User/Desktop/file.txt' # Check whether the specified# path exists or notisExist = os.path.exists(path)print(isExist)",
"e": 25888,
"s": 25510,
"text": null
},
{
"code": null,
"e": 25897,
"s": 25888,
"text": "Output: "
},
{
"code": null,
"e": 25908,
"s": 25897,
"text": "True\nFalse"
},
{
"code": null,
"e": 26025,
"s": 25910,
"text": "os.path.isfile() method in Python is used to check whether the specified path is an existing regular file or not. "
},
{
"code": null,
"e": 26359,
"s": 26025,
"text": "Syntax: os.path.isfile(path)Parameter: path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.Return Type: This method returns a Boolean value of class bool. This method returns True if specified path is an existing regular file, otherwise returns False. "
},
{
"code": null,
"e": 26369,
"s": 26359,
"text": "Example: "
},
{
"code": null,
"e": 26377,
"s": 26369,
"text": "Python3"
},
{
"code": "# Python program to explain os.path.isfile() method # importing os module import os # Pathpath = 'C:/Users/gfg/Desktop/file.txt' # Check whether the # specified path is # an existing fileisFile = os.path.isfile(path)print(isFile) # Pathpath = '/home/User/Desktop/' # Check whether the # specified path is # an existing fileisFile = os.path.isfile(path)print(isFile)",
"e": 26743,
"s": 26377,
"text": null
},
{
"code": null,
"e": 26753,
"s": 26743,
"text": "Output: "
},
{
"code": null,
"e": 26764,
"s": 26753,
"text": "True\nFalse"
},
{
"code": null,
"e": 27025,
"s": 26766,
"text": "os.path.isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows a symbolic link, which means if the specified path is a symbolic link pointing to a directory then the method will return True. "
},
{
"code": null,
"e": 27280,
"s": 27025,
"text": "Syntax: os.path.isdir(path)Parameter: path: A path-like object representing a file system path.Return Type: This method returns a Boolean value of class bool. This method returns True if specified path is an existing directory, otherwise returns False. "
},
{
"code": null,
"e": 27291,
"s": 27280,
"text": "Example: "
},
{
"code": null,
"e": 27299,
"s": 27291,
"text": "Python3"
},
{
"code": "# Python program to explain os.path.isdir() method # importing os.path module import os.path # Pathpath = '/home/User/Documents/file.txt' # Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir) # Pathpath = '/home/User/Documents/' # Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir)",
"e": 27708,
"s": 27299,
"text": null
},
{
"code": null,
"e": 27718,
"s": 27708,
"text": "Output: "
},
{
"code": null,
"e": 27729,
"s": 27718,
"text": "False\nTrue"
},
{
"code": null,
"e": 27781,
"s": 27729,
"text": "Example: If the specified path is a symbolic link. "
},
{
"code": null,
"e": 27789,
"s": 27781,
"text": "Python3"
},
{
"code": "# Python program to explain os.path.isdir() method # importing os.path module import os.path # Create a directory# (in current working directory)dirname = \"GeeksForGeeks\"os.mkdir(dirname) # Create a symbolic link# pointing to above directorysymlink_path = \"/home/User/Desktop/gfg\"os.symlink(dirname, symlink_path) path = dirname # Now, Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir) path = symlink_path # Check whether the # specified path (which is a# symbolic link ) is an# existing directory or notisdir = os.path.isdir(path)print(isdir)",
"e": 28413,
"s": 27789,
"text": null
},
{
"code": null,
"e": 28423,
"s": 28413,
"text": "Output: "
},
{
"code": null,
"e": 28433,
"s": 28423,
"text": "True\nTrue"
},
{
"code": null,
"e": 29062,
"s": 28435,
"text": "Pathlib module in Python provides various classes representing file system paths with semantics appropriate for different operating systems. This module comes under Python’s standard utility modules. Path classes in Pathlib module are divided into pure paths and concrete paths. Pure paths provide only computational operations but do not provides I/O operations, while concrete paths inherit from pure paths provides computational as well as I/O operations.Note: To know more about pathlib module click here.pathlib.Path.exists() method is used to check whether the given path points to an existing file or directory or not. "
},
{
"code": null,
"e": 29294,
"s": 29062,
"text": "Syntax: pathlib.Path.exists(path)Parameter: path: A path-like object representing a file system path.Return Type: This method returns a Boolean value of class bool. This method returns True if path exists otherwise returns False. "
},
{
"code": null,
"e": 29305,
"s": 29294,
"text": "Example: "
},
{
"code": null,
"e": 29313,
"s": 29305,
"text": "Python3"
},
{
"code": "# Import Path classfrom pathlib import Path # Pathpath = '/home/gfg/Desktop' # Instantiate the Path classobj = Path(path) # Check if path points to # an existing file or directory print(obj.exists())",
"e": 29519,
"s": 29313,
"text": null
},
{
"code": null,
"e": 29529,
"s": 29519,
"text": "Output: "
},
{
"code": null,
"e": 29534,
"s": 29529,
"text": "True"
},
{
"code": null,
"e": 29552,
"s": 29536,
"text": "aman chourasiya"
},
{
"code": null,
"e": 29582,
"s": 29552,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 29604,
"s": 29582,
"text": "Python OS-path-module"
},
{
"code": null,
"e": 29625,
"s": 29604,
"text": "python-file-handling"
},
{
"code": null,
"e": 29632,
"s": 29625,
"text": "Python"
},
{
"code": null,
"e": 29730,
"s": 29632,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29739,
"s": 29730,
"text": "Comments"
},
{
"code": null,
"e": 29752,
"s": 29739,
"text": "Old Comments"
},
{
"code": null,
"e": 29770,
"s": 29752,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29805,
"s": 29770,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29827,
"s": 29805,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29857,
"s": 29827,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29889,
"s": 29857,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29931,
"s": 29889,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29957,
"s": 29931,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29994,
"s": 29957,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 30037,
"s": 29994,
"text": "Python program to convert a list to string"
}
] |
How to create a lagged variable in R for groups? | Lagged variable is the type of variable that contains the previous value of the variable for which we want to create the lagged variable and the first value is neglected. Therefore, we will always have one missing value in each of the groups, if we are creating a lagged variable that depends on a grouping variable or factor variable.
Consider the below data frame:
> set.seed(2)
> Factor<-rep(c("F1","F2","F3","F4"),each=5)
> Rate<-c(12,54,18,26,14,25,81,47,15,12,96,25,14,34,68,78,42,56,81,75)
> df<-data.frame(Factor,Rate)
> df
Factor Rate
1 F1 12
2 F1 54
3 F1 18
4 F1 26
5 F1 14
6 F2 25
7 F2 81
8 F2 47
9 F2 15
10 F2 12
11 F3 96
12 F3 25
13 F3 14
14 F3 34
15 F3 68
16 F4 78
17 F4 42
18 F4 56
19 F4 81
20 F4 75
Creating a lagged variable for Rate treating Factor variable as group variable −
> df$Lagged_Variable <- c(NA, df$Rate[-nrow(df)])
> df$Lagged_Variable[which(!duplicated(df$Factor))] <- NA
> df
Factor Rate Lagged_Variable
1 F1 12 NA
2 F1 54 12
3 F1 18 54
4 F1 26 18
5 F1 14 26
6 F2 25 NA
7 F2 81 25
8 F2 47 81
9 F2 15 47
10 F2 12 15
11 F3 96 NA
12 F3 25 96
13 F3 14 25
14 F3 34 14
15 F3 68 34
16 F4 78 NA
17 F4 42 78
18 F4 56 42
19 F4 81 56
20 F4 75 81 | [
{
"code": null,
"e": 1398,
"s": 1062,
"text": "Lagged variable is the type of variable that contains the previous value of the variable for which we want to create the lagged variable and the first value is neglected. Therefore, we will always have one missing value in each of the groups, if we are creating a lagged variable that depends on a grouping variable or factor variable."
},
{
"code": null,
"e": 1429,
"s": 1398,
"text": "Consider the below data frame:"
},
{
"code": null,
"e": 1777,
"s": 1429,
"text": "> set.seed(2)\n> Factor<-rep(c(\"F1\",\"F2\",\"F3\",\"F4\"),each=5)\n> Rate<-c(12,54,18,26,14,25,81,47,15,12,96,25,14,34,68,78,42,56,81,75)\n> df<-data.frame(Factor,Rate)\n> df\nFactor Rate\n1 F1 12\n2 F1 54\n3 F1 18\n4 F1 26\n5 F1 14\n6 F2 25\n7 F2 81\n8 F2 47\n9 F2 15\n10 F2 12\n11 F3 96\n12 F3 25\n13 F3 14\n14 F3 34\n15 F3 68\n16 F4 78\n17 F4 42\n18 F4 56\n19 F4 81\n20 F4 75"
},
{
"code": null,
"e": 1858,
"s": 1777,
"text": "Creating a lagged variable for Rate treating Factor variable as group variable −"
},
{
"code": null,
"e": 2230,
"s": 1858,
"text": "> df$Lagged_Variable <- c(NA, df$Rate[-nrow(df)])\n> df$Lagged_Variable[which(!duplicated(df$Factor))] <- NA\n> df\nFactor Rate Lagged_Variable\n1 F1 12 NA\n2 F1 54 12\n3 F1 18 54\n4 F1 26 18\n5 F1 14 26\n6 F2 25 NA\n7 F2 81 25\n8 F2 47 81\n9 F2 15 47\n10 F2 12 15\n11 F3 96 NA\n12 F3 25 96\n13 F3 14 25\n14 F3 34 14\n15 F3 68 34\n16 F4 78 NA\n17 F4 42 78\n18 F4 56 42\n19 F4 81 56\n20 F4 75 81"
}
] |
DNSx – DNS Toolkit Allow To Run Multiple DNS Queries - GeeksforGeeks | 23 Aug, 2021
DNS Query is crucial in Penetration Testing. DNS Query, also known as DNS Request, demands data sent from a user’s system or DNS Client to DNS Server. In most cases, DNS Request is passed to ask for the IP address associated with a domain name. But we can customize DNS Requests as per our needs. To resolve DNS Queries, we have a tool named dnsx. dnsx tool is a Go language-based tool. dnsx is a fast and multi-purpose DNS toolkit that allows running multiple probes using a retryabledns library that will enable you to perform various DNS queries of your choice with a list of user-supplied resolvers that supports DNS wildcard filtering like shuffled.
It is handy and a straightforward utility to query DNS records.It has support to A,AAAA,CNAME,PTR,NS,MX,TXT,SOA.It also supports DNS Status code probingIt has support for DNS Tracing.It handles wildcard subdomains in an automated way.It is open-source and free to use.It has support to Stdin and Stdout, which can work with other tools.
It is handy and a straightforward utility to query DNS records.
It has support to A,AAAA,CNAME,PTR,NS,MX,TXT,SOA.
It also supports DNS Status code probing
It has support for DNS Tracing.
It handles wildcard subdomains in an automated way.
It is open-source and free to use.
It has support to Stdin and Stdout, which can work with other tools.
Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command.
go version
Step 2: Get the DNSx repository or clone the DNSx tool from Github, use the following command.
sudo GO111MODULE=on go get -v github.com/projectdiscovery/dnsx/cmd/dnsx
Step 3: Check the help menu page to get a better understanding of DNSx tool, use the following command.
dnsx -h
In this example, we will be collecting the subdomains associated with our target domain (geeksforgeeks.org) by filtering the dead records.
subfinder -silent -d geeksforgeeks.org | dnsx
In the below Screenshot, we are trying to open www.qa.geeksforgeeks.org which has a dead record. You can see that there is a connection issue as this subdomain has no longer access.
In this example, we are collecting the Subdomains along with their a record. A record indicates the IP address of the Subdomain.
subfinder -silent -d geeksforgeeks.org | dnsx -silent -a -resp
In this example, we are Extracting or filtering IP addresses from subdomains or records.
subfinder -silent -d geeksforgeeks.org | dnsx -silent -a -resp-only
In this example, we are Extracting CNAME records from the list of subdomains. The CNAME record is a type of DNS record that maps an alias name to a true or canonical domain name.
subfinder -silent -d geeksforgeeks.org | dnsx -silent -cname -resp
In this example, we will be collecting the information about the DNS Status Code Probe, in this, the status of each subdomain is displayed whether the subdomain has any issue or whether it has NO ERROR.
subfinder -silent -d geeksforgeeks.org | dnsx -silent -rcode noerror,servfail,refused
In this example, we are extracting Subdomains from a range of IP addresses of network range. In this example, we have provided the IP range of geeksforgeeks.org. PTR provides the domain name associated with an IP address. It’s oppositive to A record.
echo 34.218.62.116/24 | dnsx -silent -resp-only -ptr
In the below Screenshot, we have the list of subdomains of our target geeksforgeeks.org.
dnsx -l geeksforgeeeks.org_subdomains.txt -wd geeksforgeeks.org -o output.txt
In this example, we are handling the multi-level DNS-based wildcards which increase beyond a certain small threshold, it will check for wildcards on all the levels of the hosts for that IP iteratively.
In the below Screenshot, we have saved the output in the output.txt file using the -o flag.
So DNSx Tool is an excellent tool for querying DNS. You can use various tools along with this. In the above examples, we have used the SubFinder tool for getting the massive list of subdomains for our target. This list is provided to the DNSx tool for making DNS queries.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Basic Operators in Shell Scripting
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
Named Pipe or FIFO with example C program
chown command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
Start/Stop/Restart Services Using Systemctl in Linux
SED command in Linux | Set 2 | [
{
"code": null,
"e": 24326,
"s": 24298,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 24981,
"s": 24326,
"text": "DNS Query is crucial in Penetration Testing. DNS Query, also known as DNS Request, demands data sent from a user’s system or DNS Client to DNS Server. In most cases, DNS Request is passed to ask for the IP address associated with a domain name. But we can customize DNS Requests as per our needs. To resolve DNS Queries, we have a tool named dnsx. dnsx tool is a Go language-based tool. dnsx is a fast and multi-purpose DNS toolkit that allows running multiple probes using a retryabledns library that will enable you to perform various DNS queries of your choice with a list of user-supplied resolvers that supports DNS wildcard filtering like shuffled."
},
{
"code": null,
"e": 25318,
"s": 24981,
"text": "It is handy and a straightforward utility to query DNS records.It has support to A,AAAA,CNAME,PTR,NS,MX,TXT,SOA.It also supports DNS Status code probingIt has support for DNS Tracing.It handles wildcard subdomains in an automated way.It is open-source and free to use.It has support to Stdin and Stdout, which can work with other tools."
},
{
"code": null,
"e": 25382,
"s": 25318,
"text": "It is handy and a straightforward utility to query DNS records."
},
{
"code": null,
"e": 25432,
"s": 25382,
"text": "It has support to A,AAAA,CNAME,PTR,NS,MX,TXT,SOA."
},
{
"code": null,
"e": 25473,
"s": 25432,
"text": "It also supports DNS Status code probing"
},
{
"code": null,
"e": 25505,
"s": 25473,
"text": "It has support for DNS Tracing."
},
{
"code": null,
"e": 25557,
"s": 25505,
"text": "It handles wildcard subdomains in an automated way."
},
{
"code": null,
"e": 25592,
"s": 25557,
"text": "It is open-source and free to use."
},
{
"code": null,
"e": 25661,
"s": 25592,
"text": "It has support to Stdin and Stdout, which can work with other tools."
},
{
"code": null,
"e": 25801,
"s": 25661,
"text": "Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command."
},
{
"code": null,
"e": 25812,
"s": 25801,
"text": "go version"
},
{
"code": null,
"e": 25907,
"s": 25812,
"text": "Step 2: Get the DNSx repository or clone the DNSx tool from Github, use the following command."
},
{
"code": null,
"e": 25979,
"s": 25907,
"text": "sudo GO111MODULE=on go get -v github.com/projectdiscovery/dnsx/cmd/dnsx"
},
{
"code": null,
"e": 26083,
"s": 25979,
"text": "Step 3: Check the help menu page to get a better understanding of DNSx tool, use the following command."
},
{
"code": null,
"e": 26091,
"s": 26083,
"text": "dnsx -h"
},
{
"code": null,
"e": 26230,
"s": 26091,
"text": "In this example, we will be collecting the subdomains associated with our target domain (geeksforgeeks.org) by filtering the dead records."
},
{
"code": null,
"e": 26276,
"s": 26230,
"text": "subfinder -silent -d geeksforgeeks.org | dnsx"
},
{
"code": null,
"e": 26458,
"s": 26276,
"text": "In the below Screenshot, we are trying to open www.qa.geeksforgeeks.org which has a dead record. You can see that there is a connection issue as this subdomain has no longer access."
},
{
"code": null,
"e": 26587,
"s": 26458,
"text": "In this example, we are collecting the Subdomains along with their a record. A record indicates the IP address of the Subdomain."
},
{
"code": null,
"e": 26650,
"s": 26587,
"text": "subfinder -silent -d geeksforgeeks.org | dnsx -silent -a -resp"
},
{
"code": null,
"e": 26739,
"s": 26650,
"text": "In this example, we are Extracting or filtering IP addresses from subdomains or records."
},
{
"code": null,
"e": 26807,
"s": 26739,
"text": "subfinder -silent -d geeksforgeeks.org | dnsx -silent -a -resp-only"
},
{
"code": null,
"e": 26986,
"s": 26807,
"text": "In this example, we are Extracting CNAME records from the list of subdomains. The CNAME record is a type of DNS record that maps an alias name to a true or canonical domain name."
},
{
"code": null,
"e": 27053,
"s": 26986,
"text": "subfinder -silent -d geeksforgeeks.org | dnsx -silent -cname -resp"
},
{
"code": null,
"e": 27256,
"s": 27053,
"text": "In this example, we will be collecting the information about the DNS Status Code Probe, in this, the status of each subdomain is displayed whether the subdomain has any issue or whether it has NO ERROR."
},
{
"code": null,
"e": 27342,
"s": 27256,
"text": "subfinder -silent -d geeksforgeeks.org | dnsx -silent -rcode noerror,servfail,refused"
},
{
"code": null,
"e": 27593,
"s": 27342,
"text": "In this example, we are extracting Subdomains from a range of IP addresses of network range. In this example, we have provided the IP range of geeksforgeeks.org. PTR provides the domain name associated with an IP address. It’s oppositive to A record."
},
{
"code": null,
"e": 27646,
"s": 27593,
"text": "echo 34.218.62.116/24 | dnsx -silent -resp-only -ptr"
},
{
"code": null,
"e": 27735,
"s": 27646,
"text": "In the below Screenshot, we have the list of subdomains of our target geeksforgeeks.org."
},
{
"code": null,
"e": 27813,
"s": 27735,
"text": "dnsx -l geeksforgeeeks.org_subdomains.txt -wd geeksforgeeks.org -o output.txt"
},
{
"code": null,
"e": 28015,
"s": 27813,
"text": "In this example, we are handling the multi-level DNS-based wildcards which increase beyond a certain small threshold, it will check for wildcards on all the levels of the hosts for that IP iteratively."
},
{
"code": null,
"e": 28107,
"s": 28015,
"text": "In the below Screenshot, we have saved the output in the output.txt file using the -o flag."
},
{
"code": null,
"e": 28379,
"s": 28107,
"text": "So DNSx Tool is an excellent tool for querying DNS. You can use various tools along with this. In the above examples, we have used the SubFinder tool for getting the massive list of subdomains for our target. This list is provided to the DNSx tool for making DNS queries."
},
{
"code": null,
"e": 28390,
"s": 28379,
"text": "Kali-Linux"
},
{
"code": null,
"e": 28402,
"s": 28390,
"text": "Linux-Tools"
},
{
"code": null,
"e": 28413,
"s": 28402,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28511,
"s": 28413,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28520,
"s": 28511,
"text": "Comments"
},
{
"code": null,
"e": 28533,
"s": 28520,
"text": "Old Comments"
},
{
"code": null,
"e": 28559,
"s": 28533,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 28594,
"s": 28559,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 28631,
"s": 28594,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 28671,
"s": 28631,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 28713,
"s": 28671,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 28750,
"s": 28713,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 28784,
"s": 28750,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 28810,
"s": 28784,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 28863,
"s": 28810,
"text": "Start/Stop/Restart Services Using Systemctl in Linux"
}
] |
Python program to right rotate a list by n - GeeksforGeeks | 28 Mar, 2022
Given a list and an integer n, write a Python program to right rotate the list by n position.
Examples :
Input : n = 2, List_1 = [1, 2, 3, 4, 5, 6]Output : List_1 = [5, 6, 1, 2, 3, 4]Explanation: We get output list after right rotating (clockwise) given list by 2.
Input : n = 3, List_1 = [3, 0, 1, 4, 2, 3]Output : List_1 = [4, 2, 3, 3, 0, 1]
Approach #1 : Traverse the first list one by one and then put the elements at required places in a second list.
Python3
# Python program to right rotate a list by n # Returns the rotated list def rightRotate(lists, num): output_list = [] # Will add values from n to the new list for item in range(len(lists) - num, len(lists)): output_list.append(lists[item]) # Will add the values before # n to the end of new list for item in range(0, len(lists) - num): output_list.append(lists[item]) return output_list # Driver Coderotate_num = 3list_1 = [1, 2, 3, 4, 5, 6] print(rightRotate(list_1, rotate_num))
[4, 5, 6, 1, 2, 3]
Time complexity : O(n)
Approach #2 : Another approach to solve this problem by using slicing technique. One way of slicing list is by using len() method.
Python3
# Python program to right rotate# a list by n using list slicingn = 3 list_1 = [1, 2, 3, 4, 5, 6]list_1 = (list_1[len(list_1) - n:len(list_1)] + list_1[0:len(list_1) - n])print(list_1)
[4, 5, 6, 1, 2, 3]
Approach #3 : In the above method, last n elements of list_1 was taken and then remaining elements of list_1. Another way is without using len() method.
Python
# Right Rotating a list to n positionsn = 3 list_1 = [1, 2, 3, 4, 5, 6]if n>len(list_1): n = int(n%len(list_1))list_1 = (list_1[-n:] + list_1[:-n]) print(list_1)
[4, 5, 6, 1, 2, 3]
Time complexity : O(n)
Note : list_1[:] will return the whole list as the blank space on left of slicing operator refers to start of list i.e 0 and blank space on right refers to ending position of list.
akash mc
nitinnathoms
Namrata_Tiwari
Python list-programs
python-list
Python
Technical Scripter
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
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()
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 24819,
"s": 24791,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 24913,
"s": 24819,
"text": "Given a list and an integer n, write a Python program to right rotate the list by n position."
},
{
"code": null,
"e": 24925,
"s": 24913,
"text": "Examples : "
},
{
"code": null,
"e": 25085,
"s": 24925,
"text": "Input : n = 2, List_1 = [1, 2, 3, 4, 5, 6]Output : List_1 = [5, 6, 1, 2, 3, 4]Explanation: We get output list after right rotating (clockwise) given list by 2."
},
{
"code": null,
"e": 25165,
"s": 25085,
"text": "Input : n = 3, List_1 = [3, 0, 1, 4, 2, 3]Output : List_1 = [4, 2, 3, 3, 0, 1]"
},
{
"code": null,
"e": 25278,
"s": 25165,
"text": "Approach #1 : Traverse the first list one by one and then put the elements at required places in a second list. "
},
{
"code": null,
"e": 25286,
"s": 25278,
"text": "Python3"
},
{
"code": "# Python program to right rotate a list by n # Returns the rotated list def rightRotate(lists, num): output_list = [] # Will add values from n to the new list for item in range(len(lists) - num, len(lists)): output_list.append(lists[item]) # Will add the values before # n to the end of new list for item in range(0, len(lists) - num): output_list.append(lists[item]) return output_list # Driver Coderotate_num = 3list_1 = [1, 2, 3, 4, 5, 6] print(rightRotate(list_1, rotate_num))",
"e": 25806,
"s": 25286,
"text": null
},
{
"code": null,
"e": 25826,
"s": 25806,
"text": "[4, 5, 6, 1, 2, 3]\n"
},
{
"code": null,
"e": 25849,
"s": 25826,
"text": "Time complexity : O(n)"
},
{
"code": null,
"e": 25981,
"s": 25849,
"text": "Approach #2 : Another approach to solve this problem by using slicing technique. One way of slicing list is by using len() method. "
},
{
"code": null,
"e": 25989,
"s": 25981,
"text": "Python3"
},
{
"code": "# Python program to right rotate# a list by n using list slicingn = 3 list_1 = [1, 2, 3, 4, 5, 6]list_1 = (list_1[len(list_1) - n:len(list_1)] + list_1[0:len(list_1) - n])print(list_1)",
"e": 26190,
"s": 25989,
"text": null
},
{
"code": null,
"e": 26210,
"s": 26190,
"text": "[4, 5, 6, 1, 2, 3]\n"
},
{
"code": null,
"e": 26365,
"s": 26210,
"text": "Approach #3 : In the above method, last n elements of list_1 was taken and then remaining elements of list_1. Another way is without using len() method. "
},
{
"code": null,
"e": 26372,
"s": 26365,
"text": "Python"
},
{
"code": "# Right Rotating a list to n positionsn = 3 list_1 = [1, 2, 3, 4, 5, 6]if n>len(list_1): n = int(n%len(list_1))list_1 = (list_1[-n:] + list_1[:-n]) print(list_1)",
"e": 26537,
"s": 26372,
"text": null
},
{
"code": null,
"e": 26557,
"s": 26537,
"text": "[4, 5, 6, 1, 2, 3]\n"
},
{
"code": null,
"e": 26580,
"s": 26557,
"text": "Time complexity : O(n)"
},
{
"code": null,
"e": 26762,
"s": 26580,
"text": "Note : list_1[:] will return the whole list as the blank space on left of slicing operator refers to start of list i.e 0 and blank space on right refers to ending position of list. "
},
{
"code": null,
"e": 26771,
"s": 26762,
"text": "akash mc"
},
{
"code": null,
"e": 26784,
"s": 26771,
"text": "nitinnathoms"
},
{
"code": null,
"e": 26799,
"s": 26784,
"text": "Namrata_Tiwari"
},
{
"code": null,
"e": 26820,
"s": 26799,
"text": "Python list-programs"
},
{
"code": null,
"e": 26832,
"s": 26820,
"text": "python-list"
},
{
"code": null,
"e": 26839,
"s": 26832,
"text": "Python"
},
{
"code": null,
"e": 26858,
"s": 26839,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26870,
"s": 26858,
"text": "python-list"
},
{
"code": null,
"e": 26968,
"s": 26870,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26977,
"s": 26968,
"text": "Comments"
},
{
"code": null,
"e": 26990,
"s": 26977,
"text": "Old Comments"
},
{
"code": null,
"e": 27008,
"s": 26990,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27043,
"s": 27008,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27065,
"s": 27043,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27097,
"s": 27065,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27127,
"s": 27097,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27169,
"s": 27127,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27195,
"s": 27169,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27238,
"s": 27195,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27282,
"s": 27238,
"text": "Reading and Writing to text files in Python"
}
] |
Tryit Editor v3.7 | Tryit: HTML paragraphs with hr | [] |
GATE | GATE-CS-2006 | Question 85 - GeeksforGeeks | 15 Oct, 2019
Consider the following log sequence of two transactions on a bank account, with initial balance 12000, that transfer 2000 to a mortgage payment and then apply a 5% interest.
1. T1 start
2. T1 B old=12000 new=10000
3. T1 M old=0 new=2000
4. T1 commit
5. T2 start
6. T2 B old=10000 new=10500
7. T2 commit
Suppose the database system crashes just before log record 7 is written. When the system is restarted, which one statement is true of the recovery procedure?(A) We must redo log record 6 to set B to 10500(B) We must undo log record 6 to set B to 10000 and then redo log records 2 and 3.(C) We need not redo log records 2 and 3 because transaction T1 has committed.(D) We can apply redo and undo operations in arbitrary order because they are idempotentAnswer: (B)Explanation: We must undo log record 6 to set B to 10000 and then redo log records 2 and 3 bcoz system fail before commit operation. So we need to undone active transactions(T2) and redo committed transactions (T1)
Note: Here we are not using checkpoints.
Checkpoint : Checkpoint is a mechanism where all the previous logs are removed from the system and stored permanently in a storage disk. Checkpoint declares a point before which the DBMS was in consistent state, and all the transactions were committed.
Recovery:When a system with concurrent transactions crashes and recovers, it behaves in the following manner −
=>The recovery system reads the logs backwards from the end to the last checkpoint.
=>It maintains two lists, an undo-list and a redo-list.
=>If the recovery system sees a log with and or just , it puts the transaction in the redo-list.
=>If the recovery system sees a log with but no commit or abort log found, it puts the transaction in undo-list.
All the transactions in the undo-list are then undone and their logs are removed. All the transactions in the redo-list and their previous logs are removed and then redone before saving their logs.
So Answer is B redo log records 2 and 3 and undo log record 6Quiz of this Question
GATE-CS-2006
GATE-GATE-CS-2006
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-IT-2004 | Question 83
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 17
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 64 | [
{
"code": null,
"e": 24468,
"s": 24440,
"text": "\n15 Oct, 2019"
},
{
"code": null,
"e": 24642,
"s": 24468,
"text": "Consider the following log sequence of two transactions on a bank account, with initial balance 12000, that transfer 2000 to a mortgage payment and then apply a 5% interest."
},
{
"code": null,
"e": 24786,
"s": 24642,
"text": " 1. T1 start\n 2. T1 B old=12000 new=10000\n 3. T1 M old=0 new=2000\n 4. T1 commit\n 5. T2 start\n 6. T2 B old=10000 new=10500\n 7. T2 commit "
},
{
"code": null,
"e": 25464,
"s": 24786,
"text": "Suppose the database system crashes just before log record 7 is written. When the system is restarted, which one statement is true of the recovery procedure?(A) We must redo log record 6 to set B to 10500(B) We must undo log record 6 to set B to 10000 and then redo log records 2 and 3.(C) We need not redo log records 2 and 3 because transaction T1 has committed.(D) We can apply redo and undo operations in arbitrary order because they are idempotentAnswer: (B)Explanation: We must undo log record 6 to set B to 10000 and then redo log records 2 and 3 bcoz system fail before commit operation. So we need to undone active transactions(T2) and redo committed transactions (T1)"
},
{
"code": null,
"e": 25505,
"s": 25464,
"text": "Note: Here we are not using checkpoints."
},
{
"code": null,
"e": 25758,
"s": 25505,
"text": "Checkpoint : Checkpoint is a mechanism where all the previous logs are removed from the system and stored permanently in a storage disk. Checkpoint declares a point before which the DBMS was in consistent state, and all the transactions were committed."
},
{
"code": null,
"e": 25869,
"s": 25758,
"text": "Recovery:When a system with concurrent transactions crashes and recovers, it behaves in the following manner −"
},
{
"code": null,
"e": 25953,
"s": 25869,
"text": "=>The recovery system reads the logs backwards from the end to the last checkpoint."
},
{
"code": null,
"e": 26009,
"s": 25953,
"text": "=>It maintains two lists, an undo-list and a redo-list."
},
{
"code": null,
"e": 26106,
"s": 26009,
"text": "=>If the recovery system sees a log with and or just , it puts the transaction in the redo-list."
},
{
"code": null,
"e": 26219,
"s": 26106,
"text": "=>If the recovery system sees a log with but no commit or abort log found, it puts the transaction in undo-list."
},
{
"code": null,
"e": 26417,
"s": 26219,
"text": "All the transactions in the undo-list are then undone and their logs are removed. All the transactions in the redo-list and their previous logs are removed and then redone before saving their logs."
},
{
"code": null,
"e": 26500,
"s": 26417,
"text": "So Answer is B redo log records 2 and 3 and undo log record 6Quiz of this Question"
},
{
"code": null,
"e": 26513,
"s": 26500,
"text": "GATE-CS-2006"
},
{
"code": null,
"e": 26531,
"s": 26513,
"text": "GATE-GATE-CS-2006"
},
{
"code": null,
"e": 26536,
"s": 26531,
"text": "GATE"
},
{
"code": null,
"e": 26634,
"s": 26536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26643,
"s": 26634,
"text": "Comments"
},
{
"code": null,
"e": 26656,
"s": 26643,
"text": "Old Comments"
},
{
"code": null,
"e": 26698,
"s": 26656,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 26732,
"s": 26698,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 26766,
"s": 26732,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 26808,
"s": 26766,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 26850,
"s": 26808,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 26892,
"s": 26850,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
},
{
"code": null,
"e": 26926,
"s": 26892,
"text": "GATE | GATE-CS-2007 | Question 17"
},
{
"code": null,
"e": 26960,
"s": 26926,
"text": "GATE | GATE-IT-2004 | Question 12"
},
{
"code": null,
"e": 27002,
"s": 26960,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
}
] |
IDE | GeeksforGeeks | A computer science portal for geeks | Please enter your email address or userHandle. | [] |
C# | Multilevel Inheritance - GeeksforGeeks | 23 Jan, 2019
In the Multilevel inheritance, a derived class will inherit a base class and as well as the derived class also act as the base class to other class. For example, three classes called A, B, and C, as shown in the below image, where class C is derived from class B and class B, is derived from class A. In this situation, each derived class inherit all the characteristics of its base classes. So class C inherits all the features of class A and B.
Example: Here, the derived class Rectangle is used as a base class to create the derived class called ColorRectangle. Due to inheritance the ColorRectangle inherit all the characteristics of Rectangle and Shape and add an extra field called rcolor, which contains the color of the rectangle.
This example also covers the concept of constructors in a derived class. As we know that a subclass inherits all the members (fields, methods) from its superclass but constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. As shown in the below example, base refers to a constructor in the closest base class. The base in ColorRectangle calls the constructor in Rectangle and the base in Rectangle class the constructor in Shape.
// C# program to illustrate the// concept of multilevel inheritanceusing System; class Shape { double a_width; double a_length; // Default constructor public Shape() { Width = Length = 0.0; } // Constructor for Shape public Shape(double w, double l) { Width = w; Length = l; } // Construct an object with // equal length and width public Shape(double y) { Width = Length = y; } // Properties for Length and Width public double Width { get { return a_width; } set { a_width = value < 0 ? -value : value; } } public double Length { get { return a_length; } set { a_length = value < 0 ? -value : value; } } public void DisplayDim() { Console.WriteLine("Width and Length are " + Width + " and " + Length); }} // A derived class of Shape // for the rectangle.class Rectangle : Shape { string Style; // A default constructor. // This invokes the default // constructor of Shape. public Rectangle() { Style = "null"; } // Constructor public Rectangle(string s, double w, double l) : base(w, l) { Style = s; } // Construct an square. public Rectangle(double y) : base(y) { Style = "square"; } // Return area of rectangle. public double Area() { return Width * Length; } // Display a rectangle's style. public void DisplayStyle() { Console.WriteLine("Rectangle is " + Style); }} // Inheriting Rectangle classclass ColorRectangle : Rectangle { string rcolor; // Constructor public ColorRectangle(string c, string s, double w, double l) : base(s, w, l) { rcolor = c; } // Display the color. public void DisplayColor() { Console.WriteLine("Color is " + rcolor); }} // Driver Classclass GFG { // Main Method static void Main() { ColorRectangle r1 = new ColorRectangle("pink", "Fibonacci rectangle", 2.0, 3.236); ColorRectangle r2 = new ColorRectangle("black", "Square", 4.0, 4.0); Console.WriteLine("Details of r1: "); r1.DisplayStyle(); r1.DisplayDim(); r1.DisplayColor(); Console.WriteLine("Area is " + r1.Area()); Console.WriteLine(); Console.WriteLine("Details of r2: "); r2.DisplayStyle(); r2.DisplayDim(); r2.DisplayColor(); Console.WriteLine("Area is " + r2.Area()); }}
Details of r1:
Rectangle is Fibonacci rectangle
Width and Length are 2 and 3.236
Color is pink
Area is 6.472
Details of r2:
Rectangle is Square
Width and Length are 4 and 4
Color is black
Area is 16
CSharp-Inheritance
CSharp-OOP
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C# | [
{
"code": null,
"e": 23935,
"s": 23907,
"text": "\n23 Jan, 2019"
},
{
"code": null,
"e": 24382,
"s": 23935,
"text": "In the Multilevel inheritance, a derived class will inherit a base class and as well as the derived class also act as the base class to other class. For example, three classes called A, B, and C, as shown in the below image, where class C is derived from class B and class B, is derived from class A. In this situation, each derived class inherit all the characteristics of its base classes. So class C inherits all the features of class A and B."
},
{
"code": null,
"e": 24674,
"s": 24382,
"text": "Example: Here, the derived class Rectangle is used as a base class to create the derived class called ColorRectangle. Due to inheritance the ColorRectangle inherit all the characteristics of Rectangle and Shape and add an extra field called rcolor, which contains the color of the rectangle."
},
{
"code": null,
"e": 25191,
"s": 24674,
"text": "This example also covers the concept of constructors in a derived class. As we know that a subclass inherits all the members (fields, methods) from its superclass but constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. As shown in the below example, base refers to a constructor in the closest base class. The base in ColorRectangle calls the constructor in Rectangle and the base in Rectangle class the constructor in Shape."
},
{
"code": "// C# program to illustrate the// concept of multilevel inheritanceusing System; class Shape { double a_width; double a_length; // Default constructor public Shape() { Width = Length = 0.0; } // Constructor for Shape public Shape(double w, double l) { Width = w; Length = l; } // Construct an object with // equal length and width public Shape(double y) { Width = Length = y; } // Properties for Length and Width public double Width { get { return a_width; } set { a_width = value < 0 ? -value : value; } } public double Length { get { return a_length; } set { a_length = value < 0 ? -value : value; } } public void DisplayDim() { Console.WriteLine(\"Width and Length are \" + Width + \" and \" + Length); }} // A derived class of Shape // for the rectangle.class Rectangle : Shape { string Style; // A default constructor. // This invokes the default // constructor of Shape. public Rectangle() { Style = \"null\"; } // Constructor public Rectangle(string s, double w, double l) : base(w, l) { Style = s; } // Construct an square. public Rectangle(double y) : base(y) { Style = \"square\"; } // Return area of rectangle. public double Area() { return Width * Length; } // Display a rectangle's style. public void DisplayStyle() { Console.WriteLine(\"Rectangle is \" + Style); }} // Inheriting Rectangle classclass ColorRectangle : Rectangle { string rcolor; // Constructor public ColorRectangle(string c, string s, double w, double l) : base(s, w, l) { rcolor = c; } // Display the color. public void DisplayColor() { Console.WriteLine(\"Color is \" + rcolor); }} // Driver Classclass GFG { // Main Method static void Main() { ColorRectangle r1 = new ColorRectangle(\"pink\", \"Fibonacci rectangle\", 2.0, 3.236); ColorRectangle r2 = new ColorRectangle(\"black\", \"Square\", 4.0, 4.0); Console.WriteLine(\"Details of r1: \"); r1.DisplayStyle(); r1.DisplayDim(); r1.DisplayColor(); Console.WriteLine(\"Area is \" + r1.Area()); Console.WriteLine(); Console.WriteLine(\"Details of r2: \"); r2.DisplayStyle(); r2.DisplayDim(); r2.DisplayColor(); Console.WriteLine(\"Area is \" + r2.Area()); }}",
"e": 27918,
"s": 25191,
"text": null
},
{
"code": null,
"e": 28123,
"s": 27918,
"text": "Details of r1: \nRectangle is Fibonacci rectangle\nWidth and Length are 2 and 3.236\nColor is pink\nArea is 6.472\n\nDetails of r2: \nRectangle is Square\nWidth and Length are 4 and 4\nColor is black\nArea is 16\n"
},
{
"code": null,
"e": 28142,
"s": 28123,
"text": "CSharp-Inheritance"
},
{
"code": null,
"e": 28153,
"s": 28142,
"text": "CSharp-OOP"
},
{
"code": null,
"e": 28156,
"s": 28153,
"text": "C#"
},
{
"code": null,
"e": 28254,
"s": 28156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28263,
"s": 28254,
"text": "Comments"
},
{
"code": null,
"e": 28276,
"s": 28263,
"text": "Old Comments"
},
{
"code": null,
"e": 28316,
"s": 28276,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28339,
"s": 28316,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28367,
"s": 28339,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28389,
"s": 28367,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28406,
"s": 28389,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28446,
"s": 28406,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 28479,
"s": 28446,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 28522,
"s": 28479,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28538,
"s": 28522,
"text": "C# | List Class"
}
] |
How can we check the current MySQL transaction isolation level? | By executing SELECT @@TX_ISOLATION command we can check the current MySQL transaction isolation level.
mysql> SELECT @@TX_ISOLATION;
+-----------------+
| @@TX_ISOLATION |
+-----------------+
| REPEATABLE-READ |
+-----------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "By executing SELECT @@TX_ISOLATION command we can check the current MySQL transaction isolation level."
},
{
"code": null,
"e": 1319,
"s": 1165,
"text": "mysql> SELECT @@TX_ISOLATION;\n+-----------------+\n| @@TX_ISOLATION |\n+-----------------+\n| REPEATABLE-READ |\n+-----------------+\n1 row in set (0.00 sec)"
}
] |
SIFT Interest Point Detector Using Python – OpenCV | 11 Dec, 2020
SIFT (Scale Invariant Fourier Transform) Detector is used in the detection of interest points on an input image. It allows identification of localized features in images which is essential in applications such as:
Object Recognition in Images
Path detection and obstacle avoidance algorithms
Gesture recognition, Mosaic generation, etc
Unlike the Harris Detector, which is dependent on properties of the image such as viewpoint, depth, and scale, SIFT can perform feature detection independent of these properties of the image. This is achieved by the transformation of the image data into scale-invariant coordinates. The SIFT Detector has been said to be a close approximation of the system used in the primate visual system.
Fig 01: Sequence of steps followed in SIFT Detector
The concept of Scale Space deals with the application of a continuous range of Gaussian Filters to the target image such that the chosen Gaussian have differing values of the sigma parameter. The plot thus obtained is called the Scale Space. Scale Space Peak Selection depends on the Spatial Coincidence Assumption. According to this, if an edge is detected at the same location in multiple scales (indicated by zero crossings in the scale space) then we classify it as an actual edge.
Fig 02: Peaks are selected across Scales.
In 2D images, we can detect the Interest Points using the local maxima/minima in Scale Space of Laplacian of Gaussian. A potential SIFT interest point is determined for a given sigma value by picking the potential interest point and considering the pixels in the level above (with higher sigma), the same level, and the level below (with lower sigma than current sigma level). If the point is maxima/minima of all these 26 neighboring points, it is a potential SIFT interest point – and it acts as a starting point for interest point detection.
Key point localization involves the refinement of keypoints selected in the previous stage. Low contrast key-points, unstable key points, and keypoints lying on edges are eliminated. This is achieved by calculating the Laplacian of the keypoints found in the previous stage. The extrema values are computed as follows:
In the above expression, D represents the Difference of Gaussian. To remove the unstable key points, the value of z is calculated and if the function value at z is below a threshold value then the point is excluded.
Fig 03 Refinement of Keypoints after Keypoint Localization
To achieve detection which is invariant with respect to the rotation of the image, orientation needs to be calculated for the key-points. This is done by considering the neighborhood of the keypoint and calculating the magnitude and direction of gradients of the neighborhood. Based on the values obtained, a histogram is constructed with 36 bins to represent 360 degrees of orientation(10 degrees per bin). Thus, if the gradient direction of a certain point is, say, 67.8 degrees, a value, proportional to the gradient magnitude of this point, is added to the bin representing 60-70 degrees. Histogram peaks above 80% are converted into a new keypoint are used to decide the orientation of the original keypoint.
Fig 04: Assigning Orientation to Neighborhood and creating Orientation Histogram
Finally, for each keypoint, a descriptor is created using the keypoints neighborhood. These descriptors are used for matching keypoints across images. A 16×16 neighborhood of the keypoint is used for defining the descriptor of that key-point. This 16×16 neighborhood is divided into sub-block. Each such sub-block is a non-overlapping, contiguous, 4×4 neighborhood. Subsequently, for each sub-block, an 8 bin orientation is created similarly as discussed in Orientation Assignment. These 128 bin values (16 sub-blocks * 8 bins per block) are represented as a vector to generate the keypoint descriptor.
Example: SIFT detector in Python
Running the following script in the same directory with a file named “geeks.jpg” generates the “image-with-keypoints.jpg” which contains the interest points, detected using the SIFT module in OpenCV, marked using circular overlays.
Below is the implementation:
Python3
# Important NOTE: Use opencv <= 3.4.2.16 as# SIFT is no longer available in# opencv > 3.4.2.16import cv2 # Loading the imageimg = cv2.imread('geeks.jpg') # Converting image to grayscalegray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Applying SIFT detectorsift = cv2.xfeatures2d.SIFT_create() kp = sift.detect(gray, None) # Marking the keypoint on the image using circlesimg=cv2.drawKeypoints(gray , kp , img , flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) cv2.imwrite('image-with-keypoints.jpg', img)
Output:
The image on left is the original, the image on right shows the various highlighted interest points on the image
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 270,
"s": 54,
"text": "SIFT (Scale Invariant Fourier Transform) Detector is used in the detection of interest points on an input image. It allows identification of localized features in images which is essential in applications such as: "
},
{
"code": null,
"e": 299,
"s": 270,
"text": "Object Recognition in Images"
},
{
"code": null,
"e": 348,
"s": 299,
"text": "Path detection and obstacle avoidance algorithms"
},
{
"code": null,
"e": 392,
"s": 348,
"text": "Gesture recognition, Mosaic generation, etc"
},
{
"code": null,
"e": 785,
"s": 392,
"text": "Unlike the Harris Detector, which is dependent on properties of the image such as viewpoint, depth, and scale, SIFT can perform feature detection independent of these properties of the image. This is achieved by the transformation of the image data into scale-invariant coordinates. The SIFT Detector has been said to be a close approximation of the system used in the primate visual system. "
},
{
"code": null,
"e": 839,
"s": 787,
"text": "Fig 01: Sequence of steps followed in SIFT Detector"
},
{
"code": null,
"e": 1326,
"s": 839,
"text": "The concept of Scale Space deals with the application of a continuous range of Gaussian Filters to the target image such that the chosen Gaussian have differing values of the sigma parameter. The plot thus obtained is called the Scale Space. Scale Space Peak Selection depends on the Spatial Coincidence Assumption. According to this, if an edge is detected at the same location in multiple scales (indicated by zero crossings in the scale space) then we classify it as an actual edge. "
},
{
"code": null,
"e": 1368,
"s": 1326,
"text": "Fig 02: Peaks are selected across Scales."
},
{
"code": null,
"e": 1914,
"s": 1368,
"text": "In 2D images, we can detect the Interest Points using the local maxima/minima in Scale Space of Laplacian of Gaussian. A potential SIFT interest point is determined for a given sigma value by picking the potential interest point and considering the pixels in the level above (with higher sigma), the same level, and the level below (with lower sigma than current sigma level). If the point is maxima/minima of all these 26 neighboring points, it is a potential SIFT interest point – and it acts as a starting point for interest point detection. "
},
{
"code": null,
"e": 2233,
"s": 1914,
"text": "Key point localization involves the refinement of keypoints selected in the previous stage. Low contrast key-points, unstable key points, and keypoints lying on edges are eliminated. This is achieved by calculating the Laplacian of the keypoints found in the previous stage. The extrema values are computed as follows:"
},
{
"code": null,
"e": 2451,
"s": 2233,
"text": "In the above expression, D represents the Difference of Gaussian. To remove the unstable key points, the value of z is calculated and if the function value at z is below a threshold value then the point is excluded. "
},
{
"code": null,
"e": 2510,
"s": 2451,
"text": "Fig 03 Refinement of Keypoints after Keypoint Localization"
},
{
"code": null,
"e": 3228,
"s": 2512,
"text": "To achieve detection which is invariant with respect to the rotation of the image, orientation needs to be calculated for the key-points. This is done by considering the neighborhood of the keypoint and calculating the magnitude and direction of gradients of the neighborhood. Based on the values obtained, a histogram is constructed with 36 bins to represent 360 degrees of orientation(10 degrees per bin). Thus, if the gradient direction of a certain point is, say, 67.8 degrees, a value, proportional to the gradient magnitude of this point, is added to the bin representing 60-70 degrees. Histogram peaks above 80% are converted into a new keypoint are used to decide the orientation of the original keypoint. "
},
{
"code": null,
"e": 3309,
"s": 3228,
"text": "Fig 04: Assigning Orientation to Neighborhood and creating Orientation Histogram"
},
{
"code": null,
"e": 3915,
"s": 3311,
"text": "Finally, for each keypoint, a descriptor is created using the keypoints neighborhood. These descriptors are used for matching keypoints across images. A 16×16 neighborhood of the keypoint is used for defining the descriptor of that key-point. This 16×16 neighborhood is divided into sub-block. Each such sub-block is a non-overlapping, contiguous, 4×4 neighborhood. Subsequently, for each sub-block, an 8 bin orientation is created similarly as discussed in Orientation Assignment. These 128 bin values (16 sub-blocks * 8 bins per block) are represented as a vector to generate the keypoint descriptor. "
},
{
"code": null,
"e": 3948,
"s": 3915,
"text": "Example: SIFT detector in Python"
},
{
"code": null,
"e": 4180,
"s": 3948,
"text": "Running the following script in the same directory with a file named “geeks.jpg” generates the “image-with-keypoints.jpg” which contains the interest points, detected using the SIFT module in OpenCV, marked using circular overlays."
},
{
"code": null,
"e": 4210,
"s": 4180,
"text": "Below is the implementation: "
},
{
"code": null,
"e": 4218,
"s": 4210,
"text": "Python3"
},
{
"code": "# Important NOTE: Use opencv <= 3.4.2.16 as# SIFT is no longer available in# opencv > 3.4.2.16import cv2 # Loading the imageimg = cv2.imread('geeks.jpg') # Converting image to grayscalegray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Applying SIFT detectorsift = cv2.xfeatures2d.SIFT_create() kp = sift.detect(gray, None) # Marking the keypoint on the image using circlesimg=cv2.drawKeypoints(gray , kp , img , flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) cv2.imwrite('image-with-keypoints.jpg', img)",
"e": 4790,
"s": 4218,
"text": null
},
{
"code": null,
"e": 4798,
"s": 4790,
"text": "Output:"
},
{
"code": null,
"e": 4911,
"s": 4798,
"text": "The image on left is the original, the image on right shows the various highlighted interest points on the image"
},
{
"code": null,
"e": 4927,
"s": 4913,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 4934,
"s": 4927,
"text": "Python"
}
] |
Allocate minimum number of pages | 22 Jun, 2022
Given number of pages in n different books and m students. The books are arranged in ascending order of number of pages. Every student is assigned to read some consecutive books. The task is to assign books in such a way that the maximum number of pages assigned to a student is minimum. Example :
Input : pages[] = {12, 34, 67, 90} , m = 2
Output : 113
Explanation:
There are 2 number of students. Books can be distributed
in following fashion :
1) [12] and [34, 67, 90]
Max number of pages is allocated to student
'2' with 34 + 67 + 90 = 191 pages
2) [12, 34] and [67, 90]
Max number of pages is allocated to student
'2' with 67 + 90 = 157 pages
3) [12, 34, 67] and [90]
Max number of pages is allocated to student
'1' with 12 + 34 + 67 = 113 pages
Of the 3 cases, Option 3 has the minimum pages = 113.
The idea is to use Binary Search. We fix a value for the number of pages as mid of current minimum and maximum. We initialize minimum and maximum as 0 and sum-of-all-pages respectively. If a current mid can be a solution, then we search on the lower half, else we search in higher half.Now the question arises, how to check if a mid value is feasible or not? Basically, we need to check if we can assign pages to all students in a way that the maximum number doesn’t exceed current value. To do this, we sequentially assign pages to every student while the current number of assigned pages doesn’t exceed the value. In this process, if the number of students becomes more than m, then the solution is not feasible. Else feasible.Below is an implementation of above idea.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program for optimal allocation of pages#include <bits/stdc++.h>using namespace std; // Utility function to check if current minimum value// is feasible or not.bool isPossible(int arr[], int n, int m, int curr_min){ int studentsRequired = 1; int curr_sum = 0; // iterate over all books for (int i = 0; i < n; i++) { // check if current number of pages are greater // than curr_min that means we will get the result // after mid no. of pages if (arr[i] > curr_min) return false; // count how many students are required // to distribute curr_min pages if (curr_sum + arr[i] > curr_min) { // increment student count studentsRequired++; // update curr_sum curr_sum = arr[i]; // if students required becomes greater // than given no. of students,return false if (studentsRequired > m) return false; } // else update curr_sum else curr_sum += arr[i]; } return true;} // function to find minimum pagesint findPages(int arr[], int n, int m){ long long sum = 0; // return -1 if no. of books is less than // no. of students if (n < m) return -1; // Count total number of pages for (int i = 0; i < n; i++) sum += arr[i]; // initialize start as 0 pages and end as // total pages int start = 0, end = sum; int result = INT_MAX; // traverse until start <= end while (start <= end) { // check if it is possible to distribute // books by using mid as current minimum int mid = (start + end) / 2; if (isPossible(arr, n, m, mid)) { // update result to current distribution // as it's the best we have found till now. result = mid; // as we are finding minimum and books // are sorted so reduce end = mid -1 // that means end = mid - 1; } else // if not possible means pages should be // increased so update start = mid + 1 start = mid + 1; } // at-last return minimum no. of pages return result;} // Drivers codeint main(){ // Number of pages in books int arr[] = { 12, 34, 67, 90 }; int n = sizeof arr / sizeof arr[0]; int m = 2; // No. of students cout << "Minimum number of pages = " << findPages(arr, n, m) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program for optimal allocation of pages#include <limits.h>#include <stdbool.h>#include <stdio.h> // Utility function to check if current minimum value// is feasible or not.bool isPossible(int arr[], int n, int m, int curr_min){ int studentsRequired = 1; int curr_sum = 0; // iterate over all books for (int i = 0; i < n; i++) { // check if current number of pages are greater // than curr_min that means we will get the result // after mid no. of pages if (arr[i] > curr_min) return false; // count how many students are required // to distribute curr_min pages if (curr_sum + arr[i] > curr_min) { // increment student count studentsRequired++; // update curr_sum curr_sum = arr[i]; // if students required becomes greater // than given no. of students,return false if (studentsRequired > m) return false; } // else update curr_sum else curr_sum += arr[i]; } return true;} // function to find minimum pagesint findPages(int arr[], int n, int m){ long long sum = 0; // return -1 if no. of books is less than // no. of students if (n < m) return -1; // Count total number of pages for (int i = 0; i < n; i++) sum += arr[i]; // initialize start as 0 pages and end as // total pages int start = 0, end = sum; int result = INT_MAX; // traverse until start <= end while (start <= end) { // check if it is possible to distribute // books by using mid as current minimum int mid = (start + end) / 2; if (isPossible(arr, n, m, mid)) { // update result to current distribution // as it's the best we have found till now. result = mid; // as we are finding minimum and books // are sorted so reduce end = mid -1 // that means end = mid - 1; } else // if not possible means pages should be // increased so update start = mid + 1 start = mid + 1; } // at-last return minimum no. of pages return result;} // Drivers codeint main(){ // Number of pages in books int arr[] = { 12, 34, 67, 90 }; int n = sizeof arr / sizeof arr[0]; int m = 2; // No. of students printf("Minimum number of pages = %d\n", findPages(arr, n, m)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program for optimal allocation of pages public class GFG{ // Utility method to check if current minimum value // is feasible or not. static boolean isPossible(int arr[], int n, int m, int curr_min) { int studentsRequired = 1; int curr_sum = 0; // iterate over all books for(int i=0;i<n;i++) { curr_sum += arr[i]; if(curr_sum > curr_min) { studentsRequired++ ; // increment student count curr_sum = arr[i] ; // update curr_sum } } return studentsRequired <= m; } // method to find minimum pages static int findPages(int arr[], int n, int m) { int sum = 0; // return -1 if no. of books is less than // no. of students if (n < m) return -1; // Count total number of pages for (int i = 0; i < n; i++) sum += arr[i]; // initialize start as arr[n-1] pages(minimum answer possible) and end as // total pages(maximum answer possible) int start = arr[n-1], end = sum; int result = Integer.MAX_VALUE; // traverse until start <= end while (start <= end) { // check if it is possible to distribute // books by using mid is current minimum int mid = start + (end - start)/2; if (isPossible(arr, n, m, mid)) { // update result to current distribution // as it's the best we have found till now. result = mid; // as we are finding minimum so, end = mid - 1; } else // if not possible, means pages should be // increased ,so update start = mid + 1 start = mid + 1; } // at-last return minimum no. of pages return result; } // Driver Method public static void main(String[] args) { int arr[] = {12, 34, 67, 90}; //Number of pages in books int m = 2; //No. of students System.out.println("Minimum number of pages = " + findPages(arr, arr.length, m)); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program for optimal allocation of pages # Utility function to check if# current minimum value is feasible or not.def isPossible(arr, n, m, curr_min): studentsRequired = 1 curr_sum = 0 # iterate over all books for i in range(n): # check if current number of pages are # greater than curr_min that means # we will get the result after # mid no. of pages if (arr[i] > curr_min): return False # count how many students are required # to distribute curr_min pages if (curr_sum + arr[i] > curr_min): # increment student count studentsRequired += 1 # update curr_sum curr_sum = arr[i] # if students required becomes greater # than given no. of students, return False if (studentsRequired > m): return False # else update curr_sum else: curr_sum += arr[i] return True # function to find minimum pagesdef findPages(arr, n, m): sum = 0 # return -1 if no. of books is # less than no. of students if (n < m): return -1 # Count total number of pages for i in range(n): sum += arr[i] # initialize start as 0 pages and # end as total pages start, end = 0, sum result = 10**9 # traverse until start <= end while (start <= end): # check if it is possible to distribute # books by using mid as current minimum mid = (start + end) // 2 if (isPossible(arr, n, m, mid)): # update result to current distribution # as it's the best we have found till now. result = mid # as we are finding minimum and books # are sorted so reduce end = mid -1 # that means end = mid - 1 else: # if not possible means pages should be # increased so update start = mid + 1 start = mid + 1 # at-last return minimum no. of pages return result # Driver Code # Number of pages in booksarr = [12, 34, 67, 90]n = len(arr)m = 2 # No. of students print("Minimum number of pages = ", findPages(arr, n, m)) # This code is contributed by Mohit Kumar
// C# program for optimal// allocation of pagesusing System; class GFG{ // Utility function to check// if current minimum value// is feasible or not.static bool isPossible(int []arr, int n, int m, int curr_min){ int studentsRequired = 1; int curr_sum = 0; // iterate over all books for (int i = 0; i < n; i++) { // check if current number of // pages are greater than curr_min // that means we will get the // result after mid no. of pages if (arr[i] > curr_min) return false; // count how many students // are required to distribute // curr_min pages if (curr_sum + arr[i] > curr_min) { // increment student count studentsRequired++; // update curr_sum curr_sum = arr[i]; // if students required becomes // greater than given no. of // students, return false if (studentsRequired > m) return false; } // else update curr_sum else curr_sum += arr[i]; } return true;} // function to find minimum pagesstatic int findPages(int []arr, int n, int m){ long sum = 0; // return -1 if no. of books // is less than no. of students if (n < m) return -1; // Count total number of pages for (int i = 0; i < n; i++) sum += arr[i]; // initialize start as 0 pages // and end as total pages int start = 0, end = (int)sum; int result = int.MaxValue; // traverse until start <= end while (start <= end) { // check if it is possible to // distribute books by using // mid as current minimum int mid = (start + end) / 2; if (isPossible(arr, n, m, mid)) { // update result to current distribution // as it's the best we have found till now. result = mid; // as we are finding minimum and // books are sorted so reduce // end = mid -1 that means end = mid - 1; } else // if not possible means pages // should be increased so update // start = mid + 1 start = mid + 1; } // at-last return // minimum no. of pages return result;} // Drivers codestatic public void Main (){ //Number of pages in booksint []arr = {12, 34, 67, 90};int n = arr.Length;int m = 2; // No. of students Console.WriteLine("Minimum number of pages = " + findPages(arr, n, m));}} // This code is contributed by anuj_67.
<?php// PHP program for optimal allocation// of pages // Utility function to check if current// minimum value is feasible or not. function isPossible($arr, $n, $m, $curr_min){ $studentsRequired = 1; $curr_sum = 0; // iterate over all books for ( $i = 0; $i < $n; $i++) { // check if current number of pages // are greater than curr_min that // means we will get the result // after mid no. of pages if ($arr[$i] > $curr_min) return false; // count how many students are // required to distribute // curr_min pages if ($curr_sum + $arr[$i] > $curr_min) { // increment student count $studentsRequired++; // update curr_sum $curr_sum = $arr[$i]; // if students required becomes // greater than given no. of // students, return false if ($studentsRequired > $m) return false; } // else update curr_sum else $curr_sum += $arr[$i]; } return true;} // function to find minimum pagesfunction findPages($arr, $n, $m){ $sum = 0; // return -1 if no. of books is // less than no. of students if ($n < $m) return -1; // Count total number of pages for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // initialize start as 0 pages // and end as total pages $start = 0; $end = $sum; $result = PHP_INT_MAX; // traverse until start <= end while ($start <= $end) { // check if it is possible to // distribute books by using // mid as current minimum $mid = (int)($start + $end) / 2; if (isPossible($arr, $n, $m, $mid)) { // update result to current distribution // as it's the best we have found till now $result = $mid; // as we are finding minimum and // books are sorted so reduce // end = mid -1 that means $end = $mid - 1; } else // if not possible means pages // should be increased so update // start = mid + 1 $start = $mid + 1; } // at-last return minimum // no. of pages return $result;} // Driver code // Number of pages in books$arr = array(12, 34, 67, 90);$n = count($arr);$m = 2; // No. of students echo "Minimum number of pages = ", findPages($arr, $n, $m), "\n"; // This code is contributed by Sach_Code?>
<script>// Javascript program for optimal allocation of pages // Utility method to check if current minimum value // is feasible or not.function isPossible(arr,n,m,curr_min){ let studentsRequired = 1; let curr_sum = 0; // iterate over all books for (let i = 0; i < n; i++) { // check if current number of pages are greater // than curr_min that means we will get the result // after mid no. of pages if (arr[i] > curr_min) return false; // count how many students are required // to distribute curr_min pages if (curr_sum + arr[i] > curr_min) { // increment student count studentsRequired++; // update curr_sum curr_sum = arr[i]; // if students required becomes greater // than given no. of students,return false if (studentsRequired > m) return false; } // else update curr_sum else curr_sum += arr[i]; } return true;} // method to find minimum pagesfunction findPages(arr,n,m){ let sum = 0; // return -1 if no. of books is less than // no. of students if (n < m) return -1; // Count total number of pages for (let i = 0; i < n; i++) sum += arr[i]; // initialize start as 0 pages and end as // total pages let start = 0, end = sum; let result = Number.MAX_VALUE; // traverse until start <= end while (start <= end) { // check if it is possible to distribute // books by using mid as current minimum let mid =Math.floor( (start + end) / 2); if (isPossible(arr, n, m, mid)) { // if yes then find the minimum distribution result = Math.min(result, mid); // as we are finding minimum and books // are sorted so reduce end = mid -1 // that means end = mid - 1; } else // if not possible means pages should be // increased so update start = mid + 1 start = mid + 1; } // at-last return minimum no. of pages return result;} // Driver Methodlet arr=[12, 34, 67, 90];let m = 2; //No. of studentsdocument.write("Minimum number of pages = " + findPages(arr, arr.length, m)); // This code is contributed by patel2127</script>
Output :
Minimum number of pages = 113
Time Complexity: O(N*log (M – max)), where N is the number of different books , max denotes the maximum number of pages from all the books and M denotes the sum of number of pages of all different booksAuxiliary Space: O(1)
This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
Sach_Code
mohit kumar 29
patel2127
smack
pushpeshrajdx01
adityakumar129
anshulpro27
Binary Search
Google
Divide and Conquer
Searching
Google
Searching
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 352,
"s": 52,
"text": "Given number of pages in n different books and m students. The books are arranged in ascending order of number of pages. Every student is assigned to read some consecutive books. The task is to assign books in such a way that the maximum number of pages assigned to a student is minimum. Example : "
},
{
"code": null,
"e": 908,
"s": 352,
"text": "Input : pages[] = {12, 34, 67, 90} , m = 2\nOutput : 113\nExplanation:\nThere are 2 number of students. Books can be distributed \nin following fashion : \n 1) [12] and [34, 67, 90]\n Max number of pages is allocated to student \n '2' with 34 + 67 + 90 = 191 pages\n 2) [12, 34] and [67, 90]\n Max number of pages is allocated to student\n '2' with 67 + 90 = 157 pages \n 3) [12, 34, 67] and [90]\n Max number of pages is allocated to student \n '1' with 12 + 34 + 67 = 113 pages\n\nOf the 3 cases, Option 3 has the minimum pages = 113. "
},
{
"code": null,
"e": 1680,
"s": 908,
"text": "The idea is to use Binary Search. We fix a value for the number of pages as mid of current minimum and maximum. We initialize minimum and maximum as 0 and sum-of-all-pages respectively. If a current mid can be a solution, then we search on the lower half, else we search in higher half.Now the question arises, how to check if a mid value is feasible or not? Basically, we need to check if we can assign pages to all students in a way that the maximum number doesn’t exceed current value. To do this, we sequentially assign pages to every student while the current number of assigned pages doesn’t exceed the value. In this process, if the number of students becomes more than m, then the solution is not feasible. Else feasible.Below is an implementation of above idea. "
},
{
"code": null,
"e": 1684,
"s": 1680,
"text": "C++"
},
{
"code": null,
"e": 1686,
"s": 1684,
"text": "C"
},
{
"code": null,
"e": 1691,
"s": 1686,
"text": "Java"
},
{
"code": null,
"e": 1699,
"s": 1691,
"text": "Python3"
},
{
"code": null,
"e": 1702,
"s": 1699,
"text": "C#"
},
{
"code": null,
"e": 1706,
"s": 1702,
"text": "PHP"
},
{
"code": null,
"e": 1717,
"s": 1706,
"text": "Javascript"
},
{
"code": "// C++ program for optimal allocation of pages#include <bits/stdc++.h>using namespace std; // Utility function to check if current minimum value// is feasible or not.bool isPossible(int arr[], int n, int m, int curr_min){ int studentsRequired = 1; int curr_sum = 0; // iterate over all books for (int i = 0; i < n; i++) { // check if current number of pages are greater // than curr_min that means we will get the result // after mid no. of pages if (arr[i] > curr_min) return false; // count how many students are required // to distribute curr_min pages if (curr_sum + arr[i] > curr_min) { // increment student count studentsRequired++; // update curr_sum curr_sum = arr[i]; // if students required becomes greater // than given no. of students,return false if (studentsRequired > m) return false; } // else update curr_sum else curr_sum += arr[i]; } return true;} // function to find minimum pagesint findPages(int arr[], int n, int m){ long long sum = 0; // return -1 if no. of books is less than // no. of students if (n < m) return -1; // Count total number of pages for (int i = 0; i < n; i++) sum += arr[i]; // initialize start as 0 pages and end as // total pages int start = 0, end = sum; int result = INT_MAX; // traverse until start <= end while (start <= end) { // check if it is possible to distribute // books by using mid as current minimum int mid = (start + end) / 2; if (isPossible(arr, n, m, mid)) { // update result to current distribution // as it's the best we have found till now. result = mid; // as we are finding minimum and books // are sorted so reduce end = mid -1 // that means end = mid - 1; } else // if not possible means pages should be // increased so update start = mid + 1 start = mid + 1; } // at-last return minimum no. of pages return result;} // Drivers codeint main(){ // Number of pages in books int arr[] = { 12, 34, 67, 90 }; int n = sizeof arr / sizeof arr[0]; int m = 2; // No. of students cout << \"Minimum number of pages = \" << findPages(arr, n, m) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 4250,
"s": 1717,
"text": null
},
{
"code": "// C program for optimal allocation of pages#include <limits.h>#include <stdbool.h>#include <stdio.h> // Utility function to check if current minimum value// is feasible or not.bool isPossible(int arr[], int n, int m, int curr_min){ int studentsRequired = 1; int curr_sum = 0; // iterate over all books for (int i = 0; i < n; i++) { // check if current number of pages are greater // than curr_min that means we will get the result // after mid no. of pages if (arr[i] > curr_min) return false; // count how many students are required // to distribute curr_min pages if (curr_sum + arr[i] > curr_min) { // increment student count studentsRequired++; // update curr_sum curr_sum = arr[i]; // if students required becomes greater // than given no. of students,return false if (studentsRequired > m) return false; } // else update curr_sum else curr_sum += arr[i]; } return true;} // function to find minimum pagesint findPages(int arr[], int n, int m){ long long sum = 0; // return -1 if no. of books is less than // no. of students if (n < m) return -1; // Count total number of pages for (int i = 0; i < n; i++) sum += arr[i]; // initialize start as 0 pages and end as // total pages int start = 0, end = sum; int result = INT_MAX; // traverse until start <= end while (start <= end) { // check if it is possible to distribute // books by using mid as current minimum int mid = (start + end) / 2; if (isPossible(arr, n, m, mid)) { // update result to current distribution // as it's the best we have found till now. result = mid; // as we are finding minimum and books // are sorted so reduce end = mid -1 // that means end = mid - 1; } else // if not possible means pages should be // increased so update start = mid + 1 start = mid + 1; } // at-last return minimum no. of pages return result;} // Drivers codeint main(){ // Number of pages in books int arr[] = { 12, 34, 67, 90 }; int n = sizeof arr / sizeof arr[0]; int m = 2; // No. of students printf(\"Minimum number of pages = %d\\n\", findPages(arr, n, m)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 6790,
"s": 4250,
"text": null
},
{
"code": "// Java program for optimal allocation of pages public class GFG{ // Utility method to check if current minimum value // is feasible or not. static boolean isPossible(int arr[], int n, int m, int curr_min) { int studentsRequired = 1; int curr_sum = 0; // iterate over all books for(int i=0;i<n;i++) { curr_sum += arr[i]; if(curr_sum > curr_min) { studentsRequired++ ; // increment student count curr_sum = arr[i] ; // update curr_sum } } return studentsRequired <= m; } // method to find minimum pages static int findPages(int arr[], int n, int m) { int sum = 0; // return -1 if no. of books is less than // no. of students if (n < m) return -1; // Count total number of pages for (int i = 0; i < n; i++) sum += arr[i]; // initialize start as arr[n-1] pages(minimum answer possible) and end as // total pages(maximum answer possible) int start = arr[n-1], end = sum; int result = Integer.MAX_VALUE; // traverse until start <= end while (start <= end) { // check if it is possible to distribute // books by using mid is current minimum int mid = start + (end - start)/2; if (isPossible(arr, n, m, mid)) { // update result to current distribution // as it's the best we have found till now. result = mid; // as we are finding minimum so, end = mid - 1; } else // if not possible, means pages should be // increased ,so update start = mid + 1 start = mid + 1; } // at-last return minimum no. of pages return result; } // Driver Method public static void main(String[] args) { int arr[] = {12, 34, 67, 90}; //Number of pages in books int m = 2; //No. of students System.out.println(\"Minimum number of pages = \" + findPages(arr, arr.length, m)); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 9116,
"s": 6790,
"text": null
},
{
"code": "# Python3 program for optimal allocation of pages # Utility function to check if# current minimum value is feasible or not.def isPossible(arr, n, m, curr_min): studentsRequired = 1 curr_sum = 0 # iterate over all books for i in range(n): # check if current number of pages are # greater than curr_min that means # we will get the result after # mid no. of pages if (arr[i] > curr_min): return False # count how many students are required # to distribute curr_min pages if (curr_sum + arr[i] > curr_min): # increment student count studentsRequired += 1 # update curr_sum curr_sum = arr[i] # if students required becomes greater # than given no. of students, return False if (studentsRequired > m): return False # else update curr_sum else: curr_sum += arr[i] return True # function to find minimum pagesdef findPages(arr, n, m): sum = 0 # return -1 if no. of books is # less than no. of students if (n < m): return -1 # Count total number of pages for i in range(n): sum += arr[i] # initialize start as 0 pages and # end as total pages start, end = 0, sum result = 10**9 # traverse until start <= end while (start <= end): # check if it is possible to distribute # books by using mid as current minimum mid = (start + end) // 2 if (isPossible(arr, n, m, mid)): # update result to current distribution # as it's the best we have found till now. result = mid # as we are finding minimum and books # are sorted so reduce end = mid -1 # that means end = mid - 1 else: # if not possible means pages should be # increased so update start = mid + 1 start = mid + 1 # at-last return minimum no. of pages return result # Driver Code # Number of pages in booksarr = [12, 34, 67, 90]n = len(arr)m = 2 # No. of students print(\"Minimum number of pages = \", findPages(arr, n, m)) # This code is contributed by Mohit Kumar",
"e": 11358,
"s": 9116,
"text": null
},
{
"code": "// C# program for optimal// allocation of pagesusing System; class GFG{ // Utility function to check// if current minimum value// is feasible or not.static bool isPossible(int []arr, int n, int m, int curr_min){ int studentsRequired = 1; int curr_sum = 0; // iterate over all books for (int i = 0; i < n; i++) { // check if current number of // pages are greater than curr_min // that means we will get the // result after mid no. of pages if (arr[i] > curr_min) return false; // count how many students // are required to distribute // curr_min pages if (curr_sum + arr[i] > curr_min) { // increment student count studentsRequired++; // update curr_sum curr_sum = arr[i]; // if students required becomes // greater than given no. of // students, return false if (studentsRequired > m) return false; } // else update curr_sum else curr_sum += arr[i]; } return true;} // function to find minimum pagesstatic int findPages(int []arr, int n, int m){ long sum = 0; // return -1 if no. of books // is less than no. of students if (n < m) return -1; // Count total number of pages for (int i = 0; i < n; i++) sum += arr[i]; // initialize start as 0 pages // and end as total pages int start = 0, end = (int)sum; int result = int.MaxValue; // traverse until start <= end while (start <= end) { // check if it is possible to // distribute books by using // mid as current minimum int mid = (start + end) / 2; if (isPossible(arr, n, m, mid)) { // update result to current distribution // as it's the best we have found till now. result = mid; // as we are finding minimum and // books are sorted so reduce // end = mid -1 that means end = mid - 1; } else // if not possible means pages // should be increased so update // start = mid + 1 start = mid + 1; } // at-last return // minimum no. of pages return result;} // Drivers codestatic public void Main (){ //Number of pages in booksint []arr = {12, 34, 67, 90};int n = arr.Length;int m = 2; // No. of students Console.WriteLine(\"Minimum number of pages = \" + findPages(arr, n, m));}} // This code is contributed by anuj_67.",
"e": 13991,
"s": 11358,
"text": null
},
{
"code": "<?php// PHP program for optimal allocation// of pages // Utility function to check if current// minimum value is feasible or not. function isPossible($arr, $n, $m, $curr_min){ $studentsRequired = 1; $curr_sum = 0; // iterate over all books for ( $i = 0; $i < $n; $i++) { // check if current number of pages // are greater than curr_min that // means we will get the result // after mid no. of pages if ($arr[$i] > $curr_min) return false; // count how many students are // required to distribute // curr_min pages if ($curr_sum + $arr[$i] > $curr_min) { // increment student count $studentsRequired++; // update curr_sum $curr_sum = $arr[$i]; // if students required becomes // greater than given no. of // students, return false if ($studentsRequired > $m) return false; } // else update curr_sum else $curr_sum += $arr[$i]; } return true;} // function to find minimum pagesfunction findPages($arr, $n, $m){ $sum = 0; // return -1 if no. of books is // less than no. of students if ($n < $m) return -1; // Count total number of pages for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // initialize start as 0 pages // and end as total pages $start = 0; $end = $sum; $result = PHP_INT_MAX; // traverse until start <= end while ($start <= $end) { // check if it is possible to // distribute books by using // mid as current minimum $mid = (int)($start + $end) / 2; if (isPossible($arr, $n, $m, $mid)) { // update result to current distribution // as it's the best we have found till now $result = $mid; // as we are finding minimum and // books are sorted so reduce // end = mid -1 that means $end = $mid - 1; } else // if not possible means pages // should be increased so update // start = mid + 1 $start = $mid + 1; } // at-last return minimum // no. of pages return $result;} // Driver code // Number of pages in books$arr = array(12, 34, 67, 90);$n = count($arr);$m = 2; // No. of students echo \"Minimum number of pages = \", findPages($arr, $n, $m), \"\\n\"; // This code is contributed by Sach_Code?>",
"e": 16508,
"s": 13991,
"text": null
},
{
"code": "<script>// Javascript program for optimal allocation of pages // Utility method to check if current minimum value // is feasible or not.function isPossible(arr,n,m,curr_min){ let studentsRequired = 1; let curr_sum = 0; // iterate over all books for (let i = 0; i < n; i++) { // check if current number of pages are greater // than curr_min that means we will get the result // after mid no. of pages if (arr[i] > curr_min) return false; // count how many students are required // to distribute curr_min pages if (curr_sum + arr[i] > curr_min) { // increment student count studentsRequired++; // update curr_sum curr_sum = arr[i]; // if students required becomes greater // than given no. of students,return false if (studentsRequired > m) return false; } // else update curr_sum else curr_sum += arr[i]; } return true;} // method to find minimum pagesfunction findPages(arr,n,m){ let sum = 0; // return -1 if no. of books is less than // no. of students if (n < m) return -1; // Count total number of pages for (let i = 0; i < n; i++) sum += arr[i]; // initialize start as 0 pages and end as // total pages let start = 0, end = sum; let result = Number.MAX_VALUE; // traverse until start <= end while (start <= end) { // check if it is possible to distribute // books by using mid as current minimum let mid =Math.floor( (start + end) / 2); if (isPossible(arr, n, m, mid)) { // if yes then find the minimum distribution result = Math.min(result, mid); // as we are finding minimum and books // are sorted so reduce end = mid -1 // that means end = mid - 1; } else // if not possible means pages should be // increased so update start = mid + 1 start = mid + 1; } // at-last return minimum no. of pages return result;} // Driver Methodlet arr=[12, 34, 67, 90];let m = 2; //No. of studentsdocument.write(\"Minimum number of pages = \" + findPages(arr, arr.length, m)); // This code is contributed by patel2127</script>",
"e": 18913,
"s": 16508,
"text": null
},
{
"code": null,
"e": 18924,
"s": 18913,
"text": "Output : "
},
{
"code": null,
"e": 18954,
"s": 18924,
"text": "Minimum number of pages = 113"
},
{
"code": null,
"e": 19178,
"s": 18954,
"text": "Time Complexity: O(N*log (M – max)), where N is the number of different books , max denotes the maximum number of pages from all the books and M denotes the sum of number of pages of all different booksAuxiliary Space: O(1)"
},
{
"code": null,
"e": 19607,
"s": 19178,
"text": "This article is contributed by Sahil Chhabra (akku). 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": 19612,
"s": 19607,
"text": "vt_m"
},
{
"code": null,
"e": 19622,
"s": 19612,
"text": "Sach_Code"
},
{
"code": null,
"e": 19637,
"s": 19622,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 19647,
"s": 19637,
"text": "patel2127"
},
{
"code": null,
"e": 19653,
"s": 19647,
"text": "smack"
},
{
"code": null,
"e": 19669,
"s": 19653,
"text": "pushpeshrajdx01"
},
{
"code": null,
"e": 19684,
"s": 19669,
"text": "adityakumar129"
},
{
"code": null,
"e": 19696,
"s": 19684,
"text": "anshulpro27"
},
{
"code": null,
"e": 19710,
"s": 19696,
"text": "Binary Search"
},
{
"code": null,
"e": 19717,
"s": 19710,
"text": "Google"
},
{
"code": null,
"e": 19736,
"s": 19717,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 19746,
"s": 19736,
"text": "Searching"
},
{
"code": null,
"e": 19753,
"s": 19746,
"text": "Google"
},
{
"code": null,
"e": 19763,
"s": 19753,
"text": "Searching"
},
{
"code": null,
"e": 19782,
"s": 19763,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 19796,
"s": 19782,
"text": "Binary Search"
}
] |
Python NLTK | nltk.tokenize.SpaceTokenizer() | 07 Jun, 2019
With the help of nltk.tokenize.SpaceTokenizer() method, we are able to extract the tokens from string of words on the basis of space between them by using tokenize.SpaceTokenizer() method.
Syntax : tokenize.SpaceTokenizer()Return : Return the tokens of words.
Example #1 :In this example we can see that by using tokenize.SpaceTokenizer() method, we are able to extract the tokens from stream to words having space between them.
# import SpaceTokenizer() method from nltkfrom nltk.tokenize import SpaceTokenizer # Create a reference variable for Class SpaceTokenizertk = SpaceTokenizer() # Create a string inputgfg = "Geeksfor Geeks.. .$$&* \nis\t for geeks" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)
Output :
[‘Geeksfor’, ‘Geeks..’, ‘.$$&*’, ‘\nis\t’, ‘for’, ‘geeks’]
Example #2 :
# import SpaceTokenizer() method from nltkfrom nltk.tokenize import SpaceTokenizer # Create a reference variable for Class SpaceTokenizertk = SpaceTokenizer() # Create a string inputgfg = "The price\t of burger \nin BurgerKing is Rs.36.\n" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)
Output :
[‘The’, ‘price\t’, ‘of’, ‘burger’, ‘\nin’, ‘BurgerKing’, ‘is’, ‘Rs.36.\n’]
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 217,
"s": 28,
"text": "With the help of nltk.tokenize.SpaceTokenizer() method, we are able to extract the tokens from string of words on the basis of space between them by using tokenize.SpaceTokenizer() method."
},
{
"code": null,
"e": 288,
"s": 217,
"text": "Syntax : tokenize.SpaceTokenizer()Return : Return the tokens of words."
},
{
"code": null,
"e": 457,
"s": 288,
"text": "Example #1 :In this example we can see that by using tokenize.SpaceTokenizer() method, we are able to extract the tokens from stream to words having space between them."
},
{
"code": "# import SpaceTokenizer() method from nltkfrom nltk.tokenize import SpaceTokenizer # Create a reference variable for Class SpaceTokenizertk = SpaceTokenizer() # Create a string inputgfg = \"Geeksfor Geeks.. .$$&* \\nis\\t for geeks\" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)",
"e": 760,
"s": 457,
"text": null
},
{
"code": null,
"e": 769,
"s": 760,
"text": "Output :"
},
{
"code": null,
"e": 828,
"s": 769,
"text": "[‘Geeksfor’, ‘Geeks..’, ‘.$$&*’, ‘\\nis\\t’, ‘for’, ‘geeks’]"
},
{
"code": null,
"e": 841,
"s": 828,
"text": "Example #2 :"
},
{
"code": "# import SpaceTokenizer() method from nltkfrom nltk.tokenize import SpaceTokenizer # Create a reference variable for Class SpaceTokenizertk = SpaceTokenizer() # Create a string inputgfg = \"The price\\t of burger \\nin BurgerKing is Rs.36.\\n\" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)",
"e": 1154,
"s": 841,
"text": null
},
{
"code": null,
"e": 1163,
"s": 1154,
"text": "Output :"
},
{
"code": null,
"e": 1238,
"s": 1163,
"text": "[‘The’, ‘price\\t’, ‘of’, ‘burger’, ‘\\nin’, ‘BurgerKing’, ‘is’, ‘Rs.36.\\n’]"
},
{
"code": null,
"e": 1250,
"s": 1238,
"text": "Python-nltk"
},
{
"code": null,
"e": 1257,
"s": 1250,
"text": "Python"
},
{
"code": null,
"e": 1355,
"s": 1257,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1387,
"s": 1355,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1414,
"s": 1387,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1445,
"s": 1414,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1466,
"s": 1445,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1545,
"s": 1489,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1587,
"s": 1545,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1629,
"s": 1587,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1668,
"s": 1629,
"text": "Python | Get unique values from a list"
}
] |
Python – Multiple Column Sort in Tuples | 06 Jul, 2021
Sometimes, while working with records, we can have a problem in which we need to perform sort operation on one of the columns, and on other column, if equal elements, opposite sort. This kind of problem can occur as application in many domains such as web development. Lets discuss certain ways in which this problem can be solved.
Input : test_list = [(6, 7), (6, 5), (6, 4), (7, 10)] Output : [(7, 10), (6, 4), (6, 5), (6, 7)]
Input : test_list = [(10, 7), (8, 5)] Output : [(10, 7), (8, 5)]
Method #1 : Using sorted() + lambda The combination of above functions can offer one of the ways to solve this problem. In this, we perform sort using sorted() and order and column manipulation is handled by lambda function.
Python3
# Python3 code to demonstrate working of# Multiple Column Sort in Tuples# Using sorted() + lambda # initializing listtest_list = [(6, 7), (6, 5), (1, 4), (8, 10)] # printing original listprint("The original list is : " + str(test_list)) # Multiple Column Sort in Tuples# Using sorted() + lambdares = sorted(test_list, key = lambda sub: (-sub[0], sub[1])) # printing resultprint("The sorted records : " + str(res))
The original list is : [(6, 7), (6, 5), (1, 4), (8, 10)]
The sorted records : [(8, 10), (6, 5), (6, 7), (1, 4)]
Method #2 : Using itemgetter() + sorted() This is yet another way in which this task can be performed. In this, we perform the task required for lambda function using itemgetter().
Python3
# Python3 code to demonstrate working of# Multiple Column Sort in Tuples# Using itemgetter() + sorted()from operator import itemgetter # initializing listtest_list = [(6, 7), (6, 5), (1, 4), (8, 10)] # printing original listprint("The original list is : " + str(test_list)) # Multiple Column Sort in Tuples# Using itemgetter() + sorted()res = sorted(test_list, key = itemgetter(1))res = sorted(res, key = itemgetter(0), reverse = True) # printing resultprint("The sorted records : " + str(res))
The original list is : [(6, 7), (6, 5), (1, 4), (8, 10)]
The sorted records : [(8, 10), (6, 5), (6, 7), (1, 4)]
arorakashish0911
Python List-of-Tuples
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 360,
"s": 28,
"text": "Sometimes, while working with records, we can have a problem in which we need to perform sort operation on one of the columns, and on other column, if equal elements, opposite sort. This kind of problem can occur as application in many domains such as web development. Lets discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 457,
"s": 360,
"text": "Input : test_list = [(6, 7), (6, 5), (6, 4), (7, 10)] Output : [(7, 10), (6, 4), (6, 5), (6, 7)]"
},
{
"code": null,
"e": 524,
"s": 457,
"text": "Input : test_list = [(10, 7), (8, 5)] Output : [(10, 7), (8, 5)] "
},
{
"code": null,
"e": 749,
"s": 524,
"text": "Method #1 : Using sorted() + lambda The combination of above functions can offer one of the ways to solve this problem. In this, we perform sort using sorted() and order and column manipulation is handled by lambda function."
},
{
"code": null,
"e": 757,
"s": 749,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Multiple Column Sort in Tuples# Using sorted() + lambda # initializing listtest_list = [(6, 7), (6, 5), (1, 4), (8, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # Multiple Column Sort in Tuples# Using sorted() + lambdares = sorted(test_list, key = lambda sub: (-sub[0], sub[1])) # printing resultprint(\"The sorted records : \" + str(res))",
"e": 1171,
"s": 757,
"text": null
},
{
"code": null,
"e": 1283,
"s": 1171,
"text": "The original list is : [(6, 7), (6, 5), (1, 4), (8, 10)]\nThe sorted records : [(8, 10), (6, 5), (6, 7), (1, 4)]"
},
{
"code": null,
"e": 1467,
"s": 1285,
"text": " Method #2 : Using itemgetter() + sorted() This is yet another way in which this task can be performed. In this, we perform the task required for lambda function using itemgetter()."
},
{
"code": null,
"e": 1475,
"s": 1467,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Multiple Column Sort in Tuples# Using itemgetter() + sorted()from operator import itemgetter # initializing listtest_list = [(6, 7), (6, 5), (1, 4), (8, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # Multiple Column Sort in Tuples# Using itemgetter() + sorted()res = sorted(test_list, key = itemgetter(1))res = sorted(res, key = itemgetter(0), reverse = True) # printing resultprint(\"The sorted records : \" + str(res))",
"e": 1970,
"s": 1475,
"text": null
},
{
"code": null,
"e": 2082,
"s": 1970,
"text": "The original list is : [(6, 7), (6, 5), (1, 4), (8, 10)]\nThe sorted records : [(8, 10), (6, 5), (6, 7), (1, 4)]"
},
{
"code": null,
"e": 2101,
"s": 2084,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2123,
"s": 2101,
"text": "Python List-of-Tuples"
},
{
"code": null,
"e": 2144,
"s": 2123,
"text": "Python list-programs"
},
{
"code": null,
"e": 2151,
"s": 2144,
"text": "Python"
},
{
"code": null,
"e": 2167,
"s": 2151,
"text": "Python Programs"
}
] |
JavaScript Math sin( ) Method | 09 Feb, 2022
Below is the example of the Math sin() Method.
Example:<script type="text/javascript"> document.write("When zero is passed as a parameter: " + Math.sin(0));</script>
<script type="text/javascript"> document.write("When zero is passed as a parameter: " + Math.sin(0));</script>
Output:When zero is passed as a parameter: 0
When zero is passed as a parameter: 0
The Math.sin() method in Javascript is used to return the sine of a number. The Math.sin() method returns a numeric value between -1 and 1, which represents the sine of the angle given in radians.
The sin() is a static method of Math, therefore, it is always used as Math.sin(), rather than as a method of a Math object created.
Syntax:
Math.sin(value)
Parameters: This method accepts a single parameter as mentioned above and described below:value which is a number given in radians.
Return Value: The Math.sin() method returns the sine of the given numbers.
Below examples illustrates the Math sin() method in JavaScript:
Example 1:Input : Math.sin(0)
Output : 0
Input : Math.sin(0)
Output : 0
Example 1:Input : Math.sin(1)
Output : 0.8414709848078965
Input : Math.sin(1)
Output : 0.8414709848078965
Example 1:Input : Math.sin(Math.PI / 2)
Output : 1
Input : Math.sin(Math.PI / 2)
Output : 1
More codes for the above method are as follows:Program 1: When 1 is passed as a parameter.
<script type="text/javascript"> document.write("Result : " + Math.sin(1));</script>
Output:
Result : 0.8414709848078965
Program 2: When PI is passed as a parameter.
<script type="text/javascript"> document.write("Result : " + Math.sin(Math.PI / 2));</script>
Output:
Result : 1
Supported Browsers:
Google Chrome 1 and above
Internet Explorer 3 and above
Firefox 1 and above
Opera 3 and above
Safari 1 and above
ysachin2314
javascript-math
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 75,
"s": 28,
"text": "Below is the example of the Math sin() Method."
},
{
"code": null,
"e": 221,
"s": 75,
"text": "Example:<script type=\"text/javascript\"> document.write(\"When zero is passed as a parameter: \" + Math.sin(0));</script>"
},
{
"code": "<script type=\"text/javascript\"> document.write(\"When zero is passed as a parameter: \" + Math.sin(0));</script>",
"e": 359,
"s": 221,
"text": null
},
{
"code": null,
"e": 405,
"s": 359,
"text": "Output:When zero is passed as a parameter: 0"
},
{
"code": null,
"e": 444,
"s": 405,
"text": "When zero is passed as a parameter: 0"
},
{
"code": null,
"e": 641,
"s": 444,
"text": "The Math.sin() method in Javascript is used to return the sine of a number. The Math.sin() method returns a numeric value between -1 and 1, which represents the sine of the angle given in radians."
},
{
"code": null,
"e": 773,
"s": 641,
"text": "The sin() is a static method of Math, therefore, it is always used as Math.sin(), rather than as a method of a Math object created."
},
{
"code": null,
"e": 781,
"s": 773,
"text": "Syntax:"
},
{
"code": null,
"e": 797,
"s": 781,
"text": "Math.sin(value)"
},
{
"code": null,
"e": 929,
"s": 797,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:value which is a number given in radians."
},
{
"code": null,
"e": 1004,
"s": 929,
"text": "Return Value: The Math.sin() method returns the sine of the given numbers."
},
{
"code": null,
"e": 1068,
"s": 1004,
"text": "Below examples illustrates the Math sin() method in JavaScript:"
},
{
"code": null,
"e": 1109,
"s": 1068,
"text": "Example 1:Input : Math.sin(0)\nOutput : 0"
},
{
"code": null,
"e": 1140,
"s": 1109,
"text": "Input : Math.sin(0)\nOutput : 0"
},
{
"code": null,
"e": 1198,
"s": 1140,
"text": "Example 1:Input : Math.sin(1)\nOutput : 0.8414709848078965"
},
{
"code": null,
"e": 1246,
"s": 1198,
"text": "Input : Math.sin(1)\nOutput : 0.8414709848078965"
},
{
"code": null,
"e": 1297,
"s": 1246,
"text": "Example 1:Input : Math.sin(Math.PI / 2)\nOutput : 1"
},
{
"code": null,
"e": 1338,
"s": 1297,
"text": "Input : Math.sin(Math.PI / 2)\nOutput : 1"
},
{
"code": null,
"e": 1429,
"s": 1338,
"text": "More codes for the above method are as follows:Program 1: When 1 is passed as a parameter."
},
{
"code": "<script type=\"text/javascript\"> document.write(\"Result : \" + Math.sin(1));</script>",
"e": 1521,
"s": 1429,
"text": null
},
{
"code": null,
"e": 1529,
"s": 1521,
"text": "Output:"
},
{
"code": null,
"e": 1557,
"s": 1529,
"text": "Result : 0.8414709848078965"
},
{
"code": null,
"e": 1602,
"s": 1557,
"text": "Program 2: When PI is passed as a parameter."
},
{
"code": "<script type=\"text/javascript\"> document.write(\"Result : \" + Math.sin(Math.PI / 2));</script>",
"e": 1704,
"s": 1602,
"text": null
},
{
"code": null,
"e": 1712,
"s": 1704,
"text": "Output:"
},
{
"code": null,
"e": 1723,
"s": 1712,
"text": "Result : 1"
},
{
"code": null,
"e": 1743,
"s": 1723,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 1769,
"s": 1743,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 1799,
"s": 1769,
"text": "Internet Explorer 3 and above"
},
{
"code": null,
"e": 1819,
"s": 1799,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 1837,
"s": 1819,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 1856,
"s": 1837,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 1868,
"s": 1856,
"text": "ysachin2314"
},
{
"code": null,
"e": 1884,
"s": 1868,
"text": "javascript-math"
},
{
"code": null,
"e": 1903,
"s": 1884,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 1914,
"s": 1903,
"text": "JavaScript"
},
{
"code": null,
"e": 1931,
"s": 1914,
"text": "Web Technologies"
}
] |
Program to print a Hollow Triangle inside a Triangle | 24 Nov, 2021
Given a number N(≥ 8), the task is to print a Hollow Triangle inside a Triangle pattern.Example:
Input: N = 9
Output:
*
* *
* *
* * *
* * * * *
* *
* *
* *
* * * * * * * * * * * * * * * * *
Approach:
Let i be the index for rows and j be the index for columns. Then:
For sides of outer triangle: If the index of column(j) is equals to (N – i + 1) or (N + i – 1), then ‘*’ is printed for equal sides of outer triangle.
if(j == (N - i + 1)
|| j == (N + i - 1) {
print('*')
}
For sides of inner triangle: If the (index of row(i) is less than (N – 4) and greater than (4) and index of column(j) is equals to (N – i + 4) or (N + i + 4), then ‘*’ is printed for equal sides of inner triangle.
if( (i >= 4
&& i <= n - 4)
&& (j == N - i + 4
|| j == N + i - 4) ) {
print('*')
}
For bases of the outer triangle: If the index of row(i) is equal to N, then ‘*’ is printed for the base of outer triangle.
if(i == N) {
print('*')
}
For bases of the inner triangle: If the index of row(i) is equals (N – 4) and the column index(j) must be greater than equals to (N – (N – 2*4)), and j is less than equals to (N + N – 2*4), then ‘*’ is printed for the base of inner triangle.
if( (i == N - 4)
&& (j >= N - (N - 2 * 4) )
&& (j <= n + n - 2 * 4) ) ) {
print('*')
}
Below is the implementation of the above approach:
CPP
Java
Python3
C#
Javascript
// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Function to print the patternvoid printPattern(int n){ int i, j; // Loop for rows for (i = 1; i <= n; i++) { // Loop for column for (j = 1; j < 2 * n; j++) { // For printing equal sides // of outer triangle if (j == (n - i + 1) || j == (n + i - 1)) { cout << "* "; } // For printing equal sides // of inner triangle else if ((i >= 4 && i <= n - 4) && (j == n - i + 4 || j == n + i - 4)) { cout << "* "; } // For printing base // of both triangle else if (i == n || (i == n - 4 && j >= n - (n - 2 * 4) && j <= n + n - 2 * 4)) { cout << "* "; } // For spacing between the triangle else { cout << " " << " "; } } cout << "\n"; }} // Driver Codeint main(){ int N = 9; printPattern(N);}
// Java implementation of the above approachimport java.util.*; class GFG{ // Function to print the patternstatic void printPattern(int n){ int i, j; // Loop for rows for (i = 1; i <= n; i++) { // Loop for column for (j = 1; j < 2 * n; j++) { // For printing equal sides // of outer triangle if (j == (n - i + 1) || j == (n + i - 1)) { System.out.print("* "); } // For printing equal sides // of inner triangle else if ((i >= 4 && i <= n - 4) && (j == n - i + 4 || j == n + i - 4)) { System.out.print("* "); } // For printing base // of both triangle else if (i == n || (i == n - 4 && j >= n - (n - 2 * 4) && j <= n + n - 2 * 4)) { System.out.print("* "); } // For spacing between the triangle else { System.out.print(" " + " "); } } System.out.print("\n"); }} // Driver Codepublic static void main(String[] args){ int N = 9; printPattern(N);}} // This code is contributed by sapnasingh4991
# Python3 implementation of the above approach # Function to print the patterndef printPattern(n): # Loop for rows for i in range(1, n + 1): # Loop for column for j in range(1, 2 * n): # For printing equal sides # of outer triangle if (j == (n - i + 1) or j == (n + i - 1)): print("* ",end="") # For printing equal sides # of inner triangle elif ((i >= 4 and i <= n - 4) and (j == n - i + 4 or j == n + i - 4)): print("* ",end="") # For printing base # of both triangle elif (i == n or (i == n - 4 and j >= n - (n - 2 * 4) and j <= n + n - 2 * 4)): print("* ", end="") # For spacing between the triangle else : print(" "+" ", end="") print() # Driver CodeN = 9 printPattern(N) # This code is contributed by mohit kumar 29
// C# implementation of the above approachusing System; class GFG{ // Function to print the patternstatic void printPattern(int n){ int i, j; // Loop for rows for (i = 1; i <= n; i++) { // Loop for column for (j = 1; j < 2 * n; j++) { // For printing equal sides // of outer triangle if (j == (n - i + 1) || j == (n + i - 1)) { Console.Write("* "); } // For printing equal sides // of inner triangle else if ((i >= 4 && i <= n - 4) && (j == n - i + 4 || j == n + i - 4)) { Console.Write("* "); } // For printing base // of both triangle else if (i == n || (i == n - 4 && j >= n - (n - 2 * 4) && j <= n + n - 2 * 4)) { Console.Write("* "); } // For spacing between the triangle else { Console.Write(" " + " "); } } Console.Write("\n"); }} // Driver Codepublic static void Main(String[] args){ int N = 9; printPattern(N);}} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of the above approach // Function to print the pattern function printPattern(n) { var i, j; // Loop for rows for (i = 1; i <= n; i++) { // Loop for column for (j = 1; j < 2 * n; j++) { // For printing equal sides // of outer triangle if (j == n - i + 1 || j == n + i - 1) { document.write("* "); } // For printing equal sides // of inner triangle else if ( i >= 4 && i <= n - 4 && (j == n - i + 4 || j == n + i - 4) ) { document.write("* "); } // For printing base // of both triangle else if ( i == n || (i == n - 4 && j >= n - (n - 2 * 4) && j <= n + n - 2 * 4) ) { document.write("* "); } // For spacing between the triangle else { document.write(" "); document.write(" "); } } document.write("<br>"); } } // Driver Code var N = 9; printPattern(N); </script>
*
* *
* *
* * *
* * * * *
* *
* *
* *
* * * * * * * * * * * * * * * * *
Time Complexity: O(n2)
Auxiliary Space: O(1)
mohit kumar 29
sapnasingh4991
29AjayKumar
Code_Mech
rdtank
subham348
pattern-printing
Mathematical
Pattern Searching
School Programming
Mathematical
pattern-printing
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 152,
"s": 53,
"text": "Given a number N(≥ 8), the task is to print a Hollow Triangle inside a Triangle pattern.Example: "
},
{
"code": null,
"e": 488,
"s": 152,
"text": "Input: N = 9\nOutput:\n * \n * * \n * * \n * * * \n * * * * * \n * * \n * * \n * * \n* * * * * * * * * * * * * * * * * "
},
{
"code": null,
"e": 502,
"s": 490,
"text": "Approach: "
},
{
"code": null,
"e": 570,
"s": 502,
"text": "Let i be the index for rows and j be the index for columns. Then: "
},
{
"code": null,
"e": 723,
"s": 570,
"text": "For sides of outer triangle: If the index of column(j) is equals to (N – i + 1) or (N + i – 1), then ‘*’ is printed for equal sides of outer triangle. "
},
{
"code": null,
"e": 783,
"s": 723,
"text": "if(j == (N - i + 1)\n || j == (N + i - 1) {\n print('*')\n}"
},
{
"code": null,
"e": 1001,
"s": 785,
"text": "For sides of inner triangle: If the (index of row(i) is less than (N – 4) and greater than (4) and index of column(j) is equals to (N – i + 4) or (N + i + 4), then ‘*’ is printed for equal sides of inner triangle. "
},
{
"code": null,
"e": 1103,
"s": 1001,
"text": "if( (i >= 4 \n && i <= n - 4) \n && (j == N - i + 4 \n || j == N + i - 4) ) {\n print('*')\n}"
},
{
"code": null,
"e": 1230,
"s": 1105,
"text": "For bases of the outer triangle: If the index of row(i) is equal to N, then ‘*’ is printed for the base of outer triangle. "
},
{
"code": null,
"e": 1259,
"s": 1230,
"text": "if(i == N) {\n print('*')\n}"
},
{
"code": null,
"e": 1505,
"s": 1261,
"text": "For bases of the inner triangle: If the index of row(i) is equals (N – 4) and the column index(j) must be greater than equals to (N – (N – 2*4)), and j is less than equals to (N + N – 2*4), then ‘*’ is printed for the base of inner triangle. "
},
{
"code": null,
"e": 1599,
"s": 1505,
"text": "if( (i == N - 4) \n && (j >= N - (N - 2 * 4) ) \n && (j <= n + n - 2 * 4) ) ) {\n print('*')\n}"
},
{
"code": null,
"e": 1654,
"s": 1601,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1658,
"s": 1654,
"text": "CPP"
},
{
"code": null,
"e": 1663,
"s": 1658,
"text": "Java"
},
{
"code": null,
"e": 1671,
"s": 1663,
"text": "Python3"
},
{
"code": null,
"e": 1674,
"s": 1671,
"text": "C#"
},
{
"code": null,
"e": 1685,
"s": 1674,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Function to print the patternvoid printPattern(int n){ int i, j; // Loop for rows for (i = 1; i <= n; i++) { // Loop for column for (j = 1; j < 2 * n; j++) { // For printing equal sides // of outer triangle if (j == (n - i + 1) || j == (n + i - 1)) { cout << \"* \"; } // For printing equal sides // of inner triangle else if ((i >= 4 && i <= n - 4) && (j == n - i + 4 || j == n + i - 4)) { cout << \"* \"; } // For printing base // of both triangle else if (i == n || (i == n - 4 && j >= n - (n - 2 * 4) && j <= n + n - 2 * 4)) { cout << \"* \"; } // For spacing between the triangle else { cout << \" \" << \" \"; } } cout << \"\\n\"; }} // Driver Codeint main(){ int N = 9; printPattern(N);}",
"e": 2887,
"s": 1685,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function to print the patternstatic void printPattern(int n){ int i, j; // Loop for rows for (i = 1; i <= n; i++) { // Loop for column for (j = 1; j < 2 * n; j++) { // For printing equal sides // of outer triangle if (j == (n - i + 1) || j == (n + i - 1)) { System.out.print(\"* \"); } // For printing equal sides // of inner triangle else if ((i >= 4 && i <= n - 4) && (j == n - i + 4 || j == n + i - 4)) { System.out.print(\"* \"); } // For printing base // of both triangle else if (i == n || (i == n - 4 && j >= n - (n - 2 * 4) && j <= n + n - 2 * 4)) { System.out.print(\"* \"); } // For spacing between the triangle else { System.out.print(\" \" + \" \"); } } System.out.print(\"\\n\"); }} // Driver Codepublic static void main(String[] args){ int N = 9; printPattern(N);}} // This code is contributed by sapnasingh4991",
"e": 4217,
"s": 2887,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Function to print the patterndef printPattern(n): # Loop for rows for i in range(1, n + 1): # Loop for column for j in range(1, 2 * n): # For printing equal sides # of outer triangle if (j == (n - i + 1) or j == (n + i - 1)): print(\"* \",end=\"\") # For printing equal sides # of inner triangle elif ((i >= 4 and i <= n - 4) and (j == n - i + 4 or j == n + i - 4)): print(\"* \",end=\"\") # For printing base # of both triangle elif (i == n or (i == n - 4 and j >= n - (n - 2 * 4) and j <= n + n - 2 * 4)): print(\"* \", end=\"\") # For spacing between the triangle else : print(\" \"+\" \", end=\"\") print() # Driver CodeN = 9 printPattern(N) # This code is contributed by mohit kumar 29",
"e": 5278,
"s": 4217,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to print the patternstatic void printPattern(int n){ int i, j; // Loop for rows for (i = 1; i <= n; i++) { // Loop for column for (j = 1; j < 2 * n; j++) { // For printing equal sides // of outer triangle if (j == (n - i + 1) || j == (n + i - 1)) { Console.Write(\"* \"); } // For printing equal sides // of inner triangle else if ((i >= 4 && i <= n - 4) && (j == n - i + 4 || j == n + i - 4)) { Console.Write(\"* \"); } // For printing base // of both triangle else if (i == n || (i == n - 4 && j >= n - (n - 2 * 4) && j <= n + n - 2 * 4)) { Console.Write(\"* \"); } // For spacing between the triangle else { Console.Write(\" \" + \" \"); } } Console.Write(\"\\n\"); }} // Driver Codepublic static void Main(String[] args){ int N = 9; printPattern(N);}} // This code is contributed by 29AjayKumar",
"e": 6594,
"s": 5278,
"text": null
},
{
"code": "<script> // JavaScript implementation of the above approach // Function to print the pattern function printPattern(n) { var i, j; // Loop for rows for (i = 1; i <= n; i++) { // Loop for column for (j = 1; j < 2 * n; j++) { // For printing equal sides // of outer triangle if (j == n - i + 1 || j == n + i - 1) { document.write(\"* \"); } // For printing equal sides // of inner triangle else if ( i >= 4 && i <= n - 4 && (j == n - i + 4 || j == n + i - 4) ) { document.write(\"* \"); } // For printing base // of both triangle else if ( i == n || (i == n - 4 && j >= n - (n - 2 * 4) && j <= n + n - 2 * 4) ) { document.write(\"* \"); } // For spacing between the triangle else { document.write(\" \"); document.write(\" \"); } } document.write(\"<br>\"); } } // Driver Code var N = 9; printPattern(N); </script>",
"e": 7830,
"s": 6594,
"text": null
},
{
"code": null,
"e": 8144,
"s": 7830,
"text": " * \n * * \n * * \n * * * \n * * * * * \n * * \n * * \n * * \n* * * * * * * * * * * * * * * * *"
},
{
"code": null,
"e": 8169,
"s": 8146,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 8191,
"s": 8169,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8206,
"s": 8191,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8221,
"s": 8206,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 8233,
"s": 8221,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8243,
"s": 8233,
"text": "Code_Mech"
},
{
"code": null,
"e": 8250,
"s": 8243,
"text": "rdtank"
},
{
"code": null,
"e": 8260,
"s": 8250,
"text": "subham348"
},
{
"code": null,
"e": 8277,
"s": 8260,
"text": "pattern-printing"
},
{
"code": null,
"e": 8290,
"s": 8277,
"text": "Mathematical"
},
{
"code": null,
"e": 8308,
"s": 8290,
"text": "Pattern Searching"
},
{
"code": null,
"e": 8327,
"s": 8308,
"text": "School Programming"
},
{
"code": null,
"e": 8340,
"s": 8327,
"text": "Mathematical"
},
{
"code": null,
"e": 8357,
"s": 8340,
"text": "pattern-printing"
},
{
"code": null,
"e": 8375,
"s": 8357,
"text": "Pattern Searching"
}
] |
Read JSON file using Python | 07 Jul, 2022
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }.
It’s pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It’s done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
The Deserialization of JSON means the conversion of JSON objects into their respective Python objects. The load()/loads() method is used for it. If you have used JSON data from another program or obtained as a string format of JSON, then it can easily be deserialized with load()/loads(), which is usually used to load from string, otherwise, the root object is in list or dict. See the following table given below.
json.load(): json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.
Syntax:
json.load(file object)
Example: Suppose the JSON file looks like this:
We want to read the content of this file. Below is the implementation.
Python3
# Python program to read# json file import json # Opening JSON filef = open('data.json') # returns JSON object as # a dictionarydata = json.load(f) # Iterating through the json# listfor i in data['emp_details']: print(i) # Closing filef.close()
Output:
json.loads(): If you have a JSON string, you can parse it by using the json.loads() method.json.loads() does not take the file path, but the file contents as a string, using fileobject.read() with json.loads() we can return the content of the file.
Syntax:
json.loads(jsonstring) #for Json string
json.loads(fileobject.read()) #for fileobject
Example: This example shows reading from both string and JSON file. The file shown above is used.
Python3
# Python program to read# json file import json # JSON stringa = '{"name": "Bob", "languages": "English"}' # deserializes into dict # and returns dict.y = json.loads(a) print("JSON string = ", y)print() # JSON filef = open ('data.json', "r") # Reading from filedata = json.loads(f.read()) # Iterating through the json# listfor i in data['emp_details']: print(i) # Closing filef.close()
Output:
kapoorsagar226
nachiket_18
Python-json
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 468,
"s": 52,
"text": "The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. "
},
{
"code": null,
"e": 760,
"s": 468,
"text": "It’s pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It’s done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file. "
},
{
"code": null,
"e": 769,
"s": 760,
"text": "Chapters"
},
{
"code": null,
"e": 796,
"s": 769,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 846,
"s": 796,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 869,
"s": 846,
"text": "captions off, selected"
},
{
"code": null,
"e": 877,
"s": 869,
"text": "English"
},
{
"code": null,
"e": 901,
"s": 877,
"text": "This is a modal window."
},
{
"code": null,
"e": 970,
"s": 901,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 992,
"s": 970,
"text": "End of dialog window."
},
{
"code": null,
"e": 1409,
"s": 992,
"text": "The Deserialization of JSON means the conversion of JSON objects into their respective Python objects. The load()/loads() method is used for it. If you have used JSON data from another program or obtained as a string format of JSON, then it can easily be deserialized with load()/loads(), which is usually used to load from string, otherwise, the root object is in list or dict. See the following table given below. "
},
{
"code": null,
"e": 1552,
"s": 1411,
"text": "json.load(): json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you. "
},
{
"code": null,
"e": 1560,
"s": 1552,
"text": "Syntax:"
},
{
"code": null,
"e": 1583,
"s": 1560,
"text": "json.load(file object)"
},
{
"code": null,
"e": 1631,
"s": 1583,
"text": "Example: Suppose the JSON file looks like this:"
},
{
"code": null,
"e": 1702,
"s": 1631,
"text": "We want to read the content of this file. Below is the implementation."
},
{
"code": null,
"e": 1710,
"s": 1702,
"text": "Python3"
},
{
"code": "# Python program to read# json file import json # Opening JSON filef = open('data.json') # returns JSON object as # a dictionarydata = json.load(f) # Iterating through the json# listfor i in data['emp_details']: print(i) # Closing filef.close()",
"e": 1965,
"s": 1710,
"text": null
},
{
"code": null,
"e": 1973,
"s": 1965,
"text": "Output:"
},
{
"code": null,
"e": 2223,
"s": 1973,
"text": "json.loads(): If you have a JSON string, you can parse it by using the json.loads() method.json.loads() does not take the file path, but the file contents as a string, using fileobject.read() with json.loads() we can return the content of the file. "
},
{
"code": null,
"e": 2231,
"s": 2223,
"text": "Syntax:"
},
{
"code": null,
"e": 2318,
"s": 2231,
"text": "json.loads(jsonstring) #for Json string\n\njson.loads(fileobject.read()) #for fileobject"
},
{
"code": null,
"e": 2416,
"s": 2318,
"text": "Example: This example shows reading from both string and JSON file. The file shown above is used."
},
{
"code": null,
"e": 2424,
"s": 2416,
"text": "Python3"
},
{
"code": "# Python program to read# json file import json # JSON stringa = '{\"name\": \"Bob\", \"languages\": \"English\"}' # deserializes into dict # and returns dict.y = json.loads(a) print(\"JSON string = \", y)print() # JSON filef = open ('data.json', \"r\") # Reading from filedata = json.loads(f.read()) # Iterating through the json# listfor i in data['emp_details']: print(i) # Closing filef.close()",
"e": 2829,
"s": 2424,
"text": null
},
{
"code": null,
"e": 2837,
"s": 2829,
"text": "Output:"
},
{
"code": null,
"e": 2852,
"s": 2837,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 2864,
"s": 2852,
"text": "nachiket_18"
},
{
"code": null,
"e": 2876,
"s": 2864,
"text": "Python-json"
},
{
"code": null,
"e": 2883,
"s": 2876,
"text": "Python"
},
{
"code": null,
"e": 2902,
"s": 2883,
"text": "Technical Scripter"
}
] |
Python – String till Substring | 25 Jun, 2022
Sometimes, more than finding a substring, we might need to get the string that is occurring before the substring has been found. Let’s discuss certain ways in which this task can be performed.
The partition function can be used to perform this task in which we just return the part of the partition occurring before the partition word.
Python3
# Python3 code to demonstrate# String till Substring# using partition() # initializing stringtest_string = "GeeksforGeeks is best for geeks" # initializing split wordspl_word = 'best' # printing original stringprint("The original string : " + str(test_string)) # printing split stringprint("The split string : " + str(spl_word)) # using partition()# String till Substringres = test_string.partition(spl_word)[0] # print resultprint("String before the substring occurrence : " + res)
The original string : GeeksforGeeks is best for geeks
The split string : best
String before the substring occurrence : GeeksforGeeks is
The split function can also be applied to perform this particular task, in this function, we use the power of limiting the split and then print the former string.
Python3
# Python3 code to demonstrate# String till Substring# using split() # initializing stringtest_string = "GeeksforGeeks is best for geeks" # initializing split wordspl_word = 'best' # printing original stringprint("The original string : " + str(test_string)) # printing split stringprint("The split string : " + str(spl_word)) # using split()# String till Substringres = test_string.split(spl_word)[0] # print resultprint("String before the substring occurrence : " + res)
The original string : GeeksforGeeks is best for geeks
The split string : best
String before the substring occurrence : GeeksforGeeks is
Python3
# Python3 code to demonstrate# String till Substring# using find()# you can also use index(0 instead of find() # initializing stringtest_string = "GeeksforGeeks is best for geeks" # initializing substringspl_word = 'best' # printing original stringprint("The original string : " + str(test_string)) # String till Substringx=test_string.find(spl_word)res=test_string[0:x] # print resultprint("String before the substring occurrence : " + res)
The original string : GeeksforGeeks is best for geeks
String before the substring occurrence : GeeksforGeeks is
astro24
kogantibhavya
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Jun, 2022"
},
{
"code": null,
"e": 245,
"s": 52,
"text": "Sometimes, more than finding a substring, we might need to get the string that is occurring before the substring has been found. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 388,
"s": 245,
"text": "The partition function can be used to perform this task in which we just return the part of the partition occurring before the partition word."
},
{
"code": null,
"e": 396,
"s": 388,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# String till Substring# using partition() # initializing stringtest_string = \"GeeksforGeeks is best for geeks\" # initializing split wordspl_word = 'best' # printing original stringprint(\"The original string : \" + str(test_string)) # printing split stringprint(\"The split string : \" + str(spl_word)) # using partition()# String till Substringres = test_string.partition(spl_word)[0] # print resultprint(\"String before the substring occurrence : \" + res)",
"e": 879,
"s": 396,
"text": null
},
{
"code": null,
"e": 1015,
"s": 879,
"text": "The original string : GeeksforGeeks is best for geeks\nThe split string : best\nString before the substring occurrence : GeeksforGeeks is"
},
{
"code": null,
"e": 1181,
"s": 1017,
"text": "The split function can also be applied to perform this particular task, in this function, we use the power of limiting the split and then print the former string. "
},
{
"code": null,
"e": 1189,
"s": 1181,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# String till Substring# using split() # initializing stringtest_string = \"GeeksforGeeks is best for geeks\" # initializing split wordspl_word = 'best' # printing original stringprint(\"The original string : \" + str(test_string)) # printing split stringprint(\"The split string : \" + str(spl_word)) # using split()# String till Substringres = test_string.split(spl_word)[0] # print resultprint(\"String before the substring occurrence : \" + res)",
"e": 1660,
"s": 1189,
"text": null
},
{
"code": null,
"e": 1796,
"s": 1660,
"text": "The original string : GeeksforGeeks is best for geeks\nThe split string : best\nString before the substring occurrence : GeeksforGeeks is"
},
{
"code": null,
"e": 1806,
"s": 1798,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# String till Substring# using find()# you can also use index(0 instead of find() # initializing stringtest_string = \"GeeksforGeeks is best for geeks\" # initializing substringspl_word = 'best' # printing original stringprint(\"The original string : \" + str(test_string)) # String till Substringx=test_string.find(spl_word)res=test_string[0:x] # print resultprint(\"String before the substring occurrence : \" + res)",
"e": 2250,
"s": 1806,
"text": null
},
{
"code": null,
"e": 2363,
"s": 2250,
"text": "The original string : GeeksforGeeks is best for geeks\nString before the substring occurrence : GeeksforGeeks is "
},
{
"code": null,
"e": 2371,
"s": 2363,
"text": "astro24"
},
{
"code": null,
"e": 2385,
"s": 2371,
"text": "kogantibhavya"
},
{
"code": null,
"e": 2408,
"s": 2385,
"text": "Python string-programs"
},
{
"code": null,
"e": 2415,
"s": 2408,
"text": "Python"
},
{
"code": null,
"e": 2431,
"s": 2415,
"text": "Python Programs"
}
] |
setsid command in Linux with Examples | 08 Apr, 2019
setsid command in Linux system is used to run a program in a new session. The command will call the fork(2) if already a process group leader. Else, it will execute a program in the current process.
Syntax:
setsid [options] program [arguments]
Example: It will execute our shell script in a new session.
Options:
setsid -c: This option will set the controlling terminal to the current one.Example:sudo setsid -c ./add.shIn this example, we have our current terminal set to controlling terminal.
Example:
sudo setsid -c ./add.sh
In this example, we have our current terminal set to controlling terminal.
setsid -w: This option will wait for the execution of the program to end and return the exit value of this program as the return value of setsid.Example:setsid -w ./add.shIn this example, if there’s any process which is supposed to take some time to be fully executed then, in that case, it will return the exit value.
Example:
setsid -w ./add.sh
In this example, if there’s any process which is supposed to take some time to be fully executed then, in that case, it will return the exit value.
setsid -V : This option will show the version information and exit.Example:setsid -V
Example:
setsid -V
setsid -h : This option will show the help text and exit.setsid -h
setsid -h
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2019"
},
{
"code": null,
"e": 227,
"s": 28,
"text": "setsid command in Linux system is used to run a program in a new session. The command will call the fork(2) if already a process group leader. Else, it will execute a program in the current process."
},
{
"code": null,
"e": 235,
"s": 227,
"text": "Syntax:"
},
{
"code": null,
"e": 273,
"s": 235,
"text": "setsid [options] program [arguments]\n"
},
{
"code": null,
"e": 333,
"s": 273,
"text": "Example: It will execute our shell script in a new session."
},
{
"code": null,
"e": 342,
"s": 333,
"text": "Options:"
},
{
"code": null,
"e": 524,
"s": 342,
"text": "setsid -c: This option will set the controlling terminal to the current one.Example:sudo setsid -c ./add.shIn this example, we have our current terminal set to controlling terminal."
},
{
"code": null,
"e": 533,
"s": 524,
"text": "Example:"
},
{
"code": null,
"e": 557,
"s": 533,
"text": "sudo setsid -c ./add.sh"
},
{
"code": null,
"e": 632,
"s": 557,
"text": "In this example, we have our current terminal set to controlling terminal."
},
{
"code": null,
"e": 951,
"s": 632,
"text": "setsid -w: This option will wait for the execution of the program to end and return the exit value of this program as the return value of setsid.Example:setsid -w ./add.shIn this example, if there’s any process which is supposed to take some time to be fully executed then, in that case, it will return the exit value."
},
{
"code": null,
"e": 960,
"s": 951,
"text": "Example:"
},
{
"code": null,
"e": 979,
"s": 960,
"text": "setsid -w ./add.sh"
},
{
"code": null,
"e": 1127,
"s": 979,
"text": "In this example, if there’s any process which is supposed to take some time to be fully executed then, in that case, it will return the exit value."
},
{
"code": null,
"e": 1212,
"s": 1127,
"text": "setsid -V : This option will show the version information and exit.Example:setsid -V"
},
{
"code": null,
"e": 1221,
"s": 1212,
"text": "Example:"
},
{
"code": null,
"e": 1231,
"s": 1221,
"text": "setsid -V"
},
{
"code": null,
"e": 1298,
"s": 1231,
"text": "setsid -h : This option will show the help text and exit.setsid -h"
},
{
"code": null,
"e": 1308,
"s": 1298,
"text": "setsid -h"
},
{
"code": null,
"e": 1322,
"s": 1308,
"text": "linux-command"
},
{
"code": null,
"e": 1342,
"s": 1322,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 1353,
"s": 1342,
"text": "Linux-Unix"
}
] |
Java | Class and Object | Question 1 | 28 Jun, 2021
Predict the output of following Java program?
class Test { int i;} class Main { public static void main(String args[]) { Test t; System.out.println(t.i); }
(A) 0(B) garbage value(C) compiler error(D) runtime errorAnswer: (C)Explanation: t is just a reference, the object referred by t is not allocated any memory. Unlike C++, in Java all non-primitive objects must be explicitly allocated and these objects are allocated on heap. The following is corrected program.
class Test { int i;} class Main { public static void main(String args[]) { Test t = new Test(); System.out.println(t.i); }
Quiz of this Question
Class and Object
Java-Class and Object
Java Quiz
Java-Class and Object
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 98,
"s": 52,
"text": "Predict the output of following Java program?"
},
{
"code": "class Test { int i;} class Main { public static void main(String args[]) { Test t; System.out.println(t.i); } ",
"e": 223,
"s": 98,
"text": null
},
{
"code": null,
"e": 533,
"s": 223,
"text": "(A) 0(B) garbage value(C) compiler error(D) runtime errorAnswer: (C)Explanation: t is just a reference, the object referred by t is not allocated any memory. Unlike C++, in Java all non-primitive objects must be explicitly allocated and these objects are allocated on heap. The following is corrected program."
},
{
"code": "class Test { int i;} class Main { public static void main(String args[]) { Test t = new Test(); System.out.println(t.i); } ",
"e": 671,
"s": 533,
"text": null
},
{
"code": null,
"e": 693,
"s": 671,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 710,
"s": 693,
"text": "Class and Object"
},
{
"code": null,
"e": 732,
"s": 710,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 742,
"s": 732,
"text": "Java Quiz"
},
{
"code": null,
"e": 764,
"s": 742,
"text": "Java-Class and Object"
}
] |
Print “Hello World” with empty or blank main in C++ | 14 Jun, 2022
Write a program in C++ that prints “Hello World”, it has a main function and body of main function is empty.
Following are three different solutions.
We can create a global variable and assign it return value of printf() that prints “Hello World”
CPP
// C++ program to print something with empty main()#include <bits/stdc++.h> int x = printf("Hello World"); int main(){ // Blank}
We can use Constructor in C++. In the below program, we create an object of class ‘A’ outer of the main Function so object declaration time it will be call to constructor so that it will be print “Hello World”.
CPP
// C++ program to print something with empty main()#include <iostream>using namespace std; class A {public: A() // Constructor { cout << "Hello World"; }}; A obj; // Create Object of class A int main(){ // Blank}
We can initialize a global variable with return type of function that prints “Hello World”.
C++
// C++ program to print something with empty main()#include <iostream> int fun(){ std::cout << "Hello World"; return 1;} int x = fun(); // global variable int main() {}
Related article: How to print “GeeksforGeeks” with empty main() in C, C++ and Java? This article is contributed by Devanshu Agarwal. 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.
isha307
cpp-puzzle
C++
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)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 163,
"s": 54,
"text": "Write a program in C++ that prints “Hello World”, it has a main function and body of main function is empty."
},
{
"code": null,
"e": 204,
"s": 163,
"text": "Following are three different solutions."
},
{
"code": null,
"e": 302,
"s": 204,
"text": "We can create a global variable and assign it return value of printf() that prints “Hello World” "
},
{
"code": null,
"e": 306,
"s": 302,
"text": "CPP"
},
{
"code": "// C++ program to print something with empty main()#include <bits/stdc++.h> int x = printf(\"Hello World\"); int main(){ // Blank}",
"e": 438,
"s": 306,
"text": null
},
{
"code": null,
"e": 650,
"s": 438,
"text": "We can use Constructor in C++. In the below program, we create an object of class ‘A’ outer of the main Function so object declaration time it will be call to constructor so that it will be print “Hello World”. "
},
{
"code": null,
"e": 654,
"s": 650,
"text": "CPP"
},
{
"code": "// C++ program to print something with empty main()#include <iostream>using namespace std; class A {public: A() // Constructor { cout << \"Hello World\"; }}; A obj; // Create Object of class A int main(){ // Blank}",
"e": 886,
"s": 654,
"text": null
},
{
"code": null,
"e": 978,
"s": 886,
"text": "We can initialize a global variable with return type of function that prints “Hello World”."
},
{
"code": null,
"e": 982,
"s": 978,
"text": "C++"
},
{
"code": "// C++ program to print something with empty main()#include <iostream> int fun(){ std::cout << \"Hello World\"; return 1;} int x = fun(); // global variable int main() {}",
"e": 1160,
"s": 982,
"text": null
},
{
"code": null,
"e": 1669,
"s": 1160,
"text": "Related article: How to print “GeeksforGeeks” with empty main() in C, C++ and Java? This article is contributed by Devanshu Agarwal. 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": 1677,
"s": 1669,
"text": "isha307"
},
{
"code": null,
"e": 1688,
"s": 1677,
"text": "cpp-puzzle"
},
{
"code": null,
"e": 1692,
"s": 1688,
"text": "C++"
},
{
"code": null,
"e": 1696,
"s": 1692,
"text": "CPP"
},
{
"code": null,
"e": 1794,
"s": 1696,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1818,
"s": 1794,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1838,
"s": 1818,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1863,
"s": 1838,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1896,
"s": 1863,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 1940,
"s": 1896,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1985,
"s": 1940,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2033,
"s": 1985,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2077,
"s": 2033,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2094,
"s": 2077,
"text": "std::find in C++"
}
] |
XML External Entity (XXE) and Billion Laughs attack - GeeksforGeeks | 14 Oct, 2020
XXE or XML External Entity attack is a web application vulnerability that affects a website which parses unsafe XML that is driven by the user. XXE attack when performed successfully can disclose local files in the file system of the website. XXE is targeted to access these sensitive local files of the website that is vulnerable to unsafe parsing.
File Retrieval XXE: As the name implies, arbitrary files on the application server of a victim company can be exposed to the attacker, if there is an XXE vulnerable endpoint in the target system. This can be carried out by passing an external XML entity in the user-controlled file.Blind XXE: It is possible that a target system doesn’t return data from the entities placed by the attacker still being insecure and vulnerable to XXE. This is done by trying out malformed user inputs. These include the input of length more than what the system expects, the wrong data type, special entities, etc. The intention is to make the system fail and check if throws out some sensitive information in the error response.XXE to SSRF: Even if the system doesn’t return the response with local file content to the attacker, the system can be still exploited in presence of an XXE attack. The entity can be pointed to a local IP of the target company which can be accessed only by its websites/network. Placing an intranet IP in XXE payload will make the target application call its local endpoint which the attacker won’t have access to otherwise. This type of attack is called SSRF or Server Side Request Forgery.
File Retrieval XXE: As the name implies, arbitrary files on the application server of a victim company can be exposed to the attacker, if there is an XXE vulnerable endpoint in the target system. This can be carried out by passing an external XML entity in the user-controlled file.
Blind XXE: It is possible that a target system doesn’t return data from the entities placed by the attacker still being insecure and vulnerable to XXE. This is done by trying out malformed user inputs. These include the input of length more than what the system expects, the wrong data type, special entities, etc. The intention is to make the system fail and check if throws out some sensitive information in the error response.
XXE to SSRF: Even if the system doesn’t return the response with local file content to the attacker, the system can be still exploited in presence of an XXE attack. The entity can be pointed to a local IP of the target company which can be accessed only by its websites/network. Placing an intranet IP in XXE payload will make the target application call its local endpoint which the attacker won’t have access to otherwise. This type of attack is called SSRF or Server Side Request Forgery.
XML is one of the commonly used data exchange formats. Data can be transferred between User and Website in XML format. Consider a website that accepts User information in form of XML. The XML that is submitted to the website looks like follows,
XML
<?xml version="1.0" encoding="ISO-8859-1"?><profiles> <profile> <name> Siva </name> <Age> 24 </Age> <occupation> Lead </occupation> </profile> <profile> <name> Subbu </name> <Age> 25 </Age> <occupation> Developer </occupation> </profile></profiles>
The website accepts this XML, parses this obtains the Name, Age, and Occupation of records in Input XML, and returns a response of processed names in return.
XML consists of a concept of entities to refer to a single object in an XML document. An entity can be defined in an XML and can be reused multiple times across the website. For example,
XML
<!ENTITY test SYSTEM "https://www.geeksforgeeks.org/DTD.dtd"><custom>&test;;</custtom>
test is described as an Entity in an XML document and it can be reused anywhere. It is also possible to lookup an External Entity that refers to some third-party website.
There are multiple XML parsing libraries that parse XML Document and return a Queryable Object. Typically, In Java, XML is parsed as follows,
Java
import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; public class GFGXMLParser { public static void main(String[] args) { try { File file = new File("/Users/Siva-5136/Downloads/Untrusted.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbFactory.newDocumentBuilder(); Document doc = db.parse(file); NodeList nodeList = doc.getElementsByTagName("userDetails"); //Set XML XXE Related Properties for (int ind = 0; ind < nodeList.getLength(); ind++) { Node node = nodeList.item(ind); if(Node.ELEMENT_NODE == node.getNodeType() ) { Element nodeElement = (Element) node; System.out.println(nodeElement.getElementsByTagName("uId").item(0).getTextContent()); System.out.println(nodeElement.getElementsByTagName("uFirstName").item(0).getTextContent()); } } } catch (Throwable e) { System.out.println("Exception Parsing XML ",e); } } }
Consider the input XML is used controlled. The input is not validated and directly passed to the XML parser. The user may try to upload the following XML file,
XML
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE name <!ELEMENT name ANY > <!ENTITY xxe SYSTEM "file:///etc/passwd" >]><profiles> <profile> <name>`&xxe;`</name> <address>`test`</address> <profile></profiles>
When the XML parser parses the XML input it resolves the entity named ‘xxe’ by its definition. From input, the XML entity is defined as System resource “file://etc/passwd” which is a sensitive local file on the website’s application server. The parsed XML replaces the entity with the content of this sensitive local file and may send it back to the user. This is called an XML entity attack.
The website should protect itself from XXE by disabling entities in user-generated XML content before parsing them. Failing which, the website becomes vulnerable to XXE attack and hence may disclose highly sensitive private information to the attacker. There are multiple ways to disable this based on the application stack and library used to parse the XML source file.
Almost all major XML parsers provide a way to disable XML external entities in the XML parser itself. For the above XML parsing example, the safe version of code looks like follows:
Java
import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; public class GFGXMLParser { public static void main(String[] args) { try { File file = new File("/Users/Siva-5136/Downloads/Untrusted.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbFactory.newDocumentBuilder(); Document doc = db.parse(file); NodeList nodeList = doc.getElementsByTagName("userDetails"); //Set XML XXE Related Properties dbFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); for (int ind = 0; ind < nodeList.getLength(); ind++) { Node node = nodeList.item(ind); if(Node.ELEMENT_NODE == node.getNodeType() ) { Element nodeElement = (Element) node; System.out.println(nodeElement.getElementsByTagName("uId").item(0).getTextContent()); System.out.println(nodeElement.getElementsByTagName("uFirstName").item(0).getTextContent()); } } } catch (Throwable e) { System.out.println("Exception Parsing XML ",e); } } }
Another common vulnerability associated with XML parsing is called A Billion Laughs Attack. It uses an entity to resolve itself cyclically thereby consuming more CPU usage and causing a denial of service attack. An Example XML payload that can cause an XXE attack is as follows:
XML
<?xml version="1.0"?><!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;"> <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;"> <!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;"> <!ENTITY lol5 "&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;"> <!ENTITY lol6 "&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;"> <!ENTITY lol7 "&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;"> <!ENTITY lol8 "&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;"> <!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">]><lolz>&lol9;</lolz>
The entity keeps getting resolved to itself cyclically thereby slowing down requests and causing a DOS attack on the application. A billion laughs attack can be disabling DOCTYPE as in the above code snippet completely or setting a maximum limit on the evaluation of entities.
XXE can cause information leakage, it can leak system files that have critical data.Data obtained from XXE can be used to target websites for additional vulnerabilities.A billion Laughs can cause service outage or a Denial Of Service attack.
XXE can cause information leakage, it can leak system files that have critical data.
Data obtained from XXE can be used to target websites for additional vulnerabilities.
A billion Laughs can cause service outage or a Denial Of Service attack.
Cyber-security
Information-Security
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
Mounting a Volume Inside Docker Container
OpenCV - Overview
Basics of API Testing Using Postman
How to create a REST API using Java Spring Boot
Fuzzy Logic | Introduction
Classifying data using Support Vector Machines(SVMs) in Python
Getting Started with System Design
Q-Learning in Python | [
{
"code": null,
"e": 23837,
"s": 23809,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 24188,
"s": 23837,
"text": "XXE or XML External Entity attack is a web application vulnerability that affects a website which parses unsafe XML that is driven by the user. XXE attack when performed successfully can disclose local files in the file system of the website. XXE is targeted to access these sensitive local files of the website that is vulnerable to unsafe parsing."
},
{
"code": null,
"e": 25392,
"s": 24188,
"text": "File Retrieval XXE: As the name implies, arbitrary files on the application server of a victim company can be exposed to the attacker, if there is an XXE vulnerable endpoint in the target system. This can be carried out by passing an external XML entity in the user-controlled file.Blind XXE: It is possible that a target system doesn’t return data from the entities placed by the attacker still being insecure and vulnerable to XXE. This is done by trying out malformed user inputs. These include the input of length more than what the system expects, the wrong data type, special entities, etc. The intention is to make the system fail and check if throws out some sensitive information in the error response.XXE to SSRF: Even if the system doesn’t return the response with local file content to the attacker, the system can be still exploited in presence of an XXE attack. The entity can be pointed to a local IP of the target company which can be accessed only by its websites/network. Placing an intranet IP in XXE payload will make the target application call its local endpoint which the attacker won’t have access to otherwise. This type of attack is called SSRF or Server Side Request Forgery."
},
{
"code": null,
"e": 25676,
"s": 25392,
"text": "File Retrieval XXE: As the name implies, arbitrary files on the application server of a victim company can be exposed to the attacker, if there is an XXE vulnerable endpoint in the target system. This can be carried out by passing an external XML entity in the user-controlled file."
},
{
"code": null,
"e": 26106,
"s": 25676,
"text": "Blind XXE: It is possible that a target system doesn’t return data from the entities placed by the attacker still being insecure and vulnerable to XXE. This is done by trying out malformed user inputs. These include the input of length more than what the system expects, the wrong data type, special entities, etc. The intention is to make the system fail and check if throws out some sensitive information in the error response."
},
{
"code": null,
"e": 26598,
"s": 26106,
"text": "XXE to SSRF: Even if the system doesn’t return the response with local file content to the attacker, the system can be still exploited in presence of an XXE attack. The entity can be pointed to a local IP of the target company which can be accessed only by its websites/network. Placing an intranet IP in XXE payload will make the target application call its local endpoint which the attacker won’t have access to otherwise. This type of attack is called SSRF or Server Side Request Forgery."
},
{
"code": null,
"e": 26843,
"s": 26598,
"text": "XML is one of the commonly used data exchange formats. Data can be transferred between User and Website in XML format. Consider a website that accepts User information in form of XML. The XML that is submitted to the website looks like follows,"
},
{
"code": null,
"e": 26847,
"s": 26843,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><profiles> <profile> <name> Siva </name> <Age> 24 </Age> <occupation> Lead </occupation> </profile> <profile> <name> Subbu </name> <Age> 25 </Age> <occupation> Developer </occupation> </profile></profiles>",
"e": 27118,
"s": 26847,
"text": null
},
{
"code": null,
"e": 27276,
"s": 27118,
"text": "The website accepts this XML, parses this obtains the Name, Age, and Occupation of records in Input XML, and returns a response of processed names in return."
},
{
"code": null,
"e": 27463,
"s": 27276,
"text": "XML consists of a concept of entities to refer to a single object in an XML document. An entity can be defined in an XML and can be reused multiple times across the website. For example,"
},
{
"code": null,
"e": 27467,
"s": 27463,
"text": "XML"
},
{
"code": "<!ENTITY test SYSTEM \"https://www.geeksforgeeks.org/DTD.dtd\"><custom>&test;;</custtom>",
"e": 27554,
"s": 27467,
"text": null
},
{
"code": null,
"e": 27725,
"s": 27554,
"text": "test is described as an Entity in an XML document and it can be reused anywhere. It is also possible to lookup an External Entity that refers to some third-party website."
},
{
"code": null,
"e": 27867,
"s": 27725,
"text": "There are multiple XML parsing libraries that parse XML Document and return a Queryable Object. Typically, In Java, XML is parsed as follows,"
},
{
"code": null,
"e": 27872,
"s": 27867,
"text": "Java"
},
{
"code": "import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; public class GFGXMLParser { public static void main(String[] args) { try { File file = new File(\"/Users/Siva-5136/Downloads/Untrusted.xml\"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbFactory.newDocumentBuilder(); Document doc = db.parse(file); NodeList nodeList = doc.getElementsByTagName(\"userDetails\"); //Set XML XXE Related Properties for (int ind = 0; ind < nodeList.getLength(); ind++) { Node node = nodeList.item(ind); if(Node.ELEMENT_NODE == node.getNodeType() ) { Element nodeElement = (Element) node; System.out.println(nodeElement.getElementsByTagName(\"uId\").item(0).getTextContent()); System.out.println(nodeElement.getElementsByTagName(\"uFirstName\").item(0).getTextContent()); } } } catch (Throwable e) { System.out.println(\"Exception Parsing XML \",e); } } }",
"e": 29093,
"s": 27872,
"text": null
},
{
"code": null,
"e": 29253,
"s": 29093,
"text": "Consider the input XML is used controlled. The input is not validated and directly passed to the XML parser. The user may try to upload the following XML file,"
},
{
"code": null,
"e": 29257,
"s": 29253,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><!DOCTYPE name <!ELEMENT name ANY > <!ENTITY xxe SYSTEM \"file:///etc/passwd\" >]><profiles> <profile> <name>`&xxe;`</name> <address>`test`</address> <profile></profiles>",
"e": 29485,
"s": 29257,
"text": null
},
{
"code": null,
"e": 29883,
"s": 29488,
"text": "When the XML parser parses the XML input it resolves the entity named ‘xxe’ by its definition. From input, the XML entity is defined as System resource “file://etc/passwd” which is a sensitive local file on the website’s application server. The parsed XML replaces the entity with the content of this sensitive local file and may send it back to the user. This is called an XML entity attack. "
},
{
"code": null,
"e": 30254,
"s": 29883,
"text": "The website should protect itself from XXE by disabling entities in user-generated XML content before parsing them. Failing which, the website becomes vulnerable to XXE attack and hence may disclose highly sensitive private information to the attacker. There are multiple ways to disable this based on the application stack and library used to parse the XML source file."
},
{
"code": null,
"e": 30437,
"s": 30254,
"text": "Almost all major XML parsers provide a way to disable XML external entities in the XML parser itself. For the above XML parsing example, the safe version of code looks like follows:"
},
{
"code": null,
"e": 30442,
"s": 30437,
"text": "Java"
},
{
"code": "import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; public class GFGXMLParser { public static void main(String[] args) { try { File file = new File(\"/Users/Siva-5136/Downloads/Untrusted.xml\"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbFactory.newDocumentBuilder(); Document doc = db.parse(file); NodeList nodeList = doc.getElementsByTagName(\"userDetails\"); //Set XML XXE Related Properties dbFactory.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true); dbFactory.setFeature(\"http://xml.org/sax/features/external-general-entities\", false); dbFactory.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false); for (int ind = 0; ind < nodeList.getLength(); ind++) { Node node = nodeList.item(ind); if(Node.ELEMENT_NODE == node.getNodeType() ) { Element nodeElement = (Element) node; System.out.println(nodeElement.getElementsByTagName(\"uId\").item(0).getTextContent()); System.out.println(nodeElement.getElementsByTagName(\"uFirstName\").item(0).getTextContent()); } } } catch (Throwable e) { System.out.println(\"Exception Parsing XML \",e); } } }",
"e": 31939,
"s": 30442,
"text": null
},
{
"code": null,
"e": 32218,
"s": 31939,
"text": "Another common vulnerability associated with XML parsing is called A Billion Laughs Attack. It uses an entity to resolve itself cyclically thereby consuming more CPU usage and causing a denial of service attack. An Example XML payload that can cause an XXE attack is as follows:"
},
{
"code": null,
"e": 32222,
"s": 32218,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\"?><!DOCTYPE lolz [ <!ENTITY lol \"lol\"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\"> <!ENTITY lol2 \"&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;\"> <!ENTITY lol3 \"&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;\"> <!ENTITY lol4 \"&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;\"> <!ENTITY lol5 \"&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;\"> <!ENTITY lol6 \"&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;\"> <!ENTITY lol7 \"&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;\"> <!ENTITY lol8 \"&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;\"> <!ENTITY lol9 \"&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;\">]><lolz>&lol9;</lolz>",
"e": 33019,
"s": 32222,
"text": null
},
{
"code": null,
"e": 33296,
"s": 33019,
"text": "The entity keeps getting resolved to itself cyclically thereby slowing down requests and causing a DOS attack on the application. A billion laughs attack can be disabling DOCTYPE as in the above code snippet completely or setting a maximum limit on the evaluation of entities."
},
{
"code": null,
"e": 33538,
"s": 33296,
"text": "XXE can cause information leakage, it can leak system files that have critical data.Data obtained from XXE can be used to target websites for additional vulnerabilities.A billion Laughs can cause service outage or a Denial Of Service attack."
},
{
"code": null,
"e": 33623,
"s": 33538,
"text": "XXE can cause information leakage, it can leak system files that have critical data."
},
{
"code": null,
"e": 33709,
"s": 33623,
"text": "Data obtained from XXE can be used to target websites for additional vulnerabilities."
},
{
"code": null,
"e": 33782,
"s": 33709,
"text": "A billion Laughs can cause service outage or a Denial Of Service attack."
},
{
"code": null,
"e": 33797,
"s": 33782,
"text": "Cyber-security"
},
{
"code": null,
"e": 33818,
"s": 33797,
"text": "Information-Security"
},
{
"code": null,
"e": 33844,
"s": 33818,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 33942,
"s": 33844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33951,
"s": 33942,
"text": "Comments"
},
{
"code": null,
"e": 33964,
"s": 33951,
"text": "Old Comments"
},
{
"code": null,
"e": 34008,
"s": 33964,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 34049,
"s": 34008,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 34091,
"s": 34049,
"text": "Mounting a Volume Inside Docker Container"
},
{
"code": null,
"e": 34109,
"s": 34091,
"text": "OpenCV - Overview"
},
{
"code": null,
"e": 34145,
"s": 34109,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 34193,
"s": 34145,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 34220,
"s": 34193,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 34283,
"s": 34220,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 34318,
"s": 34283,
"text": "Getting Started with System Design"
}
] |
Getting maximum elements in Julia - maximum() and maximum!() Methods - GeeksforGeeks | 19 Aug, 2021
The maximum() is an inbuilt function in julia which is used to return maximum elements in different scenario.
Syntax: maximum(f, itr) or maximum(itr) or maximum(A::AbstractArray; dims)
Parameters:
f: Specified function.
itr: Specified list of elements.
A::AbstractArray: Specified array of different dimensions.
dims: Specified dimensions.
Returns: It returns the maximum elements in different scenario.
Example:
Julia
# Julia program to illustrate# the use of maximum() method # Getting maximum elements in different scenarios # In the below scenario, length function# and a list of elements are used as# parameter. Here the length of string with# maximum alphabets will be returnedprintln(maximum(length, ["GFG", "Geeks", "GeeksforGeeks"])) # In the below scenario, a list of# elements are shown and maximum elements are# returned as outputprintln(maximum([5, 10, 15, 20])) # Getting the maximum value of an array# over the given dimensionsA = [5 10; 15 20];println(maximum(A, dims = 1))println(maximum(A, dims = 2))
Output:
The maximum!() is an inbuilt function in julia which is used to calculate the maximum value of the specified array over the specified singleton dimensions.
Syntax: maximum!(r, A)Parameters:
r: Specified singleton dimensions.
A: Specified array.
Returns: It returns the maximum value of the specified array over the specified singleton dimensions.
Example:
Julia
# Julia program to illustrate# the use of maximum !() method # Getting the maximum value of the# specified array over the specified# singleton dimensions.A = [5 10; 15 20];println(maximum !([1; 1], A))println(maximum !([1 1], A))
Output:
[10, 20]
[15 20]
sumitgumber28
anikakapoor
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Formatting of Strings in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Tuples in Julia
while loop in Julia
Manipulating matrices in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Storing Output on a File in Julia
Taking Input from Users in Julia | [
{
"code": null,
"e": 23865,
"s": 23837,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 23975,
"s": 23865,
"text": "The maximum() is an inbuilt function in julia which is used to return maximum elements in different scenario."
},
{
"code": null,
"e": 24050,
"s": 23975,
"text": "Syntax: maximum(f, itr) or maximum(itr) or maximum(A::AbstractArray; dims)"
},
{
"code": null,
"e": 24063,
"s": 24050,
"text": "Parameters: "
},
{
"code": null,
"e": 24086,
"s": 24063,
"text": "f: Specified function."
},
{
"code": null,
"e": 24119,
"s": 24086,
"text": "itr: Specified list of elements."
},
{
"code": null,
"e": 24178,
"s": 24119,
"text": "A::AbstractArray: Specified array of different dimensions."
},
{
"code": null,
"e": 24206,
"s": 24178,
"text": "dims: Specified dimensions."
},
{
"code": null,
"e": 24272,
"s": 24206,
"text": "Returns: It returns the maximum elements in different scenario. "
},
{
"code": null,
"e": 24283,
"s": 24272,
"text": "Example: "
},
{
"code": null,
"e": 24289,
"s": 24283,
"text": "Julia"
},
{
"code": "# Julia program to illustrate# the use of maximum() method # Getting maximum elements in different scenarios # In the below scenario, length function# and a list of elements are used as# parameter. Here the length of string with# maximum alphabets will be returnedprintln(maximum(length, [\"GFG\", \"Geeks\", \"GeeksforGeeks\"])) # In the below scenario, a list of# elements are shown and maximum elements are# returned as outputprintln(maximum([5, 10, 15, 20])) # Getting the maximum value of an array# over the given dimensionsA = [5 10; 15 20];println(maximum(A, dims = 1))println(maximum(A, dims = 2))",
"e": 24889,
"s": 24289,
"text": null
},
{
"code": null,
"e": 24898,
"s": 24889,
"text": "Output: "
},
{
"code": null,
"e": 25055,
"s": 24898,
"text": "The maximum!() is an inbuilt function in julia which is used to calculate the maximum value of the specified array over the specified singleton dimensions. "
},
{
"code": null,
"e": 25090,
"s": 25055,
"text": "Syntax: maximum!(r, A)Parameters: "
},
{
"code": null,
"e": 25125,
"s": 25090,
"text": "r: Specified singleton dimensions."
},
{
"code": null,
"e": 25145,
"s": 25125,
"text": "A: Specified array."
},
{
"code": null,
"e": 25249,
"s": 25145,
"text": "Returns: It returns the maximum value of the specified array over the specified singleton dimensions. "
},
{
"code": null,
"e": 25259,
"s": 25249,
"text": "Example: "
},
{
"code": null,
"e": 25265,
"s": 25259,
"text": "Julia"
},
{
"code": "# Julia program to illustrate# the use of maximum !() method # Getting the maximum value of the# specified array over the specified# singleton dimensions.A = [5 10; 15 20];println(maximum !([1; 1], A))println(maximum !([1 1], A))",
"e": 25495,
"s": 25265,
"text": null
},
{
"code": null,
"e": 25504,
"s": 25495,
"text": "Output: "
},
{
"code": null,
"e": 25521,
"s": 25504,
"text": "[10, 20]\n[15 20]"
},
{
"code": null,
"e": 25537,
"s": 25523,
"text": "sumitgumber28"
},
{
"code": null,
"e": 25549,
"s": 25537,
"text": "anikakapoor"
},
{
"code": null,
"e": 25555,
"s": 25549,
"text": "Julia"
},
{
"code": null,
"e": 25653,
"s": 25555,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25662,
"s": 25653,
"text": "Comments"
},
{
"code": null,
"e": 25675,
"s": 25662,
"text": "Old Comments"
},
{
"code": null,
"e": 25692,
"s": 25675,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 25752,
"s": 25692,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 25783,
"s": 25752,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 25844,
"s": 25783,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 25860,
"s": 25844,
"text": "Tuples in Julia"
},
{
"code": null,
"e": 25880,
"s": 25860,
"text": "while loop in Julia"
},
{
"code": null,
"e": 25911,
"s": 25880,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 25981,
"s": 25911,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 26015,
"s": 25981,
"text": "Storing Output on a File in Julia"
}
] |
How to Run a Python Program | There are three different ways to start Python −
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
Here is the list of all the available command line options −
Script from the Command-line
A Python script can be executed at command line by invoking the interpreter on your application, as in the following −
$python script.py # Unix/Linux
or
python% script.py # Unix/Linux
or
C: >python script.py # Windows/DOS
Note − Be sure the file permission mode allows execution.
You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python.
Unix − IDLE is the very first Unix IDE for Python.
Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI.
Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files.
If you are not able to set up the environment properly, then you can take help from your system admin. Make sure the Python environment is properly set up and working perfectly fine. | [
{
"code": null,
"e": 1111,
"s": 1062,
"text": "There are three different ways to start Python −"
},
{
"code": null,
"e": 1135,
"s": 1111,
"text": "Interactive Interpreter"
},
{
"code": null,
"e": 1254,
"s": 1135,
"text": "You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window."
},
{
"code": null,
"e": 1285,
"s": 1254,
"text": "Enter python the command line."
},
{
"code": null,
"e": 1341,
"s": 1285,
"text": "Start coding right away in the interactive interpreter."
},
{
"code": null,
"e": 1414,
"s": 1341,
"text": "$python # Unix/Linux\nor\npython% # Unix/Linux\nor\nC:> python # Windows/DOS"
},
{
"code": null,
"e": 1475,
"s": 1414,
"text": "Here is the list of all the available command line options −"
},
{
"code": null,
"e": 1504,
"s": 1475,
"text": "Script from the Command-line"
},
{
"code": null,
"e": 1623,
"s": 1504,
"text": "A Python script can be executed at command line by invoking the interpreter on your application, as in the following −"
},
{
"code": null,
"e": 1726,
"s": 1623,
"text": "$python script.py # Unix/Linux\nor\npython% script.py # Unix/Linux\nor\nC: >python script.py # Windows/DOS"
},
{
"code": null,
"e": 1784,
"s": 1726,
"text": "Note − Be sure the file permission mode allows execution."
},
{
"code": null,
"e": 1929,
"s": 1784,
"text": "You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python."
},
{
"code": null,
"e": 1980,
"s": 1929,
"text": "Unix − IDLE is the very first Unix IDE for Python."
},
{
"code": null,
"e": 2068,
"s": 1980,
"text": "Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI."
},
{
"code": null,
"e": 2224,
"s": 2068,
"text": "Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files."
},
{
"code": null,
"e": 2407,
"s": 2224,
"text": "If you are not able to set up the environment properly, then you can take help from your system admin. Make sure the Python environment is properly set up and working perfectly fine."
}
] |
BlockingQueue offer() method in Java with examples - GeeksforGeeks | 04 Jul, 2021
There are two types of offer() method for BlockingQueue interface:Note: The offer() method of BlockingQueue has been inherited from the Queue class in Java.
The offer(E e, long timeout, TimeUnit unit) method of BlockingQueue inserts the element passed as parameter to method at the tail of this BlockingQueue if queue is not full. It will wait till a specified time for space to become available if the BlockingQueue is full. The specified waiting time and TimeUnit for time will be given as parameters to the offer() method. So it will wait till that time for BlockingQueue to remove some elements so that this method can add elements to BlockingQueue.Syntax:
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
Parameters: This method accepts three parameters:
e– the element to be inserted into BlockingQueue.
timeout– the time till which offer method will wait for inserting new element is queue is full.
unit– the Time unit for timeout parameter.
Return Value: The method returns true if insertion of element successful. Else it returns false if the specified waiting time elapses before space is available.Exception: This method throws following exceptions:
NullPointerException– if the specified element is null.
InterruptedException– if interrupted while waiting.
Below programs illustrates offer(E e, long timeout, TimeUnit unit) method of BlockingQueue class:Program 1:
Java
// Java Program Demonstrate// offer(Element e, long timeout, TimeUnit unit)// method of BlockingQueue. import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit; public class GFG { // Main method public static void main(String[] args) throws InterruptedException { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<Integer> BQ = new LinkedBlockingQueue<Integer>(capacityOfQueue); // Add 5 elements to BlockingQueue having // Timeout in seconds with value 5 secs in // offer(Element e, long timeout, TimeUnit unit) System.out.println("adding 32673821 " + BQ.offer(32673821, 5, TimeUnit.SECONDS)); System.out.println("adding 88527183: " + BQ.offer(88527183, 5, TimeUnit.SECONDS)); System.out.println("adding 431278539: " + BQ.offer(431278539, 5, TimeUnit.SECONDS)); System.out.println("adding 351278693: " + BQ.offer(351278693, 5, TimeUnit.SECONDS)); System.out.println("adding 647264: " + BQ.offer(647264, 5, TimeUnit.SECONDS)); // print the elements of queue System.out.println("list of numbers of queue:" + BQ); // now queue is full check remaining capacity of queue System.out.println("Empty spaces of queue : " + BQ.remainingCapacity()); // try to add more Integer boolean response = BQ.offer(2893476, 5, TimeUnit.SECONDS); System.out.println("Adding new Integer 2893476 is successful: " + response); }}
adding 32673821 true
adding 88527183: true
adding 431278539: true
adding 351278693: true
adding 647264: false
list of numbers of queue:[32673821, 88527183, 431278539, 351278693]
Empty spaces of queue : 0
Adding new Integer 2893476 is successful: false
Program 2:
Java
// Java Program Demonstrate// offer(Element e, long timeout, TimeUnit unit)// method of BlockingQueue. import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit; public class GFG { public static void main(String[] args) throws InterruptedException { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<Integer> BQ = new LinkedBlockingQueue<Integer>(capacityOfQueue); // Add elements to BlockingQueue having // Timeout in seconds with value 5 secs in // offer(Element e, long timeout, TimeUnit unit) System.out.println("Adding 283239 in Queue :" + BQ.offer(283239, 5, TimeUnit.SECONDS)); // try to put null value in offer method try { System.out.println("Adding null in Queue: " + BQ.offer(null, 5, TimeUnit.SECONDS)); } catch (Exception e) { // print error details System.out.println("Exception: " + e); } // print elements of queue System.out.println("Items in Queue are " + BQ); }}
Adding 283239 in Queue :true
Exception: java.lang.NullPointerException
Items in Queue are [283239]
The offer(E e) method of BlockingQueue inserts the element e, passed as parameter, at the tail of this BlockingQueue, if queue has space i.e Queue is not full. If queue is full then applying offer() method shows no effect because BlockingQueue will blocks element to be inserted. offer() method returns true when the operation of addition to BlockingQueue is successful and false if this queue is full. This method is preferred over add() method because add method throws error when queue is full but offer() method returns false in such situation.Syntax:
public boolean offer(E e)
Parameters: This method takes a mandatory parameter e which is the element to be inserted into LinkedBlockingQueue.Return Value: This method returns true if insertion of element successful. Else it returns false.Exception: The method throws NullPointerException if the specified element is null.Below programs illustrates offer() method of BlockingQueue classProgram 1:
Java
// Java Program Demonstrate// offer(Element e)// method of BlockingQueue. import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue; public class GFG { // Main method public static void main(String[] args) { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<String> BQ = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to BlockingQueue using offer BQ.offer("dean"); BQ.offer("kevin"); BQ.offer("sam"); BQ.offer("jack"); // print the elements of queue System.out.println("list of names of queue:"); System.out.println(BQ); }}
list of names of queue:
[dean, kevin, sam, jack]
Program 2:
Java
// Java Program Demonstrate// offer(Element e)// method of BlockingQueue. import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue; public class GFG { // Main method public static void main(String[] args) { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<Integer> BQ = new LinkedBlockingQueue<Integer>(capacityOfQueue); // Add element to BlockingQueue using offer BQ.offer(34567); BQ.offer(45678); BQ.offer(98323); BQ.offer(93758); // print the elements of queue System.out.println("list of numbers of queue:"); System.out.println(BQ); // now queue is full check remaining capacity of queue System.out.println("Empty spaces of queue : " + BQ.remainingCapacity()); // try to add extra Integer boolean response = BQ.offer(2893476); System.out.println("Adding new Integer 2893476 is successful: " + response); response = BQ.offer(456751); System.out.println("Adding new Integer 456751 is successful: " + response); }}
list of numbers of queue:
[34567, 45678, 98323, 93758]
Empty spaces of queue : 0
Adding new Integer 2893476 is successful: false
Adding new Integer 456751 is successful: false
Program 3: Showing Exception thrown by offer() method
Java
// Java Program Demonstrate offer(E e)// method of LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue; public class GFG { public static void main(String[] args) throws InterruptedException { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<String> BQ = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element using offer() method BQ.offer("Karan"); // try to put null value in offer method try { BQ.offer(null); } catch (Exception e) { // print error details System.out.println("Exception: " + e); } // print elements of queue System.out.println("Items in Queue are " + BQ); }}
Exception: java.lang.NullPointerException
Items in Queue are [Karan]
Reference:
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html#offer(E)
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html#offer(E, %20long, %20java.util.concurrent.TimeUnit)
gabaa406
Java-BlockingQueue
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
HashMap get() Method in Java
Strings in Java | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 24106,
"s": 23948,
"text": "There are two types of offer() method for BlockingQueue interface:Note: The offer() method of BlockingQueue has been inherited from the Queue class in Java. "
},
{
"code": null,
"e": 24612,
"s": 24106,
"text": "The offer(E e, long timeout, TimeUnit unit) method of BlockingQueue inserts the element passed as parameter to method at the tail of this BlockingQueue if queue is not full. It will wait till a specified time for space to become available if the BlockingQueue is full. The specified waiting time and TimeUnit for time will be given as parameters to the offer() method. So it will wait till that time for BlockingQueue to remove some elements so that this method can add elements to BlockingQueue.Syntax: "
},
{
"code": null,
"e": 24695,
"s": 24612,
"text": "public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException"
},
{
"code": null,
"e": 24747,
"s": 24695,
"text": "Parameters: This method accepts three parameters: "
},
{
"code": null,
"e": 24797,
"s": 24747,
"text": "e– the element to be inserted into BlockingQueue."
},
{
"code": null,
"e": 24893,
"s": 24797,
"text": "timeout– the time till which offer method will wait for inserting new element is queue is full."
},
{
"code": null,
"e": 24936,
"s": 24893,
"text": "unit– the Time unit for timeout parameter."
},
{
"code": null,
"e": 25149,
"s": 24936,
"text": "Return Value: The method returns true if insertion of element successful. Else it returns false if the specified waiting time elapses before space is available.Exception: This method throws following exceptions: "
},
{
"code": null,
"e": 25205,
"s": 25149,
"text": "NullPointerException– if the specified element is null."
},
{
"code": null,
"e": 25257,
"s": 25205,
"text": "InterruptedException– if interrupted while waiting."
},
{
"code": null,
"e": 25367,
"s": 25257,
"text": "Below programs illustrates offer(E e, long timeout, TimeUnit unit) method of BlockingQueue class:Program 1: "
},
{
"code": null,
"e": 25372,
"s": 25367,
"text": "Java"
},
{
"code": "// Java Program Demonstrate// offer(Element e, long timeout, TimeUnit unit)// method of BlockingQueue. import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit; public class GFG { // Main method public static void main(String[] args) throws InterruptedException { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<Integer> BQ = new LinkedBlockingQueue<Integer>(capacityOfQueue); // Add 5 elements to BlockingQueue having // Timeout in seconds with value 5 secs in // offer(Element e, long timeout, TimeUnit unit) System.out.println(\"adding 32673821 \" + BQ.offer(32673821, 5, TimeUnit.SECONDS)); System.out.println(\"adding 88527183: \" + BQ.offer(88527183, 5, TimeUnit.SECONDS)); System.out.println(\"adding 431278539: \" + BQ.offer(431278539, 5, TimeUnit.SECONDS)); System.out.println(\"adding 351278693: \" + BQ.offer(351278693, 5, TimeUnit.SECONDS)); System.out.println(\"adding 647264: \" + BQ.offer(647264, 5, TimeUnit.SECONDS)); // print the elements of queue System.out.println(\"list of numbers of queue:\" + BQ); // now queue is full check remaining capacity of queue System.out.println(\"Empty spaces of queue : \" + BQ.remainingCapacity()); // try to add more Integer boolean response = BQ.offer(2893476, 5, TimeUnit.SECONDS); System.out.println(\"Adding new Integer 2893476 is successful: \" + response); }}",
"e": 27624,
"s": 25372,
"text": null
},
{
"code": null,
"e": 27877,
"s": 27624,
"text": "adding 32673821 true\nadding 88527183: true\nadding 431278539: true\nadding 351278693: true\nadding 647264: false\nlist of numbers of queue:[32673821, 88527183, 431278539, 351278693]\nEmpty spaces of queue : 0\nAdding new Integer 2893476 is successful: false\n"
},
{
"code": null,
"e": 27890,
"s": 27877,
"text": "Program 2: "
},
{
"code": null,
"e": 27895,
"s": 27890,
"text": "Java"
},
{
"code": "// Java Program Demonstrate// offer(Element e, long timeout, TimeUnit unit)// method of BlockingQueue. import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit; public class GFG { public static void main(String[] args) throws InterruptedException { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<Integer> BQ = new LinkedBlockingQueue<Integer>(capacityOfQueue); // Add elements to BlockingQueue having // Timeout in seconds with value 5 secs in // offer(Element e, long timeout, TimeUnit unit) System.out.println(\"Adding 283239 in Queue :\" + BQ.offer(283239, 5, TimeUnit.SECONDS)); // try to put null value in offer method try { System.out.println(\"Adding null in Queue: \" + BQ.offer(null, 5, TimeUnit.SECONDS)); } catch (Exception e) { // print error details System.out.println(\"Exception: \" + e); } // print elements of queue System.out.println(\"Items in Queue are \" + BQ); }}",
"e": 29315,
"s": 27895,
"text": null
},
{
"code": null,
"e": 29414,
"s": 29315,
"text": "Adding 283239 in Queue :true\nException: java.lang.NullPointerException\nItems in Queue are [283239]"
},
{
"code": null,
"e": 29974,
"s": 29416,
"text": "The offer(E e) method of BlockingQueue inserts the element e, passed as parameter, at the tail of this BlockingQueue, if queue has space i.e Queue is not full. If queue is full then applying offer() method shows no effect because BlockingQueue will blocks element to be inserted. offer() method returns true when the operation of addition to BlockingQueue is successful and false if this queue is full. This method is preferred over add() method because add method throws error when queue is full but offer() method returns false in such situation.Syntax: "
},
{
"code": null,
"e": 30000,
"s": 29974,
"text": "public boolean offer(E e)"
},
{
"code": null,
"e": 30372,
"s": 30000,
"text": "Parameters: This method takes a mandatory parameter e which is the element to be inserted into LinkedBlockingQueue.Return Value: This method returns true if insertion of element successful. Else it returns false.Exception: The method throws NullPointerException if the specified element is null.Below programs illustrates offer() method of BlockingQueue classProgram 1: "
},
{
"code": null,
"e": 30377,
"s": 30372,
"text": "Java"
},
{
"code": "// Java Program Demonstrate// offer(Element e)// method of BlockingQueue. import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue; public class GFG { // Main method public static void main(String[] args) { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<String> BQ = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to BlockingQueue using offer BQ.offer(\"dean\"); BQ.offer(\"kevin\"); BQ.offer(\"sam\"); BQ.offer(\"jack\"); // print the elements of queue System.out.println(\"list of names of queue:\"); System.out.println(BQ); }}",
"e": 31121,
"s": 30377,
"text": null
},
{
"code": null,
"e": 31170,
"s": 31121,
"text": "list of names of queue:\n[dean, kevin, sam, jack]"
},
{
"code": null,
"e": 31184,
"s": 31172,
"text": "Program 2: "
},
{
"code": null,
"e": 31189,
"s": 31184,
"text": "Java"
},
{
"code": "// Java Program Demonstrate// offer(Element e)// method of BlockingQueue. import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue; public class GFG { // Main method public static void main(String[] args) { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<Integer> BQ = new LinkedBlockingQueue<Integer>(capacityOfQueue); // Add element to BlockingQueue using offer BQ.offer(34567); BQ.offer(45678); BQ.offer(98323); BQ.offer(93758); // print the elements of queue System.out.println(\"list of numbers of queue:\"); System.out.println(BQ); // now queue is full check remaining capacity of queue System.out.println(\"Empty spaces of queue : \" + BQ.remainingCapacity()); // try to add extra Integer boolean response = BQ.offer(2893476); System.out.println(\"Adding new Integer 2893476 is successful: \" + response); response = BQ.offer(456751); System.out.println(\"Adding new Integer 456751 is successful: \" + response); }}",
"e": 32441,
"s": 31189,
"text": null
},
{
"code": null,
"e": 32618,
"s": 32441,
"text": "list of numbers of queue:\n[34567, 45678, 98323, 93758]\nEmpty spaces of queue : 0\nAdding new Integer 2893476 is successful: false\nAdding new Integer 456751 is successful: false\n"
},
{
"code": null,
"e": 32673,
"s": 32618,
"text": "Program 3: Showing Exception thrown by offer() method "
},
{
"code": null,
"e": 32678,
"s": 32673,
"text": "Java"
},
{
"code": "// Java Program Demonstrate offer(E e)// method of LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.BlockingQueue; public class GFG { public static void main(String[] args) throws InterruptedException { // define capacity of BlockingQueue int capacityOfQueue = 4; // create object of BlockingQueue BlockingQueue<String> BQ = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element using offer() method BQ.offer(\"Karan\"); // try to put null value in offer method try { BQ.offer(null); } catch (Exception e) { // print error details System.out.println(\"Exception: \" + e); } // print elements of queue System.out.println(\"Items in Queue are \" + BQ); }}",
"e": 33566,
"s": 32678,
"text": null
},
{
"code": null,
"e": 33635,
"s": 33566,
"text": "Exception: java.lang.NullPointerException\nItems in Queue are [Karan]"
},
{
"code": null,
"e": 33650,
"s": 33637,
"text": "Reference: "
},
{
"code": null,
"e": 33741,
"s": 33650,
"text": "https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html#offer(E)"
},
{
"code": null,
"e": 33875,
"s": 33741,
"text": "https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html#offer(E, %20long, %20java.util.concurrent.TimeUnit)"
},
{
"code": null,
"e": 33886,
"s": 33877,
"text": "gabaa406"
},
{
"code": null,
"e": 33905,
"s": 33886,
"text": "Java-BlockingQueue"
},
{
"code": null,
"e": 33922,
"s": 33905,
"text": "Java-Collections"
},
{
"code": null,
"e": 33937,
"s": 33922,
"text": "Java-Functions"
},
{
"code": null,
"e": 33942,
"s": 33937,
"text": "Java"
},
{
"code": null,
"e": 33947,
"s": 33942,
"text": "Java"
},
{
"code": null,
"e": 33964,
"s": 33947,
"text": "Java-Collections"
},
{
"code": null,
"e": 34062,
"s": 33964,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34077,
"s": 34062,
"text": "Stream In Java"
},
{
"code": null,
"e": 34098,
"s": 34077,
"text": "Constructors in Java"
},
{
"code": null,
"e": 34144,
"s": 34098,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 34163,
"s": 34144,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 34193,
"s": 34163,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 34210,
"s": 34193,
"text": "Generics in Java"
},
{
"code": null,
"e": 34253,
"s": 34210,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 34274,
"s": 34253,
"text": "Introduction to Java"
},
{
"code": null,
"e": 34303,
"s": 34274,
"text": "HashMap get() Method in Java"
}
] |
BNY Mellon Internship Interview Experience for Software Developer | On-Campus 2022 - GeeksforGeeks | 05 Oct, 2021
BNY Mellon visited our campus on 21 Sep 2021 for Summer Internship 2022.
Eligibility: Branch – CSE, IT, E&TC, Instru
Criterion: 6.0 CGPA and above, No dead and live backlogs considered.
Pattern: 1 HackerRank coding test + 2 Tech rounds + 1 HR round
Round 1: HackerRank Coding Test
4 questions to be done in 90 mins
Easy question: similar to picking numbers question of HackerRank
Medium question: graph-based – can be done using DFS or BFS
Medium question: graph-based – minimum steps by knight problem
Hard question: Tree-based – given is a string which represents a tree, find whether is this valid or not according to specified conditions in question, if not valid then return the appropriate error code as given in the question.
Round 2: Tech round 1
Time: 45 minutes – 10 Students were shortlisted for this round
Asked about the internship I have done earlier from Cisco – asked the follow-up questions on the same.
Project discussion – tech stack used and implementation.
Write a code to remove duplicates from the given linked list on provided HackerRank code pair link.
Compiled and interpreted language differences.
What is a constructor?
Give me an example where you can do constructor overloading
What is Exception Handling – what is need for this
Explain the flow of the program in the try, catch and finally block
What is the purpose of finally block
C++ and Python difference
Which data structure you would use to design a traffic signal and why?
Give me a real-life scenario where you see stack implemented
Identify which data structure is used for the following implementations – 1)Memory allocation and deallocation in the compiler – Ans: heap 2)Browser history – Ans: stack
What is multithreading in java?
ArrayList and Vector difference
What is namespace in C++?
How much do you know python? Do you know NumPy library?
Do you have any questions for me? (I asked one)
Round 3: Tech round 2
Time: 30 minutes Total 4 students were shortlisted for this round
Which question do you feel you could have answered better in Round 1
What are threads?
About my internship at Cisco – learnings, experience
In C, if we write while(true) as a loop, what will happen and why?
What is the function pointer in C – where we can use this?
Declared array of size 5 and if I try to access 7th location, What will happen?
What is a static keyword in java?
What is a singleton in java?
The project, resume discussion, and follow up questions
What is core dump, thread dump?
Do you know Apache Tomcat? Have you worked on it? (I used this in one of my projects)
What are adaptive and responsive websites?
What is JDK, JRE, JVM?
HTTP and HTTPS difference
What is Big O notation? Do you know any other notations?
Which data structure you will use to store different country names such as India, US, UK, and then their respective state names and then respective city names. Ans – Tree Why? – As the given data is hierarchical
What are GET and POST methods
Tell me approach to code the following question
Testcase 1) Input - [email protected]
Expected output - a*@gmail.com
Testcase 2) Input - [email protected]
Expected output - p*@gmail.com
Do you have any questions for me? (I asked one)
Round 4: HR round
Time: 45 minutes Total of 2 Students were shortlisted for this round
Give a brief summary about yourself, what all things you have done so far – technical, no technical both
Java and python difference – which one do you think is better?
Why do you prefer to code in Java?
What are all projects you have done and implementations?
Why did you choose this problem statement as your project, what was your thought process to come with this problem statement specifically?
How you tested your project?
Tell me about a time when you could not do well in academics and how you tackled this situation.
Do you think that doing all these projects was beneficial? If yes then how?
What are your future plans?
Have been involved in any technical discussion forums – how do you keep yourself updated?
Do you want to highlight any point which we missed to discuss which will add value to your candidature?
At the end of my HR interview, I said Thank you, sir, Good day! and he replied, “when you will join the company, at that time don’t call me sir, call me by my name!” This was a very big hint for selection. But still, you can not assume anything until the results are out. So I was desperately waiting for results. After the HR interview, I searched for the person who took my HR round on LinkedIn and came to know that he is vice president. Results were out after 2 hours, and only I was selected!!! I was very happy, and then I also felt bad for the other candidate who was rejected after the HR round
Tips:
Keep in mind Time matters so much in all the interviews and do not lie for any reason.
If not selected then don’t get upset, analyze your mistakes and look forward to the next opportunities!!
BNY Mellon
Marketing
On-Campus
Internship
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Microsoft Interview Experience for Internship (Via Engage)
Persistent Systems Interview Experience (Martian Program)
Zoho Interview Experience (Off-Campus ) 2022
Zoho Corporation (Internship cum Offer Experience )
HashedIn by Deloitte Interview Experience for SDE Intern+FTE | (Off-Campus) 2022
Amazon Interview Questions
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience
Amazon Interview Experience for SDE-1 (On-Campus)
Microsoft Interview Experience for Internship (Via Engage) | [
{
"code": null,
"e": 25500,
"s": 25472,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 25573,
"s": 25500,
"text": "BNY Mellon visited our campus on 21 Sep 2021 for Summer Internship 2022."
},
{
"code": null,
"e": 25618,
"s": 25573,
"text": "Eligibility: Branch – CSE, IT, E&TC, Instru"
},
{
"code": null,
"e": 25688,
"s": 25618,
"text": "Criterion: 6.0 CGPA and above, No dead and live backlogs considered."
},
{
"code": null,
"e": 25751,
"s": 25688,
"text": "Pattern: 1 HackerRank coding test + 2 Tech rounds + 1 HR round"
},
{
"code": null,
"e": 25785,
"s": 25751,
"text": " Round 1: HackerRank Coding Test "
},
{
"code": null,
"e": 25819,
"s": 25785,
"text": "4 questions to be done in 90 mins"
},
{
"code": null,
"e": 25884,
"s": 25819,
"text": "Easy question: similar to picking numbers question of HackerRank"
},
{
"code": null,
"e": 25944,
"s": 25884,
"text": "Medium question: graph-based – can be done using DFS or BFS"
},
{
"code": null,
"e": 26007,
"s": 25944,
"text": "Medium question: graph-based – minimum steps by knight problem"
},
{
"code": null,
"e": 26237,
"s": 26007,
"text": "Hard question: Tree-based – given is a string which represents a tree, find whether is this valid or not according to specified conditions in question, if not valid then return the appropriate error code as given in the question."
},
{
"code": null,
"e": 26260,
"s": 26237,
"text": "Round 2: Tech round 1 "
},
{
"code": null,
"e": 26323,
"s": 26260,
"text": "Time: 45 minutes – 10 Students were shortlisted for this round"
},
{
"code": null,
"e": 26426,
"s": 26323,
"text": "Asked about the internship I have done earlier from Cisco – asked the follow-up questions on the same."
},
{
"code": null,
"e": 26483,
"s": 26426,
"text": "Project discussion – tech stack used and implementation."
},
{
"code": null,
"e": 26583,
"s": 26483,
"text": "Write a code to remove duplicates from the given linked list on provided HackerRank code pair link."
},
{
"code": null,
"e": 26630,
"s": 26583,
"text": "Compiled and interpreted language differences."
},
{
"code": null,
"e": 26653,
"s": 26630,
"text": "What is a constructor?"
},
{
"code": null,
"e": 26713,
"s": 26653,
"text": "Give me an example where you can do constructor overloading"
},
{
"code": null,
"e": 26764,
"s": 26713,
"text": "What is Exception Handling – what is need for this"
},
{
"code": null,
"e": 26832,
"s": 26764,
"text": "Explain the flow of the program in the try, catch and finally block"
},
{
"code": null,
"e": 26869,
"s": 26832,
"text": "What is the purpose of finally block"
},
{
"code": null,
"e": 26895,
"s": 26869,
"text": "C++ and Python difference"
},
{
"code": null,
"e": 26966,
"s": 26895,
"text": "Which data structure you would use to design a traffic signal and why?"
},
{
"code": null,
"e": 27027,
"s": 26966,
"text": "Give me a real-life scenario where you see stack implemented"
},
{
"code": null,
"e": 27199,
"s": 27027,
"text": "Identify which data structure is used for the following implementations – 1)Memory allocation and deallocation in the compiler – Ans: heap 2)Browser history – Ans: stack"
},
{
"code": null,
"e": 27231,
"s": 27199,
"text": "What is multithreading in java?"
},
{
"code": null,
"e": 27263,
"s": 27231,
"text": "ArrayList and Vector difference"
},
{
"code": null,
"e": 27289,
"s": 27263,
"text": "What is namespace in C++?"
},
{
"code": null,
"e": 27345,
"s": 27289,
"text": "How much do you know python? Do you know NumPy library?"
},
{
"code": null,
"e": 27393,
"s": 27345,
"text": "Do you have any questions for me? (I asked one)"
},
{
"code": null,
"e": 27415,
"s": 27393,
"text": "Round 3: Tech round 2"
},
{
"code": null,
"e": 27482,
"s": 27415,
"text": "Time: 30 minutes Total 4 students were shortlisted for this round"
},
{
"code": null,
"e": 27551,
"s": 27482,
"text": "Which question do you feel you could have answered better in Round 1"
},
{
"code": null,
"e": 27569,
"s": 27551,
"text": "What are threads?"
},
{
"code": null,
"e": 27622,
"s": 27569,
"text": "About my internship at Cisco – learnings, experience"
},
{
"code": null,
"e": 27689,
"s": 27622,
"text": "In C, if we write while(true) as a loop, what will happen and why?"
},
{
"code": null,
"e": 27748,
"s": 27689,
"text": "What is the function pointer in C – where we can use this?"
},
{
"code": null,
"e": 27828,
"s": 27748,
"text": "Declared array of size 5 and if I try to access 7th location, What will happen?"
},
{
"code": null,
"e": 27862,
"s": 27828,
"text": "What is a static keyword in java?"
},
{
"code": null,
"e": 27891,
"s": 27862,
"text": "What is a singleton in java?"
},
{
"code": null,
"e": 27947,
"s": 27891,
"text": "The project, resume discussion, and follow up questions"
},
{
"code": null,
"e": 27979,
"s": 27947,
"text": "What is core dump, thread dump?"
},
{
"code": null,
"e": 28065,
"s": 27979,
"text": "Do you know Apache Tomcat? Have you worked on it? (I used this in one of my projects)"
},
{
"code": null,
"e": 28108,
"s": 28065,
"text": "What are adaptive and responsive websites?"
},
{
"code": null,
"e": 28131,
"s": 28108,
"text": "What is JDK, JRE, JVM?"
},
{
"code": null,
"e": 28157,
"s": 28131,
"text": "HTTP and HTTPS difference"
},
{
"code": null,
"e": 28214,
"s": 28157,
"text": "What is Big O notation? Do you know any other notations?"
},
{
"code": null,
"e": 28429,
"s": 28214,
"text": "Which data structure you will use to store different country names such as India, US, UK, and then their respective state names and then respective city names. Ans – Tree Why? – As the given data is hierarchical"
},
{
"code": null,
"e": 28459,
"s": 28429,
"text": "What are GET and POST methods"
},
{
"code": null,
"e": 28507,
"s": 28459,
"text": "Tell me approach to code the following question"
},
{
"code": null,
"e": 28638,
"s": 28507,
"text": "Testcase 1) Input - [email protected]\nExpected output - a*@gmail.com\nTestcase 2) Input - [email protected]\nExpected output - p*@gmail.com"
},
{
"code": null,
"e": 28686,
"s": 28638,
"text": "Do you have any questions for me? (I asked one)"
},
{
"code": null,
"e": 28705,
"s": 28686,
"text": "Round 4: HR round "
},
{
"code": null,
"e": 28775,
"s": 28705,
"text": "Time: 45 minutes Total of 2 Students were shortlisted for this round"
},
{
"code": null,
"e": 28880,
"s": 28775,
"text": "Give a brief summary about yourself, what all things you have done so far – technical, no technical both"
},
{
"code": null,
"e": 28943,
"s": 28880,
"text": "Java and python difference – which one do you think is better?"
},
{
"code": null,
"e": 28978,
"s": 28943,
"text": "Why do you prefer to code in Java?"
},
{
"code": null,
"e": 29035,
"s": 28978,
"text": "What are all projects you have done and implementations?"
},
{
"code": null,
"e": 29174,
"s": 29035,
"text": "Why did you choose this problem statement as your project, what was your thought process to come with this problem statement specifically?"
},
{
"code": null,
"e": 29203,
"s": 29174,
"text": "How you tested your project?"
},
{
"code": null,
"e": 29300,
"s": 29203,
"text": "Tell me about a time when you could not do well in academics and how you tackled this situation."
},
{
"code": null,
"e": 29376,
"s": 29300,
"text": "Do you think that doing all these projects was beneficial? If yes then how?"
},
{
"code": null,
"e": 29404,
"s": 29376,
"text": "What are your future plans?"
},
{
"code": null,
"e": 29494,
"s": 29404,
"text": "Have been involved in any technical discussion forums – how do you keep yourself updated?"
},
{
"code": null,
"e": 29598,
"s": 29494,
"text": "Do you want to highlight any point which we missed to discuss which will add value to your candidature?"
},
{
"code": null,
"e": 30202,
"s": 29598,
"text": "At the end of my HR interview, I said Thank you, sir, Good day! and he replied, “when you will join the company, at that time don’t call me sir, call me by my name!” This was a very big hint for selection. But still, you can not assume anything until the results are out. So I was desperately waiting for results. After the HR interview, I searched for the person who took my HR round on LinkedIn and came to know that he is vice president. Results were out after 2 hours, and only I was selected!!! I was very happy, and then I also felt bad for the other candidate who was rejected after the HR round "
},
{
"code": null,
"e": 30209,
"s": 30202,
"text": "Tips: "
},
{
"code": null,
"e": 30296,
"s": 30209,
"text": "Keep in mind Time matters so much in all the interviews and do not lie for any reason."
},
{
"code": null,
"e": 30401,
"s": 30296,
"text": "If not selected then don’t get upset, analyze your mistakes and look forward to the next opportunities!!"
},
{
"code": null,
"e": 30412,
"s": 30401,
"text": "BNY Mellon"
},
{
"code": null,
"e": 30422,
"s": 30412,
"text": "Marketing"
},
{
"code": null,
"e": 30432,
"s": 30422,
"text": "On-Campus"
},
{
"code": null,
"e": 30443,
"s": 30432,
"text": "Internship"
},
{
"code": null,
"e": 30465,
"s": 30443,
"text": "Interview Experiences"
},
{
"code": null,
"e": 30563,
"s": 30465,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30622,
"s": 30563,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 30680,
"s": 30622,
"text": "Persistent Systems Interview Experience (Martian Program)"
},
{
"code": null,
"e": 30725,
"s": 30680,
"text": "Zoho Interview Experience (Off-Campus ) 2022"
},
{
"code": null,
"e": 30777,
"s": 30725,
"text": "Zoho Corporation (Internship cum Offer Experience )"
},
{
"code": null,
"e": 30858,
"s": 30777,
"text": "HashedIn by Deloitte Interview Experience for SDE Intern+FTE | (Off-Campus) 2022"
},
{
"code": null,
"e": 30885,
"s": 30858,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 30945,
"s": 30885,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 30973,
"s": 30945,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 31023,
"s": 30973,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
}
] |
Prolog - Relations | Relationship is one of the main features that we have to properly mention in Prolog. These relationships can be expressed as facts and rules. After that we will see about the family relationships, how we can express family based relationships in Prolog, and also see the recursive relationships of the family.
We will create the knowledge base by creating facts and rules, and play query on them.
In Prolog programs, it specifies relationship between objects and properties of the objects.
Suppose, there’s a statement, “Amit has a bike”, then we are actually declaring the ownership relationship between two objects — one is Amit and the other is bike.
If we ask a question, “Does Amit own a bike?”, we are actually trying to find out about one relationship.
There are various kinds of relationships, of which some can be rules as well. A rule can find out about a relationship even if the relationship is not defined explicitly as a fact.
We can define a brother relationship as follows −
Two person are brothers, if,
They both are male.
They both are male.
They have the same parent.
They have the same parent.
Now consider we have the below phrases −
parent(sudip, piyus).
parent(sudip, piyus).
parent(sudip, raj).
parent(sudip, raj).
male(piyus).
male(piyus).
male(raj).
male(raj).
brother(X,Y) :- parent(Z,X), parent(Z,Y),male(X), male(Y)
brother(X,Y) :- parent(Z,X), parent(Z,Y),male(X), male(Y)
These clauses can give us the answer that piyus and raj are brothers, but we will get three pairs of output here. They are: (piyus, piyus), (piyus, raj), (raj, raj). For these pairs, given conditions are true, but for the pairs (piyus, piyus), (raj, raj), they are not actually brothers, they are the same persons. So we have to create the clauses properly to form a relationship.
The revised relationship can be as follows −
A and B are brothers if −
A and B, both are male
A and B, both are male
They have same father
They have same father
They have same mother
They have same mother
A and B are not same
A and B are not same
Here we will see the family relationship. This is an example of complex relationship that can be formed using Prolog. We want to make a family tree, and that will be mapped into facts and rules, then we can run some queries on them.
Suppose the family tree is as follows −
Here from this tree, we can understand that there are few relationships. Here bob is a child of pam and tom, and bob also has two children — ann and pat. Bob has one brother liz, whose parent is also tom. So we want to make predicates as follows −
parent(pam, bob).
parent(pam, bob).
parent(tom, bob).
parent(tom, bob).
parent(tom, liz).
parent(tom, liz).
parent(bob, ann).
parent(bob, ann).
parent(bob, pat).
parent(bob, pat).
parent(pat, jim).
parent(pat, jim).
parent(bob, peter).
parent(bob, peter).
parent(peter, jim).
parent(peter, jim).
From our example, it has helped to illustrate some important points −
We have defined parent relation by stating the n-tuples of objects based on the given info in the family tree.
We have defined parent relation by stating the n-tuples of objects based on the given info in the family tree.
The user can easily query the Prolog system about relations defined in the program.
The user can easily query the Prolog system about relations defined in the program.
A Prolog program consists of clauses terminated by a full stop.
A Prolog program consists of clauses terminated by a full stop.
The arguments of relations can (among other things) be: concrete objects, or constants (such as pat and jim), or general objects such as X and Y. Objects of the first kind in our program are called atoms. Objects of the second kind are called variables.
The arguments of relations can (among other things) be: concrete objects, or constants (such as pat and jim), or general objects such as X and Y. Objects of the first kind in our program are called atoms. Objects of the second kind are called variables.
Questions to the system consist of one or more goals.
Questions to the system consist of one or more goals.
Some facts can be written in two different ways, like sex of family members can be written in either of the forms −
female(pam).
female(pam).
male(tom).
male(tom).
male(bob).
male(bob).
female(liz).
female(liz).
female(pat).
female(pat).
female(ann).
female(ann).
male(jim).
male(jim).
Or in the below form −
sex( pam, feminine).
sex( pam, feminine).
sex( tom, masculine).
sex( tom, masculine).
sex( bob, masculine).
sex( bob, masculine).
... and so on.
... and so on.
Now if we want to make mother and sister relationship, then we can write as given below −
In Prolog syntax, we can write −
mother(X,Y) :- parent(X,Y), female(X).
mother(X,Y) :- parent(X,Y), female(X).
sister(X,Y) :- parent(Z,X), parent(Z,Y), female(X), X \== Y.
sister(X,Y) :- parent(Z,X), parent(Z,Y), female(X), X \== Y.
Now let us see the practical demonstration −
female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).
parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
parent(bob,peter).
parent(peter,jim).
mother(X,Y):- parent(X,Y),female(X).
father(X,Y):- parent(X,Y),male(X).
haschild(X):- parent(X,_).
sister(X,Y):- parent(Z,X),parent(Z,Y),female(X),X\==Y.
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.
| ?- [family].
compiling D:/TP Prolog/Sample_Codes/family.pl for byte code...
D:/TP Prolog/Sample_Codes/family.pl compiled, 23 lines read - 3088 bytes written, 9 ms
yes
| ?- parent(X,jim).
X = pat ? ;
X = peter
yes
| ?-
mother(X,Y).
X = pam
Y = bob ? ;
X = pat
Y = jim ? ;
no
| ?- haschild(X).
X = pam ? ;
X = tom ? ;
X = tom ? ;
X = bob ? ;
X = bob ? ;
X = pat ? ;
X = bob ? ;
X = peter
yes
| ?- sister(X,Y).
X = liz
Y = bob ? ;
X = ann
Y = pat ? ;
X = ann
Y = peter ? ;
X = pat
Y = ann ? ;
X = pat
Y = peter ? ;
(16 ms) no
| ?-
Now let us see some more relationships that we can make from the previous relationships of a family. So if we want to make a grandparent relationship, that can be formed as follows −
We can also create some other relationships like wife, uncle, etc. We can write the relationships as given below −
grandparent(X,Y) :- parent(X,Z), parent(Z,Y).
grandparent(X,Y) :- parent(X,Z), parent(Z,Y).
grandmother(X,Z) :- mother(X,Y), parent(Y,Z).
grandmother(X,Z) :- mother(X,Y), parent(Y,Z).
grandfather(X,Z) :- father(X,Y), parent(Y,Z).
grandfather(X,Z) :- father(X,Y), parent(Y,Z).
wife(X,Y) :- parent(X,Z),parent(Y,Z), female(X),male(Y).
wife(X,Y) :- parent(X,Z),parent(Y,Z), female(X),male(Y).
uncle(X,Z) :- brother(X,Y), parent(Y,Z).
uncle(X,Z) :- brother(X,Y), parent(Y,Z).
So let us write a prolog program to see this in action. Here we will also see the trace to trace-out the execution.
female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).
parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
parent(bob,peter).
parent(peter,jim).
mother(X,Y):- parent(X,Y),female(X).
father(X,Y):-parent(X,Y),male(X).
sister(X,Y):-parent(Z,X),parent(Z,Y),female(X),X\==Y.
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.
grandparent(X,Y):-parent(X,Z),parent(Z,Y).
grandmother(X,Z):-mother(X,Y),parent(Y,Z).
grandfather(X,Z):-father(X,Y),parent(Y,Z).
wife(X,Y):-parent(X,Z),parent(Y,Z),female(X),male(Y).
uncle(X,Z):-brother(X,Y),parent(Y,Z).
| ?- [family_ext].
compiling D:/TP Prolog/Sample_Codes/family_ext.pl for byte code...
D:/TP Prolog/Sample_Codes/family_ext.pl compiled, 27 lines read - 4646 bytes written, 10 ms
| ?- uncle(X,Y).
X = peter
Y = jim ? ;
no
| ?- grandparent(X,Y).
X = pam
Y = ann ? ;
X = pam
Y = pat ? ;
X = pam
Y = peter ? ;
X = tom
Y = ann ? ;
X = tom
Y = pat ? ;
X = tom
Y = peter ? ;
X = bob
Y = jim ? ;
X = bob
Y = jim ? ;
no
| ?- wife(X,Y).
X = pam
Y = tom ? ;
X = pat
Y = peter ? ;
(15 ms) no
| ?-
In Prolog we can trace the execution. To trace the output, you have to enter into the trace mode by typing “trace.”. Then from the output we can see that we are just tracing “pam is mother of whom?”. See the tracing output by taking X = pam, and Y as variable, there Y will be bob as answer. To come out from the tracing mode press “notrace.”
| ?- [family_ext].
compiling D:/TP Prolog/Sample_Codes/family_ext.pl for byte code...
D:/TP Prolog/Sample_Codes/family_ext.pl compiled, 27 lines read - 4646 bytes written, 10 ms
(16 ms) yes
| ?- mother(X,Y).
X = pam
Y = bob ? ;
X = pat
Y = jim ? ;
no
| ?- trace.
The debugger will first creep -- showing everything (trace)
yes
{trace}
| ?- mother(pam,Y).
1 1 Call: mother(pam,_23) ?
2 2 Call: parent(pam,_23) ?
2 2 Exit: parent(pam,bob) ?
3 2 Call: female(pam) ?
3 2 Exit: female(pam) ?
1 1 Exit: mother(pam,bob) ?
Y = bob
(16 ms) yes
{trace}
| ?- notrace.
The debugger is switched off
yes
| ?-
In the previous section, we have seen that we can define some family relationships. These relationships are static in nature. We can also create some recursive relationships which can be expressed from the following illustration −
So we can understand that predecessor relationship is recursive. We can express this relationship using the following syntax −
predecessor(X, Z) :- parent(X, Z).
predecessor(X, Z) :- parent(X, Y),predecessor(Y, Z).
Now let us see the practical demonstration.
female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).
parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
parent(bob,peter).
parent(peter,jim).
predecessor(X, Z) :- parent(X, Z).
predecessor(X, Z) :- parent(X, Y),predecessor(Y, Z).
| ?- [family_rec].
compiling D:/TP Prolog/Sample_Codes/family_rec.pl for byte code...
D:/TP Prolog/Sample_Codes/family_rec.pl compiled, 21 lines read - 1851 bytes written, 14 ms
yes
| ?- predecessor(peter,X).
X = jim ? ;
no
| ?- trace.
The debugger will first creep -- showing everything (trace)
yes
{trace}
| ?- predecessor(bob,X).
1 1 Call: predecessor(bob,_23) ?
2 2 Call: parent(bob,_23) ?
2 2 Exit: parent(bob,ann) ?
1 1 Exit: predecessor(bob,ann) ?
X = ann ? ;
1 1 Redo: predecessor(bob,ann) ?
2 2 Redo: parent(bob,ann) ?
2 2 Exit: parent(bob,pat) ?
1 1 Exit: predecessor(bob,pat) ?
X = pat ? ;
1 1 Redo: predecessor(bob,pat) ?
2 2 Redo: parent(bob,pat) ?
2 2 Exit: parent(bob,peter) ?
1 1 Exit: predecessor(bob,peter) ?
X = peter ? ;
1 1 Redo: predecessor(bob,peter) ?
2 2 Call: parent(bob,_92) ?
2 2 Exit: parent(bob,ann) ?
3 2 Call: predecessor(ann,_23) ?
4 3 Call: parent(ann,_23) ?
4 3 Fail: parent(ann,_23) ?
4 3 Call: parent(ann,_141) ?
4 3 Fail: parent(ann,_129) ?
3 2 Fail: predecessor(ann,_23) ?
2 2 Redo: parent(bob,ann) ?
2 2 Exit: parent(bob,pat) ?
3 2 Call: predecessor(pat,_23) ?
4 3 Call: parent(pat,_23) ?
4 3 Exit: parent(pat,jim) ?
3 2 Exit: predecessor(pat,jim) ?
1 1 Exit: predecessor(bob,jim) ?
X = jim ? ;
1 1 Redo: predecessor(bob,jim) ?
3 2 Redo: predecessor(pat,jim) ?
4 3 Call: parent(pat,_141) ?
4 3 Exit: parent(pat,jim) ?
5 3 Call: predecessor(jim,_23) ?
6 4 Call: parent(jim,_23) ?
6 4 Fail: parent(jim,_23) ?
6 4 Call: parent(jim,_190) ?
6 4 Fail: parent(jim,_178) ?
5 3 Fail: predecessor(jim,_23) ?
3 2 Fail: predecessor(pat,_23) ?
2 2 Redo: parent(bob,pat) ?
2 2 Exit: parent(bob,peter) ?
3 2 Call: predecessor(peter,_23) ?
4 3 Call: parent(peter,_23) ?
4 3 Exit: parent(peter,jim) ?
3 2 Exit: predecessor(peter,jim) ?
1 1 Exit: predecessor(bob,jim) ?
X = jim ?
(78 ms) yes
{trace}
| ?-
65 Lectures
5 hours
Arnab Chakraborty
78 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2402,
"s": 2092,
"text": "Relationship is one of the main features that we have to properly mention in Prolog. These relationships can be expressed as facts and rules. After that we will see about the family relationships, how we can express family based relationships in Prolog, and also see the recursive relationships of the family."
},
{
"code": null,
"e": 2489,
"s": 2402,
"text": "We will create the knowledge base by creating facts and rules, and play query on them."
},
{
"code": null,
"e": 2582,
"s": 2489,
"text": "In Prolog programs, it specifies relationship between objects and properties of the objects."
},
{
"code": null,
"e": 2746,
"s": 2582,
"text": "Suppose, there’s a statement, “Amit has a bike”, then we are actually declaring the ownership relationship between two objects — one is Amit and the other is bike."
},
{
"code": null,
"e": 2852,
"s": 2746,
"text": "If we ask a question, “Does Amit own a bike?”, we are actually trying to find out about one relationship."
},
{
"code": null,
"e": 3033,
"s": 2852,
"text": "There are various kinds of relationships, of which some can be rules as well. A rule can find out about a relationship even if the relationship is not defined explicitly as a fact."
},
{
"code": null,
"e": 3083,
"s": 3033,
"text": "We can define a brother relationship as follows −"
},
{
"code": null,
"e": 3112,
"s": 3083,
"text": "Two person are brothers, if,"
},
{
"code": null,
"e": 3132,
"s": 3112,
"text": "They both are male."
},
{
"code": null,
"e": 3152,
"s": 3132,
"text": "They both are male."
},
{
"code": null,
"e": 3179,
"s": 3152,
"text": "They have the same parent."
},
{
"code": null,
"e": 3206,
"s": 3179,
"text": "They have the same parent."
},
{
"code": null,
"e": 3247,
"s": 3206,
"text": "Now consider we have the below phrases −"
},
{
"code": null,
"e": 3269,
"s": 3247,
"text": "parent(sudip, piyus)."
},
{
"code": null,
"e": 3291,
"s": 3269,
"text": "parent(sudip, piyus)."
},
{
"code": null,
"e": 3311,
"s": 3291,
"text": "parent(sudip, raj)."
},
{
"code": null,
"e": 3331,
"s": 3311,
"text": "parent(sudip, raj)."
},
{
"code": null,
"e": 3344,
"s": 3331,
"text": "male(piyus)."
},
{
"code": null,
"e": 3357,
"s": 3344,
"text": "male(piyus)."
},
{
"code": null,
"e": 3368,
"s": 3357,
"text": "male(raj)."
},
{
"code": null,
"e": 3379,
"s": 3368,
"text": "male(raj)."
},
{
"code": null,
"e": 3437,
"s": 3379,
"text": "brother(X,Y) :- parent(Z,X), parent(Z,Y),male(X), male(Y)"
},
{
"code": null,
"e": 3495,
"s": 3437,
"text": "brother(X,Y) :- parent(Z,X), parent(Z,Y),male(X), male(Y)"
},
{
"code": null,
"e": 3876,
"s": 3495,
"text": "These clauses can give us the answer that piyus and raj are brothers, but we will get three pairs of output here. They are: (piyus, piyus), (piyus, raj), (raj, raj). For these pairs, given conditions are true, but for the pairs (piyus, piyus), (raj, raj), they are not actually brothers, they are the same persons. So we have to create the clauses properly to form a relationship."
},
{
"code": null,
"e": 3921,
"s": 3876,
"text": "The revised relationship can be as follows −"
},
{
"code": null,
"e": 3947,
"s": 3921,
"text": "A and B are brothers if −"
},
{
"code": null,
"e": 3970,
"s": 3947,
"text": "A and B, both are male"
},
{
"code": null,
"e": 3993,
"s": 3970,
"text": "A and B, both are male"
},
{
"code": null,
"e": 4015,
"s": 3993,
"text": "They have same father"
},
{
"code": null,
"e": 4037,
"s": 4015,
"text": "They have same father"
},
{
"code": null,
"e": 4059,
"s": 4037,
"text": "They have same mother"
},
{
"code": null,
"e": 4081,
"s": 4059,
"text": "They have same mother"
},
{
"code": null,
"e": 4102,
"s": 4081,
"text": "A and B are not same"
},
{
"code": null,
"e": 4123,
"s": 4102,
"text": "A and B are not same"
},
{
"code": null,
"e": 4356,
"s": 4123,
"text": "Here we will see the family relationship. This is an example of complex relationship that can be formed using Prolog. We want to make a family tree, and that will be mapped into facts and rules, then we can run some queries on them."
},
{
"code": null,
"e": 4396,
"s": 4356,
"text": "Suppose the family tree is as follows −"
},
{
"code": null,
"e": 4644,
"s": 4396,
"text": "Here from this tree, we can understand that there are few relationships. Here bob is a child of pam and tom, and bob also has two children — ann and pat. Bob has one brother liz, whose parent is also tom. So we want to make predicates as follows −"
},
{
"code": null,
"e": 4662,
"s": 4644,
"text": "parent(pam, bob)."
},
{
"code": null,
"e": 4680,
"s": 4662,
"text": "parent(pam, bob)."
},
{
"code": null,
"e": 4698,
"s": 4680,
"text": "parent(tom, bob)."
},
{
"code": null,
"e": 4716,
"s": 4698,
"text": "parent(tom, bob)."
},
{
"code": null,
"e": 4734,
"s": 4716,
"text": "parent(tom, liz)."
},
{
"code": null,
"e": 4752,
"s": 4734,
"text": "parent(tom, liz)."
},
{
"code": null,
"e": 4770,
"s": 4752,
"text": "parent(bob, ann)."
},
{
"code": null,
"e": 4788,
"s": 4770,
"text": "parent(bob, ann)."
},
{
"code": null,
"e": 4806,
"s": 4788,
"text": "parent(bob, pat)."
},
{
"code": null,
"e": 4824,
"s": 4806,
"text": "parent(bob, pat)."
},
{
"code": null,
"e": 4842,
"s": 4824,
"text": "parent(pat, jim)."
},
{
"code": null,
"e": 4860,
"s": 4842,
"text": "parent(pat, jim)."
},
{
"code": null,
"e": 4880,
"s": 4860,
"text": "parent(bob, peter)."
},
{
"code": null,
"e": 4900,
"s": 4880,
"text": "parent(bob, peter)."
},
{
"code": null,
"e": 4920,
"s": 4900,
"text": "parent(peter, jim)."
},
{
"code": null,
"e": 4940,
"s": 4920,
"text": "parent(peter, jim)."
},
{
"code": null,
"e": 5010,
"s": 4940,
"text": "From our example, it has helped to illustrate some important points −"
},
{
"code": null,
"e": 5121,
"s": 5010,
"text": "We have defined parent relation by stating the n-tuples of objects based on the given info in the family tree."
},
{
"code": null,
"e": 5232,
"s": 5121,
"text": "We have defined parent relation by stating the n-tuples of objects based on the given info in the family tree."
},
{
"code": null,
"e": 5316,
"s": 5232,
"text": "The user can easily query the Prolog system about relations defined in the program."
},
{
"code": null,
"e": 5400,
"s": 5316,
"text": "The user can easily query the Prolog system about relations defined in the program."
},
{
"code": null,
"e": 5464,
"s": 5400,
"text": "A Prolog program consists of clauses terminated by a full stop."
},
{
"code": null,
"e": 5528,
"s": 5464,
"text": "A Prolog program consists of clauses terminated by a full stop."
},
{
"code": null,
"e": 5782,
"s": 5528,
"text": "The arguments of relations can (among other things) be: concrete objects, or constants (such as pat and jim), or general objects such as X and Y. Objects of the first kind in our program are called atoms. Objects of the second kind are called variables."
},
{
"code": null,
"e": 6036,
"s": 5782,
"text": "The arguments of relations can (among other things) be: concrete objects, or constants (such as pat and jim), or general objects such as X and Y. Objects of the first kind in our program are called atoms. Objects of the second kind are called variables."
},
{
"code": null,
"e": 6090,
"s": 6036,
"text": "Questions to the system consist of one or more goals."
},
{
"code": null,
"e": 6144,
"s": 6090,
"text": "Questions to the system consist of one or more goals."
},
{
"code": null,
"e": 6260,
"s": 6144,
"text": "Some facts can be written in two different ways, like sex of family members can be written in either of the forms −"
},
{
"code": null,
"e": 6273,
"s": 6260,
"text": "female(pam)."
},
{
"code": null,
"e": 6286,
"s": 6273,
"text": "female(pam)."
},
{
"code": null,
"e": 6297,
"s": 6286,
"text": "male(tom)."
},
{
"code": null,
"e": 6308,
"s": 6297,
"text": "male(tom)."
},
{
"code": null,
"e": 6319,
"s": 6308,
"text": "male(bob)."
},
{
"code": null,
"e": 6330,
"s": 6319,
"text": "male(bob)."
},
{
"code": null,
"e": 6343,
"s": 6330,
"text": "female(liz)."
},
{
"code": null,
"e": 6356,
"s": 6343,
"text": "female(liz)."
},
{
"code": null,
"e": 6369,
"s": 6356,
"text": "female(pat)."
},
{
"code": null,
"e": 6382,
"s": 6369,
"text": "female(pat)."
},
{
"code": null,
"e": 6395,
"s": 6382,
"text": "female(ann)."
},
{
"code": null,
"e": 6408,
"s": 6395,
"text": "female(ann)."
},
{
"code": null,
"e": 6419,
"s": 6408,
"text": "male(jim)."
},
{
"code": null,
"e": 6430,
"s": 6419,
"text": "male(jim)."
},
{
"code": null,
"e": 6453,
"s": 6430,
"text": "Or in the below form −"
},
{
"code": null,
"e": 6474,
"s": 6453,
"text": "sex( pam, feminine)."
},
{
"code": null,
"e": 6495,
"s": 6474,
"text": "sex( pam, feminine)."
},
{
"code": null,
"e": 6517,
"s": 6495,
"text": "sex( tom, masculine)."
},
{
"code": null,
"e": 6539,
"s": 6517,
"text": "sex( tom, masculine)."
},
{
"code": null,
"e": 6561,
"s": 6539,
"text": "sex( bob, masculine)."
},
{
"code": null,
"e": 6583,
"s": 6561,
"text": "sex( bob, masculine)."
},
{
"code": null,
"e": 6598,
"s": 6583,
"text": "... and so on."
},
{
"code": null,
"e": 6613,
"s": 6598,
"text": "... and so on."
},
{
"code": null,
"e": 6703,
"s": 6613,
"text": "Now if we want to make mother and sister relationship, then we can write as given below −"
},
{
"code": null,
"e": 6736,
"s": 6703,
"text": "In Prolog syntax, we can write −"
},
{
"code": null,
"e": 6775,
"s": 6736,
"text": "mother(X,Y) :- parent(X,Y), female(X)."
},
{
"code": null,
"e": 6814,
"s": 6775,
"text": "mother(X,Y) :- parent(X,Y), female(X)."
},
{
"code": null,
"e": 6875,
"s": 6814,
"text": "sister(X,Y) :- parent(Z,X), parent(Z,Y), female(X), X \\== Y."
},
{
"code": null,
"e": 6936,
"s": 6875,
"text": "sister(X,Y) :- parent(Z,X), parent(Z,Y), female(X), X \\== Y."
},
{
"code": null,
"e": 6981,
"s": 6936,
"text": "Now let us see the practical demonstration −"
},
{
"code": null,
"e": 7426,
"s": 6981,
"text": "female(pam).\nfemale(liz).\nfemale(pat).\nfemale(ann).\nmale(jim).\nmale(bob).\nmale(tom).\nmale(peter).\nparent(pam,bob).\nparent(tom,bob).\nparent(tom,liz).\nparent(bob,ann).\nparent(bob,pat).\nparent(pat,jim).\nparent(bob,peter).\nparent(peter,jim).\nmother(X,Y):- parent(X,Y),female(X).\nfather(X,Y):- parent(X,Y),male(X).\nhaschild(X):- parent(X,_).\nsister(X,Y):- parent(Z,X),parent(Z,Y),female(X),X\\==Y.\nbrother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\\==Y."
},
{
"code": null,
"e": 7979,
"s": 7426,
"text": "| ?- [family].\ncompiling D:/TP Prolog/Sample_Codes/family.pl for byte code...\nD:/TP Prolog/Sample_Codes/family.pl compiled, 23 lines read - 3088 bytes written, 9 ms\n\nyes\n| ?- parent(X,jim).\n\nX = pat ? ;\n\nX = peter\n\nyes\n| ?-\nmother(X,Y).\n\nX = pam\nY = bob ? ;\n\nX = pat\nY = jim ? ;\n\nno\n| ?- haschild(X).\n\nX = pam ? ;\n\nX = tom ? ;\n\nX = tom ? ;\n\nX = bob ? ;\n\nX = bob ? ;\n\nX = pat ? ;\n\nX = bob ? ;\n\nX = peter\n\nyes\n| ?- sister(X,Y).\n\nX = liz\nY = bob ? ;\n\nX = ann\nY = pat ? ;\n\nX = ann\nY = peter ? ;\n\nX = pat\nY = ann ? ;\n\nX = pat\nY = peter ? ;\n\n(16 ms) no\n| ?-\n"
},
{
"code": null,
"e": 8162,
"s": 7979,
"text": "Now let us see some more relationships that we can make from the previous relationships of a family. So if we want to make a grandparent relationship, that can be formed as follows −"
},
{
"code": null,
"e": 8277,
"s": 8162,
"text": "We can also create some other relationships like wife, uncle, etc. We can write the relationships as given below −"
},
{
"code": null,
"e": 8323,
"s": 8277,
"text": "grandparent(X,Y) :- parent(X,Z), parent(Z,Y)."
},
{
"code": null,
"e": 8369,
"s": 8323,
"text": "grandparent(X,Y) :- parent(X,Z), parent(Z,Y)."
},
{
"code": null,
"e": 8415,
"s": 8369,
"text": "grandmother(X,Z) :- mother(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 8461,
"s": 8415,
"text": "grandmother(X,Z) :- mother(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 8507,
"s": 8461,
"text": "grandfather(X,Z) :- father(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 8553,
"s": 8507,
"text": "grandfather(X,Z) :- father(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 8610,
"s": 8553,
"text": "wife(X,Y) :- parent(X,Z),parent(Y,Z), female(X),male(Y)."
},
{
"code": null,
"e": 8667,
"s": 8610,
"text": "wife(X,Y) :- parent(X,Z),parent(Y,Z), female(X),male(Y)."
},
{
"code": null,
"e": 8708,
"s": 8667,
"text": "uncle(X,Z) :- brother(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 8749,
"s": 8708,
"text": "uncle(X,Z) :- brother(X,Y), parent(Y,Z)."
},
{
"code": null,
"e": 8865,
"s": 8749,
"text": "So let us write a prolog program to see this in action. Here we will also see the trace to trace-out the execution."
},
{
"code": null,
"e": 9506,
"s": 8865,
"text": "female(pam).\nfemale(liz).\nfemale(pat).\nfemale(ann).\n\nmale(jim).\nmale(bob).\nmale(tom).\nmale(peter).\n\nparent(pam,bob).\nparent(tom,bob).\nparent(tom,liz).\nparent(bob,ann).\n\nparent(bob,pat).\nparent(pat,jim).\nparent(bob,peter).\nparent(peter,jim).\n\nmother(X,Y):- parent(X,Y),female(X).\nfather(X,Y):-parent(X,Y),male(X).\nsister(X,Y):-parent(Z,X),parent(Z,Y),female(X),X\\==Y.\nbrother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\\==Y.\ngrandparent(X,Y):-parent(X,Z),parent(Z,Y).\ngrandmother(X,Z):-mother(X,Y),parent(Y,Z).\ngrandfather(X,Z):-father(X,Y),parent(Y,Z).\nwife(X,Y):-parent(X,Z),parent(Y,Z),female(X),male(Y).\nuncle(X,Z):-brother(X,Y),parent(Y,Z)."
},
{
"code": null,
"e": 10006,
"s": 9506,
"text": "| ?- [family_ext].\ncompiling D:/TP Prolog/Sample_Codes/family_ext.pl for byte code...\nD:/TP Prolog/Sample_Codes/family_ext.pl compiled, 27 lines read - 4646 bytes written, 10 ms\n\n| ?- uncle(X,Y).\n\nX = peter\nY = jim ? ;\n\nno\n| ?- grandparent(X,Y).\n\nX = pam\nY = ann ? ;\n\nX = pam\nY = pat ? ;\n\nX = pam\nY = peter ? ;\n\nX = tom\nY = ann ? ;\n\nX = tom\nY = pat ? ;\n\nX = tom\nY = peter ? ;\n\nX = bob\nY = jim ? ;\n\nX = bob\nY = jim ? ;\n\nno\n| ?- wife(X,Y).\n\nX = pam\nY = tom ? ;\n\nX = pat\nY = peter ? ;\n\n(15 ms) no\n| ?-\n"
},
{
"code": null,
"e": 10349,
"s": 10006,
"text": "In Prolog we can trace the execution. To trace the output, you have to enter into the trace mode by typing “trace.”. Then from the output we can see that we are just tracing “pam is mother of whom?”. See the tracing output by taking X = pam, and Y as variable, there Y will be bob as answer. To come out from the tracing mode press “notrace.”"
},
{
"code": null,
"e": 10973,
"s": 10349,
"text": "| ?- [family_ext].\ncompiling D:/TP Prolog/Sample_Codes/family_ext.pl for byte code...\nD:/TP Prolog/Sample_Codes/family_ext.pl compiled, 27 lines read - 4646 bytes written, 10 ms\n\n(16 ms) yes\n| ?- mother(X,Y).\n\nX = pam\nY = bob ? ;\n\nX = pat\nY = jim ? ;\n\nno\n| ?- trace.\nThe debugger will first creep -- showing everything (trace)\n\nyes\n{trace}\n| ?- mother(pam,Y).\n 1 1 Call: mother(pam,_23) ?\n 2 2 Call: parent(pam,_23) ?\n 2 2 Exit: parent(pam,bob) ?\n 3 2 Call: female(pam) ?\n 3 2 Exit: female(pam) ?\n 1 1 Exit: mother(pam,bob) ?\n \nY = bob\n\n(16 ms) yes\n{trace}\n| ?- notrace.\nThe debugger is switched off\n\nyes\n| ?-"
},
{
"code": null,
"e": 11204,
"s": 10973,
"text": "In the previous section, we have seen that we can define some family relationships. These relationships are static in nature. We can also create some recursive relationships which can be expressed from the following illustration −"
},
{
"code": null,
"e": 11331,
"s": 11204,
"text": "So we can understand that predecessor relationship is recursive. We can express this relationship using the following syntax −"
},
{
"code": null,
"e": 11420,
"s": 11331,
"text": "predecessor(X, Z) :- parent(X, Z).\npredecessor(X, Z) :- parent(X, Y),predecessor(Y, Z).\n"
},
{
"code": null,
"e": 11464,
"s": 11420,
"text": "Now let us see the practical demonstration."
},
{
"code": null,
"e": 11793,
"s": 11464,
"text": "female(pam).\nfemale(liz).\nfemale(pat).\nfemale(ann).\n\nmale(jim).\nmale(bob).\nmale(tom).\nmale(peter).\n\nparent(pam,bob).\nparent(tom,bob).\nparent(tom,liz).\nparent(bob,ann).\nparent(bob,pat).\nparent(pat,jim).\nparent(bob,peter).\nparent(peter,jim).\n\npredecessor(X, Z) :- parent(X, Z).\npredecessor(X, Z) :- parent(X, Y),predecessor(Y, Z)."
},
{
"code": null,
"e": 13784,
"s": 11793,
"text": "| ?- [family_rec].\ncompiling D:/TP Prolog/Sample_Codes/family_rec.pl for byte code...\nD:/TP Prolog/Sample_Codes/family_rec.pl compiled, 21 lines read - 1851 bytes written, 14 ms\n\nyes\n| ?- predecessor(peter,X).\n\nX = jim ? ;\n\nno\n| ?- trace.\nThe debugger will first creep -- showing everything (trace)\n\nyes\n{trace}\n| ?- predecessor(bob,X).\n 1 1 Call: predecessor(bob,_23) ?\n 2 2 Call: parent(bob,_23) ?\n 2 2 Exit: parent(bob,ann) ?\n 1 1 Exit: predecessor(bob,ann) ?\n \nX = ann ? ;\n 1 1 Redo: predecessor(bob,ann) ?\n 2 2 Redo: parent(bob,ann) ?\n 2 2 Exit: parent(bob,pat) ?\n 1 1 Exit: predecessor(bob,pat) ?\n \nX = pat ? ;\n 1 1 Redo: predecessor(bob,pat) ?\n 2 2 Redo: parent(bob,pat) ?\n 2 2 Exit: parent(bob,peter) ?\n 1 1 Exit: predecessor(bob,peter) ?\n \nX = peter ? ;\n 1 1 Redo: predecessor(bob,peter) ?\n 2 2 Call: parent(bob,_92) ?\n 2 2 Exit: parent(bob,ann) ?\n 3 2 Call: predecessor(ann,_23) ?\n 4 3 Call: parent(ann,_23) ?\n 4 3 Fail: parent(ann,_23) ?\n 4 3 Call: parent(ann,_141) ?\n 4 3 Fail: parent(ann,_129) ?\n 3 2 Fail: predecessor(ann,_23) ?\n 2 2 Redo: parent(bob,ann) ?\n 2 2 Exit: parent(bob,pat) ?\n 3 2 Call: predecessor(pat,_23) ?\n 4 3 Call: parent(pat,_23) ?\n 4 3 Exit: parent(pat,jim) ?\n 3 2 Exit: predecessor(pat,jim) ?\n 1 1 Exit: predecessor(bob,jim) ?\n \nX = jim ? ;\n 1 1 Redo: predecessor(bob,jim) ?\n 3 2 Redo: predecessor(pat,jim) ?\n 4 3 Call: parent(pat,_141) ?\n 4 3 Exit: parent(pat,jim) ?\n 5 3 Call: predecessor(jim,_23) ?\n 6 4 Call: parent(jim,_23) ?\n 6 4 Fail: parent(jim,_23) ?\n 6 4 Call: parent(jim,_190) ?\n 6 4 Fail: parent(jim,_178) ?\n 5 3 Fail: predecessor(jim,_23) ?\n 3 2 Fail: predecessor(pat,_23) ?\n 2 2 Redo: parent(bob,pat) ?\n 2 2 Exit: parent(bob,peter) ?\n 3 2 Call: predecessor(peter,_23) ?\n 4 3 Call: parent(peter,_23) ?\n 4 3 Exit: parent(peter,jim) ?\n 3 2 Exit: predecessor(peter,jim) ?\n 1 1 Exit: predecessor(bob,jim) ?\n \nX = jim ?\n\n(78 ms) yes\n{trace}\n| ?-\n"
},
{
"code": null,
"e": 13817,
"s": 13784,
"text": "\n 65 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 13836,
"s": 13817,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 13869,
"s": 13836,
"text": "\n 78 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 13888,
"s": 13869,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 13895,
"s": 13888,
"text": " Print"
},
{
"code": null,
"e": 13906,
"s": 13895,
"text": " Add Notes"
}
] |
Java.lang.Runtime class in Java | 06 May, 2022
In Java, the Runtime class is used to interact with Every Java application that has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method.
Example 1:
Java
// Java Program to Illustrate Runtime class// Via getRuntime(), freeMemory() and// totalMemory() Method // Importing required classesimport java.lang.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Method 1: getRuntime() // Getting the current runtime associated // with this process Runtime run = Runtime.getRuntime(); // Printing the current free memory for this runtime // using freeMemory() method System.out.println("" + run.freeMemory()); // Method 2: freeMemory() // Printing the number of free bytes System.out.println( "" + Runtime.getRuntime().freeMemory()); // Method 3: totalMemory() // Printing the number of total bytes System.out.println( "" + Runtime.getRuntime().totalMemory()); }}
132579840
132285936
134217728
Example 2:
Java
// Java Program to Illustrate Runtime class// Via exec() Method // Importing required classesimport java.util.*;import java.lang.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating a process and execute google-chrome Process process = Runtime.getRuntime().exec( "google-chrome"); System.out.println( "Google Chrome successfully started"); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on the console e.printStackTrace(); } }}
Output:
Google Chrome successfully started
Note: Replace with any software you want to start. Here we work on Linux and google-chrome is written like this way only. May differ in windows/mac.
Example 3:
Java
// Java Program to Illustrate Runtime class// Via availableProcessors() Method, exit() Method // Importing required classesimport java.util.*;import java.lang.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Method 1: availableProcessors() // Check the number of processors available // and printing alongside System.out.println("" + Runtime.getRuntime() .availableProcessors()); // Method 2: exit() // Making program to exit Runtime.getRuntime().exit(0); // Nothing will run now System.out.println("Program Running Check"); // Note: here we will notice that there will be no // output generated on console }}
4
From the above output, it is made clear that exit() method does not let below print statement to execute as “Program Running Check” is not printed on the console. It can be made clear if we comment out the working of availableProcessors() than exit() method output is as follows:
Example 4:
Java
// Java Program to illustrate Runtime Class// Via loadLibrary(), runFinalization()// gc(), maxMemory() // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Method 1: loadLibrary() // Loading a library that is home/saket/Desktop // folder Runtime.getRuntime().loadLibrary( "/home/saket/Desktop/Library"); System.out.println("Library Loaded Successfully"); // Method 2: runFinalization() // Run the finalization Runtime.getRuntime().runFinalization(); // Print statement System.out.println("Finalized"); // Method 3: gc() // Run the garbage collector Runtime.getRuntime().gc(); System.out.println("Running"); // Method 4: maxMemory() // Printing the maximum memory System.out.println( "" + Runtime.getRuntime().maxMemory()); }}
Output:
Library Loaded Successfully
Finalized
Running
2147483648
Example 5:
Java
// Java program to illustrate halt()// method of Runtime classpublic class GFG{ public static void main(String[] args) { // halt this process Runtime.getRuntime().halt(0); // print a string, just to see if it process is halted System.out.println("Process is still running."); }}
Output:
From above output it is made clear above program compiled successfully and run. There is no print statement is execute as we have used halt() method which terminates the further execution of operations.
Example 6:
Java
// Java Program to Illustrate exec()// Method of Runtime class // Importing required classesimport java.io.*;import java.util.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Declaring a string array String[] cmd = new String[2]; // Initializing elements of string array cmd[0] = "atom"; cmd[1] = "File.java"; // Creating a file with directory from local systems File dir = new File("/Users/mayanksolanki/Desktop"); // Creating a process by creating Process class object // and execute above array using exec() method Process process = Runtime.getRuntime().exec(cmd, null); // Display message on console for successful execution System.out.println("File.java opening."); } // Catch block to handle exceptions catch (Exception e) { // Display exceptions with line number // using printStackTrace() method e.printStackTrace(); } }}
Output:
File.java opening.
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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.
sagar0719kumar
as5853535
solankimayank
surinderdawra388
sweetyty
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 May, 2022"
},
{
"code": null,
"e": 338,
"s": 54,
"text": "In Java, the Runtime class is used to interact with Every Java application that has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method."
},
{
"code": null,
"e": 349,
"s": 338,
"text": "Example 1:"
},
{
"code": null,
"e": 354,
"s": 349,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Runtime class// Via getRuntime(), freeMemory() and// totalMemory() Method // Importing required classesimport java.lang.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Method 1: getRuntime() // Getting the current runtime associated // with this process Runtime run = Runtime.getRuntime(); // Printing the current free memory for this runtime // using freeMemory() method System.out.println(\"\" + run.freeMemory()); // Method 2: freeMemory() // Printing the number of free bytes System.out.println( \"\" + Runtime.getRuntime().freeMemory()); // Method 3: totalMemory() // Printing the number of total bytes System.out.println( \"\" + Runtime.getRuntime().totalMemory()); }}",
"e": 1255,
"s": 354,
"text": null
},
{
"code": null,
"e": 1285,
"s": 1255,
"text": "132579840\n132285936\n134217728"
},
{
"code": null,
"e": 1296,
"s": 1285,
"text": "Example 2:"
},
{
"code": null,
"e": 1301,
"s": 1296,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Runtime class// Via exec() Method // Importing required classesimport java.util.*;import java.lang.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating a process and execute google-chrome Process process = Runtime.getRuntime().exec( \"google-chrome\"); System.out.println( \"Google Chrome successfully started\"); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on the console e.printStackTrace(); } }}",
"e": 2022,
"s": 1301,
"text": null
},
{
"code": null,
"e": 2031,
"s": 2022,
"text": "Output: "
},
{
"code": null,
"e": 2066,
"s": 2031,
"text": "Google Chrome successfully started"
},
{
"code": null,
"e": 2215,
"s": 2066,
"text": "Note: Replace with any software you want to start. Here we work on Linux and google-chrome is written like this way only. May differ in windows/mac."
},
{
"code": null,
"e": 2226,
"s": 2215,
"text": "Example 3:"
},
{
"code": null,
"e": 2231,
"s": 2226,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Runtime class// Via availableProcessors() Method, exit() Method // Importing required classesimport java.util.*;import java.lang.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Method 1: availableProcessors() // Check the number of processors available // and printing alongside System.out.println(\"\" + Runtime.getRuntime() .availableProcessors()); // Method 2: exit() // Making program to exit Runtime.getRuntime().exit(0); // Nothing will run now System.out.println(\"Program Running Check\"); // Note: here we will notice that there will be no // output generated on console }}",
"e": 3012,
"s": 2231,
"text": null
},
{
"code": null,
"e": 3014,
"s": 3012,
"text": "4"
},
{
"code": null,
"e": 3295,
"s": 3014,
"text": "From the above output, it is made clear that exit() method does not let below print statement to execute as “Program Running Check” is not printed on the console. It can be made clear if we comment out the working of availableProcessors() than exit() method output is as follows: "
},
{
"code": null,
"e": 3306,
"s": 3295,
"text": "Example 4:"
},
{
"code": null,
"e": 3311,
"s": 3306,
"text": "Java"
},
{
"code": "// Java Program to illustrate Runtime Class// Via loadLibrary(), runFinalization()// gc(), maxMemory() // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Method 1: loadLibrary() // Loading a library that is home/saket/Desktop // folder Runtime.getRuntime().loadLibrary( \"/home/saket/Desktop/Library\"); System.out.println(\"Library Loaded Successfully\"); // Method 2: runFinalization() // Run the finalization Runtime.getRuntime().runFinalization(); // Print statement System.out.println(\"Finalized\"); // Method 3: gc() // Run the garbage collector Runtime.getRuntime().gc(); System.out.println(\"Running\"); // Method 4: maxMemory() // Printing the maximum memory System.out.println( \"\" + Runtime.getRuntime().maxMemory()); }}",
"e": 4240,
"s": 3311,
"text": null
},
{
"code": null,
"e": 4249,
"s": 4240,
"text": "Output: "
},
{
"code": null,
"e": 4306,
"s": 4249,
"text": "Library Loaded Successfully\nFinalized\nRunning\n2147483648"
},
{
"code": null,
"e": 4317,
"s": 4306,
"text": "Example 5:"
},
{
"code": null,
"e": 4322,
"s": 4317,
"text": "Java"
},
{
"code": "// Java program to illustrate halt()// method of Runtime classpublic class GFG{ public static void main(String[] args) { // halt this process Runtime.getRuntime().halt(0); // print a string, just to see if it process is halted System.out.println(\"Process is still running.\"); }}",
"e": 4639,
"s": 4322,
"text": null
},
{
"code": null,
"e": 4648,
"s": 4639,
"text": "Output: "
},
{
"code": null,
"e": 4856,
"s": 4652,
"text": "From above output it is made clear above program compiled successfully and run. There is no print statement is execute as we have used halt() method which terminates the further execution of operations."
},
{
"code": null,
"e": 4867,
"s": 4856,
"text": "Example 6:"
},
{
"code": null,
"e": 4872,
"s": 4867,
"text": "Java"
},
{
"code": "// Java Program to Illustrate exec()// Method of Runtime class // Importing required classesimport java.io.*;import java.util.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Declaring a string array String[] cmd = new String[2]; // Initializing elements of string array cmd[0] = \"atom\"; cmd[1] = \"File.java\"; // Creating a file with directory from local systems File dir = new File(\"/Users/mayanksolanki/Desktop\"); // Creating a process by creating Process class object // and execute above array using exec() method Process process = Runtime.getRuntime().exec(cmd, null); // Display message on console for successful execution System.out.println(\"File.java opening.\"); } // Catch block to handle exceptions catch (Exception e) { // Display exceptions with line number // using printStackTrace() method e.printStackTrace(); } }}",
"e": 6017,
"s": 4872,
"text": null
},
{
"code": null,
"e": 6026,
"s": 6017,
"text": "Output: "
},
{
"code": null,
"e": 6045,
"s": 6026,
"text": "File.java opening."
},
{
"code": null,
"e": 6465,
"s": 6045,
"text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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": 6480,
"s": 6465,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 6490,
"s": 6480,
"text": "as5853535"
},
{
"code": null,
"e": 6504,
"s": 6490,
"text": "solankimayank"
},
{
"code": null,
"e": 6521,
"s": 6504,
"text": "surinderdawra388"
},
{
"code": null,
"e": 6530,
"s": 6521,
"text": "sweetyty"
},
{
"code": null,
"e": 6548,
"s": 6530,
"text": "Java-lang package"
},
{
"code": null,
"e": 6553,
"s": 6548,
"text": "Java"
},
{
"code": null,
"e": 6558,
"s": 6553,
"text": "Java"
},
{
"code": null,
"e": 6656,
"s": 6558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6671,
"s": 6656,
"text": "Arrays in Java"
},
{
"code": null,
"e": 6715,
"s": 6671,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 6751,
"s": 6715,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 6776,
"s": 6751,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 6827,
"s": 6776,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 6849,
"s": 6827,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 6880,
"s": 6849,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 6899,
"s": 6880,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 6929,
"s": 6899,
"text": "HashMap in Java with Examples"
}
] |
DateFormat Class in Java | 15 Dec, 2021
The java.text.DateFormat is an abstract class that is used to format and parse dates for any locale. It allows us to format date to text and parse text to date. DateFormat class provides many functionalities to obtain, format, parse default date/time.
DateFormat class extends Format class that means it is a subclass of Format class. Since DateFormat class is an abstract class, therefore, it can be used for date/time formatting subclasses, which format and parses dates or times in a language-independent manner.
Class Signature:
public abstract class DateFormat extends Format
DateFormat(): The DateFormat() is the constructor of the DateFormat class that is called when an instance of an object of DateFormat class is created.
Note: DateFormat is an abstract class therefore cannot be instantiated
Example: Java Program for better understanding of DateFormat class
Java
// import java.text package for using DateFormat classimport java.text.*;import java.util.*;class GFG { public static void main(String[] args) { // create instance of Date class Date date = new Date(); // to format a date for our timezone System.out.println( "Local Date and Time is : " + DateFormat.getInstance().format(date)); // to format a date for different locale System.out.println( "Date of Canada region : " + DateFormat .getDateInstance(DateFormat.LONG, Locale.CANADA) .format(date)); System.out.println( "Time of Canada region : " + DateFormat .getTimeInstance(DateFormat.LONG, Locale.CANADA) .format(date)); System.out.println( "Date of Italy region : " + DateFormat .getDateInstance(DateFormat.LONG, Locale.ITALY) .format(date)); System.out.println( "Time of Italy region : " + DateFormat .getTimeInstance(DateFormat.LONG, Locale.ITALY) .format(date)); // to get the time zone System.out.println( "Time zone is : " + DateFormat.getInstance().getTimeZone()); System.out.println( "Local Date and Time using getDateInstance() : " + DateFormat.getDateInstance().format(date)); System.out.println( "Local Date and Time using getTimeInstance() : " + DateFormat.getTimeInstance().format(date)); System.out.println( "Local Date and Time using getDateTimeInstance() : " + DateFormat.getDateTimeInstance().format( date)); System.out.println( "Local Date and Time using getDateInstance(DateFormat.LONG) : " + DateFormat.getTimeInstance(DateFormat.LONG) .format(date)); System.out.println( "Local Date and Time using getDateInstance(DateFormat.MEDIUM) : " + DateFormat.getTimeInstance(DateFormat.MEDIUM) .format(date)); System.out.println( "Local Date and Time using getDateInstance(DateFormat.SHORT) : " + DateFormat.getTimeInstance(DateFormat.SHORT) .format(date)); }}
Local Date and Time is : 11/28/21, 7:17 PM
Date of Canada region : November 28, 2021
Time of Canada region : 7:17:40 p.m. UTC
Date of Italy region : 28 novembre 2021
Time of Italy region : 19:17:40 UTC
Time zone is : sun.util.calendar.ZoneInfo[id="Etc/UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Local Date and Time using getDateInstance() : Nov 28, 2021
Local Date and Time using getTimeInstance() : 7:17:40 PM
Local Date and Time using getDateTimeInstance() : Nov 28, 2021, 7:17:40 PM
Local Date and Time using getDateInstance(DateFormat.LONG) : 7:17:40 PM UTC
Local Date and Time using getDateInstance(DateFormat.MEDIUM) : 7:17:40 PM
Local Date and Time using getDateInstance(DateFormat.SHORT) : 7:17 PM
Java-Classes
Java-DateFormat
Picked
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": 28,
"s": 0,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 280,
"s": 28,
"text": "The java.text.DateFormat is an abstract class that is used to format and parse dates for any locale. It allows us to format date to text and parse text to date. DateFormat class provides many functionalities to obtain, format, parse default date/time."
},
{
"code": null,
"e": 546,
"s": 280,
"text": "DateFormat class extends Format class that means it is a subclass of Format class. Since DateFormat class is an abstract class, therefore, it can be used for date/time formatting subclasses, which format and parses dates or times in a language-independent manner. "
},
{
"code": null,
"e": 563,
"s": 546,
"text": "Class Signature:"
},
{
"code": null,
"e": 611,
"s": 563,
"text": "public abstract class DateFormat extends Format"
},
{
"code": null,
"e": 762,
"s": 611,
"text": "DateFormat(): The DateFormat() is the constructor of the DateFormat class that is called when an instance of an object of DateFormat class is created."
},
{
"code": null,
"e": 833,
"s": 762,
"text": "Note: DateFormat is an abstract class therefore cannot be instantiated"
},
{
"code": null,
"e": 900,
"s": 833,
"text": "Example: Java Program for better understanding of DateFormat class"
},
{
"code": null,
"e": 905,
"s": 900,
"text": "Java"
},
{
"code": "// import java.text package for using DateFormat classimport java.text.*;import java.util.*;class GFG { public static void main(String[] args) { // create instance of Date class Date date = new Date(); // to format a date for our timezone System.out.println( \"Local Date and Time is : \" + DateFormat.getInstance().format(date)); // to format a date for different locale System.out.println( \"Date of Canada region : \" + DateFormat .getDateInstance(DateFormat.LONG, Locale.CANADA) .format(date)); System.out.println( \"Time of Canada region : \" + DateFormat .getTimeInstance(DateFormat.LONG, Locale.CANADA) .format(date)); System.out.println( \"Date of Italy region : \" + DateFormat .getDateInstance(DateFormat.LONG, Locale.ITALY) .format(date)); System.out.println( \"Time of Italy region : \" + DateFormat .getTimeInstance(DateFormat.LONG, Locale.ITALY) .format(date)); // to get the time zone System.out.println( \"Time zone is : \" + DateFormat.getInstance().getTimeZone()); System.out.println( \"Local Date and Time using getDateInstance() : \" + DateFormat.getDateInstance().format(date)); System.out.println( \"Local Date and Time using getTimeInstance() : \" + DateFormat.getTimeInstance().format(date)); System.out.println( \"Local Date and Time using getDateTimeInstance() : \" + DateFormat.getDateTimeInstance().format( date)); System.out.println( \"Local Date and Time using getDateInstance(DateFormat.LONG) : \" + DateFormat.getTimeInstance(DateFormat.LONG) .format(date)); System.out.println( \"Local Date and Time using getDateInstance(DateFormat.MEDIUM) : \" + DateFormat.getTimeInstance(DateFormat.MEDIUM) .format(date)); System.out.println( \"Local Date and Time using getDateInstance(DateFormat.SHORT) : \" + DateFormat.getTimeInstance(DateFormat.SHORT) .format(date)); }}",
"e": 3411,
"s": 905,
"text": null
},
{
"code": null,
"e": 4148,
"s": 3411,
"text": "Local Date and Time is : 11/28/21, 7:17 PM\nDate of Canada region : November 28, 2021\nTime of Canada region : 7:17:40 p.m. UTC\nDate of Italy region : 28 novembre 2021\nTime of Italy region : 19:17:40 UTC\nTime zone is : sun.util.calendar.ZoneInfo[id=\"Etc/UTC\",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]\nLocal Date and Time using getDateInstance() : Nov 28, 2021\nLocal Date and Time using getTimeInstance() : 7:17:40 PM\nLocal Date and Time using getDateTimeInstance() : Nov 28, 2021, 7:17:40 PM\nLocal Date and Time using getDateInstance(DateFormat.LONG) : 7:17:40 PM UTC\nLocal Date and Time using getDateInstance(DateFormat.MEDIUM) : 7:17:40 PM\nLocal Date and Time using getDateInstance(DateFormat.SHORT) : 7:17 PM"
},
{
"code": null,
"e": 4161,
"s": 4148,
"text": "Java-Classes"
},
{
"code": null,
"e": 4177,
"s": 4161,
"text": "Java-DateFormat"
},
{
"code": null,
"e": 4184,
"s": 4177,
"text": "Picked"
},
{
"code": null,
"e": 4189,
"s": 4184,
"text": "Java"
},
{
"code": null,
"e": 4194,
"s": 4189,
"text": "Java"
},
{
"code": null,
"e": 4292,
"s": 4194,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4307,
"s": 4292,
"text": "Stream In Java"
},
{
"code": null,
"e": 4328,
"s": 4307,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4349,
"s": 4328,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4368,
"s": 4349,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4385,
"s": 4368,
"text": "Generics in Java"
},
{
"code": null,
"e": 4415,
"s": 4385,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 4441,
"s": 4415,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4457,
"s": 4441,
"text": "Strings in Java"
},
{
"code": null,
"e": 4494,
"s": 4457,
"text": "Differences between JDK, JRE and JVM"
}
] |
Sum of all numbers in the given range which are divisible by M | 21 Apr, 2021
Given three numbers A, B and M such that A < B, the task is to find the sum of numbers divisible by M in the range [A, B].
Examples:
Input: A = 25, B = 100, M = 30 Output: 180 Explanation: In the given range [25, 100] 30, 60 and 90 are the numbers which are divisible by M = 30 Therefore, sum of these numbers = 180.
Input: A = 6, B = 15, M = 3 Output: 42 Explanation: In the given range [6, 15] 6, 9, 12 and 15 are the numbers which are divisible by M = 3. Therefore, sum of these numbers = 42.
Naive Approach: Check for each number in the range [A, B] if they are divisible by M or not. And finally, add all the numbers that are divisible by M.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the sum of numbers// divisible by M in the given range #include <bits/stdc++.h>using namespace std; // Function to find the sum of numbers// divisible by M in the given rangeint sumDivisibles(int A, int B, int M){ // Variable to store the sum int sum = 0; // Running a loop from A to B and check // if a number is divisible by i. for (int i = A; i <= B; i++) // If the number is divisible, // then add it to sum if (i % M == 0) sum += i; // Return the sum return sum;} // Driver codeint main(){ // A and B define the range // M is the dividend int A = 6, B = 15, M = 3; // Printing the result cout << sumDivisibles(A, B, M) << endl; return 0;}
// Java program to find the sum of numbers// divisible by M in the given rangeimport java.util.*; class GFG{ // Function to find the sum of numbers// divisible by M in the given rangestatic int sumDivisibles(int A, int B, int M){ // Variable to store the sum int sum = 0; // Running a loop from A to B and check // if a number is divisible by i. for (int i = A; i <= B; i++) // If the number is divisible, // then add it to sum if (i % M == 0) sum += i; // Return the sum return sum;} // Driver codepublic static void main(String[] args){ // A and B define the range // M is the dividend int A = 6, B = 15, M = 3; // Printing the result System.out.print(sumDivisibles(A, B, M) +"\n");}} // This code is contributed by 29AjayKumar
# Python 3 program to find the sum of numbers# divisible by M in the given range # Function to find the sum of numbers# divisible by M in the given rangedef sumDivisibles(A, B, M): # Variable to store the sum sum = 0 # Running a loop from A to B and check # if a number is divisible by i. for i in range(A, B + 1): # If the number is divisible, # then add it to sum if (i % M == 0): sum += i # Return the sum return sum # Driver codeif __name__=="__main__": # A and B define the range # M is the dividend A = 6 B = 15 M = 3 # Printing the result print(sumDivisibles(A, B, M)) # This code is contributed by chitranayal
// C# program to find the sum of numbers// divisible by M in the given rangeusing System; class GFG{ // Function to find the sum of numbers// divisible by M in the given rangestatic int sumDivisibles(int A, int B, int M){ // Variable to store the sum int sum = 0; // Running a loop from A to B and check // if a number is divisible by i. for (int i = A; i <= B; i++) // If the number is divisible, // then add it to sum if (i % M == 0) sum += i; // Return the sum return sum;} // Driver codepublic static void Main(String[] args){ // A and B define the range // M is the dividend int A = 6, B = 15, M = 3; // Printing the result Console.Write(sumDivisibles(A, B, M) +"\n");}} // This code is contributed by sapnasingh4991
<script> // Javascript program to find the sum of numbers// divisible by M in the given range // Function to find the sum of numbers// divisible by M in the given rangefunction sumDivisibles(A, B, M){ // Variable to store the sum var sum = 0; // Running a loop from A to B and check // if a number is divisible by i. for(var i = A; i <= B; i++) // If the number is divisible, // then add it to sum if (i % M == 0) sum += i; // Return the sum return sum;} // Driver code // A and B define the range// M is the dividendvar A = 6, B = 15, M = 3; // Printing the resultdocument.write(sumDivisibles(A, B, M)); // This code is contributed by rrrtnx </script>
42
Time Complexity: O(N).Efficient Approach: The idea is to use the concept of Arithmetic Progression and divisibility.
Upon visualization, the multiples of M can be seen to form a series
M, 2M, 3M, ...
If we can find the value of K which is the first term in the range [A, B] which is divisible by M, then directly, the series would be:
K, (K + M), (K + 2M), ------ (K + (N - 1)*M )
where N is the number of elements in the series.
Therefore, the first term ‘K’ in the series is nothing but the largest number smaller than or equal to A that is divisible by M.
Similarly, the last term is the smallest number greater than or equal B that is divisible by M.
However, if any of the above numbers exceed out of the range, then we can directly subtract M from it to bring it into the range.
And, the number of terms divisible by M can be found out by the formula:
N = B / M - (A - 1)/ M
Therefore, the sum of the elements can be found out by:
sum = N * ( (first term + last term) / 2)
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the sum of numbers// divisible by M in the given range #include <bits/stdc++.h>using namespace std; // Function to find the largest number// smaller than or equal to N// that is divisible by Kint findSmallNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = N % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N - rem;} // Function to find the smallest number// greater than or equal to N// that is divisible by Kint findLargeNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = (N + K) % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N + K - rem;} // Function to find the sum of numbers// divisible by M in the given rangeint sumDivisibles(int A, int B, int M){ // Variable to store the sum int sum = 0; int first = findSmallNum(A, M); int last = findLargeNum(B, M); // To bring the smallest and largest // numbers in the range [A, B] if (first < A) first += M; if (last > B) first -= M; // To count the number of terms in the AP int n = (B / M) - (A - 1) / M; // Sum of n terms of an AP return n * (first + last) / 2;} // Driver codeint main(){ // A and B define the range, // M is the dividend int A = 6, B = 15, M = 3; // Printing the result cout << sumDivisibles(A, B, M); return 0;}
// Java program to find the sum of numbers// divisible by M in the given range class GFG{ // Function to find the largest number// smaller than or equal to N// that is divisible by Kstatic int findSmallNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = N % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N - rem;} // Function to find the smallest number// greater than or equal to N// that is divisible by Kstatic int findLargeNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = (N + K) % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N + K - rem;} // Function to find the sum of numbers// divisible by M in the given rangestatic int sumDivisibles(int A, int B, int M){ // Variable to store the sum int first = findSmallNum(A, M); int last = findLargeNum(B, M); // To bring the smallest and largest // numbers in the range [A, B] if (first < A) first += M; if (last > B) first -= M; // To count the number of terms in the AP int n = (B / M) - (A - 1) / M; // Sum of n terms of an AP return n * (first + last) / 2;} // Driver codepublic static void main(String[] args){ // A and B define the range, // M is the dividend int A = 6, B = 15, M = 3; // Printing the result System.out.print(sumDivisibles(A, B, M)); }} // This code contributed by Princi Singh
# Python3 program to find the sum of numbers# divisible by M in the given range # Function to find the largest number# smaller than or equal to N# that is divisible by Kdef findSmallNum(N, K): # Finding the remainder when N is # divided by K rem = N % K # If the remainder is 0, then the # number itself is divisible by K if (rem == 0): return N else: # Else, then the difference between # N and remainder is the largest number # which is divisible by K return N - rem # Function to find the smallest number# greater than or equal to N# that is divisible by Kdef findLargeNum(N, K): # Finding the remainder when N is # divided by K rem = (N + K) % K # If the remainder is 0, then the # number itself is divisible by K if (rem == 0): return N else: # Else, then the difference between # N and remainder is the largest number # which is divisible by K return N + K - rem # Function to find the sum of numbers# divisible by M in the given rangedef sumDivisibles(A, B, M): # Variable to store the sum sum = 0 first = findSmallNum(A, M) last = findLargeNum(B, M) # To bring the smallest and largest # numbers in the range [A, B] if (first < A): first += M if (last > B): first -= M # To count the number of terms in the AP n = (B // M) - (A - 1) // M # Sum of n terms of an AP return n * (first + last) // 2 # Driver codeif __name__ == '__main__': # A and B define the range, # M is the dividend A = 6 B = 15 M = 3 # Printing the result print(sumDivisibles(A, B, M)) # This code is contributed by Surendra_Gangwar
// C# program to find the sum of numbers// divisible by M in the given rangeusing System;using System.Collections.Generic; class GFG{ // Function to find the largest number// smaller than or equal to N// that is divisible by Kstatic int findSmallNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = N % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N - rem;} // Function to find the smallest number// greater than or equal to N// that is divisible by Kstatic int findLargeNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = (N + K) % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N + K - rem;} // Function to find the sum of numbers// divisible by M in the given rangestatic int sumDivisibles(int A, int B, int M){ // Variable to store the sum int first = findSmallNum(A, M); int last = findLargeNum(B, M); // To bring the smallest and largest // numbers in the range [A, B] if (first < A) first += M; if (last > B) first -= M; // To count the number of terms in the AP int n = (B / M) - (A - 1) / M; // Sum of n terms of an AP return n * (first + last) / 2;} // Driver codepublic static void Main(String[] args){ // A and B define the range, // M is the dividend int A = 6, B = 15, M = 3; // Printing the result Console.Write(sumDivisibles(A, B, M)); }} // This code is contributed by Rajput-Ji
<script> // Javascript program to find the sum of numbers// divisible by M in the given range // Function to find the largest number// smaller than or equal to N// that is divisible by Kfunction findSmallNum(N, K){ // Finding the remainder when N is // divided by K var rem = N % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N - rem;} // Function to find the smallest number// greater than or equal to N// that is divisible by Kfunction findLargeNum(N, K){ // Finding the remainder when N is // divided by K var rem = (N + K) % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N + K - rem;} // Function to find the sum of numbers// divisible by M in the given rangefunction sumDivisibles(A, B, M){ // Variable to store the sum var sum = 0; var first = findSmallNum(A, M); var last = findLargeNum(B, M); // To bring the smallest and largest // numbers in the range [A, B] if (first < A) first += M; if (last > B) first -= M; // To count the number of terms in the AP var n = (parseInt(B / M) - parseInt((A - 1) / M)); // Sum of n terms of an AP return n * (first + last) / 2;} // Driver code // A and B define the range,// M is the dividendvar A = 6, B = 15, M = 3; // Printing the resultdocument.write( sumDivisibles(A, B, M)); // This code is contributed by rutvik_56 </script>
42
Time Complexity: O(1).
SURENDRA_GANGWAR
ukasp
29AjayKumar
sapnasingh4991
princi singh
Rajput-Ji
rrrtnx
rutvik_56
arithmetic progression
Number Divisibility
series-sum
Greedy
Mathematical
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 177,
"s": 54,
"text": "Given three numbers A, B and M such that A < B, the task is to find the sum of numbers divisible by M in the range [A, B]."
},
{
"code": null,
"e": 188,
"s": 177,
"text": "Examples: "
},
{
"code": null,
"e": 372,
"s": 188,
"text": "Input: A = 25, B = 100, M = 30 Output: 180 Explanation: In the given range [25, 100] 30, 60 and 90 are the numbers which are divisible by M = 30 Therefore, sum of these numbers = 180."
},
{
"code": null,
"e": 553,
"s": 372,
"text": "Input: A = 6, B = 15, M = 3 Output: 42 Explanation: In the given range [6, 15] 6, 9, 12 and 15 are the numbers which are divisible by M = 3. Therefore, sum of these numbers = 42. "
},
{
"code": null,
"e": 704,
"s": 553,
"text": "Naive Approach: Check for each number in the range [A, B] if they are divisible by M or not. And finally, add all the numbers that are divisible by M."
},
{
"code": null,
"e": 756,
"s": 704,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 760,
"s": 756,
"text": "C++"
},
{
"code": null,
"e": 765,
"s": 760,
"text": "Java"
},
{
"code": null,
"e": 773,
"s": 765,
"text": "Python3"
},
{
"code": null,
"e": 776,
"s": 773,
"text": "C#"
},
{
"code": null,
"e": 787,
"s": 776,
"text": "Javascript"
},
{
"code": "// C++ program to find the sum of numbers// divisible by M in the given range #include <bits/stdc++.h>using namespace std; // Function to find the sum of numbers// divisible by M in the given rangeint sumDivisibles(int A, int B, int M){ // Variable to store the sum int sum = 0; // Running a loop from A to B and check // if a number is divisible by i. for (int i = A; i <= B; i++) // If the number is divisible, // then add it to sum if (i % M == 0) sum += i; // Return the sum return sum;} // Driver codeint main(){ // A and B define the range // M is the dividend int A = 6, B = 15, M = 3; // Printing the result cout << sumDivisibles(A, B, M) << endl; return 0;}",
"e": 1530,
"s": 787,
"text": null
},
{
"code": "// Java program to find the sum of numbers// divisible by M in the given rangeimport java.util.*; class GFG{ // Function to find the sum of numbers// divisible by M in the given rangestatic int sumDivisibles(int A, int B, int M){ // Variable to store the sum int sum = 0; // Running a loop from A to B and check // if a number is divisible by i. for (int i = A; i <= B; i++) // If the number is divisible, // then add it to sum if (i % M == 0) sum += i; // Return the sum return sum;} // Driver codepublic static void main(String[] args){ // A and B define the range // M is the dividend int A = 6, B = 15, M = 3; // Printing the result System.out.print(sumDivisibles(A, B, M) +\"\\n\");}} // This code is contributed by 29AjayKumar",
"e": 2338,
"s": 1530,
"text": null
},
{
"code": "# Python 3 program to find the sum of numbers# divisible by M in the given range # Function to find the sum of numbers# divisible by M in the given rangedef sumDivisibles(A, B, M): # Variable to store the sum sum = 0 # Running a loop from A to B and check # if a number is divisible by i. for i in range(A, B + 1): # If the number is divisible, # then add it to sum if (i % M == 0): sum += i # Return the sum return sum # Driver codeif __name__==\"__main__\": # A and B define the range # M is the dividend A = 6 B = 15 M = 3 # Printing the result print(sumDivisibles(A, B, M)) # This code is contributed by chitranayal",
"e": 3044,
"s": 2338,
"text": null
},
{
"code": "// C# program to find the sum of numbers// divisible by M in the given rangeusing System; class GFG{ // Function to find the sum of numbers// divisible by M in the given rangestatic int sumDivisibles(int A, int B, int M){ // Variable to store the sum int sum = 0; // Running a loop from A to B and check // if a number is divisible by i. for (int i = A; i <= B; i++) // If the number is divisible, // then add it to sum if (i % M == 0) sum += i; // Return the sum return sum;} // Driver codepublic static void Main(String[] args){ // A and B define the range // M is the dividend int A = 6, B = 15, M = 3; // Printing the result Console.Write(sumDivisibles(A, B, M) +\"\\n\");}} // This code is contributed by sapnasingh4991",
"e": 3851,
"s": 3044,
"text": null
},
{
"code": "<script> // Javascript program to find the sum of numbers// divisible by M in the given range // Function to find the sum of numbers// divisible by M in the given rangefunction sumDivisibles(A, B, M){ // Variable to store the sum var sum = 0; // Running a loop from A to B and check // if a number is divisible by i. for(var i = A; i <= B; i++) // If the number is divisible, // then add it to sum if (i % M == 0) sum += i; // Return the sum return sum;} // Driver code // A and B define the range// M is the dividendvar A = 6, B = 15, M = 3; // Printing the resultdocument.write(sumDivisibles(A, B, M)); // This code is contributed by rrrtnx </script>",
"e": 4569,
"s": 3851,
"text": null
},
{
"code": null,
"e": 4572,
"s": 4569,
"text": "42"
},
{
"code": null,
"e": 4692,
"s": 4574,
"text": "Time Complexity: O(N).Efficient Approach: The idea is to use the concept of Arithmetic Progression and divisibility. "
},
{
"code": null,
"e": 4760,
"s": 4692,
"text": "Upon visualization, the multiples of M can be seen to form a series"
},
{
"code": null,
"e": 4775,
"s": 4760,
"text": "M, 2M, 3M, ..."
},
{
"code": null,
"e": 4910,
"s": 4775,
"text": "If we can find the value of K which is the first term in the range [A, B] which is divisible by M, then directly, the series would be:"
},
{
"code": null,
"e": 5007,
"s": 4910,
"text": "K, (K + M), (K + 2M), ------ (K + (N - 1)*M )\nwhere N is the number of elements in the series. "
},
{
"code": null,
"e": 5136,
"s": 5007,
"text": "Therefore, the first term ‘K’ in the series is nothing but the largest number smaller than or equal to A that is divisible by M."
},
{
"code": null,
"e": 5232,
"s": 5136,
"text": "Similarly, the last term is the smallest number greater than or equal B that is divisible by M."
},
{
"code": null,
"e": 5362,
"s": 5232,
"text": "However, if any of the above numbers exceed out of the range, then we can directly subtract M from it to bring it into the range."
},
{
"code": null,
"e": 5435,
"s": 5362,
"text": "And, the number of terms divisible by M can be found out by the formula:"
},
{
"code": null,
"e": 5458,
"s": 5435,
"text": "N = B / M - (A - 1)/ M"
},
{
"code": null,
"e": 5514,
"s": 5458,
"text": "Therefore, the sum of the elements can be found out by:"
},
{
"code": null,
"e": 5556,
"s": 5514,
"text": "sum = N * ( (first term + last term) / 2)"
},
{
"code": null,
"e": 5608,
"s": 5556,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 5612,
"s": 5608,
"text": "C++"
},
{
"code": null,
"e": 5617,
"s": 5612,
"text": "Java"
},
{
"code": null,
"e": 5625,
"s": 5617,
"text": "Python3"
},
{
"code": null,
"e": 5628,
"s": 5625,
"text": "C#"
},
{
"code": null,
"e": 5639,
"s": 5628,
"text": "Javascript"
},
{
"code": "// C++ program to find the sum of numbers// divisible by M in the given range #include <bits/stdc++.h>using namespace std; // Function to find the largest number// smaller than or equal to N// that is divisible by Kint findSmallNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = N % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N - rem;} // Function to find the smallest number// greater than or equal to N// that is divisible by Kint findLargeNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = (N + K) % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N + K - rem;} // Function to find the sum of numbers// divisible by M in the given rangeint sumDivisibles(int A, int B, int M){ // Variable to store the sum int sum = 0; int first = findSmallNum(A, M); int last = findLargeNum(B, M); // To bring the smallest and largest // numbers in the range [A, B] if (first < A) first += M; if (last > B) first -= M; // To count the number of terms in the AP int n = (B / M) - (A - 1) / M; // Sum of n terms of an AP return n * (first + last) / 2;} // Driver codeint main(){ // A and B define the range, // M is the dividend int A = 6, B = 15, M = 3; // Printing the result cout << sumDivisibles(A, B, M); return 0;}",
"e": 7429,
"s": 5639,
"text": null
},
{
"code": "// Java program to find the sum of numbers// divisible by M in the given range class GFG{ // Function to find the largest number// smaller than or equal to N// that is divisible by Kstatic int findSmallNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = N % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N - rem;} // Function to find the smallest number// greater than or equal to N// that is divisible by Kstatic int findLargeNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = (N + K) % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N + K - rem;} // Function to find the sum of numbers// divisible by M in the given rangestatic int sumDivisibles(int A, int B, int M){ // Variable to store the sum int first = findSmallNum(A, M); int last = findLargeNum(B, M); // To bring the smallest and largest // numbers in the range [A, B] if (first < A) first += M; if (last > B) first -= M; // To count the number of terms in the AP int n = (B / M) - (A - 1) / M; // Sum of n terms of an AP return n * (first + last) / 2;} // Driver codepublic static void main(String[] args){ // A and B define the range, // M is the dividend int A = 6, B = 15, M = 3; // Printing the result System.out.print(sumDivisibles(A, B, M)); }} // This code contributed by Princi Singh",
"e": 9273,
"s": 7429,
"text": null
},
{
"code": "# Python3 program to find the sum of numbers# divisible by M in the given range # Function to find the largest number# smaller than or equal to N# that is divisible by Kdef findSmallNum(N, K): # Finding the remainder when N is # divided by K rem = N % K # If the remainder is 0, then the # number itself is divisible by K if (rem == 0): return N else: # Else, then the difference between # N and remainder is the largest number # which is divisible by K return N - rem # Function to find the smallest number# greater than or equal to N# that is divisible by Kdef findLargeNum(N, K): # Finding the remainder when N is # divided by K rem = (N + K) % K # If the remainder is 0, then the # number itself is divisible by K if (rem == 0): return N else: # Else, then the difference between # N and remainder is the largest number # which is divisible by K return N + K - rem # Function to find the sum of numbers# divisible by M in the given rangedef sumDivisibles(A, B, M): # Variable to store the sum sum = 0 first = findSmallNum(A, M) last = findLargeNum(B, M) # To bring the smallest and largest # numbers in the range [A, B] if (first < A): first += M if (last > B): first -= M # To count the number of terms in the AP n = (B // M) - (A - 1) // M # Sum of n terms of an AP return n * (first + last) // 2 # Driver codeif __name__ == '__main__': # A and B define the range, # M is the dividend A = 6 B = 15 M = 3 # Printing the result print(sumDivisibles(A, B, M)) # This code is contributed by Surendra_Gangwar",
"e": 10992,
"s": 9273,
"text": null
},
{
"code": "// C# program to find the sum of numbers// divisible by M in the given rangeusing System;using System.Collections.Generic; class GFG{ // Function to find the largest number// smaller than or equal to N// that is divisible by Kstatic int findSmallNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = N % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N - rem;} // Function to find the smallest number// greater than or equal to N// that is divisible by Kstatic int findLargeNum(int N, int K){ // Finding the remainder when N is // divided by K int rem = (N + K) % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N + K - rem;} // Function to find the sum of numbers// divisible by M in the given rangestatic int sumDivisibles(int A, int B, int M){ // Variable to store the sum int first = findSmallNum(A, M); int last = findLargeNum(B, M); // To bring the smallest and largest // numbers in the range [A, B] if (first < A) first += M; if (last > B) first -= M; // To count the number of terms in the AP int n = (B / M) - (A - 1) / M; // Sum of n terms of an AP return n * (first + last) / 2;} // Driver codepublic static void Main(String[] args){ // A and B define the range, // M is the dividend int A = 6, B = 15, M = 3; // Printing the result Console.Write(sumDivisibles(A, B, M)); }} // This code is contributed by Rajput-Ji",
"e": 12891,
"s": 10992,
"text": null
},
{
"code": "<script> // Javascript program to find the sum of numbers// divisible by M in the given range // Function to find the largest number// smaller than or equal to N// that is divisible by Kfunction findSmallNum(N, K){ // Finding the remainder when N is // divided by K var rem = N % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N - rem;} // Function to find the smallest number// greater than or equal to N// that is divisible by Kfunction findLargeNum(N, K){ // Finding the remainder when N is // divided by K var rem = (N + K) % K; // If the remainder is 0, then the // number itself is divisible by K if (rem == 0) return N; else // Else, then the difference between // N and remainder is the largest number // which is divisible by K return N + K - rem;} // Function to find the sum of numbers// divisible by M in the given rangefunction sumDivisibles(A, B, M){ // Variable to store the sum var sum = 0; var first = findSmallNum(A, M); var last = findLargeNum(B, M); // To bring the smallest and largest // numbers in the range [A, B] if (first < A) first += M; if (last > B) first -= M; // To count the number of terms in the AP var n = (parseInt(B / M) - parseInt((A - 1) / M)); // Sum of n terms of an AP return n * (first + last) / 2;} // Driver code // A and B define the range,// M is the dividendvar A = 6, B = 15, M = 3; // Printing the resultdocument.write( sumDivisibles(A, B, M)); // This code is contributed by rutvik_56 </script>",
"e": 14701,
"s": 12891,
"text": null
},
{
"code": null,
"e": 14704,
"s": 14701,
"text": "42"
},
{
"code": null,
"e": 14730,
"s": 14706,
"text": "Time Complexity: O(1). "
},
{
"code": null,
"e": 14747,
"s": 14730,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 14753,
"s": 14747,
"text": "ukasp"
},
{
"code": null,
"e": 14765,
"s": 14753,
"text": "29AjayKumar"
},
{
"code": null,
"e": 14780,
"s": 14765,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 14793,
"s": 14780,
"text": "princi singh"
},
{
"code": null,
"e": 14803,
"s": 14793,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 14810,
"s": 14803,
"text": "rrrtnx"
},
{
"code": null,
"e": 14820,
"s": 14810,
"text": "rutvik_56"
},
{
"code": null,
"e": 14843,
"s": 14820,
"text": "arithmetic progression"
},
{
"code": null,
"e": 14863,
"s": 14843,
"text": "Number Divisibility"
},
{
"code": null,
"e": 14874,
"s": 14863,
"text": "series-sum"
},
{
"code": null,
"e": 14881,
"s": 14874,
"text": "Greedy"
},
{
"code": null,
"e": 14894,
"s": 14881,
"text": "Mathematical"
},
{
"code": null,
"e": 14901,
"s": 14894,
"text": "Greedy"
},
{
"code": null,
"e": 14914,
"s": 14901,
"text": "Mathematical"
}
] |
Heap and Stack Memory Errors in Java | 12 Sep, 2021
Memory allocation in java is managed by Java virtual machine in Java. It divides the memory into stack and heap memory which is as shown below in the below media as follows:
Stack memory in Java
It is the temporary memory allocation where local variables, reference variables are allocated memory when their methods are called. It contains references to the object are stored in a heap. After the execution of the method, the memory containing those variables is cleared. We can access this memory in Last In First Out Order. Allocation and deallocation is faster than heap memory. It is safer as data can only be accessed by the thread owner. If stack memory is full, then StackOverflowException is thrown by the JVM.
Illustration:
// Java Program to Illustrate Stack Memory
// Importing required I/O classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main (String[] args) {
// Creating an integer array
int a [] = new int[5];
}
}
Diagrammatic explanation of the above example
In the above illustration, we can conclusively perceive the above media shown and conclude out the following points
‘a’ is a variable of array type stored in a stack.
new keyword is used to allocate memory in the heap.
5 is the size of the array.
Stack Memory Error
Whenever we call a method, after its execution it leaves the stack memory. If your methods are staying in the stack then the stack will be full, If the stack is full we can’t push, if we do then we will get the error java.lang.StackOverflowError which will be thrown by JVM. It is thrown when you call a method and there is no space left in the stack. In most cases, it is thrown when we are calling a method recursively without any proper termination condition. We can avoid it by making sure that methods are executing with proper termination.
After a certain point, stack will be full
Let us take a sample example of computing factorial of a number to illustrate the same.
Java
// Java Program to Illustrate Stack Memory Error// Factorial function without termination condition// will cause StackOverflow error // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main (String[] args) { // Declaring a custom number whose factorial is to be computed int n = 5; // Print and display the factorial System.out.println(factorial(n)); } // Method // To calculate factorial static int factorial(int n) { // Note: There is no termination condition // Calling recursively to compute factorial of a number return n * factorial(n - 1); }}
Output:
Note: If you run this code you will get java.lang.StackOverflowError. We can avoid it by adding proper termination condition if we add termination condition in factorial function before return statement. Below termination condition remove error as follows:
if(n==0)
return 0;
Heap Memory in Java
Heap memory in java is used to allocate memory to the objects and JRE (Java Runtime Environment) classes. When an object is created, it is always created in heap and the reference to the object is stored in stack memory. It is not safe as a stack because it can be accessed globally. Access to this memory is relatively slower than the stack memory. It needs a garbage collector to remove unused objects. If the heap is full, java.lang.OutOfMemoryError is thrown by JVM. It is not thread-safe like a stack.
Example
Java
// Java Program to Illustrate Execution in Heap Memory // Importing input output classesimport java.io.*; // Main classclass GFG { // Static class static class Student { int roll_no; // The reference variable of String argument name // which points to the actual string from string // pool in heap memory String name; // Constructor of this static class Student(int roll_no, String name) { // This keyword refers to current instance this.roll_no = roll_no; this.name = name; } } // Main driver method public static void main(String[] args) { // Primitive roll no value directly stored in stack // memory int roll_no = 1; // Primitive name value directly stored in stack // memory String name = "Jack"; // Creating reference variable of Student class type // created in a stack memory which will point to // the object in heap memory // New object created in heap memory Student st = new Student(roll_no, name); // Print and display the student name and roll // number System.out.println("Student name -> " + st.name); System.out.println("Student roll no. -> " + st.roll_no); }}
Student name -> Jack
Student roll no. -> 1
Heap Memory Error
Also now it is suitable to discuss heap memory errors in java. So, it does occur when we creating lots of new objects in heap memory and there is no space left for new objects, then JVM will throw java.lang.OutOfMemoryError. Garbage collector removed the objects which have no references but cannot remove objects having a reference. It can be avoided by removing references to unwanted objects.
Example:
Java
// Java Program to Illustrate OutOfMemoryError// in Heap Space // Importing input output classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an array whose size is havoc Long a[] = new Long[100000 * 10000]; }}
Output:
Output explanation: In the above example, the Long array with a very large size is attempted to be initialized and the Java heap is insufficient to allocate this array, it throws a java.lang.OutOfMemoryError in java heap space.
sooda367
adnanirshad158
simmytarika5
Java-Exceptions
Picked
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": 28,
"s": 0,
"text": "\n12 Sep, 2021"
},
{
"code": null,
"e": 202,
"s": 28,
"text": "Memory allocation in java is managed by Java virtual machine in Java. It divides the memory into stack and heap memory which is as shown below in the below media as follows:"
},
{
"code": null,
"e": 224,
"s": 202,
"text": "Stack memory in Java "
},
{
"code": null,
"e": 749,
"s": 224,
"text": "It is the temporary memory allocation where local variables, reference variables are allocated memory when their methods are called. It contains references to the object are stored in a heap. After the execution of the method, the memory containing those variables is cleared. We can access this memory in Last In First Out Order. Allocation and deallocation is faster than heap memory. It is safer as data can only be accessed by the thread owner. If stack memory is full, then StackOverflowException is thrown by the JVM."
},
{
"code": null,
"e": 763,
"s": 749,
"text": "Illustration:"
},
{
"code": null,
"e": 1044,
"s": 763,
"text": "// Java Program to Illustrate Stack Memory \n\n// Importing required I/O classes \nimport java.io.*;\n\n// Main class \nclass GFG {\n\n // Main driver method \n public static void main (String[] args) {\n\n // Creating an integer array \n int a [] = new int[5]; \n }\n}"
},
{
"code": null,
"e": 1090,
"s": 1044,
"text": "Diagrammatic explanation of the above example"
},
{
"code": null,
"e": 1206,
"s": 1090,
"text": "In the above illustration, we can conclusively perceive the above media shown and conclude out the following points"
},
{
"code": null,
"e": 1257,
"s": 1206,
"text": "‘a’ is a variable of array type stored in a stack."
},
{
"code": null,
"e": 1309,
"s": 1257,
"text": "new keyword is used to allocate memory in the heap."
},
{
"code": null,
"e": 1337,
"s": 1309,
"text": "5 is the size of the array."
},
{
"code": null,
"e": 1356,
"s": 1337,
"text": "Stack Memory Error"
},
{
"code": null,
"e": 1902,
"s": 1356,
"text": "Whenever we call a method, after its execution it leaves the stack memory. If your methods are staying in the stack then the stack will be full, If the stack is full we can’t push, if we do then we will get the error java.lang.StackOverflowError which will be thrown by JVM. It is thrown when you call a method and there is no space left in the stack. In most cases, it is thrown when we are calling a method recursively without any proper termination condition. We can avoid it by making sure that methods are executing with proper termination."
},
{
"code": null,
"e": 1945,
"s": 1902,
"text": "After a certain point, stack will be full "
},
{
"code": null,
"e": 2033,
"s": 1945,
"text": "Let us take a sample example of computing factorial of a number to illustrate the same."
},
{
"code": null,
"e": 2038,
"s": 2033,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Stack Memory Error// Factorial function without termination condition// will cause StackOverflow error // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main (String[] args) { // Declaring a custom number whose factorial is to be computed int n = 5; // Print and display the factorial System.out.println(factorial(n)); } // Method // To calculate factorial static int factorial(int n) { // Note: There is no termination condition // Calling recursively to compute factorial of a number return n * factorial(n - 1); }}",
"e": 2720,
"s": 2038,
"text": null
},
{
"code": null,
"e": 2729,
"s": 2720,
"text": "Output: "
},
{
"code": null,
"e": 2986,
"s": 2729,
"text": "Note: If you run this code you will get java.lang.StackOverflowError. We can avoid it by adding proper termination condition if we add termination condition in factorial function before return statement. Below termination condition remove error as follows:"
},
{
"code": null,
"e": 2995,
"s": 2986,
"text": "if(n==0)"
},
{
"code": null,
"e": 3005,
"s": 2995,
"text": "return 0;"
},
{
"code": null,
"e": 3026,
"s": 3005,
"text": "Heap Memory in Java "
},
{
"code": null,
"e": 3533,
"s": 3026,
"text": "Heap memory in java is used to allocate memory to the objects and JRE (Java Runtime Environment) classes. When an object is created, it is always created in heap and the reference to the object is stored in stack memory. It is not safe as a stack because it can be accessed globally. Access to this memory is relatively slower than the stack memory. It needs a garbage collector to remove unused objects. If the heap is full, java.lang.OutOfMemoryError is thrown by JVM. It is not thread-safe like a stack."
},
{
"code": null,
"e": 3542,
"s": 3533,
"text": "Example "
},
{
"code": null,
"e": 3547,
"s": 3542,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Execution in Heap Memory // Importing input output classesimport java.io.*; // Main classclass GFG { // Static class static class Student { int roll_no; // The reference variable of String argument name // which points to the actual string from string // pool in heap memory String name; // Constructor of this static class Student(int roll_no, String name) { // This keyword refers to current instance this.roll_no = roll_no; this.name = name; } } // Main driver method public static void main(String[] args) { // Primitive roll no value directly stored in stack // memory int roll_no = 1; // Primitive name value directly stored in stack // memory String name = \"Jack\"; // Creating reference variable of Student class type // created in a stack memory which will point to // the object in heap memory // New object created in heap memory Student st = new Student(roll_no, name); // Print and display the student name and roll // number System.out.println(\"Student name -> \" + st.name); System.out.println(\"Student roll no. -> \" + st.roll_no); }}",
"e": 4882,
"s": 3547,
"text": null
},
{
"code": null,
"e": 4925,
"s": 4882,
"text": "Student name -> Jack\nStudent roll no. -> 1"
},
{
"code": null,
"e": 4943,
"s": 4925,
"text": "Heap Memory Error"
},
{
"code": null,
"e": 5340,
"s": 4943,
"text": "Also now it is suitable to discuss heap memory errors in java. So, it does occur when we creating lots of new objects in heap memory and there is no space left for new objects, then JVM will throw java.lang.OutOfMemoryError. Garbage collector removed the objects which have no references but cannot remove objects having a reference. It can be avoided by removing references to unwanted objects."
},
{
"code": null,
"e": 5350,
"s": 5340,
"text": "Example: "
},
{
"code": null,
"e": 5355,
"s": 5350,
"text": "Java"
},
{
"code": "// Java Program to Illustrate OutOfMemoryError// in Heap Space // Importing input output classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an array whose size is havoc Long a[] = new Long[100000 * 10000]; }}",
"e": 5666,
"s": 5355,
"text": null
},
{
"code": null,
"e": 5674,
"s": 5666,
"text": "Output:"
},
{
"code": null,
"e": 5902,
"s": 5674,
"text": "Output explanation: In the above example, the Long array with a very large size is attempted to be initialized and the Java heap is insufficient to allocate this array, it throws a java.lang.OutOfMemoryError in java heap space."
},
{
"code": null,
"e": 5911,
"s": 5902,
"text": "sooda367"
},
{
"code": null,
"e": 5926,
"s": 5911,
"text": "adnanirshad158"
},
{
"code": null,
"e": 5939,
"s": 5926,
"text": "simmytarika5"
},
{
"code": null,
"e": 5955,
"s": 5939,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 5962,
"s": 5955,
"text": "Picked"
},
{
"code": null,
"e": 5967,
"s": 5962,
"text": "Java"
},
{
"code": null,
"e": 5972,
"s": 5967,
"text": "Java"
},
{
"code": null,
"e": 6070,
"s": 5972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6085,
"s": 6070,
"text": "Stream In Java"
},
{
"code": null,
"e": 6106,
"s": 6085,
"text": "Introduction to Java"
},
{
"code": null,
"e": 6127,
"s": 6106,
"text": "Constructors in Java"
},
{
"code": null,
"e": 6146,
"s": 6127,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 6163,
"s": 6146,
"text": "Generics in Java"
},
{
"code": null,
"e": 6193,
"s": 6163,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 6219,
"s": 6193,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 6235,
"s": 6219,
"text": "Strings in Java"
},
{
"code": null,
"e": 6272,
"s": 6235,
"text": "Differences between JDK, JRE and JVM"
}
] |
FuzzyWuzzy Python library | 29 Jun, 2022
There are many methods of comparing string in python. Some of the main methods are:
Using regexSimple compareUsing difflib
Using regex
Simple compare
Using difflib
But one of the very easy method is by using fuzzywuzzy library where we can have a score out of 100, that denotes two string are equal by giving similarity index. This article talks about how we start using fuzzywuzzy library.
FuzzyWuzzy is a library of Python which is used for string matching. Fuzzy string matching is the process of finding strings that match a given pattern. Basically it uses Levenshtein Distance to calculate the differences between sequences.FuzzyWuzzy has been developed and open-sourced by SeatGeek, a service to find sport and concert tickets. Their original use case, as discussed in their blog.
Python 2.4 or higher
python-Levenshtein
Install via pip :
pip install fuzzywuzzy
pip install python-Levenshtein
How to use this library ?
First of import these modules,
from fuzzywuzzy import fuzzfrom fuzzywuzzy import process
Simple ratio usage :
fuzz.ratio('geeksforgeeks', 'geeksgeeks')87 # Exact matchfuzz.ratio('GeeksforGeeks', 'GeeksforGeeks') 100fuzz.ratio('geeks for geeks', 'Geeks For Geeks ') 80
fuzz.partial_ratio("geeks for geeks", "geeks for geeks!")100# Exclamation mark in second string, but still partially words are same so score comes 100 fuzz.partial_ratio("geeks for geeks", "geeks geeks")64# score is less because there is a extra token in the middle middle of the string.
Now, token set ratio an token sort ratio:
# Token Sort Ratiofuzz.token_sort_ratio("geeks for geeks", "for geeks geeks")100 # This gives 100 as every word is same, irrespective of the position # Token Set Ratiofuzz.token_sort_ratio("geeks for geeks", "geeks for for geeks")88 fuzz.token_set_ratio("geeks for geeks", "geeks for for geeks")100# Score comes 100 in second case because token_set_ratio considers duplicate words as a single word.
Now suppose if we have list of list of options and we want to find the closest match(es), we can use the process module
query = 'geeks for geeks'choices = ['geek for geek', 'geek geek', 'g. for geeks'] # Get a list of matches ordered by score, default limit to 5process.extract(query, choices)[('geeks geeks', 95), ('g. for geeks', 95), ('geek for geek', 93)] # If we want only the top oneprocess.extractOne(query, choices)('geeks geeks', 95)
There is also one more ratio which is used often called WRatio, sometimes its better to use WRatio instead of simple ratio as WRatio handles lower and upper cases and some other parameters too.
fuzz.WRatio('geeks for geeks', 'Geeks For Geeks')100fuzz.WRatio('geeks for geeks!!!','geeks for geeks')100# whereas simple ratio will give for above casefuzz.ratio('geeks for geeks!!!','geeks for geeks')91
Full Code
# Python code showing all the ratios together, # make sure you have installed fuzzywuzzy module from fuzzywuzzy import fuzzfrom fuzzywuzzy import process s1 = "I love GeeksforGeeks"s2 = "I am loving GeeksforGeeks"print "FuzzyWuzzy Ratio: ", fuzz.ratio(s1, s2)print "FuzzyWuzzy PartialRatio: ", fuzz.partial_ratio(s1, s2)print "FuzzyWuzzy TokenSortRatio: ", fuzz.token_sort_ratio(s1, s2)print "FuzzyWuzzy TokenSetRatio: ", fuzz.token_set_ratio(s1, s2)print "FuzzyWuzzy WRatio: ", fuzz.WRatio(s1, s2),'\n\n' # for process library,query = 'geeks for geeks'choices = ['geek for geek', 'geek geek', 'g. for geeks'] print "List of ratios: "print process.extract(query, choices), '\n'print "Best among the above list: ",process.extractOne(query, choices)
Output:
FuzzyWuzzy Ratio: 84
FuzzyWuzzy PartialRatio: 85
FuzzyWuzzy TokenSortRatio: 84
FuzzyWuzzy TokenSetRatio: 86
FuzzyWuzzy WRatio: 84
List of ratios:
[('g. for geeks', 95), ('geek for geek', 93), ('geek geek', 86)]
Best among the above list: ('g. for geeks', 95)
The FuzzyWuzzy library is built on top of difflib library, python-Levenshtein is used for speed. So it is one of the best way for string matching in python.
Python-Library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 138,
"s": 54,
"text": "There are many methods of comparing string in python. Some of the main methods are:"
},
{
"code": null,
"e": 177,
"s": 138,
"text": "Using regexSimple compareUsing difflib"
},
{
"code": null,
"e": 189,
"s": 177,
"text": "Using regex"
},
{
"code": null,
"e": 204,
"s": 189,
"text": "Simple compare"
},
{
"code": null,
"e": 218,
"s": 204,
"text": "Using difflib"
},
{
"code": null,
"e": 445,
"s": 218,
"text": "But one of the very easy method is by using fuzzywuzzy library where we can have a score out of 100, that denotes two string are equal by giving similarity index. This article talks about how we start using fuzzywuzzy library."
},
{
"code": null,
"e": 842,
"s": 445,
"text": "FuzzyWuzzy is a library of Python which is used for string matching. Fuzzy string matching is the process of finding strings that match a given pattern. Basically it uses Levenshtein Distance to calculate the differences between sequences.FuzzyWuzzy has been developed and open-sourced by SeatGeek, a service to find sport and concert tickets. Their original use case, as discussed in their blog."
},
{
"code": null,
"e": 863,
"s": 842,
"text": "Python 2.4 or higher"
},
{
"code": null,
"e": 882,
"s": 863,
"text": "python-Levenshtein"
},
{
"code": null,
"e": 900,
"s": 882,
"text": "Install via pip :"
},
{
"code": null,
"e": 955,
"s": 900,
"text": "pip install fuzzywuzzy\npip install python-Levenshtein\n"
},
{
"code": null,
"e": 981,
"s": 955,
"text": "How to use this library ?"
},
{
"code": null,
"e": 1012,
"s": 981,
"text": "First of import these modules,"
},
{
"code": "from fuzzywuzzy import fuzzfrom fuzzywuzzy import process",
"e": 1070,
"s": 1012,
"text": null
},
{
"code": null,
"e": 1091,
"s": 1070,
"text": "Simple ratio usage :"
},
{
"code": "fuzz.ratio('geeksforgeeks', 'geeksgeeks')87 # Exact matchfuzz.ratio('GeeksforGeeks', 'GeeksforGeeks') 100fuzz.ratio('geeks for geeks', 'Geeks For Geeks ') 80",
"e": 1253,
"s": 1091,
"text": null
},
{
"code": "fuzz.partial_ratio(\"geeks for geeks\", \"geeks for geeks!\")100# Exclamation mark in second string, but still partially words are same so score comes 100 fuzz.partial_ratio(\"geeks for geeks\", \"geeks geeks\")64# score is less because there is a extra token in the middle middle of the string.",
"e": 1542,
"s": 1253,
"text": null
},
{
"code": null,
"e": 1584,
"s": 1542,
"text": "Now, token set ratio an token sort ratio:"
},
{
"code": "# Token Sort Ratiofuzz.token_sort_ratio(\"geeks for geeks\", \"for geeks geeks\")100 # This gives 100 as every word is same, irrespective of the position # Token Set Ratiofuzz.token_sort_ratio(\"geeks for geeks\", \"geeks for for geeks\")88 fuzz.token_set_ratio(\"geeks for geeks\", \"geeks for for geeks\")100# Score comes 100 in second case because token_set_ratio considers duplicate words as a single word.",
"e": 1986,
"s": 1584,
"text": null
},
{
"code": null,
"e": 2106,
"s": 1986,
"text": "Now suppose if we have list of list of options and we want to find the closest match(es), we can use the process module"
},
{
"code": "query = 'geeks for geeks'choices = ['geek for geek', 'geek geek', 'g. for geeks'] # Get a list of matches ordered by score, default limit to 5process.extract(query, choices)[('geeks geeks', 95), ('g. for geeks', 95), ('geek for geek', 93)] # If we want only the top oneprocess.extractOne(query, choices)('geeks geeks', 95)",
"e": 2434,
"s": 2106,
"text": null
},
{
"code": null,
"e": 2628,
"s": 2434,
"text": "There is also one more ratio which is used often called WRatio, sometimes its better to use WRatio instead of simple ratio as WRatio handles lower and upper cases and some other parameters too."
},
{
"code": "fuzz.WRatio('geeks for geeks', 'Geeks For Geeks')100fuzz.WRatio('geeks for geeks!!!','geeks for geeks')100# whereas simple ratio will give for above casefuzz.ratio('geeks for geeks!!!','geeks for geeks')91",
"e": 2834,
"s": 2628,
"text": null
},
{
"code": null,
"e": 2844,
"s": 2834,
"text": "Full Code"
},
{
"code": "# Python code showing all the ratios together, # make sure you have installed fuzzywuzzy module from fuzzywuzzy import fuzzfrom fuzzywuzzy import process s1 = \"I love GeeksforGeeks\"s2 = \"I am loving GeeksforGeeks\"print \"FuzzyWuzzy Ratio: \", fuzz.ratio(s1, s2)print \"FuzzyWuzzy PartialRatio: \", fuzz.partial_ratio(s1, s2)print \"FuzzyWuzzy TokenSortRatio: \", fuzz.token_sort_ratio(s1, s2)print \"FuzzyWuzzy TokenSetRatio: \", fuzz.token_set_ratio(s1, s2)print \"FuzzyWuzzy WRatio: \", fuzz.WRatio(s1, s2),'\\n\\n' # for process library,query = 'geeks for geeks'choices = ['geek for geek', 'geek geek', 'g. for geeks'] print \"List of ratios: \"print process.extract(query, choices), '\\n'print \"Best among the above list: \",process.extractOne(query, choices)",
"e": 3595,
"s": 2844,
"text": null
},
{
"code": null,
"e": 3603,
"s": 3595,
"text": "Output:"
},
{
"code": null,
"e": 3875,
"s": 3603,
"text": "FuzzyWuzzy Ratio: 84\nFuzzyWuzzy PartialRatio: 85\nFuzzyWuzzy TokenSortRatio: 84\nFuzzyWuzzy TokenSetRatio: 86\nFuzzyWuzzy WRatio: 84 \n\n\nList of ratios: \n[('g. for geeks', 95), ('geek for geek', 93), ('geek geek', 86)] \n\nBest among the above list: ('g. for geeks', 95)\n"
},
{
"code": null,
"e": 4032,
"s": 3875,
"text": "The FuzzyWuzzy library is built on top of difflib library, python-Levenshtein is used for speed. So it is one of the best way for string matching in python."
},
{
"code": null,
"e": 4047,
"s": 4032,
"text": "Python-Library"
},
{
"code": null,
"e": 4054,
"s": 4047,
"text": "Python"
}
] |
How to add space around table border in HTML? | To set border spacing for an HTML table, use the CSS border-spacing property. It sets the distance between cells in a table,
You can try to run the following code to add space around table border in HTML
<!DOCTYPE html>
<html>
<head>
<style>
table, td, th {
border: 1px solid black;
border-spacing: 20px;
width: 300px;
}
</style>
</head>
<body>
<h1>Our Technologies</h1>
<table>
<tr>
<th>IDE</th>
<th>Database</th>
</tr>
<tr>
<td style="text-align:center">NetBeans</td>
<td style="text-align:center">MySQL</td>
</tr>
</table>
</body>
</html> | [
{
"code": null,
"e": 1312,
"s": 1187,
"text": "To set border spacing for an HTML table, use the CSS border-spacing property. It sets the distance between cells in a table,"
},
{
"code": null,
"e": 1391,
"s": 1312,
"text": "You can try to run the following code to add space around table border in HTML"
},
{
"code": null,
"e": 1906,
"s": 1391,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n table, td, th {\n border: 1px solid black;\n border-spacing: 20px;\n width: 300px;\n }\n </style>\n </head>\n <body>\n <h1>Our Technologies</h1>\n <table>\n <tr>\n <th>IDE</th>\n <th>Database</th>\n </tr>\n <tr>\n <td style=\"text-align:center\">NetBeans</td>\n <td style=\"text-align:center\">MySQL</td>\n </tr>\n </table>\n </body>\n</html>"
}
] |
p5.js | Keyboard | keyIsDown() | 16 Apr, 2019
The keyIsDown() function in p5.js checks the key’s current status that key is down, i.e. pressed. It can be used if you have a movable object, and you want several keys to be able to affect its behavior simultaneously, such as moving a sprite diagonally.
Syntax:
keyIsDown()
Below program illustrates the keyIsDown() function in p5.js:Example-1:
let x = 100;let y = 100; function setup() { // create canvas of size 600*600 createCanvas(600, 600);} function draw() { // fill color fill(x, y, x - y); if (keyIsDown(LEFT_ARROW)) { x -= 5; } if (keyIsDown(RIGHT_ARROW)) { x += 5; } if (keyIsDown(UP_ARROW)) { y -= 5; } if (keyIsDown(DOWN_ARROW)) { y += 5; } clear(); ellipse(x, y, 50, 50);}
Output:
Example-2:
let diameter = 30; function setup() { // Create canvas of size 600*600 createCanvas(600, 600);} function draw() { // 107 and 187 are keyCodes for "+" if (keyIsDown(107) || keyIsDown(187)) { diameter += 1; } // 109 and 189 are keyCodes for "-" if (keyIsDown(109) || keyIsDown(189)) { diameter -= 1; } clear(); fill(255, 0, 0); ellipse(width / 2, height / 2, diameter, diameter);}
Output:Reference: https://p5js.org/reference/#/p5/keyIsDown
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
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": "\n16 Apr, 2019"
},
{
"code": null,
"e": 283,
"s": 28,
"text": "The keyIsDown() function in p5.js checks the key’s current status that key is down, i.e. pressed. It can be used if you have a movable object, and you want several keys to be able to affect its behavior simultaneously, such as moving a sprite diagonally."
},
{
"code": null,
"e": 291,
"s": 283,
"text": "Syntax:"
},
{
"code": null,
"e": 304,
"s": 291,
"text": "keyIsDown()\n"
},
{
"code": null,
"e": 375,
"s": 304,
"text": "Below program illustrates the keyIsDown() function in p5.js:Example-1:"
},
{
"code": "let x = 100;let y = 100; function setup() { // create canvas of size 600*600 createCanvas(600, 600);} function draw() { // fill color fill(x, y, x - y); if (keyIsDown(LEFT_ARROW)) { x -= 5; } if (keyIsDown(RIGHT_ARROW)) { x += 5; } if (keyIsDown(UP_ARROW)) { y -= 5; } if (keyIsDown(DOWN_ARROW)) { y += 5; } clear(); ellipse(x, y, 50, 50);}",
"e": 806,
"s": 375,
"text": null
},
{
"code": null,
"e": 814,
"s": 806,
"text": "Output:"
},
{
"code": null,
"e": 825,
"s": 814,
"text": "Example-2:"
},
{
"code": "let diameter = 30; function setup() { // Create canvas of size 600*600 createCanvas(600, 600);} function draw() { // 107 and 187 are keyCodes for \"+\" if (keyIsDown(107) || keyIsDown(187)) { diameter += 1; } // 109 and 189 are keyCodes for \"-\" if (keyIsDown(109) || keyIsDown(189)) { diameter -= 1; } clear(); fill(255, 0, 0); ellipse(width / 2, height / 2, diameter, diameter);}",
"e": 1265,
"s": 825,
"text": null
},
{
"code": null,
"e": 1325,
"s": 1265,
"text": "Output:Reference: https://p5js.org/reference/#/p5/keyIsDown"
},
{
"code": null,
"e": 1342,
"s": 1325,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1353,
"s": 1342,
"text": "JavaScript"
},
{
"code": null,
"e": 1370,
"s": 1353,
"text": "Web Technologies"
},
{
"code": null,
"e": 1468,
"s": 1370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1529,
"s": 1468,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1601,
"s": 1529,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1641,
"s": 1601,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1682,
"s": 1641,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1728,
"s": 1682,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 1761,
"s": 1728,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1823,
"s": 1761,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1884,
"s": 1823,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1934,
"s": 1884,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python – math.prod() method | 23 Jan, 2020
Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.prod() method in Python is used to calculate the product of all the elements present in the given iterable. Most of the built-in containers in Python like list, tuple are iterables. The iterable must contain numeric value else non-numeric types may be rejected.This method is new in Python version 3.8.
Syntax: math.prod(iterable, *, start = 1)
Parameters:iterable: an iterable containing numeric valuesstart: an integer representing the start value. start is a named (keyword-only) parameter and its default value is 1.
Returns: the calculated product of all elements present in the given iterable.
Code #1: Use of math.prod() method
# Python Program to explain math.prod() method # Importing math moduleimport math # listarr = [1, 2, 3, 4, 5] # Calculate the product of# of all elements present# in the given listproduct = math.prod(arr)print(product) # tupletup = (0.5, 0.6, 0.7) # Calculate the product # of all elements present# in the given tupleproduct = math.prod(tup)print(product) # rangeseq = range(1, 11) # Calculate the product # of all elements present# in the given rangeproduct = math.prod(seq)print(product) # As the start value is not specified # it will default to 1
120
0.21
3628800
Code #2: if start parameter is explicitly specified
# Python Program to explain math.prod() method # Importing math moduleimport math # By default start value is 1# but can be explicitly provided# as a named (keyword-only) parameter # listarr = [1, 2, 3, 4, 5] # Calculate the product of# of all elements present# in the given listproduct = math.prod(arr, start = 2)print(product)
240
Code #3: When the given iterable is empty
# Python Program to explain math.prod() method # Importing math moduleimport math # If the given input iterable# is empty, then this method# returns the start value # listarr = [] # Calculate the product of# of all elements present# in the given listproduct = math.prod(arr)print(product) # Tupletup = () # Calculate the product of# of all elements present# in the given tupleproduct = math.prod(tup, start = 5)print(product)
1
5
Reference: Python math library
Python math-library
Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 455,
"s": 28,
"text": "Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.prod() method in Python is used to calculate the product of all the elements present in the given iterable. Most of the built-in containers in Python like list, tuple are iterables. The iterable must contain numeric value else non-numeric types may be rejected.This method is new in Python version 3.8."
},
{
"code": null,
"e": 497,
"s": 455,
"text": "Syntax: math.prod(iterable, *, start = 1)"
},
{
"code": null,
"e": 673,
"s": 497,
"text": "Parameters:iterable: an iterable containing numeric valuesstart: an integer representing the start value. start is a named (keyword-only) parameter and its default value is 1."
},
{
"code": null,
"e": 752,
"s": 673,
"text": "Returns: the calculated product of all elements present in the given iterable."
},
{
"code": null,
"e": 787,
"s": 752,
"text": "Code #1: Use of math.prod() method"
},
{
"code": "# Python Program to explain math.prod() method # Importing math moduleimport math # listarr = [1, 2, 3, 4, 5] # Calculate the product of# of all elements present# in the given listproduct = math.prod(arr)print(product) # tupletup = (0.5, 0.6, 0.7) # Calculate the product # of all elements present# in the given tupleproduct = math.prod(tup)print(product) # rangeseq = range(1, 11) # Calculate the product # of all elements present# in the given rangeproduct = math.prod(seq)print(product) # As the start value is not specified # it will default to 1",
"e": 1350,
"s": 787,
"text": null
},
{
"code": null,
"e": 1368,
"s": 1350,
"text": "120\n0.21\n3628800\n"
},
{
"code": null,
"e": 1420,
"s": 1368,
"text": "Code #2: if start parameter is explicitly specified"
},
{
"code": "# Python Program to explain math.prod() method # Importing math moduleimport math # By default start value is 1# but can be explicitly provided# as a named (keyword-only) parameter # listarr = [1, 2, 3, 4, 5] # Calculate the product of# of all elements present# in the given listproduct = math.prod(arr, start = 2)print(product)",
"e": 1755,
"s": 1420,
"text": null
},
{
"code": null,
"e": 1760,
"s": 1755,
"text": "240\n"
},
{
"code": null,
"e": 1802,
"s": 1760,
"text": "Code #3: When the given iterable is empty"
},
{
"code": "# Python Program to explain math.prod() method # Importing math moduleimport math # If the given input iterable# is empty, then this method# returns the start value # listarr = [] # Calculate the product of# of all elements present# in the given listproduct = math.prod(arr)print(product) # Tupletup = () # Calculate the product of# of all elements present# in the given tupleproduct = math.prod(tup, start = 5)print(product)",
"e": 2237,
"s": 1802,
"text": null
},
{
"code": null,
"e": 2242,
"s": 2237,
"text": "1\n5\n"
},
{
"code": null,
"e": 2273,
"s": 2242,
"text": "Reference: Python math library"
},
{
"code": null,
"e": 2293,
"s": 2273,
"text": "Python math-library"
},
{
"code": null,
"e": 2323,
"s": 2293,
"text": "Python math-library-functions"
},
{
"code": null,
"e": 2330,
"s": 2323,
"text": "Python"
},
{
"code": null,
"e": 2428,
"s": 2330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2446,
"s": 2428,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2488,
"s": 2446,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2510,
"s": 2488,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2536,
"s": 2510,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2568,
"s": 2536,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2597,
"s": 2568,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2624,
"s": 2597,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2654,
"s": 2624,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2675,
"s": 2654,
"text": "Python OOPs Concepts"
}
] |
Sub-strings of a string that are prefix of the same string | 22 Apr, 2022
Given a string str, the task is to count all possible sub-strings of the given string that are prefix of the same string.
Examples:
Input: str = “ababc” Output: 7 All possible sub-string are “a”, “ab”, “aba”, “abab”, “ababc”, “a” and “ab”
Input: str = “abdabc” Output: 8
Approach: Traverse the string character by character, if the current character is equal to the first character of the string then count all possible sub-strings starting from here that are also the prefixes of str and add it to count. After the complete string has been traversed, print the count.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>#include <string>using namespace std; // Function to return the// count of sub-strings starting// from startIndex that are// also the prefixes of strint subStringsStartingHere(string str, int n, int startIndex){ int count = 0, i = 1; while (i <= n) { if (str.substr(0,i) == str.substr(startIndex, i)) { count++; } else break; i++; } return count;} // Function to return the// count of all possible sub-strings// of str that are also the prefixes of strint countSubStrings(string str, int n){ int count = 0; for (int i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str[i] == str[0]) count += subStringsStartingHere(str, n, i); } return count;} // Driver codeint main(){ string str = "abcda"; int n = str.length(); // Function Call cout << (countSubStrings(str, n));} // This code is contributed by harshvijeta0
// Java implementation of the approachpublic class GFG{ // Function to return // the count of sub-strings starting // from startIndex that // are also the prefixes of str public static int subStringsStartingHere( String str, int n, int startIndex) { int count = 0, i = startIndex + 1; while (i <= n) { if (str.startsWith(str.substring( startIndex, i))) { count++; } else break; i++; } return count; } // Function to return the // count of all possible sub-strings // of str that are also the prefixes of str public static int countSubStrings(String str, int n) { int count = 0; for (int i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str.charAt(i) == str.charAt(0)) count += subStringsStartingHere(str, n, i); } return count; } // Driver code public static void main(String[] args) { String str = "ababc"; int n = str.length(); System.out.println(countSubStrings(str, n)); }}
# Python3 implementation of the approach # Function to return the# count of sub-strings starting# from startIndex that are# also the prefixes of stringdef subStringsStartingHere(string, n, startIndex): count = 0 i = startIndex + 1 while(i <= n) : if string.startswith( string[startIndex : i]): count += 1 else : break i += 1 return count # Function to return the# count of all possible sub-strings# of string that are also# the prefixes of stringdef countSubStrings(string, n) : count = 0 for i in range(n) : # If current character is equal to # the starting character of str if string[i] == string[0] : count += subStringsStartingHere( string, n, i) return count # Driver Codeif __name__ == "__main__" : string = "ababc" n = len(string) print(countSubStrings(string, n)) # this code is contributed by Ryuga
// C# implementation of the approachusing System;class GFG{ // Function to return the // count of sub-strings starting // from startIndex that // are also the prefixes of str static int subStringsStartingHere( String str, int n, int startIndex) { int count = 0, i = startIndex + 1; while (i <= n) { if (str.StartsWith(str.Substring( startIndex, i-startIndex))) { count++; } else break; i++; } return count; } // Function to return the // count of all possible sub-strings // of str that are also the prefixes of str static int countSubStrings(String str, int n) { int count = 0; for (int i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str[i] == str[0]) count += subStringsStartingHere( str, n, i); } return count; } // Driver code static public void Main(String []args) { String str = "ababc"; int n = str.Length; Console.WriteLine(countSubStrings(str, n)); }}//contributed by Arnab Kundu
<script> // Javascript implementation of the approach // Function to return the// count of sub-strings starting// from startIndex that are// also the prefixes of strfunction subStringsStartingHere(str, n, startIndex){ var count = 0, i = startIndex + 1; while (i <= n) { if (str.startsWith( str.substring(startIndex, i))) { count++; } else break; i++; } return count;} // Function to return the count of all// possible sub-strings of str that are// also the prefixes of strfunction countSubStrings(str, n){ var count = 0; for(var i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str[i] == str[0]) count += subStringsStartingHere(str, n, i); } return count;} // Driver codevar str = "abcda";var n = str.length; // Function Calldocument.write(countSubStrings(str, n)); // This code is contributed by rutvik_56 </script>
6
Time Complexity: O(N^2) Auxiliary Space: O(1)
Efficient Approach:
Prerequisite: Z-Algorithm
Approach: Calculate z-array of the string such that z[i] stores length of the longest substring starting from i which is also a prefix of string s. Then to count all possible sub-strings of the string that are prefix of the same string, we just need to add all the values of the z-array since the total number of substrings matching would be equal to the length of longest substring.
Implementation of the above approach:-
C++
Python3
Javascript
#include <bits/stdc++.h>using namespace std; // returns an array z such that z[i]// stores length of the longest substring starting// from i which is also a prefix of string svector<int> z_function(string s){ int n = (int)s.length(); vector<int> z(n); // consider a window [l,r] // which matches with prefix of s int l = 0, r = 0; z[0] = n; for (int i = 1; i < n; ++i) { // when i<=r, we make use of already computed z // value for some smaller index if (i <= r) z[i] = min(r - i + 1, z[i - l]); // if i>r nothing matches so we will calculate // z[i] using naive way. while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i]; // update window size if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1; } return z;} int main(){ string s = "abcda"; int n = s.length(); vector<int> z = z_function(s); // stores the count of // Sub-strings of a string that // are prefix of the same string int count = 0; for (auto x : z) count += x; cout << count << '\n'; return 0;}
# returns an array z such that z[i]# stores length of the longest substring starting# from i which is also a prefix of sdef z_function(s): n = len(s) z=[0]*n # consider a window [l,r] # which matches with prefix of s l = 0; r = 0 z[0] = n for i in range(1, n) : # when i<=r, we make use of already computed z # value for some smaller index if (i <= r): z[i] = min(r - i + 1, z[i - l]) # if i>r nothing matches so we will calculate # z[i] using naive way. while (i + z[i] < n and s[z[i]] == s[i + z[i]]): z[i]+=1 # update window size if (i + z[i] - 1 > r): l = i; r = i + z[i] - 1 return z if __name__ == '__main__': s = "abcda" n = len(s) z = z_function(s) # stores the count of # Sub-strings of a that # are prefix of the same string count = 0 for x in z: count += x print(count)
<script> // JavaScript code for the approach // returns an array z such that z[i]// stores length of the longest substring starting// from i which is also a prefix of string sfunction z_function(s){ let n = s.length; let z = new Array(n).fill(0); // consider a window [l,r] // which matches with prefix of s let l = 0, r = 0; z[0] = n; for (let i = 1; i < n; i++) { // when i<=r, we make use of already computed z // value for some smaller index if (i <= r) z[i] = Math.min(r - i + 1, z[i - l]); // if i>r nothing matches so we will calculate // z[i] using naive way. while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++; // update window size if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1; } return z;} // driver codelet s = "abcda";let n = s.length;let z = z_function(s); // stores the count of// Sub-strings of a string that// are prefix of the same stringlet count = 0;for (let x of z) count += x; document.write(count) // This code is contributed by shinjanpatra </script>
6
Time Complexity: O(n)
Auxiliary Space: O(n)
ankthon
andrew1234
Rajput-Ji
harshvijeta0
rutvik_56
pankajsharmagfg
ashutoshsinghgeeksforgeeks
amartyaghoshgfg
varshagumber28
surinderdawra388
shinjanpatra
Java-Strings
prefix
substring
Technical Scripter 2018
Algorithms
Strings
Technical Scripter
Java-Strings
Strings
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 174,
"s": 52,
"text": "Given a string str, the task is to count all possible sub-strings of the given string that are prefix of the same string."
},
{
"code": null,
"e": 185,
"s": 174,
"text": "Examples: "
},
{
"code": null,
"e": 292,
"s": 185,
"text": "Input: str = “ababc” Output: 7 All possible sub-string are “a”, “ab”, “aba”, “abab”, “ababc”, “a” and “ab”"
},
{
"code": null,
"e": 325,
"s": 292,
"text": "Input: str = “abdabc” Output: 8 "
},
{
"code": null,
"e": 623,
"s": 325,
"text": "Approach: Traverse the string character by character, if the current character is equal to the first character of the string then count all possible sub-strings starting from here that are also the prefixes of str and add it to count. After the complete string has been traversed, print the count."
},
{
"code": null,
"e": 675,
"s": 623,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 681,
"s": 675,
"text": "C++14"
},
{
"code": null,
"e": 686,
"s": 681,
"text": "Java"
},
{
"code": null,
"e": 694,
"s": 686,
"text": "Python3"
},
{
"code": null,
"e": 697,
"s": 694,
"text": "C#"
},
{
"code": null,
"e": 708,
"s": 697,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>#include <string>using namespace std; // Function to return the// count of sub-strings starting// from startIndex that are// also the prefixes of strint subStringsStartingHere(string str, int n, int startIndex){ int count = 0, i = 1; while (i <= n) { if (str.substr(0,i) == str.substr(startIndex, i)) { count++; } else break; i++; } return count;} // Function to return the// count of all possible sub-strings// of str that are also the prefixes of strint countSubStrings(string str, int n){ int count = 0; for (int i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str[i] == str[0]) count += subStringsStartingHere(str, n, i); } return count;} // Driver codeint main(){ string str = \"abcda\"; int n = str.length(); // Function Call cout << (countSubStrings(str, n));} // This code is contributed by harshvijeta0",
"e": 1841,
"s": 708,
"text": null
},
{
"code": "// Java implementation of the approachpublic class GFG{ // Function to return // the count of sub-strings starting // from startIndex that // are also the prefixes of str public static int subStringsStartingHere( String str, int n, int startIndex) { int count = 0, i = startIndex + 1; while (i <= n) { if (str.startsWith(str.substring( startIndex, i))) { count++; } else break; i++; } return count; } // Function to return the // count of all possible sub-strings // of str that are also the prefixes of str public static int countSubStrings(String str, int n) { int count = 0; for (int i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str.charAt(i) == str.charAt(0)) count += subStringsStartingHere(str, n, i); } return count; } // Driver code public static void main(String[] args) { String str = \"ababc\"; int n = str.length(); System.out.println(countSubStrings(str, n)); }}",
"e": 3025,
"s": 1841,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the# count of sub-strings starting# from startIndex that are# also the prefixes of stringdef subStringsStartingHere(string, n, startIndex): count = 0 i = startIndex + 1 while(i <= n) : if string.startswith( string[startIndex : i]): count += 1 else : break i += 1 return count # Function to return the# count of all possible sub-strings# of string that are also# the prefixes of stringdef countSubStrings(string, n) : count = 0 for i in range(n) : # If current character is equal to # the starting character of str if string[i] == string[0] : count += subStringsStartingHere( string, n, i) return count # Driver Codeif __name__ == \"__main__\" : string = \"ababc\" n = len(string) print(countSubStrings(string, n)) # this code is contributed by Ryuga",
"e": 4054,
"s": 3025,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG{ // Function to return the // count of sub-strings starting // from startIndex that // are also the prefixes of str static int subStringsStartingHere( String str, int n, int startIndex) { int count = 0, i = startIndex + 1; while (i <= n) { if (str.StartsWith(str.Substring( startIndex, i-startIndex))) { count++; } else break; i++; } return count; } // Function to return the // count of all possible sub-strings // of str that are also the prefixes of str static int countSubStrings(String str, int n) { int count = 0; for (int i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str[i] == str[0]) count += subStringsStartingHere( str, n, i); } return count; } // Driver code static public void Main(String []args) { String str = \"ababc\"; int n = str.Length; Console.WriteLine(countSubStrings(str, n)); }}//contributed by Arnab Kundu",
"e": 5385,
"s": 4054,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the// count of sub-strings starting// from startIndex that are// also the prefixes of strfunction subStringsStartingHere(str, n, startIndex){ var count = 0, i = startIndex + 1; while (i <= n) { if (str.startsWith( str.substring(startIndex, i))) { count++; } else break; i++; } return count;} // Function to return the count of all// possible sub-strings of str that are// also the prefixes of strfunction countSubStrings(str, n){ var count = 0; for(var i = 0; i < n; i++) { // If current character is equal to // the starting character of str if (str[i] == str[0]) count += subStringsStartingHere(str, n, i); } return count;} // Driver codevar str = \"abcda\";var n = str.length; // Function Calldocument.write(countSubStrings(str, n)); // This code is contributed by rutvik_56 </script>",
"e": 6478,
"s": 5385,
"text": null
},
{
"code": null,
"e": 6480,
"s": 6478,
"text": "6"
},
{
"code": null,
"e": 6526,
"s": 6480,
"text": "Time Complexity: O(N^2) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6546,
"s": 6526,
"text": "Efficient Approach:"
},
{
"code": null,
"e": 6572,
"s": 6546,
"text": "Prerequisite: Z-Algorithm"
},
{
"code": null,
"e": 6958,
"s": 6572,
"text": "Approach: Calculate z-array of the string such that z[i] stores length of the longest substring starting from i which is also a prefix of string s. Then to count all possible sub-strings of the string that are prefix of the same string, we just need to add all the values of the z-array since the total number of substrings matching would be equal to the length of longest substring."
},
{
"code": null,
"e": 6997,
"s": 6958,
"text": "Implementation of the above approach:-"
},
{
"code": null,
"e": 7001,
"s": 6997,
"text": "C++"
},
{
"code": null,
"e": 7009,
"s": 7001,
"text": "Python3"
},
{
"code": null,
"e": 7020,
"s": 7009,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // returns an array z such that z[i]// stores length of the longest substring starting// from i which is also a prefix of string svector<int> z_function(string s){ int n = (int)s.length(); vector<int> z(n); // consider a window [l,r] // which matches with prefix of s int l = 0, r = 0; z[0] = n; for (int i = 1; i < n; ++i) { // when i<=r, we make use of already computed z // value for some smaller index if (i <= r) z[i] = min(r - i + 1, z[i - l]); // if i>r nothing matches so we will calculate // z[i] using naive way. while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i]; // update window size if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1; } return z;} int main(){ string s = \"abcda\"; int n = s.length(); vector<int> z = z_function(s); // stores the count of // Sub-strings of a string that // are prefix of the same string int count = 0; for (auto x : z) count += x; cout << count << '\\n'; return 0;}",
"e": 8135,
"s": 7020,
"text": null
},
{
"code": "# returns an array z such that z[i]# stores length of the longest substring starting# from i which is also a prefix of sdef z_function(s): n = len(s) z=[0]*n # consider a window [l,r] # which matches with prefix of s l = 0; r = 0 z[0] = n for i in range(1, n) : # when i<=r, we make use of already computed z # value for some smaller index if (i <= r): z[i] = min(r - i + 1, z[i - l]) # if i>r nothing matches so we will calculate # z[i] using naive way. while (i + z[i] < n and s[z[i]] == s[i + z[i]]): z[i]+=1 # update window size if (i + z[i] - 1 > r): l = i; r = i + z[i] - 1 return z if __name__ == '__main__': s = \"abcda\" n = len(s) z = z_function(s) # stores the count of # Sub-strings of a that # are prefix of the same string count = 0 for x in z: count += x print(count)",
"e": 9076,
"s": 8135,
"text": null
},
{
"code": "<script> // JavaScript code for the approach // returns an array z such that z[i]// stores length of the longest substring starting// from i which is also a prefix of string sfunction z_function(s){ let n = s.length; let z = new Array(n).fill(0); // consider a window [l,r] // which matches with prefix of s let l = 0, r = 0; z[0] = n; for (let i = 1; i < n; i++) { // when i<=r, we make use of already computed z // value for some smaller index if (i <= r) z[i] = Math.min(r - i + 1, z[i - l]); // if i>r nothing matches so we will calculate // z[i] using naive way. while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++; // update window size if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1; } return z;} // driver codelet s = \"abcda\";let n = s.length;let z = z_function(s); // stores the count of// Sub-strings of a string that// are prefix of the same stringlet count = 0;for (let x of z) count += x; document.write(count) // This code is contributed by shinjanpatra </script>",
"e": 10189,
"s": 9076,
"text": null
},
{
"code": null,
"e": 10191,
"s": 10189,
"text": "6"
},
{
"code": null,
"e": 10213,
"s": 10191,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 10236,
"s": 10213,
"text": "Auxiliary Space: O(n) "
},
{
"code": null,
"e": 10244,
"s": 10236,
"text": "ankthon"
},
{
"code": null,
"e": 10255,
"s": 10244,
"text": "andrew1234"
},
{
"code": null,
"e": 10265,
"s": 10255,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 10278,
"s": 10265,
"text": "harshvijeta0"
},
{
"code": null,
"e": 10288,
"s": 10278,
"text": "rutvik_56"
},
{
"code": null,
"e": 10304,
"s": 10288,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 10331,
"s": 10304,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 10347,
"s": 10331,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 10362,
"s": 10347,
"text": "varshagumber28"
},
{
"code": null,
"e": 10379,
"s": 10362,
"text": "surinderdawra388"
},
{
"code": null,
"e": 10392,
"s": 10379,
"text": "shinjanpatra"
},
{
"code": null,
"e": 10405,
"s": 10392,
"text": "Java-Strings"
},
{
"code": null,
"e": 10412,
"s": 10405,
"text": "prefix"
},
{
"code": null,
"e": 10422,
"s": 10412,
"text": "substring"
},
{
"code": null,
"e": 10446,
"s": 10422,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 10457,
"s": 10446,
"text": "Algorithms"
},
{
"code": null,
"e": 10465,
"s": 10457,
"text": "Strings"
},
{
"code": null,
"e": 10484,
"s": 10465,
"text": "Technical Scripter"
},
{
"code": null,
"e": 10497,
"s": 10484,
"text": "Java-Strings"
},
{
"code": null,
"e": 10505,
"s": 10497,
"text": "Strings"
},
{
"code": null,
"e": 10516,
"s": 10505,
"text": "Algorithms"
}
] |
Powershell - ForEach-Object Cmdlet | ForEach-Object cmdlet can be used to perform operations on each object of a collection of objects.
In these examples, we're see the ForEach-Object cmdlet in action.
In this example, we'll divide integer in an array. We'll refer to each object using $_.
1000,2000,3000 | ForEach-Object -Process {$_/1000}
You can see following output in PowerShell console.
1
2
3
Get the names of the items in current directory.
In this example, we'll split powershell module names.
"Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | ForEach-Object {$_.Split(".")}
You can see following output in PowerShell console. | [
{
"code": null,
"e": 2267,
"s": 2168,
"text": "ForEach-Object cmdlet can be used to perform operations on each object of a collection of objects."
},
{
"code": null,
"e": 2333,
"s": 2267,
"text": "In these examples, we're see the ForEach-Object cmdlet in action."
},
{
"code": null,
"e": 2421,
"s": 2333,
"text": "In this example, we'll divide integer in an array. We'll refer to each object using $_."
},
{
"code": null,
"e": 2472,
"s": 2421,
"text": "1000,2000,3000 | ForEach-Object -Process {$_/1000}"
},
{
"code": null,
"e": 2524,
"s": 2472,
"text": "You can see following output in PowerShell console."
},
{
"code": null,
"e": 2539,
"s": 2524,
"text": "1\n2\n3 \n"
},
{
"code": null,
"e": 2588,
"s": 2539,
"text": "Get the names of the items in current directory."
},
{
"code": null,
"e": 2642,
"s": 2588,
"text": "In this example, we'll split powershell module names."
},
{
"code": null,
"e": 2732,
"s": 2642,
"text": "\"Microsoft.PowerShell.Core\", \"Microsoft.PowerShell.Host\" | ForEach-Object {$_.Split(\".\")}"
}
] |
p5.js | Mouse | pmouseX | 16 Apr, 2019
The pmouseX variable in p5.js is used to store the horizontal position of the mouse cursor in the frame previous to the currently active frame, relative to the origin of the canvas.
Syntax:
mouseX
Below programs illustrate the pmouseX variable in p5.js:
Example 1: This example uses pmouseX variable to draw mouse pointer as circle.
function setup() { // Create canvas createCanvas(1000, 400);} function draw() { // Set the background color background(244, 248, 252); // Fill color relative pmouseX, // pmouseY and mouseY fill(pmouseX%255, pmouseY%255, mouseY%255); // Draw circle circle(pmouseX, mouseX, pmouseX%100);}
Output:
Example 2: This example uses pmouseX variable to display the position of mouse pointer.
function setup() { // Create canvas createCanvas(1000, 400); // Set font size textSize(20);} function draw() { // Set background color background(200); // Display result text("Position of pmouseX is " + pmouseX, 30, 40);}
Output:
Reference: https://p5js.org/reference/#/p5/pmouseX
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
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": "\n16 Apr, 2019"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "The pmouseX variable in p5.js is used to store the horizontal position of the mouse cursor in the frame previous to the currently active frame, relative to the origin of the canvas."
},
{
"code": null,
"e": 218,
"s": 210,
"text": "Syntax:"
},
{
"code": null,
"e": 225,
"s": 218,
"text": "mouseX"
},
{
"code": null,
"e": 282,
"s": 225,
"text": "Below programs illustrate the pmouseX variable in p5.js:"
},
{
"code": null,
"e": 361,
"s": 282,
"text": "Example 1: This example uses pmouseX variable to draw mouse pointer as circle."
},
{
"code": "function setup() { // Create canvas createCanvas(1000, 400);} function draw() { // Set the background color background(244, 248, 252); // Fill color relative pmouseX, // pmouseY and mouseY fill(pmouseX%255, pmouseY%255, mouseY%255); // Draw circle circle(pmouseX, mouseX, pmouseX%100);}",
"e": 698,
"s": 361,
"text": null
},
{
"code": null,
"e": 706,
"s": 698,
"text": "Output:"
},
{
"code": null,
"e": 794,
"s": 706,
"text": "Example 2: This example uses pmouseX variable to display the position of mouse pointer."
},
{
"code": "function setup() { // Create canvas createCanvas(1000, 400); // Set font size textSize(20);} function draw() { // Set background color background(200); // Display result text(\"Position of pmouseX is \" + pmouseX, 30, 40);}",
"e": 1069,
"s": 794,
"text": null
},
{
"code": null,
"e": 1077,
"s": 1069,
"text": "Output:"
},
{
"code": null,
"e": 1128,
"s": 1077,
"text": "Reference: https://p5js.org/reference/#/p5/pmouseX"
},
{
"code": null,
"e": 1145,
"s": 1128,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1156,
"s": 1145,
"text": "JavaScript"
},
{
"code": null,
"e": 1173,
"s": 1156,
"text": "Web Technologies"
},
{
"code": null,
"e": 1271,
"s": 1173,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1332,
"s": 1271,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1404,
"s": 1332,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1444,
"s": 1404,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1485,
"s": 1444,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1531,
"s": 1485,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 1564,
"s": 1531,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1626,
"s": 1564,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1687,
"s": 1626,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1737,
"s": 1687,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Replace all consonants with nearest vowels in a string | 21 Jun, 2022
Given a string with lowercase English alphabets. The task is to replace all the consonants in the string with the nearest vowels. If a consonant is near to two vowels then replace it with the one that comes first in English alphabets. Note: Vowels already present in the string must be left as it is.Examples:
Input : str = "geeksforgeeks"
Output : eeeiueooeeeiu
Input : str = "gfg"
Output : eee
A simple approach is to compare the consonant with vowels to determine the nearest vowel. First, check if the consonant falls between two vowels. If it falls between 2 vowels then find the absolute difference between the ASCII value of consonant with the ASCII value of both vowels. Replace it with that vowel, with which the absolute difference is minimum. However, if the ASCII code of consonant does not fall between two vowels, then the consonant can be ‘v’, ‘w’, ‘x’, ‘y’, ‘z’. Hence, the answer is ‘u’ in this case.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to replace all consonants// with nearest vowels in a string#include <bits/stdc++.h>using namespace std; // Function to check if a character is// vowel or notbool isVowel(char ch){ if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') return false; return true;} // Function to replace consonant with// nearest vowelsstring replacingConsonants(string s){ for (int i = 0; i < s.length(); i++) { // if, string element is vowel, // jump to next element if (isVowel(s[i])) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s[i] > 'a' && s[i] < 'e') { // here the absolute difference of // ascii value is considered if (abs(s[i] - 'a') > abs(s[i] - 'e')) s[i] = 'e'; else s[i] = 'a'; } else if (s[i] > 'e' && s[i] < 'i') { if (abs(s[i] - 'e') > abs(s[i] - 'i')) s[i] = 'i'; else s[i] = 'e'; } else if (s[i] > 'i' && s[i] < 'o') { if (abs(s[i] - 'i') > abs(s[i] - 'o')) s[i] = 'o'; else s[i] = 'i'; } else if (s[i] > 'o' && s[i] < 'u') { if (abs(s[i] - 'o') > abs(s[i] - 'u')) s[i] = 'u'; else s[i] = 'o'; } // when s[i] is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s[i] > 'u') s[i] = 'u'; } } return s;} // Driver codeint main(){ string s = "geeksforgeeks"; cout << replacingConsonants(s); return 0;}
// Java program to replace all consonants// with nearest vowels in a string import java.util.*;class Solution{ // Function to check if a character is// vowel or notstatic boolean isVowel(char ch){ if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') return false; return true;} // Function to replace consonant with// nearest vowelsstatic String replacingConsonants(String s){ for (int i = 0; i < s.length(); i++) { // if, string element is vowel, // jump to next element if (isVowel(s.charAt(i))) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s.charAt(i) > 'a' && s.charAt(i) < 'e') { // here the absolute difference of // ascii value is considered if (Math.abs(s.charAt(i) - 'a') > Math.abs(s.charAt(i) - 'e')) s = s.substring(0,i)+'e'+s.substring(i+1); else s= s.substring(0,i)+'a'+s.substring(i+1); } else if (s.charAt(i) > 'e' && s.charAt(i) < 'i') { if (Math.abs(s.charAt(i) - 'e') > Math.abs(s.charAt(i) - 'i')) s = s.substring(0,i)+'i'+s.substring(i+1); else s = s.substring(0,i)+'e'+s.substring(i+1); } else if (s.charAt(i) > 'i' && s.charAt(i) < 'o') { if (Math.abs(s.charAt(i) - 'i') > Math.abs(s.charAt(i) - 'o')) s= s.substring(0,i)+'o'+s.substring(i+1); else s= s.substring(0,i)+'i'+s.substring(i+1); } else if (s.charAt(i) > 'o' && s.charAt(i) < 'u') { if (Math.abs(s.charAt(i) - 'o') > Math.abs(s.charAt(i) - 'u')) s= s.substring(0,i)+'u'+s.substring(i+1); else s= s.substring(0,i)+'o'+s.substring(i+1); } // when s.charAt(i) is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s.charAt(i) > 'u') s =s.substring(0,i)+'u'+s.substring(i+1); } } return s;} // Driver codepublic static void main(String args[]){ String s = "geeksforgeeks"; System.out.print( replacingConsonants(s)); } }//contributed by Arnab Kundu
# Python3 program to replace all consonants# with nearest vowels in a string # Function to check if a# character is vowel or notdef isVowel(ch): if (ch != 'a' and ch != 'e' and ch != 'i' and ch != 'o' and ch != 'u'): return False return True # Function to replace consonant# with nearest vowelsdef replacingConsonants(s): for i in range(0, len(s)): # if, string element is vowel, # jump to next element if isVowel(s[i]): continue # check if consonant lies between two vowels, # if it lies, than replace it with nearest vowel else: if s[i] > 'a' and s[i] < 'e': # here the absolute difference of # ascii value is considered if (abs(ord(s[i]) - ord('a')) > abs(ord(s[i]) - ord('e'))): s[i] = 'e' else: s[i] = 'a' elif s[i] > 'e' and s[i] < 'i': if (abs(ord(s[i]) - ord('e')) > abs(ord(s[i]) - ord('i'))): s[i] = 'i' else: s[i] = 'e' elif (s[i] > 'i' and s[i] < 'o'): if (abs(ord(s[i]) - ord('i')) > abs(ord(s[i]) - ord('o'))): s[i] = 'o' else: s[i] = 'i' elif (s[i] > 'o' and s[i] < 'u'): if (abs(ord(s[i]) - ord('o')) > abs(ord(s[i]) - ord('u'))): s[i] = 'u' else: s[i] = 'o' # when s[i] is equal to either # 'v', 'w', 'x', 'y', 'z' elif (s[i] > 'u'): s[i] = 'u' return ''.join(s) # Driver codeif __name__ == "__main__": s = "geeksforgeeks" print(replacingConsonants(list(s))) # This code is contributed by Rituraj Jain
// C# program to replace all consonants// with nearest vowels in a stringusing System;public class Solution{ // Function to check if a character is // vowel or not static bool isVowel(char ch) { if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') return false; return true; } // Function to replace consonant with // nearest vowels static String replacingConsonants(String s) { for (int i = 0; i < s.Length; i++) { // if, string element is vowel, // jump to next element if (isVowel(s[i])) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s[i] > 'a' && s[i] < 'e') { // here the absolute difference of // ascii value is considered if (Math.Abs(s[i] - 'a') > Math.Abs(s[i] - 'e')) s = s.Substring(0,i)+'e'+s.Substring(i+1); else s= s.Substring(0,i)+'a'+s.Substring(i+1); } else if (s[i] > 'e' && s[i] < 'i') { if (Math.Abs(s[i] - 'e') > Math.Abs(s[i] - 'i')) s = s.Substring(0,i)+'i'+s.Substring(i+1); else s = s.Substring(0,i)+'e'+s.Substring(i+1); } else if (s[i] > 'i' && s[i] < 'o') { if (Math.Abs(s[i] - 'i') > Math.Abs(s[i] - 'o')) s= s.Substring(0,i)+'o'+s.Substring(i+1); else s= s.Substring(0,i)+'i'+s.Substring(i+1); } else if (s[i] > 'o' && s[i] < 'u') { if (Math.Abs(s[i] - 'o') > Math.Abs(s[i] - 'u')) s= s.Substring(0,i)+'u'+s.Substring(i+1); else s= s.Substring(0,i)+'o'+s.Substring(i+1); } // when s[i] is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s[i] > 'u') s =s.Substring(0,i)+'u'+s.Substring(i+1); } } return s; } // Driver code public static void Main() { String s = "geeksforgeeks"; Console.WriteLine( replacingConsonants(s)); }} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to replace all consonants // with nearest vowels in a string // Function to check if a character is // vowel or not function isVowel(ch) { if (ch !== "a" && ch !== "e" && ch !== "i" && ch !== "o" && ch !== "u") return false; return true; } // Function to replace consonant with // nearest vowels function replacingConsonants(s) { for (var i = 0; i < s.length; i++) { // if, string element is vowel, // jump to next element if (isVowel(s[i])) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s[i] > "a" && s[i] < "e") { // here the absolute difference of // ascii value is considered if ( Math.abs(s[i].charCodeAt(0) - "a".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - "e".charCodeAt(0)) ) s = s.substring(0, i) + "e" + s.substring(i + 1); else s = s.substring(0, i) + "a" + s.substring(i + 1); } else if (s[i] > "e" && s[i] < "i") { if ( Math.abs(s[i].charCodeAt(0) - "e".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - "i".charCodeAt(0)) ) s = s.substring(0, i) + "i" + s.substring(i + 1); else s = s.substring(0, i) + "e" + s.substring(i + 1); } else if (s[i] > "i" && s[i] < "o") { if ( Math.abs(s[i].charCodeAt(0) - "i".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - "o".charCodeAt(0)) ) s = s.substring(0, i) + "o" + s.substring(i + 1); else s = s.substring(0, i) + "i" + s.substring(i + 1); } else if (s[i] > "o" && s[i] < "u") { if ( Math.abs(s[i].charCodeAt(0) - "o".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - "u".charCodeAt(0)) ) s = s.substring(0, i) + "u" + s.substring(i + 1); else s = s.substring(0, i) + "o" + s.substring(i + 1); } // when s[i] is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s[i] > "u") s = s.substring(0, i) + "u" + s.substring(i + 1); } } return s; } // Driver code var s = "geeksforgeeks"; document.write(replacingConsonants(s)); </script>
eeeiueooeeeiu
Time Complexity: O(n), where n is the size of string sAuxiliary Space: O(1)
A better approach is to make an array of size 26 that stores nearest vowel for every character.
C++
Java
Python3
C#
Javascript
// C++ program to replace all consonants// with nearest vowels in a string#include <bits/stdc++.h>using namespace std; // Function to replace consonant with// nearest vowelsstring replacingConsonants(string s){ char nVowel[] = "aaaeeeeiiiiioooooouuuuuuuu"; for (int i = 0; i < s.length(); i++) s[i] = nVowel[s[i] - 'a']; return s;} // Driver codeint main(){ string s = "geeksforgeeks"; cout << replacingConsonants(s); return 0;}
// Java program to replace all consonants// with nearest vowels in a stringimport java.util.*; class solution{ // Function to replace consonant with// nearest vowelsstatic String replacingConsonants(String s){ String str = "aaaeeeeiiiiioooooouuuuuuuu"; char[] st = s.toCharArray(); for (int i = 0; i < s.length(); i++) { int index = st[i]-'a'; st[i] = str.charAt(index); } String str1 = new String(st); return str1;} // Driver codepublic static void main(String arr[]){ String s = "geeksforgeeks"; System.out.println(replacingConsonants(s)); } }// This code is contributed by Surendra_Gangwar
# Python3 program to replace all consonants# with nearest vowels in a string # Function to replace consonant with# nearest vowelsdef replacingConsonants(s): nVowel = "aaaeeeeiiiiioooooouuuuuuuu" for i in range (0, len(s)): s = s.replace(s[i], nVowel[ord(s[i]) - 97]) return s # Driver codes = "geeksforgeeks"; print(replacingConsonants(s)); # This code is contributed by# archana_kumari.
// C# program to replace all consonants// with nearest vowels in a stringusing System; public class solution{ // Function to replace consonant with // nearest vowels static String replacingConsonants(String s) { String str = "aaaeeeeiiiiioooooouuuuuuuu"; char[] st = s.ToCharArray(); for (int i = 0; i < s.Length; i++) { int index = st[i]-'a'; st[i] = str[index]; } String str1 = new String(st); return str1; } // Driver code public static void Main() { String s = "geeksforgeeks"; Console.WriteLine(replacingConsonants(s)); } } // This code is contributed by 29AjayKumar
<script> // Javascript program to replace all consonants// with nearest vowels in a string // Function to replace consonant with// nearest vowelsfunction replacingConsonants(s){ var nVowel = "aaaeeeeiiiiioooooouuuuuuuu"; for (var i = 0; i < s.length; i++) s[i] = nVowel[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]; return s.join('');} // Driver codevar s = "geeksforgeeks".split('');document.write( replacingConsonants(s)); </script>
eeeiueooeeeiu
Time Complexity: O(n), where n is the size of string sAuxiliary Space: O(26)
SURENDRA_GANGWAR
andrew1234
29AjayKumar
princiraj1992
archana_kumari
rituraj_jain
itsok
rdtank
sweetyty
singhh3010
Technical Scripter 2018
vowel-consonant
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 365,
"s": 53,
"text": "Given a string with lowercase English alphabets. The task is to replace all the consonants in the string with the nearest vowels. If a consonant is near to two vowels then replace it with the one that comes first in English alphabets. Note: Vowels already present in the string must be left as it is.Examples: "
},
{
"code": null,
"e": 452,
"s": 365,
"text": "Input : str = \"geeksforgeeks\"\nOutput : eeeiueooeeeiu\n\nInput : str = \"gfg\"\nOutput : eee"
},
{
"code": null,
"e": 1028,
"s": 454,
"text": "A simple approach is to compare the consonant with vowels to determine the nearest vowel. First, check if the consonant falls between two vowels. If it falls between 2 vowels then find the absolute difference between the ASCII value of consonant with the ASCII value of both vowels. Replace it with that vowel, with which the absolute difference is minimum. However, if the ASCII code of consonant does not fall between two vowels, then the consonant can be ‘v’, ‘w’, ‘x’, ‘y’, ‘z’. Hence, the answer is ‘u’ in this case.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1032,
"s": 1028,
"text": "C++"
},
{
"code": null,
"e": 1037,
"s": 1032,
"text": "Java"
},
{
"code": null,
"e": 1045,
"s": 1037,
"text": "Python3"
},
{
"code": null,
"e": 1048,
"s": 1045,
"text": "C#"
},
{
"code": null,
"e": 1059,
"s": 1048,
"text": "Javascript"
},
{
"code": "// C++ program to replace all consonants// with nearest vowels in a string#include <bits/stdc++.h>using namespace std; // Function to check if a character is// vowel or notbool isVowel(char ch){ if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') return false; return true;} // Function to replace consonant with// nearest vowelsstring replacingConsonants(string s){ for (int i = 0; i < s.length(); i++) { // if, string element is vowel, // jump to next element if (isVowel(s[i])) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s[i] > 'a' && s[i] < 'e') { // here the absolute difference of // ascii value is considered if (abs(s[i] - 'a') > abs(s[i] - 'e')) s[i] = 'e'; else s[i] = 'a'; } else if (s[i] > 'e' && s[i] < 'i') { if (abs(s[i] - 'e') > abs(s[i] - 'i')) s[i] = 'i'; else s[i] = 'e'; } else if (s[i] > 'i' && s[i] < 'o') { if (abs(s[i] - 'i') > abs(s[i] - 'o')) s[i] = 'o'; else s[i] = 'i'; } else if (s[i] > 'o' && s[i] < 'u') { if (abs(s[i] - 'o') > abs(s[i] - 'u')) s[i] = 'u'; else s[i] = 'o'; } // when s[i] is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s[i] > 'u') s[i] = 'u'; } } return s;} // Driver codeint main(){ string s = \"geeksforgeeks\"; cout << replacingConsonants(s); return 0;}",
"e": 2905,
"s": 1059,
"text": null
},
{
"code": "// Java program to replace all consonants// with nearest vowels in a string import java.util.*;class Solution{ // Function to check if a character is// vowel or notstatic boolean isVowel(char ch){ if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') return false; return true;} // Function to replace consonant with// nearest vowelsstatic String replacingConsonants(String s){ for (int i = 0; i < s.length(); i++) { // if, string element is vowel, // jump to next element if (isVowel(s.charAt(i))) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s.charAt(i) > 'a' && s.charAt(i) < 'e') { // here the absolute difference of // ascii value is considered if (Math.abs(s.charAt(i) - 'a') > Math.abs(s.charAt(i) - 'e')) s = s.substring(0,i)+'e'+s.substring(i+1); else s= s.substring(0,i)+'a'+s.substring(i+1); } else if (s.charAt(i) > 'e' && s.charAt(i) < 'i') { if (Math.abs(s.charAt(i) - 'e') > Math.abs(s.charAt(i) - 'i')) s = s.substring(0,i)+'i'+s.substring(i+1); else s = s.substring(0,i)+'e'+s.substring(i+1); } else if (s.charAt(i) > 'i' && s.charAt(i) < 'o') { if (Math.abs(s.charAt(i) - 'i') > Math.abs(s.charAt(i) - 'o')) s= s.substring(0,i)+'o'+s.substring(i+1); else s= s.substring(0,i)+'i'+s.substring(i+1); } else if (s.charAt(i) > 'o' && s.charAt(i) < 'u') { if (Math.abs(s.charAt(i) - 'o') > Math.abs(s.charAt(i) - 'u')) s= s.substring(0,i)+'u'+s.substring(i+1); else s= s.substring(0,i)+'o'+s.substring(i+1); } // when s.charAt(i) is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s.charAt(i) > 'u') s =s.substring(0,i)+'u'+s.substring(i+1); } } return s;} // Driver codepublic static void main(String args[]){ String s = \"geeksforgeeks\"; System.out.print( replacingConsonants(s)); } }//contributed by Arnab Kundu",
"e": 5274,
"s": 2905,
"text": null
},
{
"code": "# Python3 program to replace all consonants# with nearest vowels in a string # Function to check if a# character is vowel or notdef isVowel(ch): if (ch != 'a' and ch != 'e' and ch != 'i' and ch != 'o' and ch != 'u'): return False return True # Function to replace consonant# with nearest vowelsdef replacingConsonants(s): for i in range(0, len(s)): # if, string element is vowel, # jump to next element if isVowel(s[i]): continue # check if consonant lies between two vowels, # if it lies, than replace it with nearest vowel else: if s[i] > 'a' and s[i] < 'e': # here the absolute difference of # ascii value is considered if (abs(ord(s[i]) - ord('a')) > abs(ord(s[i]) - ord('e'))): s[i] = 'e' else: s[i] = 'a' elif s[i] > 'e' and s[i] < 'i': if (abs(ord(s[i]) - ord('e')) > abs(ord(s[i]) - ord('i'))): s[i] = 'i' else: s[i] = 'e' elif (s[i] > 'i' and s[i] < 'o'): if (abs(ord(s[i]) - ord('i')) > abs(ord(s[i]) - ord('o'))): s[i] = 'o' else: s[i] = 'i' elif (s[i] > 'o' and s[i] < 'u'): if (abs(ord(s[i]) - ord('o')) > abs(ord(s[i]) - ord('u'))): s[i] = 'u' else: s[i] = 'o' # when s[i] is equal to either # 'v', 'w', 'x', 'y', 'z' elif (s[i] > 'u'): s[i] = 'u' return ''.join(s) # Driver codeif __name__ == \"__main__\": s = \"geeksforgeeks\" print(replacingConsonants(list(s))) # This code is contributed by Rituraj Jain",
"e": 7157,
"s": 5274,
"text": null
},
{
"code": " // C# program to replace all consonants// with nearest vowels in a stringusing System;public class Solution{ // Function to check if a character is // vowel or not static bool isVowel(char ch) { if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') return false; return true; } // Function to replace consonant with // nearest vowels static String replacingConsonants(String s) { for (int i = 0; i < s.Length; i++) { // if, string element is vowel, // jump to next element if (isVowel(s[i])) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s[i] > 'a' && s[i] < 'e') { // here the absolute difference of // ascii value is considered if (Math.Abs(s[i] - 'a') > Math.Abs(s[i] - 'e')) s = s.Substring(0,i)+'e'+s.Substring(i+1); else s= s.Substring(0,i)+'a'+s.Substring(i+1); } else if (s[i] > 'e' && s[i] < 'i') { if (Math.Abs(s[i] - 'e') > Math.Abs(s[i] - 'i')) s = s.Substring(0,i)+'i'+s.Substring(i+1); else s = s.Substring(0,i)+'e'+s.Substring(i+1); } else if (s[i] > 'i' && s[i] < 'o') { if (Math.Abs(s[i] - 'i') > Math.Abs(s[i] - 'o')) s= s.Substring(0,i)+'o'+s.Substring(i+1); else s= s.Substring(0,i)+'i'+s.Substring(i+1); } else if (s[i] > 'o' && s[i] < 'u') { if (Math.Abs(s[i] - 'o') > Math.Abs(s[i] - 'u')) s= s.Substring(0,i)+'u'+s.Substring(i+1); else s= s.Substring(0,i)+'o'+s.Substring(i+1); } // when s[i] is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s[i] > 'u') s =s.Substring(0,i)+'u'+s.Substring(i+1); } } return s; } // Driver code public static void Main() { String s = \"geeksforgeeks\"; Console.WriteLine( replacingConsonants(s)); }} // This code is contributed by PrinciRaj1992",
"e": 9638,
"s": 7157,
"text": null
},
{
"code": "<script> // JavaScript program to replace all consonants // with nearest vowels in a string // Function to check if a character is // vowel or not function isVowel(ch) { if (ch !== \"a\" && ch !== \"e\" && ch !== \"i\" && ch !== \"o\" && ch !== \"u\") return false; return true; } // Function to replace consonant with // nearest vowels function replacingConsonants(s) { for (var i = 0; i < s.length; i++) { // if, string element is vowel, // jump to next element if (isVowel(s[i])) continue; // check if consonant lies between two vowels, // if it lies, than replace it with nearest vowel else { if (s[i] > \"a\" && s[i] < \"e\") { // here the absolute difference of // ascii value is considered if ( Math.abs(s[i].charCodeAt(0) - \"a\".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - \"e\".charCodeAt(0)) ) s = s.substring(0, i) + \"e\" + s.substring(i + 1); else s = s.substring(0, i) + \"a\" + s.substring(i + 1); } else if (s[i] > \"e\" && s[i] < \"i\") { if ( Math.abs(s[i].charCodeAt(0) - \"e\".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - \"i\".charCodeAt(0)) ) s = s.substring(0, i) + \"i\" + s.substring(i + 1); else s = s.substring(0, i) + \"e\" + s.substring(i + 1); } else if (s[i] > \"i\" && s[i] < \"o\") { if ( Math.abs(s[i].charCodeAt(0) - \"i\".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - \"o\".charCodeAt(0)) ) s = s.substring(0, i) + \"o\" + s.substring(i + 1); else s = s.substring(0, i) + \"i\" + s.substring(i + 1); } else if (s[i] > \"o\" && s[i] < \"u\") { if ( Math.abs(s[i].charCodeAt(0) - \"o\".charCodeAt(0)) > Math.abs(s[i].charCodeAt(0) - \"u\".charCodeAt(0)) ) s = s.substring(0, i) + \"u\" + s.substring(i + 1); else s = s.substring(0, i) + \"o\" + s.substring(i + 1); } // when s[i] is equal to either // 'v', 'w', 'x', 'y', 'z' else if (s[i] > \"u\") s = s.substring(0, i) + \"u\" + s.substring(i + 1); } } return s; } // Driver code var s = \"geeksforgeeks\"; document.write(replacingConsonants(s)); </script>",
"e": 12168,
"s": 9638,
"text": null
},
{
"code": null,
"e": 12182,
"s": 12168,
"text": "eeeiueooeeeiu"
},
{
"code": null,
"e": 12260,
"s": 12184,
"text": "Time Complexity: O(n), where n is the size of string sAuxiliary Space: O(1)"
},
{
"code": null,
"e": 12358,
"s": 12260,
"text": "A better approach is to make an array of size 26 that stores nearest vowel for every character. "
},
{
"code": null,
"e": 12362,
"s": 12358,
"text": "C++"
},
{
"code": null,
"e": 12367,
"s": 12362,
"text": "Java"
},
{
"code": null,
"e": 12375,
"s": 12367,
"text": "Python3"
},
{
"code": null,
"e": 12378,
"s": 12375,
"text": "C#"
},
{
"code": null,
"e": 12389,
"s": 12378,
"text": "Javascript"
},
{
"code": "// C++ program to replace all consonants// with nearest vowels in a string#include <bits/stdc++.h>using namespace std; // Function to replace consonant with// nearest vowelsstring replacingConsonants(string s){ char nVowel[] = \"aaaeeeeiiiiioooooouuuuuuuu\"; for (int i = 0; i < s.length(); i++) s[i] = nVowel[s[i] - 'a']; return s;} // Driver codeint main(){ string s = \"geeksforgeeks\"; cout << replacingConsonants(s); return 0;}",
"e": 12845,
"s": 12389,
"text": null
},
{
"code": "// Java program to replace all consonants// with nearest vowels in a stringimport java.util.*; class solution{ // Function to replace consonant with// nearest vowelsstatic String replacingConsonants(String s){ String str = \"aaaeeeeiiiiioooooouuuuuuuu\"; char[] st = s.toCharArray(); for (int i = 0; i < s.length(); i++) { int index = st[i]-'a'; st[i] = str.charAt(index); } String str1 = new String(st); return str1;} // Driver codepublic static void main(String arr[]){ String s = \"geeksforgeeks\"; System.out.println(replacingConsonants(s)); } }// This code is contributed by Surendra_Gangwar",
"e": 13485,
"s": 12845,
"text": null
},
{
"code": "# Python3 program to replace all consonants# with nearest vowels in a string # Function to replace consonant with# nearest vowelsdef replacingConsonants(s): nVowel = \"aaaeeeeiiiiioooooouuuuuuuu\" for i in range (0, len(s)): s = s.replace(s[i], nVowel[ord(s[i]) - 97]) return s # Driver codes = \"geeksforgeeks\"; print(replacingConsonants(s)); # This code is contributed by# archana_kumari.",
"e": 13900,
"s": 13485,
"text": null
},
{
"code": " // C# program to replace all consonants// with nearest vowels in a stringusing System; public class solution{ // Function to replace consonant with // nearest vowels static String replacingConsonants(String s) { String str = \"aaaeeeeiiiiioooooouuuuuuuu\"; char[] st = s.ToCharArray(); for (int i = 0; i < s.Length; i++) { int index = st[i]-'a'; st[i] = str[index]; } String str1 = new String(st); return str1; } // Driver code public static void Main() { String s = \"geeksforgeeks\"; Console.WriteLine(replacingConsonants(s)); } } // This code is contributed by 29AjayKumar",
"e": 14602,
"s": 13900,
"text": null
},
{
"code": "<script> // Javascript program to replace all consonants// with nearest vowels in a string // Function to replace consonant with// nearest vowelsfunction replacingConsonants(s){ var nVowel = \"aaaeeeeiiiiioooooouuuuuuuu\"; for (var i = 0; i < s.length; i++) s[i] = nVowel[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]; return s.join('');} // Driver codevar s = \"geeksforgeeks\".split('');document.write( replacingConsonants(s)); </script>",
"e": 15048,
"s": 14602,
"text": null
},
{
"code": null,
"e": 15062,
"s": 15048,
"text": "eeeiueooeeeiu"
},
{
"code": null,
"e": 15141,
"s": 15064,
"text": "Time Complexity: O(n), where n is the size of string sAuxiliary Space: O(26)"
},
{
"code": null,
"e": 15158,
"s": 15141,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 15169,
"s": 15158,
"text": "andrew1234"
},
{
"code": null,
"e": 15181,
"s": 15169,
"text": "29AjayKumar"
},
{
"code": null,
"e": 15195,
"s": 15181,
"text": "princiraj1992"
},
{
"code": null,
"e": 15210,
"s": 15195,
"text": "archana_kumari"
},
{
"code": null,
"e": 15223,
"s": 15210,
"text": "rituraj_jain"
},
{
"code": null,
"e": 15229,
"s": 15223,
"text": "itsok"
},
{
"code": null,
"e": 15236,
"s": 15229,
"text": "rdtank"
},
{
"code": null,
"e": 15245,
"s": 15236,
"text": "sweetyty"
},
{
"code": null,
"e": 15256,
"s": 15245,
"text": "singhh3010"
},
{
"code": null,
"e": 15280,
"s": 15256,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 15296,
"s": 15280,
"text": "vowel-consonant"
},
{
"code": null,
"e": 15304,
"s": 15296,
"text": "Strings"
},
{
"code": null,
"e": 15312,
"s": 15304,
"text": "Strings"
}
] |
Condition of schedules to View-equivalent | 28 Jun, 2021
Two schedules S1 and S2 are said to be view-equivalent if below conditions are satisfied :
1) Initial Read If a transaction T1 reading data item A from database in S1 then in S2 also T1 should read A from database.
T1 T2 T3
-------------------
R(A)
W(A)
R(A)
R(B)
Transaction T2 is reading A from database.
2)Updated Read If Ti is reading A which is updated by Tj in S1 then in S2 also Ti should read A which is updated by Tj.
T1 T2 T3 T1 T2 T3
------------------- ----------------
W(A) W(A)
W(A) R(A)
R(A) W(A)
Above two schedule are not view-equivalent as in S1 :T3 is reading A updated by T2, in S2 T3 is reading A updated by T1.
3)Final Write operation If a transaction T1 updated A at last in S1, then in S2 also T1 should perform final write operations.
T1 T2 T1 T2
------------ ---------------
R(A) R(A)
W(A) W(A)
W(A) W(A)
Above two schedules are not view-equivalent as Final write operation in S1 is done by T1 while in S2 done by T2.
View Serializability: A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions).
Below are the previous Year Gate Question asked on this topic https://www.geeksforgeeks.org/dbms-gq/transactions-and-concurrency-control-gq/
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
AmolBarge
madhav_mohan
nunemunthalashiva
DBMS-Transactions and Concurrency Control
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
CTE in SQL
Difference between Clustered and Non-clustered index
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Data Preprocessing in Data Mining
Difference between DELETE, DROP and TRUNCATE | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 144,
"s": 52,
"text": "Two schedules S1 and S2 are said to be view-equivalent if below conditions are satisfied : "
},
{
"code": null,
"e": 269,
"s": 144,
"text": "1) Initial Read If a transaction T1 reading data item A from database in S1 then in S2 also T1 should read A from database. "
},
{
"code": null,
"e": 372,
"s": 271,
"text": " T1 T2 T3\n-------------------\n R(A)\n W(A) \n R(A)\n R(B)"
},
{
"code": null,
"e": 416,
"s": 372,
"text": "Transaction T2 is reading A from database. "
},
{
"code": null,
"e": 537,
"s": 416,
"text": "2)Updated Read If Ti is reading A which is updated by Tj in S1 then in S2 also Ti should read A which is updated by Tj. "
},
{
"code": null,
"e": 770,
"s": 539,
"text": " T1 T2 T3 T1 T2 T3 \n------------------- ----------------\n W(A) W(A) \n W(A) R(A)\n R(A) W(A)"
},
{
"code": null,
"e": 892,
"s": 770,
"text": "Above two schedule are not view-equivalent as in S1 :T3 is reading A updated by T2, in S2 T3 is reading A updated by T1. "
},
{
"code": null,
"e": 1020,
"s": 892,
"text": "3)Final Write operation If a transaction T1 updated A at last in S1, then in S2 also T1 should perform final write operations. "
},
{
"code": null,
"e": 1173,
"s": 1022,
"text": " T1 T2 T1 T2 \n------------ ---------------\n R(A) R(A)\n W(A) W(A)\n W(A) W(A)"
},
{
"code": null,
"e": 1287,
"s": 1173,
"text": "Above two schedules are not view-equivalent as Final write operation in S1 is done by T1 while in S2 done by T2. "
},
{
"code": null,
"e": 1421,
"s": 1287,
"text": "View Serializability: A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). "
},
{
"code": null,
"e": 1563,
"s": 1421,
"text": "Below are the previous Year Gate Question asked on this topic https://www.geeksforgeeks.org/dbms-gq/transactions-and-concurrency-control-gq/ "
},
{
"code": null,
"e": 1688,
"s": 1563,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 1698,
"s": 1688,
"text": "AmolBarge"
},
{
"code": null,
"e": 1711,
"s": 1698,
"text": "madhav_mohan"
},
{
"code": null,
"e": 1729,
"s": 1711,
"text": "nunemunthalashiva"
},
{
"code": null,
"e": 1771,
"s": 1729,
"text": "DBMS-Transactions and Concurrency Control"
},
{
"code": null,
"e": 1776,
"s": 1771,
"text": "DBMS"
},
{
"code": null,
"e": 1781,
"s": 1776,
"text": "DBMS"
},
{
"code": null,
"e": 1879,
"s": 1781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1926,
"s": 1879,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 1944,
"s": 1926,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 1985,
"s": 1944,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 1996,
"s": 1985,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2049,
"s": 1996,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 2080,
"s": 2049,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 2104,
"s": 2080,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 2116,
"s": 2104,
"text": "SQL | Views"
},
{
"code": null,
"e": 2150,
"s": 2116,
"text": "Data Preprocessing in Data Mining"
}
] |
Node.js fsPromises.open() Method | 08 Oct, 2021
The fsPromises.open() method is used to asynchronously open a file that returns a Promise that, when resolved, yields a FileHandle object.
Syntax:
fsPromises.open( filename, flags, mode)
Parameter: This method accept three parameters as mentioned above and described below:
filename: It is a String, Buffer or an URL that holds the name of the file to read or the entire path if stored at other location.
flags: It is a String or a Number, which gives operation in which file has to be opened. Default ‘r’.
mode: It is a String or an Integer. Sets the mode of file i.e. r:read, w:write, r+:readwrite. It sets to default as readwrite.
Return Value: It returns the Promise.
Below example illustrates the fsPromises.open() method in Node.js:
Example:
// Node.js program to demonstrate the // fsPromises.open() Method // Include the fs module var fs = require('fs'); var fsPromises = fs.promises; // Open file Demo.txt in read mode fsPromises.open('Demo.txt', 'r').then((result)=>{ console.log(result);}).catch((error)=>{ console.log(error);});
Output:
FileHandle { [Symbol(handle)]: FileHandle { fd: 3 } }
Explanation: The file is opened and the flag is set to read mode. After opening of file function is called to read the contents of file and store in memory.
Note: mode sets the file mode (permission and sticky bits), but only if the file was created.
Some characters (< > : ” / \ | ? *) are reserved under Windows as documented by Naming Files, Paths, and Namespaces.
Akanksha_Rai
Node.js-fs-module
Node.js
Web Technologies
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": "\n08 Oct, 2021"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "The fsPromises.open() method is used to asynchronously open a file that returns a Promise that, when resolved, yields a FileHandle object."
},
{
"code": null,
"e": 175,
"s": 167,
"text": "Syntax:"
},
{
"code": null,
"e": 215,
"s": 175,
"text": "fsPromises.open( filename, flags, mode)"
},
{
"code": null,
"e": 302,
"s": 215,
"text": "Parameter: This method accept three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 433,
"s": 302,
"text": "filename: It is a String, Buffer or an URL that holds the name of the file to read or the entire path if stored at other location."
},
{
"code": null,
"e": 535,
"s": 433,
"text": "flags: It is a String or a Number, which gives operation in which file has to be opened. Default ‘r’."
},
{
"code": null,
"e": 663,
"s": 535,
"text": "mode: It is a String or an Integer. Sets the mode of file i.e. r:read, w:write, r+:readwrite. It sets to default as readwrite."
},
{
"code": null,
"e": 701,
"s": 663,
"text": "Return Value: It returns the Promise."
},
{
"code": null,
"e": 768,
"s": 701,
"text": "Below example illustrates the fsPromises.open() method in Node.js:"
},
{
"code": null,
"e": 777,
"s": 768,
"text": "Example:"
},
{
"code": "// Node.js program to demonstrate the // fsPromises.open() Method // Include the fs module var fs = require('fs'); var fsPromises = fs.promises; // Open file Demo.txt in read mode fsPromises.open('Demo.txt', 'r').then((result)=>{ console.log(result);}).catch((error)=>{ console.log(error);});",
"e": 1088,
"s": 777,
"text": null
},
{
"code": null,
"e": 1096,
"s": 1088,
"text": "Output:"
},
{
"code": null,
"e": 1150,
"s": 1096,
"text": "FileHandle { [Symbol(handle)]: FileHandle { fd: 3 } }"
},
{
"code": null,
"e": 1307,
"s": 1150,
"text": "Explanation: The file is opened and the flag is set to read mode. After opening of file function is called to read the contents of file and store in memory."
},
{
"code": null,
"e": 1401,
"s": 1307,
"text": "Note: mode sets the file mode (permission and sticky bits), but only if the file was created."
},
{
"code": null,
"e": 1518,
"s": 1401,
"text": "Some characters (< > : ” / \\ | ? *) are reserved under Windows as documented by Naming Files, Paths, and Namespaces."
},
{
"code": null,
"e": 1531,
"s": 1518,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1549,
"s": 1531,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 1557,
"s": 1549,
"text": "Node.js"
},
{
"code": null,
"e": 1574,
"s": 1557,
"text": "Web Technologies"
},
{
"code": null,
"e": 1672,
"s": 1574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1704,
"s": 1672,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 1739,
"s": 1704,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 1809,
"s": 1739,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 1836,
"s": 1809,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 1861,
"s": 1836,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 1923,
"s": 1861,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1984,
"s": 1923,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2034,
"s": 1984,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2077,
"s": 2034,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
MySQL ORDER BY Keyword | The ORDER BY keyword is used to sort the result-set in ascending or
descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the
DESC keyword.
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL statement selects all customers from the "Customers" table,
sorted by the "Country" column:
The following SQL statement selects all customers from the "Customers" table,
sorted DESCENDING by the "Country" column:
The following SQL statement selects all customers from the "Customers" table,
sorted by the "Country" and the "CustomerName" column. This means that it orders
by Country, but if some rows have the same Country, it orders them by
CustomerName:
The following SQL statement selects all customers from the "Customers" table,
sorted ascending by the "Country" and descending by the "CustomerName" column:
Select all records from the Customers table, sort the result alphabetically by the column City.
SELECT * FROM Customers
;
Start the Exercise
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": 87,
"s": 0,
"text": "The ORDER BY keyword is used to sort the result-set in ascending or \ndescending order."
},
{
"code": null,
"e": 221,
"s": 87,
"text": "The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the \nDESC keyword."
},
{
"code": null,
"e": 303,
"s": 221,
"text": "Below is a selection from the \"Customers\" table in the Northwind sample database:"
},
{
"code": null,
"e": 414,
"s": 303,
"text": "The following SQL statement selects all customers from the \"Customers\" table, \nsorted by the \"Country\" column:"
},
{
"code": null,
"e": 536,
"s": 414,
"text": "The following SQL statement selects all customers from the \"Customers\" table, \nsorted DESCENDING by the \"Country\" column:"
},
{
"code": null,
"e": 782,
"s": 536,
"text": "The following SQL statement selects all customers from the \"Customers\" table, \nsorted by the \"Country\" and the \"CustomerName\" column. This means that it orders \nby Country, but if some rows have the same Country, it orders them by \nCustomerName:"
},
{
"code": null,
"e": 940,
"s": 782,
"text": "The following SQL statement selects all customers from the \"Customers\" table, \nsorted ascending by the \"Country\" and descending by the \"CustomerName\" column:"
},
{
"code": null,
"e": 1036,
"s": 940,
"text": "Select all records from the Customers table, sort the result alphabetically by the column City."
},
{
"code": null,
"e": 1064,
"s": 1036,
"text": "SELECT * FROM Customers\n ;\n"
},
{
"code": null,
"e": 1083,
"s": 1064,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1116,
"s": 1083,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1158,
"s": 1116,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1265,
"s": 1158,
"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": 1284,
"s": 1265,
"text": "[email protected]"
}
] |
How to sort a dictionary in Python? | A dictionary is a data structure that consists of key and value pairs. We can sort a dictionary using two criteria −
Sort by key − The dictionary is sorted in ascending order of its keys. The values are not taken care of.
Sort by value − The dictionary is sorted in ascending order of the values.
In this approach, the dictionary is sorted in ascending order of its keys.
Input:
{2:90, 1: 100, 8: 3, 5: 67, 3: 5}
Output:
{1:100, 2:90, 3:5, 5:67, 8:3}
As shown above, we can see the dictionary is sorted according to its keys.
Live Demo
dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2={}
for i in sorted(dic):
dic2[i]=dic[i]
print(dic2)
{1: 100, 2: 90, 3: 5, 5: 67, 8: 3}
Declare a dictionary which is to be sorted
Declare a dictionary which is to be sorted
Declare an empty dictionary where sorted key value pairs are to be added
Declare an empty dictionary where sorted key value pairs are to be added
sorted(dic) has all the keys of dic in sorted order.It only has the keys and not keyvalue pairs. sorted(dic) will have [1,2,3,5,8]
sorted(dic) has all the keys of dic in sorted order.It only has the keys and not keyvalue pairs. sorted(dic) will have [1,2,3,5,8]
For each key in sorted order, add the key and the corresponding value into dic2.
For each key in sorted order, add the key and the corresponding value into dic2.
dic2 has all the key-value pairs in sorted order of keys
dic2 has all the key-value pairs in sorted order of keys
In this approach, the dictionary is sorted in ascending order of values.
Input:
{2:90, 1: 100, 8: 3, 5: 67, 3: 5}
Output:
{8:3, 3:5 ,5:67 , 2:90, 1:100}
As shown above, we can see the dictionary is sorted according to its values.
We use the sorted() and items() methods together to sort the dictionary by value.
We use the sorted() and items() methods together to sort the dictionary by value.
The items() is used to retrieve the items or values of the dictionary.
The items() is used to retrieve the items or values of the dictionary.
The key=lambda x: x[1] is a sorting mechanism that uses a lambda function.
The key=lambda x: x[1] is a sorting mechanism that uses a lambda function.
This gives us key value pairs ehich are then converted into a dictionary using dict().
This gives us key value pairs ehich are then converted into a dictionary using dict().
Live Demo
dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2=dict(sorted(dic.items(),key= lambda x:x[1]))
print(dic2)
{8: 3, 3: 5, 5: 67, 2: 90, 1: 100} | [
{
"code": null,
"e": 1179,
"s": 1062,
"text": "A dictionary is a data structure that consists of key and value pairs. We can sort a dictionary using two criteria −"
},
{
"code": null,
"e": 1284,
"s": 1179,
"text": "Sort by key − The dictionary is sorted in ascending order of its keys. The values are not taken care of."
},
{
"code": null,
"e": 1359,
"s": 1284,
"text": "Sort by value − The dictionary is sorted in ascending order of the values."
},
{
"code": null,
"e": 1434,
"s": 1359,
"text": "In this approach, the dictionary is sorted in ascending order of its keys."
},
{
"code": null,
"e": 1441,
"s": 1434,
"text": "Input:"
},
{
"code": null,
"e": 1475,
"s": 1441,
"text": "{2:90, 1: 100, 8: 3, 5: 67, 3: 5}"
},
{
"code": null,
"e": 1483,
"s": 1475,
"text": "Output:"
},
{
"code": null,
"e": 1513,
"s": 1483,
"text": "{1:100, 2:90, 3:5, 5:67, 8:3}"
},
{
"code": null,
"e": 1588,
"s": 1513,
"text": "As shown above, we can see the dictionary is sorted according to its keys."
},
{
"code": null,
"e": 1599,
"s": 1588,
"text": " Live Demo"
},
{
"code": null,
"e": 1697,
"s": 1599,
"text": "dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}\ndic2={}\nfor i in sorted(dic):\n dic2[i]=dic[i]\nprint(dic2)"
},
{
"code": null,
"e": 1732,
"s": 1697,
"text": "{1: 100, 2: 90, 3: 5, 5: 67, 8: 3}"
},
{
"code": null,
"e": 1775,
"s": 1732,
"text": "Declare a dictionary which is to be sorted"
},
{
"code": null,
"e": 1818,
"s": 1775,
"text": "Declare a dictionary which is to be sorted"
},
{
"code": null,
"e": 1891,
"s": 1818,
"text": "Declare an empty dictionary where sorted key value pairs are to be added"
},
{
"code": null,
"e": 1964,
"s": 1891,
"text": "Declare an empty dictionary where sorted key value pairs are to be added"
},
{
"code": null,
"e": 2095,
"s": 1964,
"text": "sorted(dic) has all the keys of dic in sorted order.It only has the keys and not keyvalue pairs. sorted(dic) will have [1,2,3,5,8]"
},
{
"code": null,
"e": 2226,
"s": 2095,
"text": "sorted(dic) has all the keys of dic in sorted order.It only has the keys and not keyvalue pairs. sorted(dic) will have [1,2,3,5,8]"
},
{
"code": null,
"e": 2307,
"s": 2226,
"text": "For each key in sorted order, add the key and the corresponding value into dic2."
},
{
"code": null,
"e": 2388,
"s": 2307,
"text": "For each key in sorted order, add the key and the corresponding value into dic2."
},
{
"code": null,
"e": 2445,
"s": 2388,
"text": "dic2 has all the key-value pairs in sorted order of keys"
},
{
"code": null,
"e": 2502,
"s": 2445,
"text": "dic2 has all the key-value pairs in sorted order of keys"
},
{
"code": null,
"e": 2575,
"s": 2502,
"text": "In this approach, the dictionary is sorted in ascending order of values."
},
{
"code": null,
"e": 2582,
"s": 2575,
"text": "Input:"
},
{
"code": null,
"e": 2616,
"s": 2582,
"text": "{2:90, 1: 100, 8: 3, 5: 67, 3: 5}"
},
{
"code": null,
"e": 2624,
"s": 2616,
"text": "Output:"
},
{
"code": null,
"e": 2655,
"s": 2624,
"text": "{8:3, 3:5 ,5:67 , 2:90, 1:100}"
},
{
"code": null,
"e": 2732,
"s": 2655,
"text": "As shown above, we can see the dictionary is sorted according to its values."
},
{
"code": null,
"e": 2814,
"s": 2732,
"text": "We use the sorted() and items() methods together to sort the dictionary by value."
},
{
"code": null,
"e": 2896,
"s": 2814,
"text": "We use the sorted() and items() methods together to sort the dictionary by value."
},
{
"code": null,
"e": 2967,
"s": 2896,
"text": "The items() is used to retrieve the items or values of the dictionary."
},
{
"code": null,
"e": 3038,
"s": 2967,
"text": "The items() is used to retrieve the items or values of the dictionary."
},
{
"code": null,
"e": 3113,
"s": 3038,
"text": "The key=lambda x: x[1] is a sorting mechanism that uses a lambda function."
},
{
"code": null,
"e": 3188,
"s": 3113,
"text": "The key=lambda x: x[1] is a sorting mechanism that uses a lambda function."
},
{
"code": null,
"e": 3275,
"s": 3188,
"text": "This gives us key value pairs ehich are then converted into a dictionary using dict()."
},
{
"code": null,
"e": 3362,
"s": 3275,
"text": "This gives us key value pairs ehich are then converted into a dictionary using dict()."
},
{
"code": null,
"e": 3373,
"s": 3362,
"text": " Live Demo"
},
{
"code": null,
"e": 3473,
"s": 3373,
"text": "dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}\ndic2=dict(sorted(dic.items(),key= lambda x:x[1]))\nprint(dic2)"
},
{
"code": null,
"e": 3508,
"s": 3473,
"text": "{8: 3, 3: 5, 5: 67, 2: 90, 1: 100}"
}
] |
Android - Loading Spinner | You can show progress of a task in android through loading progress bar. The progress bar comes in two shapes. Loading bar and Loading Spinner. In this chapter we will discuss spinner.
Spinner is used to display progress of those tasks whose total time of completion is unknown. In order to use that, you just need to define it in the xml like this.
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
After defining it in xml, you have to get its reference in java file through ProgressBar class. Its syntax is given below −
private ProgressBar spinner;
spinner = (ProgressBar)findViewById(R.id.progressBar1);
After that you can make its disappear , and bring it back when needed through setVisibility Method. Its syntax is given below −
spinner.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);
Apart from these Methods, there are other methods defined in the ProgressBar class , that you can use to handle spinner more effectively.
isIndeterminate()
Indicate whether this progress bar is in indeterminate mode
postInvalidate()
Cause an invalidate to happen on a subsequent cycle through the event loop
setIndeterminate(boolean indeterminate)
Change the indeterminate mode for this progress bar
invalidateDrawable(Drawable dr)
Invalidates the specified Drawable
incrementSecondaryProgressBy(int diff)
Increase the progress bar's secondary progress by the specified amount
getProgressDrawable()
Get the drawable used to draw the progress bar in progress mode
Here is an example demonstrating the use of ProgressBar to handle spinner. It creates a basic application that allows you to turn on the spinner on clicking the button.
To experiment with this example , you can run this on an actual device or in an emulator.
Following is the content of the modified main activity file src/MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
Button b1;
private ProgressBar spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
spinner=(ProgressBar)findViewById(R.id.progressBar);
spinner.setVisibility(View.GONE);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
spinner.setVisibility(View.VISIBLE);
}
});
}
}
Following is the modified content of the xml res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="Progress Dialog" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="download"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:progressDrawable="@drawable/circular_progress_bar"
android:layout_below="@+id/button"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:layout_alignLeft="@+id/textview"
android:layout_alignStart="@+id/textview"
android:layout_alignParentBottom="true" />
</RelativeLayout>
Following is the content of the res/drawable/circular_progress_bar.xml.
<?xml version="1.0" encoding="utf-8"?>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="90"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="7.0">
<gradient
android:centerColor="#007DD6"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:angle="0"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Now click on the load spinner button to turn on the loading spinner. It is shown in the image below −
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3792,
"s": 3607,
"text": "You can show progress of a task in android through loading progress bar. The progress bar comes in two shapes. Loading bar and Loading Spinner. In this chapter we will discuss spinner."
},
{
"code": null,
"e": 3957,
"s": 3792,
"text": "Spinner is used to display progress of those tasks whose total time of completion is unknown. In order to use that, you just need to define it in the xml like this."
},
{
"code": null,
"e": 4175,
"s": 3957,
"text": "<ProgressBar\n android:id=\"@+id/progressBar1\"\n style=\"?android:attr/progressBarStyleLarge\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\" />"
},
{
"code": null,
"e": 4299,
"s": 4175,
"text": "After defining it in xml, you have to get its reference in java file through ProgressBar class. Its syntax is given below −"
},
{
"code": null,
"e": 4384,
"s": 4299,
"text": "private ProgressBar spinner;\nspinner = (ProgressBar)findViewById(R.id.progressBar1);"
},
{
"code": null,
"e": 4512,
"s": 4384,
"text": "After that you can make its disappear , and bring it back when needed through setVisibility Method. Its syntax is given below −"
},
{
"code": null,
"e": 4584,
"s": 4512,
"text": "spinner.setVisibility(View.GONE);\nspinner.setVisibility(View.VISIBLE);\t"
},
{
"code": null,
"e": 4722,
"s": 4584,
"text": "Apart from these Methods, there are other methods defined in the ProgressBar class , that you can use to handle spinner more effectively."
},
{
"code": null,
"e": 4740,
"s": 4722,
"text": "isIndeterminate()"
},
{
"code": null,
"e": 4800,
"s": 4740,
"text": "Indicate whether this progress bar is in indeterminate mode"
},
{
"code": null,
"e": 4817,
"s": 4800,
"text": "postInvalidate()"
},
{
"code": null,
"e": 4892,
"s": 4817,
"text": "Cause an invalidate to happen on a subsequent cycle through the event loop"
},
{
"code": null,
"e": 4932,
"s": 4892,
"text": "setIndeterminate(boolean indeterminate)"
},
{
"code": null,
"e": 4984,
"s": 4932,
"text": "Change the indeterminate mode for this progress bar"
},
{
"code": null,
"e": 5016,
"s": 4984,
"text": "invalidateDrawable(Drawable dr)"
},
{
"code": null,
"e": 5051,
"s": 5016,
"text": "Invalidates the specified Drawable"
},
{
"code": null,
"e": 5090,
"s": 5051,
"text": "incrementSecondaryProgressBy(int diff)"
},
{
"code": null,
"e": 5161,
"s": 5090,
"text": "Increase the progress bar's secondary progress by the specified amount"
},
{
"code": null,
"e": 5183,
"s": 5161,
"text": "getProgressDrawable()"
},
{
"code": null,
"e": 5247,
"s": 5183,
"text": "Get the drawable used to draw the progress bar in progress mode"
},
{
"code": null,
"e": 5416,
"s": 5247,
"text": "Here is an example demonstrating the use of ProgressBar to handle spinner. It creates a basic application that allows you to turn on the spinner on clicking the button."
},
{
"code": null,
"e": 5506,
"s": 5416,
"text": "To experiment with this example , you can run this on an actual device or in an emulator."
},
{
"code": null,
"e": 5590,
"s": 5506,
"text": "Following is the content of the modified main activity file src/MainActivity.java. "
},
{
"code": null,
"e": 6382,
"s": 5590,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ProgressBar;\n\n\npublic class MainActivity extends Activity {\n Button b1;\n\n private ProgressBar spinner;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n b1=(Button)findViewById(R.id.button);\n spinner=(ProgressBar)findViewById(R.id.progressBar);\n spinner.setVisibility(View.GONE);\n\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n spinner.setVisibility(View.VISIBLE);\n }\n });\n }\n}"
},
{
"code": null,
"e": 6457,
"s": 6382,
"text": "Following is the modified content of the xml res/layout/activity_main.xml."
},
{
"code": null,
"e": 8654,
"s": 6457,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" \n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" tools:context=\".MainActivity\">\n \n <TextView android:text=\"Progress Dialog\" android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"download\"\n android:id=\"@+id/button\"\n android:layout_below=\"@+id/imageView\"\n android:layout_centerHorizontal=\"true\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\" />\n \n <ProgressBar\n style=\"?android:attr/progressBarStyleLarge\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/progressBar\"\n android:progressDrawable=\"@drawable/circular_progress_bar\"\n android:layout_below=\"@+id/button\"\n android:layout_alignRight=\"@+id/textView\"\n android:layout_alignEnd=\"@+id/textView\"\n android:layout_alignLeft=\"@+id/textview\"\n android:layout_alignStart=\"@+id/textview\"\n android:layout_alignParentBottom=\"true\" />\n\n</RelativeLayout>"
},
{
"code": null,
"e": 8726,
"s": 8654,
"text": "Following is the content of the res/drawable/circular_progress_bar.xml."
},
{
"code": null,
"e": 9307,
"s": 8726,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rotate\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:fromDegrees=\"90\"\n android:pivotX=\"50%\"\n android:pivotY=\"50%\"\n android:toDegrees=\"360\">\n \n <shape\n android:innerRadiusRatio=\"3\"\n android:shape=\"ring\"\n android:thicknessRatio=\"7.0\">\n \n <gradient\n android:centerColor=\"#007DD6\"\n android:endColor=\"#007DD6\"\n android:startColor=\"#007DD6\"\n android:angle=\"0\"\n android:type=\"sweep\"\n android:useLevel=\"false\" />\n </shape>\n \n</rotate>"
},
{
"code": null,
"e": 9361,
"s": 9307,
"text": "Following is the content of AndroidManifest.xml file."
},
{
"code": null,
"e": 10104,
"s": 9361,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.sairamkrishna.myapplication.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 10497,
"s": 10104,
"text": "Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 10599,
"s": 10497,
"text": "Now click on the load spinner button to turn on the loading spinner. It is shown in the image below −"
},
{
"code": null,
"e": 10634,
"s": 10599,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 10646,
"s": 10634,
"text": " Aditya Dua"
},
{
"code": null,
"e": 10681,
"s": 10646,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10695,
"s": 10681,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 10727,
"s": 10695,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10744,
"s": 10727,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10779,
"s": 10744,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10796,
"s": 10779,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10831,
"s": 10796,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10848,
"s": 10831,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10881,
"s": 10848,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10898,
"s": 10881,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10905,
"s": 10898,
"text": " Print"
},
{
"code": null,
"e": 10916,
"s": 10905,
"text": " Add Notes"
}
] |
What is the difference between MySQL TRUNCATE and DELETE command? | As we know that TRUNCATE will remove all the rows without removing table’s structure from the database. Same work can be done with the help of DELETE command on removing all the rows from the table. But there is a significant difference of re-initialization of PRIMARY KEY AUTO_INCREMENT between both the commands.
Suppose a column is defined AUTO_INCREMENT having PRIMARY KEY CONSTRAINT, then on deleting all the rows with DELETE command would not re-initialize the table i.e. on entering the new rows, the AUTO_INCREMENT number will start after the last inserted row. In contrast, on using TRUNCATE, the table will be re-initializing like a newly created table. It means after using TRUNCATE command and on inserting new rows the AUTO_INCREMENT number will start from 1.
Following example will demonstrate the above concept −
mysql> Create table Testing(Id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(20));
Query OK, 0 rows affected (0.15 sec)
mysql> Insert into testing(Name) values('Gaurav'),('Rahul'),('Aarav'),('Yashraj'),('Manak');
Query OK, 5 rows affected (0.09 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> Select * from testing;
+----+---------+
| Id | Name |
+----+---------+
| 1 | Gaurav |
| 2 | Rahul |
| 3 | Aarav |
| 4 | Yashraj |
| 5 | Manak |
+----+---------+
5 rows in set (0.00 sec)
mysql> Delete from testing where id >=4;
Query OK, 2 rows affected (0.04 sec)
mysql> Select * from testing;
+----+--------+
| Id | Name |
+----+--------+
| 1 | Gaurav |
| 2 | Rahul |
| 3 | Aarav |
+----+--------+
3 rows in set (0.00 sec)
mysql> Insert into testing(Name) values('Harshit'),('Lovkesh');
Query OK, 2 rows affected (0.06 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> Select * from testing;
+----+---------+
| Id | Name |
+----+---------+
| 1 | Gaurav |
| 2 | Rahul |
| 3 | Aarav |
| 6 | Harshit |
| 7 | Lovkesh |
+----+---------+
5 rows in set (0.00 sec)
mysql> Truncate table testing;
Query OK, 0 rows affected (0.10 sec)
mysql> Insert into testing(Name) values('Harshit'),('Lovkesh'),('Ram'),('Gaurav');
Query OK, 4 rows affected (0.11 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> Select * from testing;
+----+---------+
| Id | Name |
+----+---------+
| 1 | Harshit |
| 2 | Lovkesh |
| 3 | Ram |
| 4 | Gaurav |
+----+---------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1377,
"s": 1062,
"text": "As we know that TRUNCATE will remove all the rows without removing table’s structure from the database. Same work can be done with the help of DELETE command on removing all the rows from the table. But there is a significant difference of re-initialization of PRIMARY KEY AUTO_INCREMENT between both the commands."
},
{
"code": null,
"e": 1835,
"s": 1377,
"text": "Suppose a column is defined AUTO_INCREMENT having PRIMARY KEY CONSTRAINT, then on deleting all the rows with DELETE command would not re-initialize the table i.e. on entering the new rows, the AUTO_INCREMENT number will start after the last inserted row. In contrast, on using TRUNCATE, the table will be re-initializing like a newly created table. It means after using TRUNCATE command and on inserting new rows the AUTO_INCREMENT number will start from 1."
},
{
"code": null,
"e": 1890,
"s": 1835,
"text": "Following example will demonstrate the above concept −"
},
{
"code": null,
"e": 3417,
"s": 1890,
"text": "mysql> Create table Testing(Id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(20));\nQuery OK, 0 rows affected (0.15 sec)\n\nmysql> Insert into testing(Name) values('Gaurav'),('Rahul'),('Aarav'),('Yashraj'),('Manak');\nQuery OK, 5 rows affected (0.09 sec)\nRecords: 5 Duplicates: 0 Warnings: 0\n\nmysql> Select * from testing;\n\n+----+---------+\n| Id | Name |\n+----+---------+\n| 1 | Gaurav |\n| 2 | Rahul |\n| 3 | Aarav |\n| 4 | Yashraj |\n| 5 | Manak |\n+----+---------+\n\n5 rows in set (0.00 sec)\n\nmysql> Delete from testing where id >=4;\nQuery OK, 2 rows affected (0.04 sec)\n\nmysql> Select * from testing;\n\n+----+--------+\n| Id | Name |\n+----+--------+\n| 1 | Gaurav |\n| 2 | Rahul |\n| 3 | Aarav |\n+----+--------+\n\n3 rows in set (0.00 sec)\n\nmysql> Insert into testing(Name) values('Harshit'),('Lovkesh');\nQuery OK, 2 rows affected (0.06 sec)\nRecords: 2 Duplicates: 0 Warnings: 0\n\nmysql> Select * from testing;\n\n+----+---------+\n| Id | Name |\n+----+---------+\n| 1 | Gaurav |\n| 2 | Rahul |\n| 3 | Aarav |\n| 6 | Harshit |\n| 7 | Lovkesh |\n+----+---------+\n\n5 rows in set (0.00 sec)\n\nmysql> Truncate table testing;\nQuery OK, 0 rows affected (0.10 sec)\n\nmysql> Insert into testing(Name) values('Harshit'),('Lovkesh'),('Ram'),('Gaurav');\nQuery OK, 4 rows affected (0.11 sec)\nRecords: 4 Duplicates: 0 Warnings: 0\n\nmysql> Select * from testing;\n\n+----+---------+\n| Id | Name |\n+----+---------+\n| 1 | Harshit |\n| 2 | Lovkesh |\n| 3 | Ram |\n| 4 | Gaurav |\n+----+---------+\n\n4 rows in set (0.00 sec)"
}
] |
How to animate Scatterplots on Mapbox using Plotly Express? | by Usama Bin Tariq | Towards Data Science | Plotly Express is a data visualization library that allows us to visualize small bits of data quickly and efficiently. In this tutorial, we will be learning how to make animations using Plotly express’s built-in scatter Mapbox functionality.
The Scatter Mapbox requires the following arguments:
df, which is your Panda’s data frame.lat is the name of the column containing latitude coordinates.lon is the name of a column containing longitude coordinates.color is the name of the column for coloring individual scatters.size is the name of the column determining the size of the individual scatter.
df, which is your Panda’s data frame.
lat is the name of the column containing latitude coordinates.
lon is the name of a column containing longitude coordinates.
color is the name of the column for coloring individual scatters.
size is the name of the column determining the size of the individual scatter.
Though the above-mentioned arguments are basics and we can create a scatter plot through them, this is not all. Plotly Express Scatter Mapbox function offers a ton of functionalities and can be found at its documentation here.
With these understood we can now create a simple scatter plot on Mapbox which can be converted into an animation later on. But before this, we have to take a look and understand our dataset.
For this example, we will be using COVID-19 Dataset, that can be found here. It is further processed. For more information on the preprocessing of data, please check it here.
As shown in the dataset below, we have the first column that shows the name of the country, the next two columns show the latitude and longitude coordinates of the country. The Continent column shows the continent of the respective country. The date column shows the date when data for the country was last updated. The confirmed column represents confirmed COVID cases, deaths represent the number of people who have died due to COVID, and the Recovery column represents the number of people who are cured of the virus.
All the data shown for a specific country represents total accumulative numbers since the first case was recorded and not daily increase.
With the dataset understood, its time to create a scatter plot now. We will be creating a scatter plot for Confirmed COVID cases and plotting it on the Mapbox. Let’s see how we can do it.
Now since we are to visualize confirmed cases, the “confirmed” column would be forwarded to size and color arguments. Please take a look at the code below:
# Necessary Importingimport pandas as pdimport plotly.express as px#Importing dataset as pandas dataframedatasets = pd.read_csv('covid-dataset.csv')# Creating and visualizing a scatter plot on Mapboxfig = px.scatter_mapbox(datasets, lat="Lat", lon="Long", color="Confirmed", size="Confirmed", color_continuous_scale=px.colors.cyclical.IceFire, size_max=70, zoom=0.75, hover_name='Country', hover_data = ['Confirmed', 'Deaths', 'Recovery'], title = 'Accumulative COVID-19 Confirmed Cases till 17 June, 2020')fig.show()
As we can see from the code above, there are few unknown arguments here. Let’s break it one by one.
“datasets” is just the name of the panda’s data frame passed into the function.“lat” and “long” are names on columns inside a data frame with latitude and longitude coordinates.Since we are interested in visualizing confirmed cases, we have forwarded the “confirmed” column to size and color arguments.“color_continuous_scale” is asking for the color scheme we would be using for visualizing our data. There are few options available, please refer to the documentation link above.“size_max” is asking for the maximum size of the bubble plotted on the map. While “zoom” is the default zoom value to visualize your map. Feel free to play with both of these values and optimize as you like.“hover_name” and “hover_data” are asking for columns to be displayed when a cursor hovers over a specific bubble on the map.“title” as the name implies assigns the title of the map.
“datasets” is just the name of the panda’s data frame passed into the function.
“lat” and “long” are names on columns inside a data frame with latitude and longitude coordinates.
Since we are interested in visualizing confirmed cases, we have forwarded the “confirmed” column to size and color arguments.
“color_continuous_scale” is asking for the color scheme we would be using for visualizing our data. There are few options available, please refer to the documentation link above.
“size_max” is asking for the maximum size of the bubble plotted on the map. While “zoom” is the default zoom value to visualize your map. Feel free to play with both of these values and optimize as you like.
“hover_name” and “hover_data” are asking for columns to be displayed when a cursor hovers over a specific bubble on the map.
“title” as the name implies assigns the title of the map.
With this now understood, let’s visualize the output of the code snippet above.
Wow, that looks great. You can generate similar maps for deaths and recovery columns as well. Try it for yourself.
With that done, the next task is to animate the “date” column in the data frame and see how confirmed cases buildup since the outbreak of the virus in January.
The data set used previously was sliced to visualize data at the maximum recorded date, which was 17th June 2020. To create an animation we need to remove the slicer and understand our dataset once again. Let’s take a look.
The dataset contains recorded confirmed cases, deaths, and recovery from Coronavirus from 22nd January 2020 to 17th June 2020. All the rest columns in the database are the same as explained previously.
Now, we need to animate date on a Scatter Mapbox plot and visualize how COVID19 confirmed cases have spread around the world. To this, we need to give a few extra arguments to the scatter_mapbox function.
fig = px.scatter_mapbox(datas, lat="Lat", lon="Long", animation_frame = 'Date', animation_group = 'Country', color="Confirmed", size="Confirmed", color_continuous_scale=px.colors.cyclical.IceFire, size_max=70, zoom=0.75, hover_name='Country', hover_data = ['Confirmed', 'Deaths', 'Recovery'], title = 'Visualizing spread of COVID from 22/1/2020 to 17/6/2020')fig.show()
As evident from the code above, two additional arguments are given to the scatter_mapbox function to create an animation. These arguments are “animation_frame” and “animation_group”. “animation_frame” asks for a column containing time-series information that is to be animated. With this being done, we have finally generated the animation below:
That’s it for this tutorial, please take a look at GitHub for this project, here. | [
{
"code": null,
"e": 414,
"s": 172,
"text": "Plotly Express is a data visualization library that allows us to visualize small bits of data quickly and efficiently. In this tutorial, we will be learning how to make animations using Plotly express’s built-in scatter Mapbox functionality."
},
{
"code": null,
"e": 467,
"s": 414,
"text": "The Scatter Mapbox requires the following arguments:"
},
{
"code": null,
"e": 771,
"s": 467,
"text": "df, which is your Panda’s data frame.lat is the name of the column containing latitude coordinates.lon is the name of a column containing longitude coordinates.color is the name of the column for coloring individual scatters.size is the name of the column determining the size of the individual scatter."
},
{
"code": null,
"e": 809,
"s": 771,
"text": "df, which is your Panda’s data frame."
},
{
"code": null,
"e": 872,
"s": 809,
"text": "lat is the name of the column containing latitude coordinates."
},
{
"code": null,
"e": 934,
"s": 872,
"text": "lon is the name of a column containing longitude coordinates."
},
{
"code": null,
"e": 1000,
"s": 934,
"text": "color is the name of the column for coloring individual scatters."
},
{
"code": null,
"e": 1079,
"s": 1000,
"text": "size is the name of the column determining the size of the individual scatter."
},
{
"code": null,
"e": 1306,
"s": 1079,
"text": "Though the above-mentioned arguments are basics and we can create a scatter plot through them, this is not all. Plotly Express Scatter Mapbox function offers a ton of functionalities and can be found at its documentation here."
},
{
"code": null,
"e": 1497,
"s": 1306,
"text": "With these understood we can now create a simple scatter plot on Mapbox which can be converted into an animation later on. But before this, we have to take a look and understand our dataset."
},
{
"code": null,
"e": 1672,
"s": 1497,
"text": "For this example, we will be using COVID-19 Dataset, that can be found here. It is further processed. For more information on the preprocessing of data, please check it here."
},
{
"code": null,
"e": 2193,
"s": 1672,
"text": "As shown in the dataset below, we have the first column that shows the name of the country, the next two columns show the latitude and longitude coordinates of the country. The Continent column shows the continent of the respective country. The date column shows the date when data for the country was last updated. The confirmed column represents confirmed COVID cases, deaths represent the number of people who have died due to COVID, and the Recovery column represents the number of people who are cured of the virus."
},
{
"code": null,
"e": 2331,
"s": 2193,
"text": "All the data shown for a specific country represents total accumulative numbers since the first case was recorded and not daily increase."
},
{
"code": null,
"e": 2519,
"s": 2331,
"text": "With the dataset understood, its time to create a scatter plot now. We will be creating a scatter plot for Confirmed COVID cases and plotting it on the Mapbox. Let’s see how we can do it."
},
{
"code": null,
"e": 2675,
"s": 2519,
"text": "Now since we are to visualize confirmed cases, the “confirmed” column would be forwarded to size and color arguments. Please take a look at the code below:"
},
{
"code": null,
"e": 3297,
"s": 2675,
"text": "# Necessary Importingimport pandas as pdimport plotly.express as px#Importing dataset as pandas dataframedatasets = pd.read_csv('covid-dataset.csv')# Creating and visualizing a scatter plot on Mapboxfig = px.scatter_mapbox(datasets, lat=\"Lat\", lon=\"Long\", color=\"Confirmed\", size=\"Confirmed\", color_continuous_scale=px.colors.cyclical.IceFire, size_max=70, zoom=0.75, hover_name='Country', hover_data = ['Confirmed', 'Deaths', 'Recovery'], title = 'Accumulative COVID-19 Confirmed Cases till 17 June, 2020')fig.show()"
},
{
"code": null,
"e": 3397,
"s": 3297,
"text": "As we can see from the code above, there are few unknown arguments here. Let’s break it one by one."
},
{
"code": null,
"e": 4266,
"s": 3397,
"text": "“datasets” is just the name of the panda’s data frame passed into the function.“lat” and “long” are names on columns inside a data frame with latitude and longitude coordinates.Since we are interested in visualizing confirmed cases, we have forwarded the “confirmed” column to size and color arguments.“color_continuous_scale” is asking for the color scheme we would be using for visualizing our data. There are few options available, please refer to the documentation link above.“size_max” is asking for the maximum size of the bubble plotted on the map. While “zoom” is the default zoom value to visualize your map. Feel free to play with both of these values and optimize as you like.“hover_name” and “hover_data” are asking for columns to be displayed when a cursor hovers over a specific bubble on the map.“title” as the name implies assigns the title of the map."
},
{
"code": null,
"e": 4346,
"s": 4266,
"text": "“datasets” is just the name of the panda’s data frame passed into the function."
},
{
"code": null,
"e": 4445,
"s": 4346,
"text": "“lat” and “long” are names on columns inside a data frame with latitude and longitude coordinates."
},
{
"code": null,
"e": 4571,
"s": 4445,
"text": "Since we are interested in visualizing confirmed cases, we have forwarded the “confirmed” column to size and color arguments."
},
{
"code": null,
"e": 4750,
"s": 4571,
"text": "“color_continuous_scale” is asking for the color scheme we would be using for visualizing our data. There are few options available, please refer to the documentation link above."
},
{
"code": null,
"e": 4958,
"s": 4750,
"text": "“size_max” is asking for the maximum size of the bubble plotted on the map. While “zoom” is the default zoom value to visualize your map. Feel free to play with both of these values and optimize as you like."
},
{
"code": null,
"e": 5083,
"s": 4958,
"text": "“hover_name” and “hover_data” are asking for columns to be displayed when a cursor hovers over a specific bubble on the map."
},
{
"code": null,
"e": 5141,
"s": 5083,
"text": "“title” as the name implies assigns the title of the map."
},
{
"code": null,
"e": 5221,
"s": 5141,
"text": "With this now understood, let’s visualize the output of the code snippet above."
},
{
"code": null,
"e": 5336,
"s": 5221,
"text": "Wow, that looks great. You can generate similar maps for deaths and recovery columns as well. Try it for yourself."
},
{
"code": null,
"e": 5496,
"s": 5336,
"text": "With that done, the next task is to animate the “date” column in the data frame and see how confirmed cases buildup since the outbreak of the virus in January."
},
{
"code": null,
"e": 5720,
"s": 5496,
"text": "The data set used previously was sliced to visualize data at the maximum recorded date, which was 17th June 2020. To create an animation we need to remove the slicer and understand our dataset once again. Let’s take a look."
},
{
"code": null,
"e": 5922,
"s": 5720,
"text": "The dataset contains recorded confirmed cases, deaths, and recovery from Coronavirus from 22nd January 2020 to 17th June 2020. All the rest columns in the database are the same as explained previously."
},
{
"code": null,
"e": 6127,
"s": 5922,
"text": "Now, we need to animate date on a Scatter Mapbox plot and visualize how COVID19 confirmed cases have spread around the world. To this, we need to give a few extra arguments to the scatter_mapbox function."
},
{
"code": null,
"e": 6578,
"s": 6127,
"text": "fig = px.scatter_mapbox(datas, lat=\"Lat\", lon=\"Long\", animation_frame = 'Date', animation_group = 'Country', color=\"Confirmed\", size=\"Confirmed\", color_continuous_scale=px.colors.cyclical.IceFire, size_max=70, zoom=0.75, hover_name='Country', hover_data = ['Confirmed', 'Deaths', 'Recovery'], title = 'Visualizing spread of COVID from 22/1/2020 to 17/6/2020')fig.show()"
},
{
"code": null,
"e": 6925,
"s": 6578,
"text": "As evident from the code above, two additional arguments are given to the scatter_mapbox function to create an animation. These arguments are “animation_frame” and “animation_group”. “animation_frame” asks for a column containing time-series information that is to be animated. With this being done, we have finally generated the animation below:"
}
] |
Python | Linear Regression using sklearn - GeeksforGeeks | 28 Nov, 2019
Prerequisite: Linear Regression
Linear Regression is a machine learning algorithm based on supervised learning. It performs a regression task. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on – the kind of relationship between dependent and independent variables, they are considering and the number of independent variables being used.
This article is going to demonstrate how to use the various Python libraries to implement linear regression on a given dataset. We will demonstrate a binary linear model as this will be easier to visualize.
In this demonstration, the model will use Gradient Descent to learn. You can learn about it here.
Step 1: Importing all the required libraries
import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltfrom sklearn import preprocessing, svmfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegression
Step 2: Reading the dataset
You can download the dataset here.
cd C:\Users\Dev\Desktop\Kaggle\Salinity # Changing the file read location to the location of the datasetdf = pd.read_csv('bottle.csv')df_binary = df[['Salnty', 'T_degC']] # Taking only the selected two attributes from the datasetdf_binary.columns = ['Sal', 'Temp'] # Renaming the columns for easier writing of the codedf_binary.head() # Displaying only the 1st rows along with the column names
Step 3: Exploring the data scatter
sns.lmplot(x ="Sal", y ="Temp", data = df_binary, order = 2, ci = None) # Plotting the data scatter
Step 4: Data cleaning
# Eliminating NaN or missing input numbersdf_binary.fillna(method ='ffill', inplace = True)
Step 5: Training our model
X = np.array(df_binary['Sal']).reshape(-1, 1)y = np.array(df_binary['Temp']).reshape(-1, 1) # Separating the data into independent and dependent variables# Converting each dataframe into a numpy array # since each dataframe contains only one columndf_binary.dropna(inplace = True) # Dropping any rows with Nan valuesX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25) # Splitting the data into training and testing dataregr = LinearRegression() regr.fit(X_train, y_train)print(regr.score(X_test, y_test))
Step 6: Exploring our results
y_pred = regr.predict(X_test)plt.scatter(X_test, y_test, color ='b')plt.plot(X_test, y_pred, color ='k') plt.show()# Data scatter of predicted values
The low accuracy score of our model suggests that our regressive model has not fitted very well to the existing data. This suggests that our data is not suitable for linear regression. But sometimes, a dataset may accept a linear regressor if we consider only a part of it. Let us check for that possibility. Step 7: Working with a smaller dataset
df_binary500 = df_binary[:][:500] # Selecting the 1st 500 rows of the datasns.lmplot(x ="Sal", y ="Temp", data = df_binary500, order = 2, ci = None)
We can already see that the first 500 rows follow a linear model. Continuing with the same steps as before.
df_binary500.fillna(method ='ffill', inplace = True) X = np.array(df_binary500['Sal']).reshape(-1, 1)y = np.array(df_binary500['Temp']).reshape(-1, 1) df_binary500.dropna(inplace = True)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25) regr = LinearRegression()regr.fit(X_train, y_train)print(regr.score(X_test, y_test))
y_pred = regr.predict(X_test)plt.scatter(X_test, y_test, color ='b')plt.plot(X_test, y_pred, color ='k') plt.show()
shubham_singh
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python | Decision tree implementation
ML | Underfitting and Overfitting
Support Vector Machine Algorithm
Elbow Method for optimal value of k in KMeans
ML | Label Encoding of datasets in Python
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": 24520,
"s": 24492,
"text": "\n28 Nov, 2019"
},
{
"code": null,
"e": 24552,
"s": 24520,
"text": "Prerequisite: Linear Regression"
},
{
"code": null,
"e": 25014,
"s": 24552,
"text": "Linear Regression is a machine learning algorithm based on supervised learning. It performs a regression task. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on – the kind of relationship between dependent and independent variables, they are considering and the number of independent variables being used."
},
{
"code": null,
"e": 25221,
"s": 25014,
"text": "This article is going to demonstrate how to use the various Python libraries to implement linear regression on a given dataset. We will demonstrate a binary linear model as this will be easier to visualize."
},
{
"code": null,
"e": 25319,
"s": 25221,
"text": "In this demonstration, the model will use Gradient Descent to learn. You can learn about it here."
},
{
"code": null,
"e": 25364,
"s": 25319,
"text": "Step 1: Importing all the required libraries"
},
{
"code": "import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltfrom sklearn import preprocessing, svmfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegression",
"e": 25593,
"s": 25364,
"text": null
},
{
"code": null,
"e": 25623,
"s": 25595,
"text": "Step 2: Reading the dataset"
},
{
"code": null,
"e": 25658,
"s": 25623,
"text": "You can download the dataset here."
},
{
"code": "cd C:\\Users\\Dev\\Desktop\\Kaggle\\Salinity # Changing the file read location to the location of the datasetdf = pd.read_csv('bottle.csv')df_binary = df[['Salnty', 'T_degC']] # Taking only the selected two attributes from the datasetdf_binary.columns = ['Sal', 'Temp'] # Renaming the columns for easier writing of the codedf_binary.head() # Displaying only the 1st rows along with the column names",
"e": 26057,
"s": 25658,
"text": null
},
{
"code": null,
"e": 26093,
"s": 26057,
"text": " Step 3: Exploring the data scatter"
},
{
"code": "sns.lmplot(x =\"Sal\", y =\"Temp\", data = df_binary, order = 2, ci = None) # Plotting the data scatter",
"e": 26194,
"s": 26093,
"text": null
},
{
"code": null,
"e": 26217,
"s": 26194,
"text": " Step 4: Data cleaning"
},
{
"code": "# Eliminating NaN or missing input numbersdf_binary.fillna(method ='ffill', inplace = True)",
"e": 26309,
"s": 26217,
"text": null
},
{
"code": null,
"e": 26337,
"s": 26309,
"text": " Step 5: Training our model"
},
{
"code": "X = np.array(df_binary['Sal']).reshape(-1, 1)y = np.array(df_binary['Temp']).reshape(-1, 1) # Separating the data into independent and dependent variables# Converting each dataframe into a numpy array # since each dataframe contains only one columndf_binary.dropna(inplace = True) # Dropping any rows with Nan valuesX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25) # Splitting the data into training and testing dataregr = LinearRegression() regr.fit(X_train, y_train)print(regr.score(X_test, y_test))",
"e": 26870,
"s": 26337,
"text": null
},
{
"code": null,
"e": 26901,
"s": 26870,
"text": " Step 6: Exploring our results"
},
{
"code": "y_pred = regr.predict(X_test)plt.scatter(X_test, y_test, color ='b')plt.plot(X_test, y_pred, color ='k') plt.show()# Data scatter of predicted values",
"e": 27052,
"s": 26901,
"text": null
},
{
"code": null,
"e": 27400,
"s": 27052,
"text": "The low accuracy score of our model suggests that our regressive model has not fitted very well to the existing data. This suggests that our data is not suitable for linear regression. But sometimes, a dataset may accept a linear regressor if we consider only a part of it. Let us check for that possibility. Step 7: Working with a smaller dataset"
},
{
"code": "df_binary500 = df_binary[:][:500] # Selecting the 1st 500 rows of the datasns.lmplot(x =\"Sal\", y =\"Temp\", data = df_binary500, order = 2, ci = None)",
"e": 27580,
"s": 27400,
"text": null
},
{
"code": null,
"e": 27688,
"s": 27580,
"text": "We can already see that the first 500 rows follow a linear model. Continuing with the same steps as before."
},
{
"code": "df_binary500.fillna(method ='ffill', inplace = True) X = np.array(df_binary500['Sal']).reshape(-1, 1)y = np.array(df_binary500['Temp']).reshape(-1, 1) df_binary500.dropna(inplace = True)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25) regr = LinearRegression()regr.fit(X_train, y_train)print(regr.score(X_test, y_test))",
"e": 28038,
"s": 27688,
"text": null
},
{
"code": "y_pred = regr.predict(X_test)plt.scatter(X_test, y_test, color ='b')plt.plot(X_test, y_pred, color ='k') plt.show()",
"e": 28155,
"s": 28038,
"text": null
},
{
"code": null,
"e": 28169,
"s": 28155,
"text": "shubham_singh"
},
{
"code": null,
"e": 28186,
"s": 28169,
"text": "Machine Learning"
},
{
"code": null,
"e": 28193,
"s": 28186,
"text": "Python"
},
{
"code": null,
"e": 28210,
"s": 28193,
"text": "Machine Learning"
},
{
"code": null,
"e": 28308,
"s": 28210,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28317,
"s": 28308,
"text": "Comments"
},
{
"code": null,
"e": 28330,
"s": 28317,
"text": "Old Comments"
},
{
"code": null,
"e": 28368,
"s": 28330,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 28402,
"s": 28368,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 28435,
"s": 28402,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 28481,
"s": 28435,
"text": "Elbow Method for optimal value of k in KMeans"
},
{
"code": null,
"e": 28523,
"s": 28481,
"text": "ML | Label Encoding of datasets in Python"
},
{
"code": null,
"e": 28551,
"s": 28523,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28601,
"s": 28551,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28623,
"s": 28601,
"text": "Python map() function"
}
] |
What is Bitwise XOR Assignment Operator (^=) in JavaScript? | It performs XOR operation on the right operand with the left operand and assigns the result to the left operand.
You can try to run the following code to learn how to work with Bitwise XOR Assignment Operator
Live Demo
<html>
<body>
<script>
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
document.write("(a ^= b) => ");
document.write(a ^= b);
</script>
</body>
</html> | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "It performs XOR operation on the right operand with the left operand and assigns the result to the left operand."
},
{
"code": null,
"e": 1271,
"s": 1175,
"text": "You can try to run the following code to learn how to work with Bitwise XOR Assignment Operator"
},
{
"code": null,
"e": 1281,
"s": 1271,
"text": "Live Demo"
},
{
"code": null,
"e": 1512,
"s": 1281,
"text": "<html>\n <body>\n <script>\n var a = 2; // Bit presentation 10\n var b = 3; // Bit presentation 11\n document.write(\"(a ^= b) => \");\n document.write(a ^= b);\n </script>\n </body>\n</html>"
}
] |
bitset none() in C++ STL - GeeksforGeeks | 12 Nov, 2020
bitset::none() is a built-in STL in C++ which returns True if none of its bits are set. It returns False if a minimum of one bit is set.
Syntax:
bool none()
Parameter: The function accepts no parameter.
Return Value: The function returns a boolean. The boolean value is True if none of its bits are set. It is False if at least one bit is set.
Below programs illustrates the bitset::none() function.
Program 1:
C++
// C++ program to illustrate the// bitset::none() function#include <bits/stdc++.h>using namespace std; int main(){ // initialization of bitset bitset<4> b1(string("1100")); bitset<6> b2(string("000000")); // Function to check if none of // the bits are set or not in b1 bool result1 = b1.none(); if (result1) cout << b1 << " has no bits set" << endl; else cout << b1 << " has a minimum of one bit set" << endl; // Function to check if none of // the bits are set or not in b1 bool result2 = b2.none(); if (result2) cout << b2 << " has no bits set" << endl; else cout << b2 << " has a minimum of one bit set" << endl; return 0;}
1100 has a minimum of one bit set
000000 has no bits set
Program 2:
C++
// C++ program to illustrate the// bitset::none() function// when the input is a number#include <bits/stdc++.h>using namespace std; int main(){ // initialization of bitset bitset<3> b1(4); bitset<6> b2(0); // Function to check if none of // the bits are set or not in b1 bool result1 = b1.none(); if (result1) cout << b1 << " has no bits set" << endl; else cout << b1 << " has a minimum of one bit set" << endl; // Function to check if none of // the bits are set or not in b1 bool result2 = b2.none(); if (result2) cout << b2 << " has no bits set" << endl; else cout << b2 << " has a minimum of one bit set" << endl; return 0;}
100 has a minimum of one bit set
000000 has no bits set
arorakashish0911
CPP-bitset
CPP-Functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Friend class and function in C++
Polymorphism in C++
List in C++ Standard Template Library (STL)
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
new and delete operators in C++ for dynamic memory
Destructors in C++
Queue in C++ Standard Template Library (STL) | [
{
"code": null,
"e": 23707,
"s": 23679,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 23845,
"s": 23707,
"text": "bitset::none() is a built-in STL in C++ which returns True if none of its bits are set. It returns False if a minimum of one bit is set. "
},
{
"code": null,
"e": 23855,
"s": 23845,
"text": "Syntax: "
},
{
"code": null,
"e": 23869,
"s": 23855,
"text": "bool none() \n"
},
{
"code": null,
"e": 23916,
"s": 23869,
"text": "Parameter: The function accepts no parameter. "
},
{
"code": null,
"e": 24058,
"s": 23916,
"text": "Return Value: The function returns a boolean. The boolean value is True if none of its bits are set. It is False if at least one bit is set. "
},
{
"code": null,
"e": 24115,
"s": 24058,
"text": "Below programs illustrates the bitset::none() function. "
},
{
"code": null,
"e": 24128,
"s": 24115,
"text": "Program 1: "
},
{
"code": null,
"e": 24132,
"s": 24128,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// bitset::none() function#include <bits/stdc++.h>using namespace std; int main(){ // initialization of bitset bitset<4> b1(string(\"1100\")); bitset<6> b2(string(\"000000\")); // Function to check if none of // the bits are set or not in b1 bool result1 = b1.none(); if (result1) cout << b1 << \" has no bits set\" << endl; else cout << b1 << \" has a minimum of one bit set\" << endl; // Function to check if none of // the bits are set or not in b1 bool result2 = b2.none(); if (result2) cout << b2 << \" has no bits set\" << endl; else cout << b2 << \" has a minimum of one bit set\" << endl; return 0;}",
"e": 24882,
"s": 24132,
"text": null
},
{
"code": null,
"e": 24944,
"s": 24882,
"text": "1100 has a minimum of one bit set\n000000 has no bits set\n\n\n\n\n"
},
{
"code": null,
"e": 24959,
"s": 24946,
"text": "Program 2: "
},
{
"code": null,
"e": 24963,
"s": 24959,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// bitset::none() function// when the input is a number#include <bits/stdc++.h>using namespace std; int main(){ // initialization of bitset bitset<3> b1(4); bitset<6> b2(0); // Function to check if none of // the bits are set or not in b1 bool result1 = b1.none(); if (result1) cout << b1 << \" has no bits set\" << endl; else cout << b1 << \" has a minimum of one bit set\" << endl; // Function to check if none of // the bits are set or not in b1 bool result2 = b2.none(); if (result2) cout << b2 << \" has no bits set\" << endl; else cout << b2 << \" has a minimum of one bit set\" << endl; return 0;}",
"e": 25713,
"s": 24963,
"text": null
},
{
"code": null,
"e": 25774,
"s": 25713,
"text": "100 has a minimum of one bit set\n000000 has no bits set\n\n\n\n\n"
},
{
"code": null,
"e": 25793,
"s": 25776,
"text": "arorakashish0911"
},
{
"code": null,
"e": 25804,
"s": 25793,
"text": "CPP-bitset"
},
{
"code": null,
"e": 25818,
"s": 25804,
"text": "CPP-Functions"
},
{
"code": null,
"e": 25822,
"s": 25818,
"text": "STL"
},
{
"code": null,
"e": 25826,
"s": 25822,
"text": "C++"
},
{
"code": null,
"e": 25830,
"s": 25826,
"text": "STL"
},
{
"code": null,
"e": 25834,
"s": 25830,
"text": "CPP"
},
{
"code": null,
"e": 25932,
"s": 25834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25941,
"s": 25932,
"text": "Comments"
},
{
"code": null,
"e": 25954,
"s": 25941,
"text": "Old Comments"
},
{
"code": null,
"e": 25982,
"s": 25954,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26006,
"s": 25982,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 26039,
"s": 26006,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 26059,
"s": 26039,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 26103,
"s": 26059,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26147,
"s": 26103,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26183,
"s": 26147,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 26234,
"s": 26183,
"text": "new and delete operators in C++ for dynamic memory"
},
{
"code": null,
"e": 26253,
"s": 26234,
"text": "Destructors in C++"
}
] |
How to change status bar color to match app Android using Kotlin? | This example demonstrates how to change status bar color to match app Android 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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Check the Color of the Status Bar"
android:textAlignment="center"
android:textColor="@color/colorAccent"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.view.Window
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val window: Window = [email protected]
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.statusBarColor = ContextCompat.getColor(this@MainActivity, R.color.colorAccent)
}
}
Step 4 − 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="com.example.q11">
<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" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</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": 1154,
"s": 1062,
"text": "This example demonstrates how to change status bar color to match app Android using Kotlin."
},
{
"code": null,
"e": 1282,
"s": 1154,
"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": 1347,
"s": 1282,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2303,
"s": 1347,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Check the Color of the Status Bar\"\n android:textAlignment=\"center\"\n android:textColor=\"@color/colorAccent\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2358,
"s": 2303,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3058,
"s": 2358,
"text": "import android.os.Bundle\nimport android.view.Window\nimport android.view.WindowManager\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.core.content.ContextCompat\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val window: Window = [email protected]\n window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)\n window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)\n window.statusBarColor = ContextCompat.getColor(this@MainActivity, R.color.colorAccent)\n }\n}"
},
{
"code": null,
"e": 3113,
"s": 3058,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3784,
"s": 3113,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\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\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4132,
"s": 3784,
"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": 4173,
"s": 4132,
"text": "Click here to download the project code."
}
] |
Entity Framework - Spatial Data Type | Spatial type support was introduced in Entity Framework 5. A set of operators is also included to allow queries to analyze spatial data. For example, a query can filter based on the distance between two geographic locations.
Entity Framework will allow new spatial data types to be exposed as properties on your classes and map them to spatial columns in your database.
Entity Framework will allow new spatial data types to be exposed as properties on your classes and map them to spatial columns in your database.
You will also be able to write LINQ queries that make use of the spatial operators to filter, sort, and group based on spatial calculations performed in the database.
You will also be able to write LINQ queries that make use of the spatial operators to filter, sort, and group based on spatial calculations performed in the database.
There are two main spatial data types −
The geography data type stores ellipsoidal data, for example, GPS latitude and longitude coordinates.
The geography data type stores ellipsoidal data, for example, GPS latitude and longitude coordinates.
The geometry data type represents Euclidean (flat) coordinate system.
The geometry data type represents Euclidean (flat) coordinate system.
Let’s take a look into the following example of Cricket ground.
Step 1 − Create new project from File → New → Project menu option.
Step 2 − In the left pane, select the Console Application.
Step 3 − Right-click on project name and select Manage NuGet Packages...
Step 4 − Install Entity Framework.
Step 5 − Add reference to System.Data.Entity assembly and also add the System.Data.Spatial using statement for spatial data types.
Step 6 − Add the following class in Program.cs file.
public class CricketGround {
public int ID { get; set; }
public string Name { get; set; }
public DbGeography Location { get; set; }
}
Step 7 − In addition to defining entities, you need to define a class that derives from DbContext and exposes DbSet<TEntity> properties.
In the Program.cs add the context definition.
public partial class CricketGroundContext : DbContext {
public DbSet<CricketGround> CricketGrounds { get; set; }
}
Step 8 − Add the following code into the Main function, which will add two new CricketGround objects to the context.
class Program {
static void Main(string[] args) {
using (var context = new CricketGroundContext()) {
context.CricketGrounds.Add(new CricketGround() {
Name = "Shalimar Cricket Ground",
Location = DbGeography.FromText("POINT(-122.336106 47.605049)"),
});
context.CricketGrounds.Add(new CricketGround() {
Name = "Marghazar Stadium", Location = DbGeography
.FromText("POINT(-122.335197 47.646711)"),
});
context.SaveChanges();
var myLocation = DbGeography.FromText("POINT(-122.296623 47.640405)");
var cricketGround = (from cg in context.CricketGrounds
orderby cg.Location.Distance(myLocation) select cg).FirstOrDefault();
Console.WriteLine("The closest Cricket Ground to you is: {0}.", cricketGround.Name);
}
}
}
Spatial properties are initialized by using the DbGeography.FromText method. The geography point represented as WellKnownText is passed to the method and then saves the data. After that CricketGround object will be retrieved where its location is closest to the specified location.
When the above code is executed, you will receive the following output −
The closest Cricket Ground to you is: Marghazar Stadium
We recommend that you execute the above example in a step-by-step manner for better understanding.
19 Lectures
5 hours
Trevoir Williams
33 Lectures
3.5 hours
Nilay Mehta
21 Lectures
2.5 hours
TELCOMA Global
89 Lectures
7.5 hours
Mustafa Radaideh
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3257,
"s": 3032,
"text": "Spatial type support was introduced in Entity Framework 5. A set of operators is also included to allow queries to analyze spatial data. For example, a query can filter based on the distance between two geographic locations."
},
{
"code": null,
"e": 3402,
"s": 3257,
"text": "Entity Framework will allow new spatial data types to be exposed as properties on your classes and map them to spatial columns in your database."
},
{
"code": null,
"e": 3547,
"s": 3402,
"text": "Entity Framework will allow new spatial data types to be exposed as properties on your classes and map them to spatial columns in your database."
},
{
"code": null,
"e": 3714,
"s": 3547,
"text": "You will also be able to write LINQ queries that make use of the spatial operators to filter, sort, and group based on spatial calculations performed in the database."
},
{
"code": null,
"e": 3881,
"s": 3714,
"text": "You will also be able to write LINQ queries that make use of the spatial operators to filter, sort, and group based on spatial calculations performed in the database."
},
{
"code": null,
"e": 3921,
"s": 3881,
"text": "There are two main spatial data types −"
},
{
"code": null,
"e": 4023,
"s": 3921,
"text": "The geography data type stores ellipsoidal data, for example, GPS latitude and longitude coordinates."
},
{
"code": null,
"e": 4125,
"s": 4023,
"text": "The geography data type stores ellipsoidal data, for example, GPS latitude and longitude coordinates."
},
{
"code": null,
"e": 4195,
"s": 4125,
"text": "The geometry data type represents Euclidean (flat) coordinate system."
},
{
"code": null,
"e": 4265,
"s": 4195,
"text": "The geometry data type represents Euclidean (flat) coordinate system."
},
{
"code": null,
"e": 4329,
"s": 4265,
"text": "Let’s take a look into the following example of Cricket ground."
},
{
"code": null,
"e": 4396,
"s": 4329,
"text": "Step 1 − Create new project from File → New → Project menu option."
},
{
"code": null,
"e": 4455,
"s": 4396,
"text": "Step 2 − In the left pane, select the Console Application."
},
{
"code": null,
"e": 4528,
"s": 4455,
"text": "Step 3 − Right-click on project name and select Manage NuGet Packages..."
},
{
"code": null,
"e": 4563,
"s": 4528,
"text": "Step 4 − Install Entity Framework."
},
{
"code": null,
"e": 4694,
"s": 4563,
"text": "Step 5 − Add reference to System.Data.Entity assembly and also add the System.Data.Spatial using statement for spatial data types."
},
{
"code": null,
"e": 4747,
"s": 4694,
"text": "Step 6 − Add the following class in Program.cs file."
},
{
"code": null,
"e": 4890,
"s": 4747,
"text": "public class CricketGround {\n public int ID { get; set; }\n public string Name { get; set; }\n public DbGeography Location { get; set; }\n}"
},
{
"code": null,
"e": 5027,
"s": 4890,
"text": "Step 7 − In addition to defining entities, you need to define a class that derives from DbContext and exposes DbSet<TEntity> properties."
},
{
"code": null,
"e": 5073,
"s": 5027,
"text": "In the Program.cs add the context definition."
},
{
"code": null,
"e": 5191,
"s": 5073,
"text": "public partial class CricketGroundContext : DbContext {\n public DbSet<CricketGround> CricketGrounds { get; set; }\n}"
},
{
"code": null,
"e": 5308,
"s": 5191,
"text": "Step 8 − Add the following code into the Main function, which will add two new CricketGround objects to the context."
},
{
"code": null,
"e": 6182,
"s": 5308,
"text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new CricketGroundContext()) {\n\n context.CricketGrounds.Add(new CricketGround() {\n Name = \"Shalimar Cricket Ground\", \n Location = DbGeography.FromText(\"POINT(-122.336106 47.605049)\"), \n });\n\n context.CricketGrounds.Add(new CricketGround() {\n Name = \"Marghazar Stadium\", Location = DbGeography\n .FromText(\"POINT(-122.335197 47.646711)\"), \n });\n\n context.SaveChanges();\n\n var myLocation = DbGeography.FromText(\"POINT(-122.296623 47.640405)\");\n\n var cricketGround = (from cg in context.CricketGrounds\n orderby cg.Location.Distance(myLocation) select cg).FirstOrDefault();\n\n Console.WriteLine(\"The closest Cricket Ground to you is: {0}.\", cricketGround.Name);\n }\n }\n}"
},
{
"code": null,
"e": 6464,
"s": 6182,
"text": "Spatial properties are initialized by using the DbGeography.FromText method. The geography point represented as WellKnownText is passed to the method and then saves the data. After that CricketGround object will be retrieved where its location is closest to the specified location."
},
{
"code": null,
"e": 6537,
"s": 6464,
"text": "When the above code is executed, you will receive the following output −"
},
{
"code": null,
"e": 6594,
"s": 6537,
"text": "The closest Cricket Ground to you is: Marghazar Stadium\n"
},
{
"code": null,
"e": 6693,
"s": 6594,
"text": "We recommend that you execute the above example in a step-by-step manner for better understanding."
},
{
"code": null,
"e": 6726,
"s": 6693,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6744,
"s": 6726,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 6779,
"s": 6744,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6792,
"s": 6779,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 6827,
"s": 6792,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6843,
"s": 6827,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 6878,
"s": 6843,
"text": "\n 89 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6896,
"s": 6878,
"text": " Mustafa Radaideh"
},
{
"code": null,
"e": 6903,
"s": 6896,
"text": " Print"
},
{
"code": null,
"e": 6914,
"s": 6903,
"text": " Add Notes"
}
] |
How to use Bar chart graph in android? | This example demonstrates How to use Bar chart graph in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Open build.gradle(module level) and add library dependency.
apply plugin: 'com.android.application'
android {
packagingOptions {
exclude 'META-INF/proguard/androidx-annotations.pro'
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/ASL2.0'
}
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.myapplication"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Step 3 − Open build.gradle(application level) and add library dependency.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Step 4 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<com.github.mikephil.charting.charts.BarChart
android:id = "@+id/BarChart"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken the Bar Chart view to show a Bar chart
Step 4 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
BarChart barChart;
BarData barData;
BarDataSet barDataSet;
ArrayList barEntries;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
barChart = findViewById(R.id.BarChart);
getEntries();
barDataSet = new BarDataSet(barEntries, "");
barData = new BarData(barDataSet);
barChart.setData(barData);
barDataSet.setColors(ColorTemplate.JOYFUL_COLORS);
barDataSet.setValueTextColor(Color.BLACK);
barDataSet.setValueTextSize(18f);
}
private void getEntries() {
barEntries = new ArrayList<>();
barEntries.add(new BarEntry(2f, 0));
barEntries.add(new BarEntry(4f, 1));
barEntries.add(new BarEntry(6f, 1));
barEntries.add(new BarEntry(8f, 3));
barEntries.add(new BarEntry(7f, 4));
barEntries.add(new BarEntry(3f, 3));
}
}
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 the android studio, open one of your project's activity files and click Run play.jpg icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
In the above result, it is showing the Bar chart as per our data set values.
Click here to download the project code | [
{
"code": null,
"e": 1127,
"s": 1062,
"text": "This example demonstrates How to use Bar chart graph in android."
},
{
"code": null,
"e": 1256,
"s": 1127,
"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": 1325,
"s": 1256,
"text": "Step 2 − Open build.gradle(module level) and add library dependency."
},
{
"code": null,
"e": 2686,
"s": 1325,
"text": "apply plugin: 'com.android.application'\nandroid {\n packagingOptions {\n exclude 'META-INF/proguard/androidx-annotations.pro'\n }\n packagingOptions {\n exclude 'META-INF/DEPENDENCIES'\n exclude 'META-INF/LICENSE'\n exclude 'META-INF/LICENSE.txt'\n exclude 'META-INF/license.txt'\n exclude 'META-INF/NOTICE'\n exclude 'META-INF/NOTICE.txt'\n exclude 'META-INF/notice.txt'\n exclude 'META-INF/ASL2.0'\n }\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"
},
{
"code": null,
"e": 2760,
"s": 2686,
"text": "Step 3 − Open build.gradle(application level) and add library dependency."
},
{
"code": null,
"e": 3308,
"s": 2760,
"text": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\nbuildscript {\n repositories {\n google()\n jcenter()\n }\n dependencies {\n classpath 'com.android.tools.build:gradle:3.2.1'\n // NOTE: Do not place your application dependencies here; they belong\n // in the individual module build.gradle files\n }\n}\nallprojects {\n repositories {\n google()\n jcenter()\n maven { url 'https://jitpack.io' }\n }\n}\ntask clean(type: Delete) {\n delete rootProject.buildDir\n}"
},
{
"code": null,
"e": 3373,
"s": 3308,
"text": "Step 4 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3971,
"s": 3373,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <com.github.mikephil.charting.charts.BarChart\n android:id = \"@+id/BarChart\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"fill_parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 4043,
"s": 3971,
"text": "In the above code, we have taken the Bar Chart view to show a Bar chart"
},
{
"code": null,
"e": 4100,
"s": 4043,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 5518,
"s": 4100,
"text": "package com.example.andy.myapplication;\nimport android.graphics.Color;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport com.github.mikephil.charting.charts.BarChart;\nimport com.github.mikephil.charting.data.BarData;\nimport com.github.mikephil.charting.data.BarDataSet;\nimport com.github.mikephil.charting.data.BarEntry;\nimport com.github.mikephil.charting.utils.ColorTemplate;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n BarChart barChart;\n BarData barData;\n BarDataSet barDataSet;\n ArrayList barEntries;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n barChart = findViewById(R.id.BarChart);\n getEntries();\n barDataSet = new BarDataSet(barEntries, \"\");\n barData = new BarData(barDataSet);\n barChart.setData(barData);\n barDataSet.setColors(ColorTemplate.JOYFUL_COLORS);\n barDataSet.setValueTextColor(Color.BLACK);\n barDataSet.setValueTextSize(18f);\n }\n private void getEntries() {\n barEntries = new ArrayList<>();\n barEntries.add(new BarEntry(2f, 0));\n barEntries.add(new BarEntry(4f, 1));\n barEntries.add(new BarEntry(6f, 1));\n barEntries.add(new BarEntry(8f, 3));\n barEntries.add(new BarEntry(7f, 4));\n barEntries.add(new BarEntry(3f, 3));\n }\n}"
},
{
"code": null,
"e": 5877,
"s": 5518,
"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 the android studio, open one of your project's activity files and click Run play.jpg 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": 5954,
"s": 5877,
"text": "In the above result, it is showing the Bar chart as per our data set values."
},
{
"code": null,
"e": 5994,
"s": 5954,
"text": "Click here to download the project code"
}
] |
Find all factorial numbers less than or equal to n - GeeksforGeeks | 15 Mar, 2021
A number N is called a factorial number if it is the factorial of a positive integer. For example, the first few factorial numbers are1, 2, 6, 24, 120, ...Given a number n, print all factorial numbers smaller than or equal to n. Examples :
Input : n = 100
Output : 1 2 6 24
Input : n = 1500
Output : 1 2 6 24 120 720
A simple solution is to generate all factorials one by one until the generated factorial is greater than n.An efficient solution is to find next factorial using previous factorial.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find all factorial numbers// smaller than or equal to n.#include <iostream>using namespace std; void printFactorialNums(int n){ int fact = 1; int x = 2; while (fact <= n) { cout << fact << " "; // Compute next factorial // using previous fact = fact * x; x++; }} // Driver codeint main(){ int n = 100; printFactorialNums(n); return 0;}
// Java program to find all factorial numbers// smaller than or equal to n. class GFG{ static void printFactorialNums(int n) { int fact = 1; int x = 2; while (fact <= n) { System.out.print(fact + " "); // Compute next factorial // using previous fact = fact * x; x++; } } // Driver code public static void main (String[] args) { int n = 100; printFactorialNums(n); }} // This code is contributed by Anant Agarwal.
# Python3 program to find all factorial# numbers smaller than or equal to n. def printFactorialNums( n): fact = 1 x = 2 while fact <= n: print(fact, end = " ") # Compute next factorial # using previous fact = fact * x x += 1 # Driver coden = 100printFactorialNums(n) # This code is contributed by "Abhishek Sharma 44"
// C# program to find all factorial numbers// smaller than or equal to n.using System; class GFG{ static void printFactorialNums(int n) { int fact = 1; int x = 2; while (fact <= n) { Console.Write(fact + " "); // Compute next factorial // using previous fact = fact * x; x++; } } // Driver code public static void Main () { int n = 100; printFactorialNums(n); }} // This code is contributed by vt_m.
<?php// PHP program to find all// factorial numbers smaller// than or equal to n. function printFactorialNums($n){ $fact = 1; $x = 2; while ($fact <= $n) { echo $fact, " "; // Compute next factorial // using previous $fact = $fact * $x; $x++; }} // Driver code $n = 100; echo printFactorialNums($n); // This code is contributed by ajit.?>
<script> // Javascript program to find all factorial numbers// smaller than or equal to n. function printFactorialNums(n){ let fact = 1; let x = 2; while (fact <= n) { document.write(fact + " "); // Compute next factorial // using previous fact = fact * x; x++; }} // Driver code let n = 100; printFactorialNums(n); // This code is contributed by Mayank Tyagi </script>
Output:
1 2 6 24
Time Complexity : O(n)If there are multiple queries, then we can cache all previously computed factorial numbers to avoid re-computations.This article is contributed by Shubham Sagar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
jit_t
mayanktyagi1709
factorial
Mathematical
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program for Decimal to Binary Conversion
Sieve of Eratosthenes
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
The Knight's tour problem | Backtracking-1
Operators in C / C++
Minimum number of jumps to reach end | [
{
"code": null,
"e": 24289,
"s": 24261,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 24531,
"s": 24289,
"text": "A number N is called a factorial number if it is the factorial of a positive integer. For example, the first few factorial numbers are1, 2, 6, 24, 120, ...Given a number n, print all factorial numbers smaller than or equal to n. Examples : "
},
{
"code": null,
"e": 24609,
"s": 24531,
"text": "Input : n = 100\nOutput : 1 2 6 24\n\nInput : n = 1500\nOutput : 1 2 6 24 120 720"
},
{
"code": null,
"e": 24794,
"s": 24611,
"text": "A simple solution is to generate all factorials one by one until the generated factorial is greater than n.An efficient solution is to find next factorial using previous factorial. "
},
{
"code": null,
"e": 24798,
"s": 24794,
"text": "C++"
},
{
"code": null,
"e": 24803,
"s": 24798,
"text": "Java"
},
{
"code": null,
"e": 24811,
"s": 24803,
"text": "Python3"
},
{
"code": null,
"e": 24814,
"s": 24811,
"text": "C#"
},
{
"code": null,
"e": 24818,
"s": 24814,
"text": "PHP"
},
{
"code": null,
"e": 24829,
"s": 24818,
"text": "Javascript"
},
{
"code": "// CPP program to find all factorial numbers// smaller than or equal to n.#include <iostream>using namespace std; void printFactorialNums(int n){ int fact = 1; int x = 2; while (fact <= n) { cout << fact << \" \"; // Compute next factorial // using previous fact = fact * x; x++; }} // Driver codeint main(){ int n = 100; printFactorialNums(n); return 0;}",
"e": 25241,
"s": 24829,
"text": null
},
{
"code": "// Java program to find all factorial numbers// smaller than or equal to n. class GFG{ static void printFactorialNums(int n) { int fact = 1; int x = 2; while (fact <= n) { System.out.print(fact + \" \"); // Compute next factorial // using previous fact = fact * x; x++; } } // Driver code public static void main (String[] args) { int n = 100; printFactorialNums(n); }} // This code is contributed by Anant Agarwal.",
"e": 25795,
"s": 25241,
"text": null
},
{
"code": "# Python3 program to find all factorial# numbers smaller than or equal to n. def printFactorialNums( n): fact = 1 x = 2 while fact <= n: print(fact, end = \" \") # Compute next factorial # using previous fact = fact * x x += 1 # Driver coden = 100printFactorialNums(n) # This code is contributed by \"Abhishek Sharma 44\"",
"e": 26175,
"s": 25795,
"text": null
},
{
"code": "// C# program to find all factorial numbers// smaller than or equal to n.using System; class GFG{ static void printFactorialNums(int n) { int fact = 1; int x = 2; while (fact <= n) { Console.Write(fact + \" \"); // Compute next factorial // using previous fact = fact * x; x++; } } // Driver code public static void Main () { int n = 100; printFactorialNums(n); }} // This code is contributed by vt_m.",
"e": 26715,
"s": 26175,
"text": null
},
{
"code": "<?php// PHP program to find all// factorial numbers smaller// than or equal to n. function printFactorialNums($n){ $fact = 1; $x = 2; while ($fact <= $n) { echo $fact, \" \"; // Compute next factorial // using previous $fact = $fact * $x; $x++; }} // Driver code $n = 100; echo printFactorialNums($n); // This code is contributed by ajit.?>",
"e": 27115,
"s": 26715,
"text": null
},
{
"code": "<script> // Javascript program to find all factorial numbers// smaller than or equal to n. function printFactorialNums(n){ let fact = 1; let x = 2; while (fact <= n) { document.write(fact + \" \"); // Compute next factorial // using previous fact = fact * x; x++; }} // Driver code let n = 100; printFactorialNums(n); // This code is contributed by Mayank Tyagi </script>",
"e": 27545,
"s": 27115,
"text": null
},
{
"code": null,
"e": 27555,
"s": 27545,
"text": "Output: "
},
{
"code": null,
"e": 27564,
"s": 27555,
"text": "1 2 6 24"
},
{
"code": null,
"e": 28124,
"s": 27564,
"text": "Time Complexity : O(n)If there are multiple queries, then we can cache all previously computed factorial numbers to avoid re-computations.This article is contributed by Shubham Sagar. 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": 28129,
"s": 28124,
"text": "vt_m"
},
{
"code": null,
"e": 28135,
"s": 28129,
"text": "jit_t"
},
{
"code": null,
"e": 28151,
"s": 28135,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 28161,
"s": 28151,
"text": "factorial"
},
{
"code": null,
"e": 28174,
"s": 28161,
"text": "Mathematical"
},
{
"code": null,
"e": 28187,
"s": 28174,
"text": "Mathematical"
},
{
"code": null,
"e": 28197,
"s": 28187,
"text": "factorial"
},
{
"code": null,
"e": 28295,
"s": 28197,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28304,
"s": 28295,
"text": "Comments"
},
{
"code": null,
"e": 28317,
"s": 28304,
"text": "Old Comments"
},
{
"code": null,
"e": 28341,
"s": 28317,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 28384,
"s": 28341,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 28398,
"s": 28384,
"text": "Prime Numbers"
},
{
"code": null,
"e": 28439,
"s": 28398,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 28461,
"s": 28439,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 28506,
"s": 28461,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 28555,
"s": 28506,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28598,
"s": 28555,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 28619,
"s": 28598,
"text": "Operators in C / C++"
}
] |
Java Program to place component in bottom-right corner with BorderLayout | We have created a button component here, which will places in bottom-right corner −
JButton button = new JButton("This is Demo Text!");
button.setBackground(Color.blue);
button.setForeground(Color.white);
Create panels now to arrange the above created button component in the bottom right −
JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(button, BorderLayout.LINE_END);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
The following is an example to place a component in bottom-right corner with BorderLayout −
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
public static void main(String[] args) {
JButton button = new JButton("This is Demo Text!");
button.setBackground(Color.blue);
button.setForeground(Color.white);
JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(button, BorderLayout.LINE_END);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
// mainPanel.setPreferredSize(new Dimension(550, 400));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setSize(550, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
} | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "We have created a button component here, which will places in bottom-right corner −"
},
{
"code": null,
"e": 1267,
"s": 1146,
"text": "JButton button = new JButton(\"This is Demo Text!\");\nbutton.setBackground(Color.blue);\nbutton.setForeground(Color.white);"
},
{
"code": null,
"e": 1353,
"s": 1267,
"text": "Create panels now to arrange the above created button component in the bottom right −"
},
{
"code": null,
"e": 1556,
"s": 1353,
"text": "JPanel bottomPanel = new JPanel(new BorderLayout());\nbottomPanel.add(button, BorderLayout.LINE_END);\nJPanel mainPanel = new JPanel(new BorderLayout());\nmainPanel.add(bottomPanel, BorderLayout.PAGE_END);"
},
{
"code": null,
"e": 1648,
"s": 1556,
"text": "The following is an example to place a component in bottom-right corner with BorderLayout −"
},
{
"code": null,
"e": 2541,
"s": 1648,
"text": "package my;\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\npublic class SwingDemo {\n public static void main(String[] args) {\n JButton button = new JButton(\"This is Demo Text!\");\n button.setBackground(Color.blue);\n button.setForeground(Color.white);\n JPanel bottomPanel = new JPanel(new BorderLayout());\n bottomPanel.add(button, BorderLayout.LINE_END);\n JPanel mainPanel = new JPanel(new BorderLayout());\n mainPanel.add(bottomPanel, BorderLayout.PAGE_END);\n // mainPanel.setPreferredSize(new Dimension(550, 400));\n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.getContentPane().add(mainPanel);\n frame.setSize(550, 400);\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n}"
}
] |
XSD - Date Time | Date and Time data types are used to represent date and time in the XML documents.
The <xs:date> data type is used to represent date in YYYY-MM-DD format.
YYYY − represents year
YYYY − represents year
MM − represents month
MM − represents month
DD − represents day
DD − represents day
Element declaration in XSD −
<xs:element name = "birthdate" type = "xs:date"/>
Element usage in XML −
<birthdate>1980-03-23</birthdate>
The <xs:time> data type is used to represent time in hh:mm:ss format.
hh − represents hours
hh − represents hours
mm − represents minutes
mm − represents minutes
ss − represents seconds
ss − represents seconds
Element declaration in XSD −
<xs:element name = "startTime" type = "xs:time"/>
Element usage in XML −
<startTime>10:20:15</startTime>
The <xs:datetime> data type is used to represent date and time in YYYY-MM-DDThh:mm:ss format.
YYYY − represents year
YYYY − represents year
MM − represents month
MM − represents month
DD − represents day
DD − represents day
T − represents start of time section
T − represents start of time section
hh − represents hours
hh − represents hours
mm − represents minutes
mm − represents minutes
ss − represents seconds
ss − represents seconds
Element declaration in XSD −
<xs:element name = "startTime" type = "xs:datetime"/>
Element usage in XML −
<startTime>1980-03-23T10:20:15</startTime>
The <xs:duration> data type is used to represent time interval in PnYnMnDTnHnMnS format. Each component is optional except P.
P − represents start of date section
P − represents start of date section
nY − represents year
nY − represents year
nM − represents month
nM − represents month
nD − represents day
nD − represents day
T − represents start of time section
T − represents start of time section
nH − represents hours
nH − represents hours
nM − represents minutes
nM − represents minutes
nS − represents seconds
nS − represents seconds
Element declaration in XSD −
<xs:element name = "period" type = "xs:duration"/>
Element usage in xml to represent period of 6 years, 3 months, 10 days and 15 hours.
<period>P6Y3M10DT15H</period>
Following is the list of commonly used date data types.
date
Represents a date value
dateTime
Represents a date and time value
duration
Represents a time interval
gDay
Represents a part of a date as the day (DD)
gMonth
Represents a part of a date as the month (MM)
gMonthDay
Represents a part of a date as the month and day (MM-DD)
gYear
Represents a part of a date as the year (YYYY)
gYearMonth
Represents a part of a date as the year and month (YYYY-MM)
time
Represents a time value
Following types of restrictions can be used with Date data types −
enumeration
maxExclusive
maxInclusive
minExclusive
minInclusive
pattern
whiteSpace
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1787,
"s": 1704,
"text": "Date and Time data types are used to represent date and time in the XML documents."
},
{
"code": null,
"e": 1859,
"s": 1787,
"text": "The <xs:date> data type is used to represent date in YYYY-MM-DD format."
},
{
"code": null,
"e": 1882,
"s": 1859,
"text": "YYYY − represents year"
},
{
"code": null,
"e": 1905,
"s": 1882,
"text": "YYYY − represents year"
},
{
"code": null,
"e": 1927,
"s": 1905,
"text": "MM − represents month"
},
{
"code": null,
"e": 1949,
"s": 1927,
"text": "MM − represents month"
},
{
"code": null,
"e": 1969,
"s": 1949,
"text": "DD − represents day"
},
{
"code": null,
"e": 1989,
"s": 1969,
"text": "DD − represents day"
},
{
"code": null,
"e": 2018,
"s": 1989,
"text": "Element declaration in XSD −"
},
{
"code": null,
"e": 2069,
"s": 2018,
"text": "<xs:element name = \"birthdate\" type = \"xs:date\"/>\n"
},
{
"code": null,
"e": 2092,
"s": 2069,
"text": "Element usage in XML −"
},
{
"code": null,
"e": 2127,
"s": 2092,
"text": "<birthdate>1980-03-23</birthdate>\n"
},
{
"code": null,
"e": 2197,
"s": 2127,
"text": "The <xs:time> data type is used to represent time in hh:mm:ss format."
},
{
"code": null,
"e": 2219,
"s": 2197,
"text": "hh − represents hours"
},
{
"code": null,
"e": 2241,
"s": 2219,
"text": "hh − represents hours"
},
{
"code": null,
"e": 2265,
"s": 2241,
"text": "mm − represents minutes"
},
{
"code": null,
"e": 2289,
"s": 2265,
"text": "mm − represents minutes"
},
{
"code": null,
"e": 2313,
"s": 2289,
"text": "ss − represents seconds"
},
{
"code": null,
"e": 2337,
"s": 2313,
"text": "ss − represents seconds"
},
{
"code": null,
"e": 2366,
"s": 2337,
"text": "Element declaration in XSD −"
},
{
"code": null,
"e": 2417,
"s": 2366,
"text": "<xs:element name = \"startTime\" type = \"xs:time\"/>\n"
},
{
"code": null,
"e": 2440,
"s": 2417,
"text": "Element usage in XML −"
},
{
"code": null,
"e": 2473,
"s": 2440,
"text": "<startTime>10:20:15</startTime>\n"
},
{
"code": null,
"e": 2567,
"s": 2473,
"text": "The <xs:datetime> data type is used to represent date and time in YYYY-MM-DDThh:mm:ss format."
},
{
"code": null,
"e": 2590,
"s": 2567,
"text": "YYYY − represents year"
},
{
"code": null,
"e": 2613,
"s": 2590,
"text": "YYYY − represents year"
},
{
"code": null,
"e": 2635,
"s": 2613,
"text": "MM − represents month"
},
{
"code": null,
"e": 2657,
"s": 2635,
"text": "MM − represents month"
},
{
"code": null,
"e": 2677,
"s": 2657,
"text": "DD − represents day"
},
{
"code": null,
"e": 2697,
"s": 2677,
"text": "DD − represents day"
},
{
"code": null,
"e": 2734,
"s": 2697,
"text": "T − represents start of time section"
},
{
"code": null,
"e": 2771,
"s": 2734,
"text": "T − represents start of time section"
},
{
"code": null,
"e": 2793,
"s": 2771,
"text": "hh − represents hours"
},
{
"code": null,
"e": 2815,
"s": 2793,
"text": "hh − represents hours"
},
{
"code": null,
"e": 2839,
"s": 2815,
"text": "mm − represents minutes"
},
{
"code": null,
"e": 2863,
"s": 2839,
"text": "mm − represents minutes"
},
{
"code": null,
"e": 2887,
"s": 2863,
"text": "ss − represents seconds"
},
{
"code": null,
"e": 2911,
"s": 2887,
"text": "ss − represents seconds"
},
{
"code": null,
"e": 2940,
"s": 2911,
"text": "Element declaration in XSD −"
},
{
"code": null,
"e": 2995,
"s": 2940,
"text": "<xs:element name = \"startTime\" type = \"xs:datetime\"/>\n"
},
{
"code": null,
"e": 3018,
"s": 2995,
"text": "Element usage in XML −"
},
{
"code": null,
"e": 3062,
"s": 3018,
"text": "<startTime>1980-03-23T10:20:15</startTime>\n"
},
{
"code": null,
"e": 3188,
"s": 3062,
"text": "The <xs:duration> data type is used to represent time interval in PnYnMnDTnHnMnS format. Each component is optional except P."
},
{
"code": null,
"e": 3225,
"s": 3188,
"text": "P − represents start of date section"
},
{
"code": null,
"e": 3262,
"s": 3225,
"text": "P − represents start of date section"
},
{
"code": null,
"e": 3283,
"s": 3262,
"text": "nY − represents year"
},
{
"code": null,
"e": 3304,
"s": 3283,
"text": "nY − represents year"
},
{
"code": null,
"e": 3326,
"s": 3304,
"text": "nM − represents month"
},
{
"code": null,
"e": 3348,
"s": 3326,
"text": "nM − represents month"
},
{
"code": null,
"e": 3368,
"s": 3348,
"text": "nD − represents day"
},
{
"code": null,
"e": 3388,
"s": 3368,
"text": "nD − represents day"
},
{
"code": null,
"e": 3425,
"s": 3388,
"text": "T − represents start of time section"
},
{
"code": null,
"e": 3462,
"s": 3425,
"text": "T − represents start of time section"
},
{
"code": null,
"e": 3484,
"s": 3462,
"text": "nH − represents hours"
},
{
"code": null,
"e": 3506,
"s": 3484,
"text": "nH − represents hours"
},
{
"code": null,
"e": 3530,
"s": 3506,
"text": "nM − represents minutes"
},
{
"code": null,
"e": 3554,
"s": 3530,
"text": "nM − represents minutes"
},
{
"code": null,
"e": 3578,
"s": 3554,
"text": "nS − represents seconds"
},
{
"code": null,
"e": 3602,
"s": 3578,
"text": "nS − represents seconds"
},
{
"code": null,
"e": 3631,
"s": 3602,
"text": "Element declaration in XSD −"
},
{
"code": null,
"e": 3683,
"s": 3631,
"text": "<xs:element name = \"period\" type = \"xs:duration\"/>\n"
},
{
"code": null,
"e": 3768,
"s": 3683,
"text": "Element usage in xml to represent period of 6 years, 3 months, 10 days and 15 hours."
},
{
"code": null,
"e": 3799,
"s": 3768,
"text": "<period>P6Y3M10DT15H</period>\n"
},
{
"code": null,
"e": 3855,
"s": 3799,
"text": "Following is the list of commonly used date data types."
},
{
"code": null,
"e": 3860,
"s": 3855,
"text": "date"
},
{
"code": null,
"e": 3884,
"s": 3860,
"text": "Represents a date value"
},
{
"code": null,
"e": 3893,
"s": 3884,
"text": "dateTime"
},
{
"code": null,
"e": 3926,
"s": 3893,
"text": "Represents a date and time value"
},
{
"code": null,
"e": 3935,
"s": 3926,
"text": "duration"
},
{
"code": null,
"e": 3962,
"s": 3935,
"text": "Represents a time interval"
},
{
"code": null,
"e": 3967,
"s": 3962,
"text": "gDay"
},
{
"code": null,
"e": 4011,
"s": 3967,
"text": "Represents a part of a date as the day (DD)"
},
{
"code": null,
"e": 4018,
"s": 4011,
"text": "gMonth"
},
{
"code": null,
"e": 4064,
"s": 4018,
"text": "Represents a part of a date as the month (MM)"
},
{
"code": null,
"e": 4074,
"s": 4064,
"text": "gMonthDay"
},
{
"code": null,
"e": 4131,
"s": 4074,
"text": "Represents a part of a date as the month and day (MM-DD)"
},
{
"code": null,
"e": 4137,
"s": 4131,
"text": "gYear"
},
{
"code": null,
"e": 4184,
"s": 4137,
"text": "Represents a part of a date as the year (YYYY)"
},
{
"code": null,
"e": 4195,
"s": 4184,
"text": "gYearMonth"
},
{
"code": null,
"e": 4255,
"s": 4195,
"text": "Represents a part of a date as the year and month (YYYY-MM)"
},
{
"code": null,
"e": 4260,
"s": 4255,
"text": "time"
},
{
"code": null,
"e": 4284,
"s": 4260,
"text": "Represents a time value"
},
{
"code": null,
"e": 4351,
"s": 4284,
"text": "Following types of restrictions can be used with Date data types −"
},
{
"code": null,
"e": 4363,
"s": 4351,
"text": "enumeration"
},
{
"code": null,
"e": 4376,
"s": 4363,
"text": "maxExclusive"
},
{
"code": null,
"e": 4389,
"s": 4376,
"text": "maxInclusive"
},
{
"code": null,
"e": 4402,
"s": 4389,
"text": "minExclusive"
},
{
"code": null,
"e": 4415,
"s": 4402,
"text": "minInclusive"
},
{
"code": null,
"e": 4423,
"s": 4415,
"text": "pattern"
},
{
"code": null,
"e": 4434,
"s": 4423,
"text": "whiteSpace"
},
{
"code": null,
"e": 4441,
"s": 4434,
"text": " Print"
},
{
"code": null,
"e": 4452,
"s": 4441,
"text": " Add Notes"
}
] |
C++ Program to Implement Russian Peasant Multiplication | Russian Peasant algorithm to multiply two numbers. It is a quick algorithm to calculate multiplication of two long numbers.
Begin
Russianpeasant(num1, num2)
Int result=0
while (num2 > 0)
if (num2 and 1)
result = result + n;
num1= num1 left shift 1;
num2= num2left shift 1;
return result
End
#include <iostream>
using namespace std;
unsigned int russianPeasant(unsigned int n, unsigned int m) {
int result = 0;
while (m > 0) {
if (m & 1)
result = result + n;
n = n << 1;
m = m >> 1;
}
return result;
}
int main() {
cout << russianPeasant(10, 20) << endl;
cout << russianPeasant(7, 6) << endl;
return 0;
}
200
42 | [
{
"code": null,
"e": 1186,
"s": 1062,
"text": "Russian Peasant algorithm to multiply two numbers. It is a quick algorithm to calculate multiplication of two long numbers."
},
{
"code": null,
"e": 1398,
"s": 1186,
"text": "Begin\n Russianpeasant(num1, num2)\n Int result=0\n while (num2 > 0)\n if (num2 and 1)\n result = result + n;\n num1= num1 left shift 1;\n num2= num2left shift 1;\n return result\nEnd"
},
{
"code": null,
"e": 1765,
"s": 1398,
"text": "#include <iostream>\nusing namespace std;\nunsigned int russianPeasant(unsigned int n, unsigned int m) {\n int result = 0;\n while (m > 0) {\n if (m & 1)\n result = result + n;\n n = n << 1;\n m = m >> 1;\n }\n return result;\n}\nint main() {\n cout << russianPeasant(10, 20) << endl;\n cout << russianPeasant(7, 6) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 1772,
"s": 1765,
"text": "200\n42"
}
] |
Graph Database, GraphQL and Machine Learning for Carbohydrate-Active Enzymes | by Sixing Huang | Towards Data Science | This article shows how to:
1. Convert the CAZy database into Neo4j
2. Analyze the CAZynome of Formosa agariphila KMM 3901 to gain new insights
3. Build a GraphQL API for language-agnostic data access
4. Perform graph embedding and node classification for cellulose degradation prediction
What is the most abundant polymer in the world? The answer may surprise many: cellulose. It is a polysaccharide found in the plant cell walls. And we make it into paper, T-shirt and cellophane. And the second place is also taken by a polysaccharide: chitin. It is inside the cell walls of fungi, the scales of fish, the shells of crabs, shrimps and lobsters. In fact, all cellular organisms cannot live without polysaccharides.
Polysaccharide is a form of carbohydrate. As its name suggests, a polysaccharide is made up of multiple monosaccharides, a.k.a simple sugars. Monosaccharides are chained together via glycosidic bonds. There are several types of monosaccharides (glucose, xylose and so on) and several types of glycosidic bonds (alpha-1,4 and beta-1,3 and so on). The various combinations of monosaccharides and glycosidic bonds create the diversity of polysaccharides. For example, glycogen, starch and laminarin are also polysaccharides. But they are storage compounds and act as an energy reservoir in the cells. The cells can break down these molecules into monosaccharides easily in a process called hydrolysis and then oxidize the monosaccharides to gain fuel. In contrast, both cellulose and chitin are structural components. They are tough to break down so that they can support and protect their host cells. Humans consume both glycogen and starch, but can digest neither cellulose nor chitin.
That is where fungi and bacteria come in. Whenever you see rotten woods, wood-decay fungi are at work. And herbivores can break down cellulose because of a community of cellulolytic microbes in their gastrointestinal tracts. Chitin is mainly degraded by fungi and bacteria as well. Therefore, thanks to their work, our planet has not yet been blanketed by these two polysaccharides.
Those fungi and bacteria can accomplish such great feats because they produce certain kinds of enzymes for breaking the glycosidic bonds in cellulose or chitin. Enzymes that synthesize or degrade polysaccharides are called carbohydrate-active enzymes (CAZymes). The research into CAZymes is not just about manufacturing and nutrition. It also brings us new knowledge in ecology. Ultimately, it holds the key to the next-generation biofuels, too. To better understand the biorecycling of polysaccharides, a group of researchers led by Prof. Henrissat have set up a database called CAZy, short for Carbohydrate-Active enZYmes. They have collected over a million CAZyme sequences and put them into six categories based on their interactions with the carbohydrate substrates:
Glycoside hydrolases (GHs) are enzymes that hydrolyze or rearrange glycosidic bonds.Glycosyltransferases (GTs) are the ones that form glycosidic bonds.Polysaccharide lyases (PLs) are enzymes that perform non-hydrolytic cleavage of glycosidic bonds.Carbohydrate esterases (CEs) hydrolyze carbohydrate esters.Auxiliary activities (AAs) are redox enzymes that act in conjunction with CAZymes.Carbohydrate-binding modules (CBMs) are the non-catalytic domains of CAZymes. CBMs bind the CAZyme and the carbohydrates together so that the catalytic reaction can take place.
Glycoside hydrolases (GHs) are enzymes that hydrolyze or rearrange glycosidic bonds.
Glycosyltransferases (GTs) are the ones that form glycosidic bonds.
Polysaccharide lyases (PLs) are enzymes that perform non-hydrolytic cleavage of glycosidic bonds.
Carbohydrate esterases (CEs) hydrolyze carbohydrate esters.
Auxiliary activities (AAs) are redox enzymes that act in conjunction with CAZymes.
Carbohydrate-binding modules (CBMs) are the non-catalytic domains of CAZymes. CBMs bind the CAZyme and the carbohydrates together so that the catalytic reaction can take place.
Inside each category, the researchers have grouped the sequences into different families and even subfamilies based on sequence similarities. As of this writing, there are 171 GH families and 114 GT families.
Because CAZy is based on sequence similarity and similar sequences do not necessarily have the same functional activities, CAZyme families often contain different members that act on different carbohydrates or at different glycosidic bonds. Sometimes, the substrates are similar within a family. For example, sequences of pullulanase (EC 3.2.1.41) and alpha-amylase (EC 3.2.1.1) are found in GH13 (Figure 3.), both of which are polysaccharides with alpha glycosidic bonds.
The CAZy team also annotated over 10,000 genomes from Archaea, Bacteria, Eukaryota and viruses and put the results on the website. All the CAZymes within an organism constitute its CAZynome. The CAZynome decides which carbohydrates that the organism can metabolize — i.e. synthesize or degrade.
The CAZy database is an extremely valuable resource for genome analyses. However, the CAZy website is more like a text website other than a data portal. Descriptive information is displayed but no download or API is provided. It does not offer sequence annotation service (they only accept offline academic collaboration). And its access can sometimes be erratic.
To make CAZy more accessible, I have previously written an article about CAZy annotation with AWS Batch. In it, I implemented in the cloud one of the most sought-after feature requests for CAZy. My next goal is to build a CAZy website mirror for my own data analyses. I have previously shown how to use Neo4j to host genome annotations because a graph database is an excellent choice to store data with complicated relationships. It is also very easy to construct GraphQL APIs for data access. Finally, Neo4j can perform graph embedding and node classification for machine learning. This capability will be very useful for metabolism prediction in bioinformatics.
My previous article explains how to start a Neo4j project. In this article, I created a project called cazy in Neo4j Desktop and enabled the APOC and Graph Data Science Library plugins. Later, I set up GraphQL for the database via Apollo and neo4j-graphql.js. Finally, I predicted which genomes are capable of degrading cellulose with the Neo4j Graph Data Science library.
The code for this project is hosted on my Github repository here:
github.com
For this project, I collected the taxonomies and CAZy annotations of all the bacterial and archaeal genomes and the family descriptions from CAZy. The descriptions of all their four-digit EC numbers, i.e. EC without wildcard, were retrieved from the KEGG database. In addition, I annotated the cellulose degradation capabilities of 186 genomes from primary strain description papers and from the bacterial metadata database BacDive. The data are structured in Neo4j as follows:
All the scripts for download and post-processing are available in my repository, as well as the raw and formated data. Put all the CSV files from “data_for_neo4j” into the “import” folder of cazy. Afterwards, import and index the data with the following commnads in the Neo4j Browser:
After the import, we can calculate some basic statistics about the database. For example, the query below calculates the average amount of GH families among all the genomes. The result is 16 GH families.
Next, I took a new look at the GH families within the genome of Formosa agariphila KMM 3901, which was analyzed by my colleague Alexander Mann in 2013 but its CAZy annotations have since been updated.
This bacterium was isolated from the green alga Acrosiphonia sonderi and can degrade a wide range of algal polysaccharides. The graph above shows that KMM 3901 possesses 37 GH families, more than twice the average of 16. Compared to the annotations done by Mann et al., GH130, GH149, GH158, GH168 and GH171 are new additions in the GH category.
In this section, I can do some analyses similar to those in Analyzing Genomes in a Graph Database. Again I took the genome of Formosa agariphila KMM 3901 as my example. As of this writing, there were five annotated genomes under the genus Formosa.
I can quickly display the unique CAZy families of KMM 3901 by issuing:
The results show that KMM 3901 has eight unique GH and two unique PL but nothing new in the GT, CE or CBM categories. Both PL28 and PL37 contain ulvan lyase. It is an enzyme that degrades ulvan, a complex sulfated polysaccharide present in the cell walls of the green algae Ulva (Chlorophyta). In the GH category, the list contains GH86. This family harbors beta-agarase and beta-porphyranase. Both attack the sulfated carbohydrates in red algae. Furthermore, GH168 contains endo-alpha-(1,3)-L-fucanase (EC3.2.1.211) that breaks the (1→3)-α-L-fucoside linkages in fucan, a sulfated polysaccharide found mainly in different species of seaweed. Finally, the unique GH28, GH78 and GH105 are involved in pectin degradation. Pectins or pectin-like carbohydrates are found in green algae. In summary, these new results revealed the unique agarolytic life strategy of KMM 3901 and its ecological niche away from its sisters. They also added some important details to the study by Mann et al..
Next, I compared the combination of GH families in KMM 3901 with all the bacterial and archaeal genomes in the database. Among the most similar genomes, the four sisters were not even in the top one hundred.
Members from the phylum Bacteroidetes have completed the top ten list. Taxonomically, Mucilaginibacter, Chitinophaga and KMM 3901 differ on the class level. Surprisingly, unlike KMM 3901, all these top ten bacteria were isolated from land. Unfortunately, information about their carbohydrate degradation capability was insufficient and only some information about their close taxonomic neighbors was available. For example, Mucilaginibacter contains members such as M. paludis and M. gracilis that can degrade pectin, xylan and laminarin. Unfortunately, neither of their genomes have been yet annotated in CAZy.
Although Cypher is an easy query language to learn, it is not the only way we can fetch data from Neo4j. GraphQL is the alternative. On the one hand, its execution is language agnostic so that developers without mastering Cypher can also access the data. On the other hand, modern microservice architecture frequently requires each component to communicate through HTTP APIs. And GraphQL is a good way to expose data from Neo4j in HTTP. Compared to REST, users can fine-tune their requests to avoid excessive data delivery. To learn more, please read my previous article “Build Your Own GraphQL GenBank in AWS”.
It is surprisingly easy to set up an Apollo server for GraphQL in Neo4j. The Neo4j team have developed a Javascript library called neo4j-graphql.js. This library auto-generates the query and the resolver codes. In fact, the only thing that a user needs to do is to define the typeDefs schema. The client can then query the data without even a single line of Cypher. The following 58 lines of code in the index.js can power up a GraphQL server for this entire project (please first fill in the password of the database in line 48):
Lines 5–44 define the schema for accessing the taxon, genome, cazy and ec data. The DataPoint type helps us with retrieving the amount of each CAZy family.
Run this script in the Terminal:
nodemon index.js
To test the API, direct your browser to http://localhost:4000. Enter the following query into the left panel and press the round button:
With just one single query, GraphQL returned the taxonomic details of Formosa and the CAZynomes of all its five species. The data were in the JSON format. A Python client is as simple as:
It is also quite easy to mutate data in GraphQL for Neo4j. For more details please refer to the “DOCS” and “SCHEMA” tabs at the right edge of the page (Figure 7.).
One of the goals in CAZy annotation is to predict what kind of carbohydrates that an organism can metabolize. Although the exact percentage has been under constant debate, it is quite clear that the majority of the microorganisms have not yet been cultivated in the lab. Fortunately, we can still obtain their genomes through metagenomics or single-cell genomics without cultivating them. If we can predict their carbohydrate substrates, we can hypothesize the ecological roles that they play in their natural habitats and their industrial potentials. And these predictions may perhaps help us with finding the suitable media for their cultivation.
It is logical to use machine learning for this task. But we need two good sources of data: the features (the Xs) and the targets (the Ys). Since CAZy is all about carbohydrate metabolism and over 10,000 genomes have been annotated in the database, they serve as good features. The glaring problem however is the scarcity of the target biochemical data. On the one hand, many annotated species in CAZy have not yet been studied biochemically. On the other hand, many bacteria that have been studied biochemically have not yet been sequenced. The overlaps of the two are very small.
For this project, I manually annotated the cellulose degradation capabilities for 186 genomes as model training data. My sources were primary strain descriptions and BacDive. Among them, 43 were positive and the other 143 were negative for cellulose degradation. All the other genomes served as holdout samples.
After the target data were somehow managed, I moved on to the feature data. Similar to natural language processing (NLP), I had to represent all the genomes in fixed-length vectors before machine learning. But our genomes were nodes in a graph and each of them had various combinations of CAZy connections. Fortunately, the Graph Data Science Library in Neo4j provides us with graph embedding. Analog to the word embedding in NLP, graph embedding generates a fixed-length vector for each node based on its graph topology. We can then use only these vectors as features for the machine learning.
The gds.graph.create part creates an in-memory graph projection to hold all the necessary data for the machine learning. The gds.fastRP.mutate part calculates the graph embedding and writes the results back into the memory graph.
Next, I called the nodeClassification.train method to start the training. Under the hood, Neo4j uses multiclass node logistic regression. I also set up a five-fold cross-validation and configure “F1 weighted” as the metric.
The training score of 67% and testing score of 65% were both low (Figure 8.). I tried with other parameters and they did not improve the results.
Nevertheless, I still applied the model to predict the cellulose degradation in the holdout data with:
This model predicted eleven genomes positive for cellulose degradation:
Among them, firstly, Micromonospora carbonacea is a known cellulase producer and it degrades the cellulose cell wall of Phytophthora. However, Fu et al. reported that its sister HM134, the second one in the list, is negative for cellulose degradation. Their result is a bit surprising because HM134 shares 58 out of the 61 CAZy families in M. carbonacea and the three exceptions (GH154, GT75 and CBM22) have no obvious connections with cellulose metabolism. Thirdly, Streptomyces sp. SirexAA-E is known to be capable of deconstructing lignocellulosic biomass. Fourthly, Xanthomonas citri pv. citri UI7 is a cellulolytic plant pathogen responsible for type A citrus canker. Fifthly, whether Streptomyces prasinus ATCC 13879 can degrade cellulose is undetermined according to BacDive. Finally, little is known about the remaining six in the list.
Once again, this article has shown that Neo4j is a powerful analytic platform for bioinformatic research. The connection-rich data in CAZy are better modeled in a graph database than in a relational database like MySQL. The Cypher language is easy to learn and brings a new way of thinking to the users. The CAZy annotations are now in a graph, in which genomes are connected via their shared CAZymes and CAZy families are connected via shared EC numbers. This can bring forth new discoveries from the data because it is more natural for us humans to analyze complex things in context. All in all the insights have already been in the data, Neo4j just makes it more visible.
GraphQL can deliver data from different data sources as long as they conform to its specification. It allows developers without Cypher knowledge to extract data efficiently. And it can surely convert Neo4j into a microservice for a larger application. However, it does not replace Cypher. GraphQL cannot provide us with the connection-driven query experience, let alone the aggregation and machine learning functionalities.
One of the holy grails in bioinformatics is to predict metabolism based on genomic data. The exercise in cellulose degradation prediction highlighted the challenges. The small training data set certainly contributed to the low training and testing scores. But we also need to ask ourselves, whether the sequence-similarity-based CAZy is really suitable for metabolism prediction with machine learning. So far, there is no published study with any success in this avenue. Perhaps the function-similarity-based EC numbers are better features than CAZy?
Genome sequencing is getting cheaper and easier. Metagenomics and single-cell genomics are also getting better and better. As a result, genomic data are no longer the bottleneck. In contrast, the metabolic data are hard to generate. In fact, the gap between the genomic and the metabolic data can only get larger and larger in the future. Biochemical tests are labor intensive and error prone. Bacterial strain description papers often neglect to mention carbohydrate metabolism. Also, the digitalization of the results is time consuming. Finally, there have been many dedicated databases for genomic sequences, but none could be found for the metabolic data until the 2012 release of the BacDive database. Since then, more metabolic data have been made available but they are still not sufficient for any large-scale machine learning project.
To close the data gap, the BacDive team on the one hand are working hard to collect more biochemical metadata from primary research papers. On the other hand, they are planning to test many sequenced bacterial strains within their DiASPora project. Also, strain descriptions should be standardized and mandatory biochemical tests should be required for their publications.
Finally, although the article has used Neo4j Desktop, it is actually quite easy to move it into the cloud serverlessly. For more information, please read the excellent article “Working With Spatial Data In Neo4j GraphQL In The Cloud” by William Lyon. Once migrated to the cloud, the Neo4j CAZy can be open to the public or a defined group of users with high availability. The serverless option also reduces costs.
In the end, I thank the CAZy team sincerely for all their hard work. And you can read more about the database in their publication here: https://pubmed.ncbi.nlm.nih.gov/24270786/. | [
{
"code": null,
"e": 199,
"s": 172,
"text": "This article shows how to:"
},
{
"code": null,
"e": 239,
"s": 199,
"text": "1. Convert the CAZy database into Neo4j"
},
{
"code": null,
"e": 315,
"s": 239,
"text": "2. Analyze the CAZynome of Formosa agariphila KMM 3901 to gain new insights"
},
{
"code": null,
"e": 372,
"s": 315,
"text": "3. Build a GraphQL API for language-agnostic data access"
},
{
"code": null,
"e": 460,
"s": 372,
"text": "4. Perform graph embedding and node classification for cellulose degradation prediction"
},
{
"code": null,
"e": 888,
"s": 460,
"text": "What is the most abundant polymer in the world? The answer may surprise many: cellulose. It is a polysaccharide found in the plant cell walls. And we make it into paper, T-shirt and cellophane. And the second place is also taken by a polysaccharide: chitin. It is inside the cell walls of fungi, the scales of fish, the shells of crabs, shrimps and lobsters. In fact, all cellular organisms cannot live without polysaccharides."
},
{
"code": null,
"e": 1873,
"s": 888,
"text": "Polysaccharide is a form of carbohydrate. As its name suggests, a polysaccharide is made up of multiple monosaccharides, a.k.a simple sugars. Monosaccharides are chained together via glycosidic bonds. There are several types of monosaccharides (glucose, xylose and so on) and several types of glycosidic bonds (alpha-1,4 and beta-1,3 and so on). The various combinations of monosaccharides and glycosidic bonds create the diversity of polysaccharides. For example, glycogen, starch and laminarin are also polysaccharides. But they are storage compounds and act as an energy reservoir in the cells. The cells can break down these molecules into monosaccharides easily in a process called hydrolysis and then oxidize the monosaccharides to gain fuel. In contrast, both cellulose and chitin are structural components. They are tough to break down so that they can support and protect their host cells. Humans consume both glycogen and starch, but can digest neither cellulose nor chitin."
},
{
"code": null,
"e": 2256,
"s": 1873,
"text": "That is where fungi and bacteria come in. Whenever you see rotten woods, wood-decay fungi are at work. And herbivores can break down cellulose because of a community of cellulolytic microbes in their gastrointestinal tracts. Chitin is mainly degraded by fungi and bacteria as well. Therefore, thanks to their work, our planet has not yet been blanketed by these two polysaccharides."
},
{
"code": null,
"e": 3028,
"s": 2256,
"text": "Those fungi and bacteria can accomplish such great feats because they produce certain kinds of enzymes for breaking the glycosidic bonds in cellulose or chitin. Enzymes that synthesize or degrade polysaccharides are called carbohydrate-active enzymes (CAZymes). The research into CAZymes is not just about manufacturing and nutrition. It also brings us new knowledge in ecology. Ultimately, it holds the key to the next-generation biofuels, too. To better understand the biorecycling of polysaccharides, a group of researchers led by Prof. Henrissat have set up a database called CAZy, short for Carbohydrate-Active enZYmes. They have collected over a million CAZyme sequences and put them into six categories based on their interactions with the carbohydrate substrates:"
},
{
"code": null,
"e": 3594,
"s": 3028,
"text": "Glycoside hydrolases (GHs) are enzymes that hydrolyze or rearrange glycosidic bonds.Glycosyltransferases (GTs) are the ones that form glycosidic bonds.Polysaccharide lyases (PLs) are enzymes that perform non-hydrolytic cleavage of glycosidic bonds.Carbohydrate esterases (CEs) hydrolyze carbohydrate esters.Auxiliary activities (AAs) are redox enzymes that act in conjunction with CAZymes.Carbohydrate-binding modules (CBMs) are the non-catalytic domains of CAZymes. CBMs bind the CAZyme and the carbohydrates together so that the catalytic reaction can take place."
},
{
"code": null,
"e": 3679,
"s": 3594,
"text": "Glycoside hydrolases (GHs) are enzymes that hydrolyze or rearrange glycosidic bonds."
},
{
"code": null,
"e": 3747,
"s": 3679,
"text": "Glycosyltransferases (GTs) are the ones that form glycosidic bonds."
},
{
"code": null,
"e": 3845,
"s": 3747,
"text": "Polysaccharide lyases (PLs) are enzymes that perform non-hydrolytic cleavage of glycosidic bonds."
},
{
"code": null,
"e": 3905,
"s": 3845,
"text": "Carbohydrate esterases (CEs) hydrolyze carbohydrate esters."
},
{
"code": null,
"e": 3988,
"s": 3905,
"text": "Auxiliary activities (AAs) are redox enzymes that act in conjunction with CAZymes."
},
{
"code": null,
"e": 4165,
"s": 3988,
"text": "Carbohydrate-binding modules (CBMs) are the non-catalytic domains of CAZymes. CBMs bind the CAZyme and the carbohydrates together so that the catalytic reaction can take place."
},
{
"code": null,
"e": 4374,
"s": 4165,
"text": "Inside each category, the researchers have grouped the sequences into different families and even subfamilies based on sequence similarities. As of this writing, there are 171 GH families and 114 GT families."
},
{
"code": null,
"e": 4847,
"s": 4374,
"text": "Because CAZy is based on sequence similarity and similar sequences do not necessarily have the same functional activities, CAZyme families often contain different members that act on different carbohydrates or at different glycosidic bonds. Sometimes, the substrates are similar within a family. For example, sequences of pullulanase (EC 3.2.1.41) and alpha-amylase (EC 3.2.1.1) are found in GH13 (Figure 3.), both of which are polysaccharides with alpha glycosidic bonds."
},
{
"code": null,
"e": 5142,
"s": 4847,
"text": "The CAZy team also annotated over 10,000 genomes from Archaea, Bacteria, Eukaryota and viruses and put the results on the website. All the CAZymes within an organism constitute its CAZynome. The CAZynome decides which carbohydrates that the organism can metabolize — i.e. synthesize or degrade."
},
{
"code": null,
"e": 5506,
"s": 5142,
"text": "The CAZy database is an extremely valuable resource for genome analyses. However, the CAZy website is more like a text website other than a data portal. Descriptive information is displayed but no download or API is provided. It does not offer sequence annotation service (they only accept offline academic collaboration). And its access can sometimes be erratic."
},
{
"code": null,
"e": 6170,
"s": 5506,
"text": "To make CAZy more accessible, I have previously written an article about CAZy annotation with AWS Batch. In it, I implemented in the cloud one of the most sought-after feature requests for CAZy. My next goal is to build a CAZy website mirror for my own data analyses. I have previously shown how to use Neo4j to host genome annotations because a graph database is an excellent choice to store data with complicated relationships. It is also very easy to construct GraphQL APIs for data access. Finally, Neo4j can perform graph embedding and node classification for machine learning. This capability will be very useful for metabolism prediction in bioinformatics."
},
{
"code": null,
"e": 6543,
"s": 6170,
"text": "My previous article explains how to start a Neo4j project. In this article, I created a project called cazy in Neo4j Desktop and enabled the APOC and Graph Data Science Library plugins. Later, I set up GraphQL for the database via Apollo and neo4j-graphql.js. Finally, I predicted which genomes are capable of degrading cellulose with the Neo4j Graph Data Science library."
},
{
"code": null,
"e": 6609,
"s": 6543,
"text": "The code for this project is hosted on my Github repository here:"
},
{
"code": null,
"e": 6620,
"s": 6609,
"text": "github.com"
},
{
"code": null,
"e": 7098,
"s": 6620,
"text": "For this project, I collected the taxonomies and CAZy annotations of all the bacterial and archaeal genomes and the family descriptions from CAZy. The descriptions of all their four-digit EC numbers, i.e. EC without wildcard, were retrieved from the KEGG database. In addition, I annotated the cellulose degradation capabilities of 186 genomes from primary strain description papers and from the bacterial metadata database BacDive. The data are structured in Neo4j as follows:"
},
{
"code": null,
"e": 7383,
"s": 7098,
"text": "All the scripts for download and post-processing are available in my repository, as well as the raw and formated data. Put all the CSV files from “data_for_neo4j” into the “import” folder of cazy. Afterwards, import and index the data with the following commnads in the Neo4j Browser:"
},
{
"code": null,
"e": 7587,
"s": 7383,
"text": "After the import, we can calculate some basic statistics about the database. For example, the query below calculates the average amount of GH families among all the genomes. The result is 16 GH families."
},
{
"code": null,
"e": 7788,
"s": 7587,
"text": "Next, I took a new look at the GH families within the genome of Formosa agariphila KMM 3901, which was analyzed by my colleague Alexander Mann in 2013 but its CAZy annotations have since been updated."
},
{
"code": null,
"e": 8133,
"s": 7788,
"text": "This bacterium was isolated from the green alga Acrosiphonia sonderi and can degrade a wide range of algal polysaccharides. The graph above shows that KMM 3901 possesses 37 GH families, more than twice the average of 16. Compared to the annotations done by Mann et al., GH130, GH149, GH158, GH168 and GH171 are new additions in the GH category."
},
{
"code": null,
"e": 8381,
"s": 8133,
"text": "In this section, I can do some analyses similar to those in Analyzing Genomes in a Graph Database. Again I took the genome of Formosa agariphila KMM 3901 as my example. As of this writing, there were five annotated genomes under the genus Formosa."
},
{
"code": null,
"e": 8452,
"s": 8381,
"text": "I can quickly display the unique CAZy families of KMM 3901 by issuing:"
},
{
"code": null,
"e": 9438,
"s": 8452,
"text": "The results show that KMM 3901 has eight unique GH and two unique PL but nothing new in the GT, CE or CBM categories. Both PL28 and PL37 contain ulvan lyase. It is an enzyme that degrades ulvan, a complex sulfated polysaccharide present in the cell walls of the green algae Ulva (Chlorophyta). In the GH category, the list contains GH86. This family harbors beta-agarase and beta-porphyranase. Both attack the sulfated carbohydrates in red algae. Furthermore, GH168 contains endo-alpha-(1,3)-L-fucanase (EC3.2.1.211) that breaks the (1→3)-α-L-fucoside linkages in fucan, a sulfated polysaccharide found mainly in different species of seaweed. Finally, the unique GH28, GH78 and GH105 are involved in pectin degradation. Pectins or pectin-like carbohydrates are found in green algae. In summary, these new results revealed the unique agarolytic life strategy of KMM 3901 and its ecological niche away from its sisters. They also added some important details to the study by Mann et al.."
},
{
"code": null,
"e": 9646,
"s": 9438,
"text": "Next, I compared the combination of GH families in KMM 3901 with all the bacterial and archaeal genomes in the database. Among the most similar genomes, the four sisters were not even in the top one hundred."
},
{
"code": null,
"e": 10258,
"s": 9646,
"text": "Members from the phylum Bacteroidetes have completed the top ten list. Taxonomically, Mucilaginibacter, Chitinophaga and KMM 3901 differ on the class level. Surprisingly, unlike KMM 3901, all these top ten bacteria were isolated from land. Unfortunately, information about their carbohydrate degradation capability was insufficient and only some information about their close taxonomic neighbors was available. For example, Mucilaginibacter contains members such as M. paludis and M. gracilis that can degrade pectin, xylan and laminarin. Unfortunately, neither of their genomes have been yet annotated in CAZy."
},
{
"code": null,
"e": 10870,
"s": 10258,
"text": "Although Cypher is an easy query language to learn, it is not the only way we can fetch data from Neo4j. GraphQL is the alternative. On the one hand, its execution is language agnostic so that developers without mastering Cypher can also access the data. On the other hand, modern microservice architecture frequently requires each component to communicate through HTTP APIs. And GraphQL is a good way to expose data from Neo4j in HTTP. Compared to REST, users can fine-tune their requests to avoid excessive data delivery. To learn more, please read my previous article “Build Your Own GraphQL GenBank in AWS”."
},
{
"code": null,
"e": 11401,
"s": 10870,
"text": "It is surprisingly easy to set up an Apollo server for GraphQL in Neo4j. The Neo4j team have developed a Javascript library called neo4j-graphql.js. This library auto-generates the query and the resolver codes. In fact, the only thing that a user needs to do is to define the typeDefs schema. The client can then query the data without even a single line of Cypher. The following 58 lines of code in the index.js can power up a GraphQL server for this entire project (please first fill in the password of the database in line 48):"
},
{
"code": null,
"e": 11557,
"s": 11401,
"text": "Lines 5–44 define the schema for accessing the taxon, genome, cazy and ec data. The DataPoint type helps us with retrieving the amount of each CAZy family."
},
{
"code": null,
"e": 11590,
"s": 11557,
"text": "Run this script in the Terminal:"
},
{
"code": null,
"e": 11607,
"s": 11590,
"text": "nodemon index.js"
},
{
"code": null,
"e": 11744,
"s": 11607,
"text": "To test the API, direct your browser to http://localhost:4000. Enter the following query into the left panel and press the round button:"
},
{
"code": null,
"e": 11932,
"s": 11744,
"text": "With just one single query, GraphQL returned the taxonomic details of Formosa and the CAZynomes of all its five species. The data were in the JSON format. A Python client is as simple as:"
},
{
"code": null,
"e": 12096,
"s": 11932,
"text": "It is also quite easy to mutate data in GraphQL for Neo4j. For more details please refer to the “DOCS” and “SCHEMA” tabs at the right edge of the page (Figure 7.)."
},
{
"code": null,
"e": 12745,
"s": 12096,
"text": "One of the goals in CAZy annotation is to predict what kind of carbohydrates that an organism can metabolize. Although the exact percentage has been under constant debate, it is quite clear that the majority of the microorganisms have not yet been cultivated in the lab. Fortunately, we can still obtain their genomes through metagenomics or single-cell genomics without cultivating them. If we can predict their carbohydrate substrates, we can hypothesize the ecological roles that they play in their natural habitats and their industrial potentials. And these predictions may perhaps help us with finding the suitable media for their cultivation."
},
{
"code": null,
"e": 13326,
"s": 12745,
"text": "It is logical to use machine learning for this task. But we need two good sources of data: the features (the Xs) and the targets (the Ys). Since CAZy is all about carbohydrate metabolism and over 10,000 genomes have been annotated in the database, they serve as good features. The glaring problem however is the scarcity of the target biochemical data. On the one hand, many annotated species in CAZy have not yet been studied biochemically. On the other hand, many bacteria that have been studied biochemically have not yet been sequenced. The overlaps of the two are very small."
},
{
"code": null,
"e": 13638,
"s": 13326,
"text": "For this project, I manually annotated the cellulose degradation capabilities for 186 genomes as model training data. My sources were primary strain descriptions and BacDive. Among them, 43 were positive and the other 143 were negative for cellulose degradation. All the other genomes served as holdout samples."
},
{
"code": null,
"e": 14233,
"s": 13638,
"text": "After the target data were somehow managed, I moved on to the feature data. Similar to natural language processing (NLP), I had to represent all the genomes in fixed-length vectors before machine learning. But our genomes were nodes in a graph and each of them had various combinations of CAZy connections. Fortunately, the Graph Data Science Library in Neo4j provides us with graph embedding. Analog to the word embedding in NLP, graph embedding generates a fixed-length vector for each node based on its graph topology. We can then use only these vectors as features for the machine learning."
},
{
"code": null,
"e": 14463,
"s": 14233,
"text": "The gds.graph.create part creates an in-memory graph projection to hold all the necessary data for the machine learning. The gds.fastRP.mutate part calculates the graph embedding and writes the results back into the memory graph."
},
{
"code": null,
"e": 14687,
"s": 14463,
"text": "Next, I called the nodeClassification.train method to start the training. Under the hood, Neo4j uses multiclass node logistic regression. I also set up a five-fold cross-validation and configure “F1 weighted” as the metric."
},
{
"code": null,
"e": 14833,
"s": 14687,
"text": "The training score of 67% and testing score of 65% were both low (Figure 8.). I tried with other parameters and they did not improve the results."
},
{
"code": null,
"e": 14936,
"s": 14833,
"text": "Nevertheless, I still applied the model to predict the cellulose degradation in the holdout data with:"
},
{
"code": null,
"e": 15008,
"s": 14936,
"text": "This model predicted eleven genomes positive for cellulose degradation:"
},
{
"code": null,
"e": 15853,
"s": 15008,
"text": "Among them, firstly, Micromonospora carbonacea is a known cellulase producer and it degrades the cellulose cell wall of Phytophthora. However, Fu et al. reported that its sister HM134, the second one in the list, is negative for cellulose degradation. Their result is a bit surprising because HM134 shares 58 out of the 61 CAZy families in M. carbonacea and the three exceptions (GH154, GT75 and CBM22) have no obvious connections with cellulose metabolism. Thirdly, Streptomyces sp. SirexAA-E is known to be capable of deconstructing lignocellulosic biomass. Fourthly, Xanthomonas citri pv. citri UI7 is a cellulolytic plant pathogen responsible for type A citrus canker. Fifthly, whether Streptomyces prasinus ATCC 13879 can degrade cellulose is undetermined according to BacDive. Finally, little is known about the remaining six in the list."
},
{
"code": null,
"e": 16528,
"s": 15853,
"text": "Once again, this article has shown that Neo4j is a powerful analytic platform for bioinformatic research. The connection-rich data in CAZy are better modeled in a graph database than in a relational database like MySQL. The Cypher language is easy to learn and brings a new way of thinking to the users. The CAZy annotations are now in a graph, in which genomes are connected via their shared CAZymes and CAZy families are connected via shared EC numbers. This can bring forth new discoveries from the data because it is more natural for us humans to analyze complex things in context. All in all the insights have already been in the data, Neo4j just makes it more visible."
},
{
"code": null,
"e": 16952,
"s": 16528,
"text": "GraphQL can deliver data from different data sources as long as they conform to its specification. It allows developers without Cypher knowledge to extract data efficiently. And it can surely convert Neo4j into a microservice for a larger application. However, it does not replace Cypher. GraphQL cannot provide us with the connection-driven query experience, let alone the aggregation and machine learning functionalities."
},
{
"code": null,
"e": 17503,
"s": 16952,
"text": "One of the holy grails in bioinformatics is to predict metabolism based on genomic data. The exercise in cellulose degradation prediction highlighted the challenges. The small training data set certainly contributed to the low training and testing scores. But we also need to ask ourselves, whether the sequence-similarity-based CAZy is really suitable for metabolism prediction with machine learning. So far, there is no published study with any success in this avenue. Perhaps the function-similarity-based EC numbers are better features than CAZy?"
},
{
"code": null,
"e": 18347,
"s": 17503,
"text": "Genome sequencing is getting cheaper and easier. Metagenomics and single-cell genomics are also getting better and better. As a result, genomic data are no longer the bottleneck. In contrast, the metabolic data are hard to generate. In fact, the gap between the genomic and the metabolic data can only get larger and larger in the future. Biochemical tests are labor intensive and error prone. Bacterial strain description papers often neglect to mention carbohydrate metabolism. Also, the digitalization of the results is time consuming. Finally, there have been many dedicated databases for genomic sequences, but none could be found for the metabolic data until the 2012 release of the BacDive database. Since then, more metabolic data have been made available but they are still not sufficient for any large-scale machine learning project."
},
{
"code": null,
"e": 18720,
"s": 18347,
"text": "To close the data gap, the BacDive team on the one hand are working hard to collect more biochemical metadata from primary research papers. On the other hand, they are planning to test many sequenced bacterial strains within their DiASPora project. Also, strain descriptions should be standardized and mandatory biochemical tests should be required for their publications."
},
{
"code": null,
"e": 19134,
"s": 18720,
"text": "Finally, although the article has used Neo4j Desktop, it is actually quite easy to move it into the cloud serverlessly. For more information, please read the excellent article “Working With Spatial Data In Neo4j GraphQL In The Cloud” by William Lyon. Once migrated to the cloud, the Neo4j CAZy can be open to the public or a defined group of users with high availability. The serverless option also reduces costs."
}
] |
Go - Pointer to pointer | A pointer to a pointer is a form of chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, the following statement declares a pointer to a pointer of type int −
var ptr **int;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown in the following example −
package main
import "fmt"
func main() {
var a int
var ptr *int
var pptr **int
a = 3000
/* take the address of var */
ptr = &a
/* take the address of ptr using address of operator & */
pptr = &ptr
/* take the value using pptr */
fmt.Printf("Value of a = %d\n", a )
fmt.Printf("Value available at *ptr = %d\n", *ptr )
fmt.Printf("Value available at **pptr = %d\n", **pptr)
}
When the above code is compiled and executed, it produces the following result −
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
64 Lectures
6.5 hours
Ridhi Arora
20 Lectures
2.5 hours
Asif Hussain
22 Lectures
4 hours
Dilip Padmanabhan
48 Lectures
6 hours
Arnab Chakraborty
7 Lectures
1 hours
Aditya Kulkarni
44 Lectures
3 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2225,
"s": 1937,
"text": "A pointer to a pointer is a form of chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below."
},
{
"code": null,
"e": 2445,
"s": 2225,
"text": "A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, the following statement declares a pointer to a pointer of type int −"
},
{
"code": null,
"e": 2461,
"s": 2445,
"text": "var ptr **int;\n"
},
{
"code": null,
"e": 2647,
"s": 2461,
"text": "When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown in the following example −"
},
{
"code": null,
"e": 3062,
"s": 2647,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var a int\n var ptr *int\n var pptr **int\n\n a = 3000\n\n /* take the address of var */\n ptr = &a\n\n /* take the address of ptr using address of operator & */\n pptr = &ptr\n\n /* take the value using pptr */\n fmt.Printf(\"Value of a = %d\\n\", a )\n fmt.Printf(\"Value available at *ptr = %d\\n\", *ptr )\n fmt.Printf(\"Value available at **pptr = %d\\n\", **pptr)\n}"
},
{
"code": null,
"e": 3143,
"s": 3062,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3228,
"s": 3143,
"text": "Value of var = 3000\nValue available at *ptr = 3000\nValue available at **pptr = 3000\n"
},
{
"code": null,
"e": 3263,
"s": 3228,
"text": "\n 64 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3276,
"s": 3263,
"text": " Ridhi Arora"
},
{
"code": null,
"e": 3311,
"s": 3276,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3325,
"s": 3311,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3358,
"s": 3325,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3377,
"s": 3358,
"text": " Dilip Padmanabhan"
},
{
"code": null,
"e": 3410,
"s": 3377,
"text": "\n 48 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3429,
"s": 3410,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3461,
"s": 3429,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3478,
"s": 3461,
"text": " Aditya Kulkarni"
},
{
"code": null,
"e": 3511,
"s": 3478,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3530,
"s": 3511,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3537,
"s": 3530,
"text": " Print"
},
{
"code": null,
"e": 3548,
"s": 3537,
"text": " Add Notes"
}
] |
GATE | GATE-CS-2001 | Question 23 - GeeksforGeeks | 28 Jun, 2021
Consider a schema R(A,B,C,D) and functional dependencies A->B and C->D.
Then the decomposition of R into R1(AB) and R2(CD) is(A) dependency preserving and lossless join(B) lossless join but not dependency preserving(C) dependency preserving but not lossless join(D) not dependency preserving and not lossless joinAnswer: (C)Explanation: Dependency Preserving Decomposition:Decomposition of R into R1 and R2 is a dependency preserving decomposition if closure of functional dependencies after decomposition is same as closure of of FDs before decomposition.A simple way is to just check whether we can derive all the original FDs from the FDs present after decomposition.
In the above question R(A, B, C, D) is decomposed into R1 (A, B) and R2(C, D) and there are only two FDs A -> B and C -> D. So, the decomposition is dependency preserving
Lossless-Join Decomposition:Decomposition of R into R1 and R2 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies)
R1 ∩ R2 → R1
OR
R1 ∩ R2 → R2
In the above question R(A, B, C, D) is decomposed into R1 (A, B) and R2(C, D), and R1 ∩ R2 is empty. So, the decomposition is not lossless.
Quiz of this Question
GATE-CS-2001
GATE-GATE-CS-2001
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-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
GATE | GATE-CS-2001 | Question 48 | [
{
"code": null,
"e": 23985,
"s": 23957,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24057,
"s": 23985,
"text": "Consider a schema R(A,B,C,D) and functional dependencies A->B and C->D."
},
{
"code": null,
"e": 24656,
"s": 24057,
"text": "Then the decomposition of R into R1(AB) and R2(CD) is(A) dependency preserving and lossless join(B) lossless join but not dependency preserving(C) dependency preserving but not lossless join(D) not dependency preserving and not lossless joinAnswer: (C)Explanation: Dependency Preserving Decomposition:Decomposition of R into R1 and R2 is a dependency preserving decomposition if closure of functional dependencies after decomposition is same as closure of of FDs before decomposition.A simple way is to just check whether we can derive all the original FDs from the FDs present after decomposition."
},
{
"code": null,
"e": 24827,
"s": 24656,
"text": "In the above question R(A, B, C, D) is decomposed into R1 (A, B) and R2(C, D) and there are only two FDs A -> B and C -> D. So, the decomposition is dependency preserving"
},
{
"code": null,
"e": 25026,
"s": 24827,
"text": "Lossless-Join Decomposition:Decomposition of R into R1 and R2 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies)"
},
{
"code": null,
"e": 25067,
"s": 25026,
"text": " R1 ∩ R2 → R1\n OR\n R1 ∩ R2 → R2\n"
},
{
"code": null,
"e": 25207,
"s": 25067,
"text": "In the above question R(A, B, C, D) is decomposed into R1 (A, B) and R2(C, D), and R1 ∩ R2 is empty. So, the decomposition is not lossless."
},
{
"code": null,
"e": 25229,
"s": 25207,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25242,
"s": 25229,
"text": "GATE-CS-2001"
},
{
"code": null,
"e": 25260,
"s": 25242,
"text": "GATE-GATE-CS-2001"
},
{
"code": null,
"e": 25265,
"s": 25260,
"text": "GATE"
},
{
"code": null,
"e": 25363,
"s": 25265,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25372,
"s": 25363,
"text": "Comments"
},
{
"code": null,
"e": 25385,
"s": 25372,
"text": "Old Comments"
},
{
"code": null,
"e": 25427,
"s": 25385,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25469,
"s": 25427,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 25511,
"s": 25469,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 25545,
"s": 25511,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 25587,
"s": 25545,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25620,
"s": 25587,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25662,
"s": 25620,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 25716,
"s": 25662,
"text": "C++ Program to count Vowels in a string using Pointer"
},
{
"code": null,
"e": 25758,
"s": 25716,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 42"
}
] |
Append special characters to column values in MySQL | Let us first create a −
mysql> create table DemoTable1626
-> (
-> Name varchar(20)
-> );
Query OK, 0 rows affected (0.37 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1626 values('Chris');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1626 values('Bob');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable1626 values('Robert');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select −
mysql> select * from DemoTable1626;
This will produce the following output −
+--------+
| Name |
+--------+
| Chris |
| Bob |
| Robert |
+--------+
3 rows in set (0.00 sec)
Following is the query to append special characters −
mysql> select rpad(Name,if(length(Name) >= 5,10,7),'*') from DemoTable1626;
This will produce the following output −
+-------------------------------------------+
| rpad(Name,if(length(Name) >= 5,10,7),'*') |
+-------------------------------------------+
| Chris***** |
| Bob**** |
| Robert**** |
+-------------------------------------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1086,
"s": 1062,
"text": "Let us first create a −"
},
{
"code": null,
"e": 1197,
"s": 1086,
"text": "mysql> create table DemoTable1626\n -> (\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.37 sec)"
},
{
"code": null,
"e": 1245,
"s": 1197,
"text": "Insert some records in the table using insert −"
},
{
"code": null,
"e": 1502,
"s": 1245,
"text": "mysql> insert into DemoTable1626 values('Chris');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable1626 values('Bob');\nQuery OK, 1 row affected (0.34 sec)\nmysql> insert into DemoTable1626 values('Robert');\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1552,
"s": 1502,
"text": "Display all records from the table using select −"
},
{
"code": null,
"e": 1588,
"s": 1552,
"text": "mysql> select * from DemoTable1626;"
},
{
"code": null,
"e": 1629,
"s": 1588,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1731,
"s": 1629,
"text": "+--------+\n| Name |\n+--------+\n| Chris |\n| Bob |\n| Robert |\n+--------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1785,
"s": 1731,
"text": "Following is the query to append special characters −"
},
{
"code": null,
"e": 1861,
"s": 1785,
"text": "mysql> select rpad(Name,if(length(Name) >= 5,10,7),'*') from DemoTable1626;"
},
{
"code": null,
"e": 1902,
"s": 1861,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2249,
"s": 1902,
"text": "+-------------------------------------------+\n| rpad(Name,if(length(Name) >= 5,10,7),'*') |\n+-------------------------------------------+\n| Chris***** |\n| Bob**** |\n| Robert**** |\n+-------------------------------------------+\n3 rows in set (0.00 sec)"
}
] |
JUnit - Time Test | JUnit provides a handy option of Timeout. If a test case takes more time than the specified number of milliseconds, then JUnit will automatically mark it as failed. The timeout parameter is used along with @Test annotation. Let us see the @Test(timeout) in action.
Create a java class to be tested, say, MessageUtil.java in C:\>JUNIT_WORKSPACE.
Add an infinite while loop inside the printMessage() method.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
private String message;
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
// prints the message
public void printMessage(){
System.out.println(message);
while(true);
}
// add "Hi!" to the message
public String salutationMessage(){
message = "Hi!" + message;
System.out.println(message);
return message;
}
}
Create a java test class, say, TestJunit.java. Add a timeout of 1000 to testPrintMessage() test case.
Create a java class file named TestJunit.java in C:\>JUNIT_WORKSPACE.
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
public class TestJunit {
String message = "Robert";
MessageUtil messageUtil = new MessageUtil(message);
@Test(timeout = 1000)
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
messageUtil.printMessage();
}
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
Create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s).
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the MessageUtil, Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java
Now run the Test Runner, which will run the test cases defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output. testPrintMessage() test case will mark the unit testing failed.
Inside testPrintMessage()
Robert
Inside testSalutationMessage()
Hi!Robert
testPrintMessage(TestJunit): test timed out after 1000 milliseconds
false
24 Lectures
2.5 hours
Nishita Bhatt
56 Lectures
7.5 hours
Dinesh Varyani
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2237,
"s": 1972,
"text": "JUnit provides a handy option of Timeout. If a test case takes more time than the specified number of milliseconds, then JUnit will automatically mark it as failed. The timeout parameter is used along with @Test annotation. Let us see the @Test(timeout) in action."
},
{
"code": null,
"e": 2317,
"s": 2237,
"text": "Create a java class to be tested, say, MessageUtil.java in C:\\>JUNIT_WORKSPACE."
},
{
"code": null,
"e": 2378,
"s": 2317,
"text": "Add an infinite while loop inside the printMessage() method."
},
{
"code": null,
"e": 2909,
"s": 2378,
"text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message; \n }\n\n // prints the message\n public void printMessage(){\n System.out.println(message);\n while(true);\n } \n\n // add \"Hi!\" to the message\n public String salutationMessage(){\n message = \"Hi!\" + message;\n System.out.println(message);\n return message;\n } \n} \t"
},
{
"code": null,
"e": 3011,
"s": 2909,
"text": "Create a java test class, say, TestJunit.java. Add a timeout of 1000 to testPrintMessage() test case."
},
{
"code": null,
"e": 3081,
"s": 3011,
"text": "Create a java class file named TestJunit.java in C:\\>JUNIT_WORKSPACE."
},
{
"code": null,
"e": 3670,
"s": 3081,
"text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Test(timeout = 1000)\n public void testPrintMessage() {\t\n System.out.println(\"Inside testPrintMessage()\"); \n messageUtil.printMessage(); \n }\n\n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Robert\";\n assertEquals(message,messageUtil.salutationMessage());\n }\n}"
},
{
"code": null,
"e": 3765,
"s": 3670,
"text": "Create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)."
},
{
"code": null,
"e": 4186,
"s": 3765,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t"
},
{
"code": null,
"e": 4258,
"s": 4186,
"text": "Compile the MessageUtil, Test case and Test Runner classes using javac."
},
{
"code": null,
"e": 4332,
"s": 4258,
"text": "C:\\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java\n"
},
{
"code": null,
"e": 4428,
"s": 4332,
"text": "Now run the Test Runner, which will run the test cases defined in the provided Test Case class."
},
{
"code": null,
"e": 4464,
"s": 4428,
"text": "C:\\JUNIT_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 4547,
"s": 4464,
"text": "Verify the output. testPrintMessage() test case will mark the unit testing failed."
},
{
"code": null,
"e": 4696,
"s": 4547,
"text": "Inside testPrintMessage()\nRobert\nInside testSalutationMessage()\nHi!Robert\ntestPrintMessage(TestJunit): test timed out after 1000 milliseconds\nfalse\n"
},
{
"code": null,
"e": 4731,
"s": 4696,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4746,
"s": 4731,
"text": " Nishita Bhatt"
},
{
"code": null,
"e": 4781,
"s": 4746,
"text": "\n 56 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4797,
"s": 4781,
"text": " Dinesh Varyani"
},
{
"code": null,
"e": 4804,
"s": 4797,
"text": " Print"
},
{
"code": null,
"e": 4815,
"s": 4804,
"text": " Add Notes"
}
] |
Profile Memory Consumption of Python functions in a single line of code | by Satyam Kumar | Towards Data Science | Python is a popular language among the data science community known for its robustness and vast presence of frameworks. Python prefers simplicity over complexity which makes it more popular but compromising the performance. Python programs are often prone to memory management issues.
Data Scientists use Python language to process a vast amount of data on a fixed memory constraint. If the code execution exceeds the RAM limit, one may experience memory errors and the program execution terminates. A quick solution is to increase the memory allocation to avoid memory management issues, but this is not always feasible.
Often newbies do not release unused memories and continuously assign new variables, that may increase memory consumption. When the code is been executed, more and more memory is been assigned. Python automatically manages the memory, but it may fail to return the memory consumption to the operating system while executing long Python codes.
So external tools are required to monitor the memory consumption that will further help to optimize the memory.
This article will discuss the memory profiler module that monitors the memory consumption of the Python functions.
Memory Profiler is an open-source Python module that uses psutil module internally, to monitor the memory consumption of Python functions. It performs a line-by-line memory consumption analysis of the function.
Memory Profiler can be installed from PyPl using:
pip install -U memory_profiler
and can be imported using
from memory_profiler import profile
After everything is set up, it's pretty easy to use this module to track the memory consumption of the function. @profile decorator can be used before every function that needs to be tracked. This will track the memory consumption line-by-line in the same way as of line-profiler.
After decorating all the functions with @profile execute the python script with a specific set of arguments.
Execute the above Python script using bypassing -m memory profiler to the Python interpreter. This will load the memory_profiler module and print the memory consumption line-by-line.
Use the below to execute the Python script along with the memory profiler.
python -m memory_profiler <filename>.py
After successful execution, you will get a line-by-line memory consumption report, similar to the above image. The report has 5 columns:
Line #: Line Number
Line Contents: Python code at each line number
Mem usage: Memory usage by the Python interpreter after every execution of the line.
Increment: Difference in memory consumption from the current line to the last line. It basically denotes the memory consumed by a particular line of Python code.
Occurrences: Number of times a particular line of code is executed.
Mem Usage can be tracked to observe the total memory occupancy by the Python interpreter, whereas the Increment column can be observed to see the memory consumption for a particular line of code. By observing the memory usage one can optimize the memory consumption to develop a production-ready code.
Optimizing the memory consumption is as important as optimizing the time complexity of the Python code. By optimizing the memory consumption, one can speed up the execution to some extent and avoid memory crashes.
One can also try custom @profile decorators to specify the precision of the argument. Read the documentation of the memory profiler module for better understanding.
[1] Memory Profiler Documentation: https://pypi.org/project/memory-profiler/
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you.
satyam-kumar.medium.com
Thank You for Reading | [
{
"code": null,
"e": 456,
"s": 171,
"text": "Python is a popular language among the data science community known for its robustness and vast presence of frameworks. Python prefers simplicity over complexity which makes it more popular but compromising the performance. Python programs are often prone to memory management issues."
},
{
"code": null,
"e": 793,
"s": 456,
"text": "Data Scientists use Python language to process a vast amount of data on a fixed memory constraint. If the code execution exceeds the RAM limit, one may experience memory errors and the program execution terminates. A quick solution is to increase the memory allocation to avoid memory management issues, but this is not always feasible."
},
{
"code": null,
"e": 1135,
"s": 793,
"text": "Often newbies do not release unused memories and continuously assign new variables, that may increase memory consumption. When the code is been executed, more and more memory is been assigned. Python automatically manages the memory, but it may fail to return the memory consumption to the operating system while executing long Python codes."
},
{
"code": null,
"e": 1247,
"s": 1135,
"text": "So external tools are required to monitor the memory consumption that will further help to optimize the memory."
},
{
"code": null,
"e": 1362,
"s": 1247,
"text": "This article will discuss the memory profiler module that monitors the memory consumption of the Python functions."
},
{
"code": null,
"e": 1573,
"s": 1362,
"text": "Memory Profiler is an open-source Python module that uses psutil module internally, to monitor the memory consumption of Python functions. It performs a line-by-line memory consumption analysis of the function."
},
{
"code": null,
"e": 1623,
"s": 1573,
"text": "Memory Profiler can be installed from PyPl using:"
},
{
"code": null,
"e": 1654,
"s": 1623,
"text": "pip install -U memory_profiler"
},
{
"code": null,
"e": 1680,
"s": 1654,
"text": "and can be imported using"
},
{
"code": null,
"e": 1716,
"s": 1680,
"text": "from memory_profiler import profile"
},
{
"code": null,
"e": 1997,
"s": 1716,
"text": "After everything is set up, it's pretty easy to use this module to track the memory consumption of the function. @profile decorator can be used before every function that needs to be tracked. This will track the memory consumption line-by-line in the same way as of line-profiler."
},
{
"code": null,
"e": 2106,
"s": 1997,
"text": "After decorating all the functions with @profile execute the python script with a specific set of arguments."
},
{
"code": null,
"e": 2289,
"s": 2106,
"text": "Execute the above Python script using bypassing -m memory profiler to the Python interpreter. This will load the memory_profiler module and print the memory consumption line-by-line."
},
{
"code": null,
"e": 2364,
"s": 2289,
"text": "Use the below to execute the Python script along with the memory profiler."
},
{
"code": null,
"e": 2404,
"s": 2364,
"text": "python -m memory_profiler <filename>.py"
},
{
"code": null,
"e": 2541,
"s": 2404,
"text": "After successful execution, you will get a line-by-line memory consumption report, similar to the above image. The report has 5 columns:"
},
{
"code": null,
"e": 2561,
"s": 2541,
"text": "Line #: Line Number"
},
{
"code": null,
"e": 2608,
"s": 2561,
"text": "Line Contents: Python code at each line number"
},
{
"code": null,
"e": 2693,
"s": 2608,
"text": "Mem usage: Memory usage by the Python interpreter after every execution of the line."
},
{
"code": null,
"e": 2855,
"s": 2693,
"text": "Increment: Difference in memory consumption from the current line to the last line. It basically denotes the memory consumed by a particular line of Python code."
},
{
"code": null,
"e": 2923,
"s": 2855,
"text": "Occurrences: Number of times a particular line of code is executed."
},
{
"code": null,
"e": 3225,
"s": 2923,
"text": "Mem Usage can be tracked to observe the total memory occupancy by the Python interpreter, whereas the Increment column can be observed to see the memory consumption for a particular line of code. By observing the memory usage one can optimize the memory consumption to develop a production-ready code."
},
{
"code": null,
"e": 3439,
"s": 3225,
"text": "Optimizing the memory consumption is as important as optimizing the time complexity of the Python code. By optimizing the memory consumption, one can speed up the execution to some extent and avoid memory crashes."
},
{
"code": null,
"e": 3604,
"s": 3439,
"text": "One can also try custom @profile decorators to specify the precision of the argument. Read the documentation of the memory profiler module for better understanding."
},
{
"code": null,
"e": 3681,
"s": 3604,
"text": "[1] Memory Profiler Documentation: https://pypi.org/project/memory-profiler/"
},
{
"code": null,
"e": 3870,
"s": 3681,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 3894,
"s": 3870,
"text": "satyam-kumar.medium.com"
}
] |
How to Extract Data from JSON Array in Android using Volley Library? | 28 Jan, 2021
In the previous article on JSON Parsing in Android using Volley Library, we have seen how we can get the data from JSON Object in our android app and display that JSON Object in our app. In this article, we will take a look at How to extract data from JSON Array and display that in our app.
JSON Array: JSON Array is a set or called a collection of data that holds multiple JSON Objects with similar sort of data. JSON Array can be easily identified with “[” braces opening and “]” braces closing. A JSON array is having multiple JSON objects which are having similar data. And each JSON object is having data stored in the form of key and value pair.
We will be building a simple application in which we will be displaying a list of CardView in which we will display some courses which are available on Geeks for Geeks. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Below is our JSON array from which we will be displaying the data in our Android App.
[
{
“courseName”:”Fork CPP”,
“courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/fork-cpp-thumbnail.png”,
“courseMode”:”Online Batch”,
“courseTracks”:”6 Tracks”
},
{
“courseName”:”Linux & Shell Scripting Foundation”,
“courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/linux-shell-scripting-thumbnail.png”,
“courseMode”:”Online Batch”,
“courseTracks”:”8 Tracks”
},
{
“courseName”:”11 Weeks Workshop on Data Structures and Algorithms”,
“courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/Workshop-DSA-thumbnail.png”,
“courseMode”:”Online Batch”,
“courseTracks”:”47 Tracks”
},
{
“courseName”:”Data Structures and Algorithms”,
“courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/dsa-self-paced-thumbnail.png”,
“courseMode”:”Online Batch”,
“courseTracks”:”24 Tracks”
}
]
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add the below dependency in your build.gradle file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL.
// below line is used for volley library
implementation ‘com.android.volley:volley:1.1.1’
// below line is used for image loading library
implementation ‘com.squareup.picasso:picasso:2.71828’
After adding this dependency sync your project and now move towards the AndroidManifest.xml part.
Step 3: Adding permissions to the internet in the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml and add the below code to it.
XML
<!--permissions for INTERNET--><uses-permission android:name="android.permission.INTERNET"/>
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--progress bar for loading indicator--> <ProgressBar android:id="@+id/idPB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> <!--recycler view to display our data--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVCourses" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone" /> </RelativeLayout>
Step 5: Creating a Modal class for storing our data
For storing our data we have to create a new java class. For creating a new java class, Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseModal and add the below code to it. Comments are added inside the code to understand the code in more detail.
Java
public class CourseModal { // variables for our course // name and description. private String courseName; private String courseimg; private String courseMode; private String courseTracks; // creating constructor for our variables. public CourseModal(String courseName, String courseimg, String courseMode, String courseTracks) { this.courseName = courseName; this.courseimg = courseimg; this.courseMode = courseMode; this.courseTracks = courseTracks; } // creating getter and setter methods. public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseimg() { return courseimg; } public void setCourseimg(String courseimg) { this.courseimg = courseimg; } public String getCourseMode() { return courseMode; } public void setCourseMode(String courseMode) { this.courseMode = courseMode; } public String getCourseTracks() { return courseTracks; } public void setCourseTracks(String courseTracks) { this.courseTracks = courseTracks; }}
Step 6: Creating a layout file for each item of our RecyclerView
Navigate to the app > res > layout > Right-click on it > New > layout resource file and give the file name as course_rv_item and add the below code to it. Comments are added in the code to get to know in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:elevation="8dp" app:cardCornerRadius="8dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--ImageView to display our course image--> <ImageView android:id="@+id/idIVCourse" android:layout_width="match_parent" android:layout_height="300dp" android:layout_margin="5dp" /> <!--text view for our course name--> <TextView android:id="@+id/idTVCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="Course Name " android:textColor="@color/black" android:textSize="18sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" android:weightSum="2"> <!--text view for our batch name--> <TextView android:id="@+id/idTVBatch" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:padding="5dp" android:text="Batch" android:textColor="@color/black" /> <!--text view to display course tracks--> <TextView android:id="@+id/idTVTracks" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:padding="5dp" android:text="Tracks" android:textColor="@color/black" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView>
Step 7: Creating an Adapter class for setting data to our RecyclerView item
For creating a new Adapter class navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseAdapter and add the below code to it.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.ViewHolder> { // creating a variable for array list and context. private ArrayList<CourseModal> courseModalArrayList; private Context context; // creating a constructor for our variables. public CourseAdapter(ArrayList<CourseModal> courseModalArrayList, Context context) { this.courseModalArrayList = courseModalArrayList; this.context = context; } @NonNull @Override public CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // below line is to inflate our layout. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) { // setting data to our views of recycler view. CourseModal modal = courseModalArrayList.get(position); holder.courseNameTV.setText(modal.getCourseName()); holder.courseTracksTV.setText(modal.getCourseTracks()); holder.courseModeTV.setText(modal.getCourseMode()); Picasso.get().load(modal.getCourseimg()).into(holder.courseIV); } @Override public int getItemCount() { // returning the size of array list. return courseModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our views. private TextView courseNameTV, courseModeTV, courseTracksTV; private ImageView courseIV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our views with their ids. courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseModeTV = itemView.findViewById(R.id.idTVBatch); courseTracksTV = itemView.findViewById(R.id.idTVTracks); courseIV = itemView.findViewById(R.id.idIVCourse); } }}
Step 8: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonArrayRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for // our ui components. private RecyclerView courseRV; // variable for our adapter // class and array list private CourseAdapter adapter; private ArrayList<CourseModal> courseModalArrayList; // below line is the variable for url from // where we will be querying our data. String url = "https://jsonkeeper.com/b/WO6S"; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. courseRV = findViewById(R.id.idRVCourses); progressBar = findViewById(R.id.idPB); // below line we are creating a new array list courseModalArrayList = new ArrayList<>(); getData(); // calling method to // build recycler view. buildRecyclerView(); } private void getData() { // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // in this case the data we are getting is in the form // of array so we are making a json array request. // below is the line where we are making an json array // request and then extracting data from each json object. JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { progressBar.setVisibility(View.GONE); courseRV.setVisibility(View.VISIBLE); for (int i = 0; i < response.length(); i++) { // creating a new json object and // getting each object from our json array. try { // we are getting each json object. JSONObject responseObj = response.getJSONObject(i); // now we get our response from API in json object format. // in below line we are extracting a string with // its key value from our json object. // similarly we are extracting all the strings from our json object. String courseName = responseObj.getString("courseName"); String courseTracks = responseObj.getString("courseTracks"); String courseMode = responseObj.getString("courseMode"); String courseImageURL = responseObj.getString("courseimg"); courseModalArrayList.add(new CourseModal(courseName, courseImageURL, courseMode, courseTracks)); buildRecyclerView(); } catch (JSONException e) { e.printStackTrace(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show(); } }); queue.add(jsonArrayRequest); } private void buildRecyclerView() { // initializing our adapter class. adapter = new CourseAdapter(courseModalArrayList, MainActivity.this); // adding layout manager // to our recycler view. LinearLayoutManager manager = new LinearLayoutManager(this); courseRV.setHasFixedSize(true); // setting layout manager // to our recycler view. courseRV.setLayoutManager(manager); // setting adapter to // our recycler view. courseRV.setAdapter(adapter); }}
Now run your app and see the output of the app.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Android RecyclerView in Kotlin
Android Project folder Structure
Broadcast Receiver in Android With Example
Flutter - Custom Bottom Navigation Bar
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
For-each loop in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 321,
"s": 28,
"text": "In the previous article on JSON Parsing in Android using Volley Library, we have seen how we can get the data from JSON Object in our android app and display that JSON Object in our app. In this article, we will take a look at How to extract data from JSON Array and display that in our app. "
},
{
"code": null,
"e": 683,
"s": 321,
"text": "JSON Array: JSON Array is a set or called a collection of data that holds multiple JSON Objects with similar sort of data. JSON Array can be easily identified with “[” braces opening and “]” braces closing. A JSON array is having multiple JSON objects which are having similar data. And each JSON object is having data stored in the form of key and value pair. "
},
{
"code": null,
"e": 1017,
"s": 683,
"text": "We will be building a simple application in which we will be displaying a list of CardView in which we will display some courses which are available on Geeks for Geeks. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 1104,
"s": 1017,
"text": "Below is our JSON array from which we will be displaying the data in our Android App. "
},
{
"code": null,
"e": 1106,
"s": 1104,
"text": "["
},
{
"code": null,
"e": 1110,
"s": 1106,
"text": " {"
},
{
"code": null,
"e": 1140,
"s": 1110,
"text": " “courseName”:”Fork CPP”,"
},
{
"code": null,
"e": 1235,
"s": 1140,
"text": " “courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/fork-cpp-thumbnail.png”,"
},
{
"code": null,
"e": 1269,
"s": 1235,
"text": " “courseMode”:”Online Batch”,"
},
{
"code": null,
"e": 1300,
"s": 1269,
"text": " “courseTracks”:”6 Tracks”"
},
{
"code": null,
"e": 1305,
"s": 1300,
"text": " },"
},
{
"code": null,
"e": 1309,
"s": 1305,
"text": " {"
},
{
"code": null,
"e": 1365,
"s": 1309,
"text": " “courseName”:”Linux & Shell Scripting Foundation”,"
},
{
"code": null,
"e": 1473,
"s": 1365,
"text": " “courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/linux-shell-scripting-thumbnail.png”,"
},
{
"code": null,
"e": 1507,
"s": 1473,
"text": " “courseMode”:”Online Batch”,"
},
{
"code": null,
"e": 1538,
"s": 1507,
"text": " “courseTracks”:”8 Tracks”"
},
{
"code": null,
"e": 1543,
"s": 1538,
"text": " },"
},
{
"code": null,
"e": 1547,
"s": 1543,
"text": " {"
},
{
"code": null,
"e": 1620,
"s": 1547,
"text": " “courseName”:”11 Weeks Workshop on Data Structures and Algorithms”,"
},
{
"code": null,
"e": 1719,
"s": 1620,
"text": " “courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/Workshop-DSA-thumbnail.png”,"
},
{
"code": null,
"e": 1753,
"s": 1719,
"text": " “courseMode”:”Online Batch”,"
},
{
"code": null,
"e": 1785,
"s": 1753,
"text": " “courseTracks”:”47 Tracks”"
},
{
"code": null,
"e": 1790,
"s": 1785,
"text": " },"
},
{
"code": null,
"e": 1794,
"s": 1790,
"text": " {"
},
{
"code": null,
"e": 1846,
"s": 1794,
"text": " “courseName”:”Data Structures and Algorithms”,"
},
{
"code": null,
"e": 1947,
"s": 1846,
"text": " “courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/dsa-self-paced-thumbnail.png”,"
},
{
"code": null,
"e": 1981,
"s": 1947,
"text": " “courseMode”:”Online Batch”,"
},
{
"code": null,
"e": 2013,
"s": 1981,
"text": " “courseTracks”:”24 Tracks”"
},
{
"code": null,
"e": 2017,
"s": 2013,
"text": " }"
},
{
"code": null,
"e": 2020,
"s": 2017,
"text": "] "
},
{
"code": null,
"e": 2049,
"s": 2020,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 2211,
"s": 2049,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 2270,
"s": 2211,
"text": "Step 2: Add the below dependency in your build.gradle file"
},
{
"code": null,
"e": 2567,
"s": 2270,
"text": "Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL. "
},
{
"code": null,
"e": 2608,
"s": 2567,
"text": "// below line is used for volley library"
},
{
"code": null,
"e": 2657,
"s": 2608,
"text": "implementation ‘com.android.volley:volley:1.1.1’"
},
{
"code": null,
"e": 2705,
"s": 2657,
"text": "// below line is used for image loading library"
},
{
"code": null,
"e": 2759,
"s": 2705,
"text": "implementation ‘com.squareup.picasso:picasso:2.71828’"
},
{
"code": null,
"e": 2859,
"s": 2759,
"text": "After adding this dependency sync your project and now move towards the AndroidManifest.xml part. "
},
{
"code": null,
"e": 2934,
"s": 2859,
"text": "Step 3: Adding permissions to the internet in the AndroidManifest.xml file"
},
{
"code": null,
"e": 3007,
"s": 2934,
"text": "Navigate to the app > AndroidManifest.xml and add the below code to it. "
},
{
"code": null,
"e": 3011,
"s": 3007,
"text": "XML"
},
{
"code": "<!--permissions for INTERNET--><uses-permission android:name=\"android.permission.INTERNET\"/>",
"e": 3104,
"s": 3011,
"text": null
},
{
"code": null,
"e": 3152,
"s": 3104,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 3295,
"s": 3152,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 3299,
"s": 3295,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--progress bar for loading indicator--> <ProgressBar android:id=\"@+id/idPB\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" /> <!--recycler view to display our data--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVCourses\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:visibility=\"gone\" /> </RelativeLayout>",
"e": 4081,
"s": 3299,
"text": null
},
{
"code": null,
"e": 4133,
"s": 4081,
"text": "Step 5: Creating a Modal class for storing our data"
},
{
"code": null,
"e": 4444,
"s": 4133,
"text": "For storing our data we have to create a new java class. For creating a new java class, Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseModal and add the below code to it. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 4449,
"s": 4444,
"text": "Java"
},
{
"code": "public class CourseModal { // variables for our course // name and description. private String courseName; private String courseimg; private String courseMode; private String courseTracks; // creating constructor for our variables. public CourseModal(String courseName, String courseimg, String courseMode, String courseTracks) { this.courseName = courseName; this.courseimg = courseimg; this.courseMode = courseMode; this.courseTracks = courseTracks; } // creating getter and setter methods. public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseimg() { return courseimg; } public void setCourseimg(String courseimg) { this.courseimg = courseimg; } public String getCourseMode() { return courseMode; } public void setCourseMode(String courseMode) { this.courseMode = courseMode; } public String getCourseTracks() { return courseTracks; } public void setCourseTracks(String courseTracks) { this.courseTracks = courseTracks; }}",
"e": 5660,
"s": 4449,
"text": null
},
{
"code": null,
"e": 5725,
"s": 5660,
"text": "Step 6: Creating a layout file for each item of our RecyclerView"
},
{
"code": null,
"e": 5943,
"s": 5725,
"text": "Navigate to the app > res > layout > Right-click on it > New > layout resource file and give the file name as course_rv_item and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 5947,
"s": 5943,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:elevation=\"8dp\" app:cardCornerRadius=\"8dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--ImageView to display our course image--> <ImageView android:id=\"@+id/idIVCourse\" android:layout_width=\"match_parent\" android:layout_height=\"300dp\" android:layout_margin=\"5dp\" /> <!--text view for our course name--> <TextView android:id=\"@+id/idTVCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:padding=\"5dp\" android:text=\"Course Name \" android:textColor=\"@color/black\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <!--text view for our batch name--> <TextView android:id=\"@+id/idTVBatch\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:padding=\"5dp\" android:text=\"Batch\" android:textColor=\"@color/black\" /> <!--text view to display course tracks--> <TextView android:id=\"@+id/idTVTracks\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:padding=\"5dp\" android:text=\"Tracks\" android:textColor=\"@color/black\" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView>",
"e": 8205,
"s": 5947,
"text": null
},
{
"code": null,
"e": 8281,
"s": 8205,
"text": "Step 7: Creating an Adapter class for setting data to our RecyclerView item"
},
{
"code": null,
"e": 8466,
"s": 8281,
"text": "For creating a new Adapter class navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseAdapter and add the below code to it. "
},
{
"code": null,
"e": 8471,
"s": 8466,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.ViewHolder> { // creating a variable for array list and context. private ArrayList<CourseModal> courseModalArrayList; private Context context; // creating a constructor for our variables. public CourseAdapter(ArrayList<CourseModal> courseModalArrayList, Context context) { this.courseModalArrayList = courseModalArrayList; this.context = context; } @NonNull @Override public CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // below line is to inflate our layout. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) { // setting data to our views of recycler view. CourseModal modal = courseModalArrayList.get(position); holder.courseNameTV.setText(modal.getCourseName()); holder.courseTracksTV.setText(modal.getCourseTracks()); holder.courseModeTV.setText(modal.getCourseMode()); Picasso.get().load(modal.getCourseimg()).into(holder.courseIV); } @Override public int getItemCount() { // returning the size of array list. return courseModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our views. private TextView courseNameTV, courseModeTV, courseTracksTV; private ImageView courseIV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our views with their ids. courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseModeTV = itemView.findViewById(R.id.idTVBatch); courseTracksTV = itemView.findViewById(R.id.idTVTracks); courseIV = itemView.findViewById(R.id.idIVCourse); } }}",
"e": 10843,
"s": 8471,
"text": null
},
{
"code": null,
"e": 10891,
"s": 10843,
"text": "Step 8: Working with the MainActivity.java file"
},
{
"code": null,
"e": 11081,
"s": 10891,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 11086,
"s": 11081,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.ProgressBar;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonArrayRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for // our ui components. private RecyclerView courseRV; // variable for our adapter // class and array list private CourseAdapter adapter; private ArrayList<CourseModal> courseModalArrayList; // below line is the variable for url from // where we will be querying our data. String url = \"https://jsonkeeper.com/b/WO6S\"; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. courseRV = findViewById(R.id.idRVCourses); progressBar = findViewById(R.id.idPB); // below line we are creating a new array list courseModalArrayList = new ArrayList<>(); getData(); // calling method to // build recycler view. buildRecyclerView(); } private void getData() { // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // in this case the data we are getting is in the form // of array so we are making a json array request. // below is the line where we are making an json array // request and then extracting data from each json object. JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { progressBar.setVisibility(View.GONE); courseRV.setVisibility(View.VISIBLE); for (int i = 0; i < response.length(); i++) { // creating a new json object and // getting each object from our json array. try { // we are getting each json object. JSONObject responseObj = response.getJSONObject(i); // now we get our response from API in json object format. // in below line we are extracting a string with // its key value from our json object. // similarly we are extracting all the strings from our json object. String courseName = responseObj.getString(\"courseName\"); String courseTracks = responseObj.getString(\"courseTracks\"); String courseMode = responseObj.getString(\"courseMode\"); String courseImageURL = responseObj.getString(\"courseimg\"); courseModalArrayList.add(new CourseModal(courseName, courseImageURL, courseMode, courseTracks)); buildRecyclerView(); } catch (JSONException e) { e.printStackTrace(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, \"Fail to get the data..\", Toast.LENGTH_SHORT).show(); } }); queue.add(jsonArrayRequest); } private void buildRecyclerView() { // initializing our adapter class. adapter = new CourseAdapter(courseModalArrayList, MainActivity.this); // adding layout manager // to our recycler view. LinearLayoutManager manager = new LinearLayoutManager(this); courseRV.setHasFixedSize(true); // setting layout manager // to our recycler view. courseRV.setLayoutManager(manager); // setting adapter to // our recycler view. courseRV.setAdapter(adapter); }}",
"e": 15614,
"s": 11086,
"text": null
},
{
"code": null,
"e": 15662,
"s": 15614,
"text": "Now run your app and see the output of the app."
},
{
"code": null,
"e": 15670,
"s": 15662,
"text": "android"
},
{
"code": null,
"e": 15694,
"s": 15670,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 15702,
"s": 15694,
"text": "Android"
},
{
"code": null,
"e": 15707,
"s": 15702,
"text": "Java"
},
{
"code": null,
"e": 15726,
"s": 15707,
"text": "Technical Scripter"
},
{
"code": null,
"e": 15731,
"s": 15726,
"text": "Java"
},
{
"code": null,
"e": 15739,
"s": 15731,
"text": "Android"
},
{
"code": null,
"e": 15837,
"s": 15739,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15869,
"s": 15837,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 15900,
"s": 15869,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 15933,
"s": 15900,
"text": "Android Project folder Structure"
},
{
"code": null,
"e": 15976,
"s": 15933,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 16015,
"s": 15976,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 16030,
"s": 16015,
"text": "Arrays in Java"
},
{
"code": null,
"e": 16074,
"s": 16030,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 16110,
"s": 16074,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 16135,
"s": 16110,
"text": "Reverse a string in Java"
}
] |
Sum of pairwise products | 31 Jan, 2022
For given any unsigned int n find the final value of ∑(i*j) where (1<=i<=n) and (i <= j <= n).Examples:
Input : n = 3
Output : 25
We get the sum as following. Note that
first term i varies from 1 to 3 and second
term values from value of first term to n.
1*1 + 1*2 + 1*3 + 2*2 + 2*3 + 3*3 = 25
Input : 5
Output : 140
Method 1 (Simple) We run two loops and compute the required sum.
C++
Java
Python3
C#
PHP
Javascript
// Simple CPP program to find sum// of given series.#include <bits/stdc++.h>using namespace std; long long int findSum(int n){ long long int sum = 0; for (int i=1; i<=n; i++) for (int j=i; j<=n; j++) sum = sum + i*j; return sum;} int main(){ int n = 5; cout << findSum(n); return 0;}
// Simple Java program to find sum// of given series.class GFG { static int findSum(int n) { int sum = 0; for (int i=1; i<=n; i++) for (int j=i; j<=n; j++) sum = sum + i*j; return sum; } // Driver code public static void main(String[] args) { int n = 5; System.out.println(findSum(n)); }} // This code is contributed by Smitha Dinesh Semwal.
# Simple Python3 program to # find sum of given series. def findSum(n) : sm = 0 for i in range(1, n + 1) : for j in range(i, n + 1) : sm = sm + i * j return sm # Driver Coden = 5print(findSum(n)) # This code is contributed by Nikita Tiwari.
// Simple C# program to find sum// of given series.class GFG { static int findSum(int n) { int sum = 0; for (int i=1; i<=n; i++) for (int j=i; j<=n; j++) sum = sum + i*j; return sum; } // Driver code public static void Main() { int n = 5; System.Console.WriteLine(findSum(n)); }} // This code is contributed by mits.
<?php// Simple PHP program to find sum// of given series. function findSum($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) for ($j = $i; $j <= $n; $j++) $sum = $sum + $i * $j; return $sum;} // Driver Code$n = 5;echo findSum($n); // This code is contributed by mits?>
<script> // Simple JavaScript program to find sum// of given series. function findSum(n) { let sum = 0; for (let i=1; i<=n; i++) for (let j=i; j<=n; j++) sum = sum + i*j; return sum; } // Driver Code let n = 5; document.write(findSum(n)); </script>
140
Time Complexity: O(n^2).Method 2 (Better) We can observe following in the given problem. 1 is multiplied with all numbers from 1 to n. 2 is multiplied with all numbers from 2 to n. ............................................. ............................................. i is multiplied with all numbers from i to n.We compute sum of first n natural numbers which is our first term. For remaining terms, we multiply i with sum of numbers from i to n. We keep track of this sum by subtracting i from initial sum in every iteration.
C++
Java
Python3
C#
PHP
Javascript
// Efficient CPP program to find sum// of given series.#include <bits/stdc++.h>using namespace std; long long int findSum(int n){ long long int multiTerms = n * (n + 1) / 2; // Sum of multiples of 1 is 1 * (1 + 2 + ..) long long int sum = multiTerms; // Adding sum of multiples of numbers other // than 1, starting from 2. for (int i=2; i<=n; i++) { // Subtract previous number // from current multiple. multiTerms = multiTerms - (i - 1); // For example, for 2, we get sum // as (2 + 3 + 4 + ....) * 2 sum = sum + multiTerms * i; } return sum;} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;}
// Efficient Java program to find sum// of given series.class GFG { static int findSum(int n) { int multiTerms = n * (n + 1) / 2; // Sum of multiples of 1 is 1 * (1 + 2 + ..) int sum = multiTerms; // Adding sum of multiples of numbers other // than 1, starting from 2. for (int i = 2; i <= n; i++) { // Subtract previous number // from current multiple. multiTerms = multiTerms - (i - 1); // For example, for 2, we get sum // as (2 + 3 + 4 + ....) * 2 sum = sum + multiTerms*i; } return sum; } // Driver code public static void main(String[] args) { int n = 5; System.out.println(findSum(n)); }} // This code is contributed by Smitha Dinesh Semwal.
# Efficient Python3 program# to find sum of given series. def findSum(n) : multiTerms = n * (n + 1) // 2 # Sum of multiples of 1 is 1 * (1 + 2 + ..) sm = multiTerms # Adding sum of multiples of numbers # other than 1, starting from 2. for i in range(2, n+1) : # Subtract previous number # from current multiple. multiTerms = multiTerms - (i - 1) # For example, for 2, we get sum # as (2 + 3 + 4 + ....) * 2 sm = sm + multiTerms * i return sm # Driver coden = 5print(findSum(n)) # This code is contributed by Nikita Tiwari.
// C# program to find sum// of given series.using System;class GFG { static int findSum(int n) { int multiTerms = n * (n + 1) / 2; // Sum of multiples of 1 is 1 * (1 + 2 + ..) int sum = multiTerms; // Adding sum of multiples of numbers other // than 1, starting from 2. for (int i = 2; i <= n; i++) { // Subtract previous number // from current multiple. multiTerms = multiTerms - (i - 1); // For example, for 2, we get sum // as (2 + 3 + 4 + ....) * 2 sum = sum + multiTerms*i; } return sum; } // Driver code public static void Main() { int n = 5; Console.WriteLine(findSum(n)); }} // This code is contributed by Mukul Singh.
<?php// Efficient PHP program to find sum// of given series. function findSum($n){ $multiTerms = (int)($n * ($n + 1) / 2); // Sum of multiples of 1 is 1 * (1 + 2 + ..)$sum = $multiTerms; // Adding sum of multiples of numbers other// than 1, starting from 2.for ($i=2; $i<=$n; $i++){ // Subtract previous number // from current multiple. $multiTerms = $multiTerms - ($i - 1); // For example, for 2, we get sum // as (2 + 3 + 4 + ....) * 2 $sum = $sum + $multiTerms * $i;}return $sum;} // Driver code $n = 5; echo findSum($n); //This code is contributed by mits?>
<script> // Javascript program to find // sum of given series. function findSum(n) { let multiTerms = n * (n + 1) / 2; // Sum of multiples of 1 is 1 * (1 + 2 + ..) let sum = multiTerms; // Adding sum of multiples // of numbers other // than 1, starting from 2. for (let i = 2; i <= n; i++) { // Subtract previous number // from current multiple. multiTerms = multiTerms - (i - 1); // For example, for 2, we get sum // as (2 + 3 + 4 + ....) * 2 sum = sum + multiTerms*i; } return sum; } let n = 5; document.write(findSum(n)); </script>
140
Time Complexity: O(n).Method 3 (Efficient) The whole calculation can be done in the O(1) time as there is a closed-form expression for the sum. Let i and j run from 1 through n. We want to compute S = sum(i*j) overall i and j such that i <= j otherwise we would have duplicates such as 2*3 + ...+3*2; on the other hand, having i = j is OK which gives us 2*2 + ... This is all by the problem specification. (Sorry if my notation is bizarre.)Now, there are two kinds of terms in the sum S: those with i = j (squares, denoted S1) and those with i j always, but the value is the same, by symmetry: 2 * S2 = (sum i)^2 – sum (i^2) . Note that 2*S2 = S3 – S1 as the latter sum is just S1; the former sum (denoted S3) is new here, but there is a closed-form solution for it too. We can now eliminate the mixed term completely: S = S1 + S2 = (S1 + S3) / 2.Since sum(i) = n*(n+1)/2, we get S3 = n*n*(n+1)*(n+1)/4 ; likewise for the sum of squares: S1 = n*(2*n+1)*(n+1)/6. The final expression simplifies to: S = n*(n+1)*(n+2)*(3*n+1)/24 . (As an exercise, you may want to prove that the numerator is indeed divisible by 24.)
C++
Java
Python3
C#
PHP
Javascript
// Efficient CPP program to find sum// of given series.#include <bits/stdc++.h>using namespace std; long long int findSum(int n){ return n*(n+1)*(n+2)*(3*n+1)/24;} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;}
// Efficient Java program to find sum// of given series.class GFG { static int findSum(int n) { return n * (n + 1) * (n + 2) * (3 * n + 1) / 24; } // Driver code public static void main(String[] args) { int n = 5; System.out.println(findSum(n)); }} // This code is contributed by Smitha Dinesh Semwal.
# Efficient Python3 program to find # sum of given series. def findSum(n): return n * (n + 1) * (n + 2) * (3 * n + 1) / 24 # Driver coden = 5print(int(findSum(n))) # This code is contributed by Smitha Dinesh Semwal.
// Efficient C# program// to find sum of given// series.using System; class GFG{static int findSum(int n){ return n * (n + 1) * (n + 2) * (3 * n + 1) / 24;} // Driver codestatic public void Main (){ int n = 5; Console.WriteLine(findSum(n));}} // This code is contributed// by ajit.
<?php// Efficient PHP// program to find sum// of given series. function findSum($n){ return $n * ($n + 1) * ($n + 2) * (3 * $n + 1) / 24;} // Driver code$n = 5;echo findSum($n); // This code is contributed// by akt_mit?>
<script> // Efficient Javascript program // to find sum of given // series. function findSum(n) { return n * (n + 1) * (n + 2) * (3 * n + 1) / 24; } let n = 5; document.write(findSum(n)); </script>
140
Time Complexity: O(1).Thanks to diprey1 for suggesting this efficient solution.
jit_t
Mithun Kumar
Code_Mech
chinmoy1997pal
divyesh072019
divyeshrabadiya07
surinderdawra388
series
series-sum
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Jan, 2022"
},
{
"code": null,
"e": 160,
"s": 54,
"text": "For given any unsigned int n find the final value of ∑(i*j) where (1<=i<=n) and (i <= j <= n).Examples: "
},
{
"code": null,
"e": 374,
"s": 160,
"text": "Input : n = 3\nOutput : 25\nWe get the sum as following. Note that\nfirst term i varies from 1 to 3 and second\nterm values from value of first term to n.\n1*1 + 1*2 + 1*3 + 2*2 + 2*3 + 3*3 = 25\n\nInput : 5\nOutput : 140"
},
{
"code": null,
"e": 443,
"s": 376,
"text": "Method 1 (Simple) We run two loops and compute the required sum. "
},
{
"code": null,
"e": 447,
"s": 443,
"text": "C++"
},
{
"code": null,
"e": 452,
"s": 447,
"text": "Java"
},
{
"code": null,
"e": 460,
"s": 452,
"text": "Python3"
},
{
"code": null,
"e": 463,
"s": 460,
"text": "C#"
},
{
"code": null,
"e": 467,
"s": 463,
"text": "PHP"
},
{
"code": null,
"e": 478,
"s": 467,
"text": "Javascript"
},
{
"code": "// Simple CPP program to find sum// of given series.#include <bits/stdc++.h>using namespace std; long long int findSum(int n){ long long int sum = 0; for (int i=1; i<=n; i++) for (int j=i; j<=n; j++) sum = sum + i*j; return sum;} int main(){ int n = 5; cout << findSum(n); return 0;}",
"e": 788,
"s": 478,
"text": null
},
{
"code": "// Simple Java program to find sum// of given series.class GFG { static int findSum(int n) { int sum = 0; for (int i=1; i<=n; i++) for (int j=i; j<=n; j++) sum = sum + i*j; return sum; } // Driver code public static void main(String[] args) { int n = 5; System.out.println(findSum(n)); }} // This code is contributed by Smitha Dinesh Semwal.",
"e": 1266,
"s": 788,
"text": null
},
{
"code": "# Simple Python3 program to # find sum of given series. def findSum(n) : sm = 0 for i in range(1, n + 1) : for j in range(i, n + 1) : sm = sm + i * j return sm # Driver Coden = 5print(findSum(n)) # This code is contributed by Nikita Tiwari.",
"e": 1552,
"s": 1266,
"text": null
},
{
"code": "// Simple C# program to find sum// of given series.class GFG { static int findSum(int n) { int sum = 0; for (int i=1; i<=n; i++) for (int j=i; j<=n; j++) sum = sum + i*j; return sum; } // Driver code public static void Main() { int n = 5; System.Console.WriteLine(findSum(n)); }} // This code is contributed by mits.",
"e": 2005,
"s": 1552,
"text": null
},
{
"code": "<?php// Simple PHP program to find sum// of given series. function findSum($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) for ($j = $i; $j <= $n; $j++) $sum = $sum + $i * $j; return $sum;} // Driver Code$n = 5;echo findSum($n); // This code is contributed by mits?>",
"e": 2295,
"s": 2005,
"text": null
},
{
"code": "<script> // Simple JavaScript program to find sum// of given series. function findSum(n) { let sum = 0; for (let i=1; i<=n; i++) for (let j=i; j<=n; j++) sum = sum + i*j; return sum; } // Driver Code let n = 5; document.write(findSum(n)); </script>",
"e": 2657,
"s": 2295,
"text": null
},
{
"code": null,
"e": 2661,
"s": 2657,
"text": "140"
},
{
"code": null,
"e": 3197,
"s": 2663,
"text": "Time Complexity: O(n^2).Method 2 (Better) We can observe following in the given problem. 1 is multiplied with all numbers from 1 to n. 2 is multiplied with all numbers from 2 to n. ............................................. ............................................. i is multiplied with all numbers from i to n.We compute sum of first n natural numbers which is our first term. For remaining terms, we multiply i with sum of numbers from i to n. We keep track of this sum by subtracting i from initial sum in every iteration. "
},
{
"code": null,
"e": 3201,
"s": 3197,
"text": "C++"
},
{
"code": null,
"e": 3206,
"s": 3201,
"text": "Java"
},
{
"code": null,
"e": 3214,
"s": 3206,
"text": "Python3"
},
{
"code": null,
"e": 3217,
"s": 3214,
"text": "C#"
},
{
"code": null,
"e": 3221,
"s": 3217,
"text": "PHP"
},
{
"code": null,
"e": 3232,
"s": 3221,
"text": "Javascript"
},
{
"code": "// Efficient CPP program to find sum// of given series.#include <bits/stdc++.h>using namespace std; long long int findSum(int n){ long long int multiTerms = n * (n + 1) / 2; // Sum of multiples of 1 is 1 * (1 + 2 + ..) long long int sum = multiTerms; // Adding sum of multiples of numbers other // than 1, starting from 2. for (int i=2; i<=n; i++) { // Subtract previous number // from current multiple. multiTerms = multiTerms - (i - 1); // For example, for 2, we get sum // as (2 + 3 + 4 + ....) * 2 sum = sum + multiTerms * i; } return sum;} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;}",
"e": 3911,
"s": 3232,
"text": null
},
{
"code": "// Efficient Java program to find sum// of given series.class GFG { static int findSum(int n) { int multiTerms = n * (n + 1) / 2; // Sum of multiples of 1 is 1 * (1 + 2 + ..) int sum = multiTerms; // Adding sum of multiples of numbers other // than 1, starting from 2. for (int i = 2; i <= n; i++) { // Subtract previous number // from current multiple. multiTerms = multiTerms - (i - 1); // For example, for 2, we get sum // as (2 + 3 + 4 + ....) * 2 sum = sum + multiTerms*i; } return sum; } // Driver code public static void main(String[] args) { int n = 5; System.out.println(findSum(n)); }} // This code is contributed by Smitha Dinesh Semwal.",
"e": 4810,
"s": 3911,
"text": null
},
{
"code": "# Efficient Python3 program# to find sum of given series. def findSum(n) : multiTerms = n * (n + 1) // 2 # Sum of multiples of 1 is 1 * (1 + 2 + ..) sm = multiTerms # Adding sum of multiples of numbers # other than 1, starting from 2. for i in range(2, n+1) : # Subtract previous number # from current multiple. multiTerms = multiTerms - (i - 1) # For example, for 2, we get sum # as (2 + 3 + 4 + ....) * 2 sm = sm + multiTerms * i return sm # Driver coden = 5print(findSum(n)) # This code is contributed by Nikita Tiwari.",
"e": 5425,
"s": 4810,
"text": null
},
{
"code": "// C# program to find sum// of given series.using System;class GFG { static int findSum(int n) { int multiTerms = n * (n + 1) / 2; // Sum of multiples of 1 is 1 * (1 + 2 + ..) int sum = multiTerms; // Adding sum of multiples of numbers other // than 1, starting from 2. for (int i = 2; i <= n; i++) { // Subtract previous number // from current multiple. multiTerms = multiTerms - (i - 1); // For example, for 2, we get sum // as (2 + 3 + 4 + ....) * 2 sum = sum + multiTerms*i; } return sum; } // Driver code public static void Main() { int n = 5; Console.WriteLine(findSum(n)); }} // This code is contributed by Mukul Singh.",
"e": 6302,
"s": 5425,
"text": null
},
{
"code": "<?php// Efficient PHP program to find sum// of given series. function findSum($n){ $multiTerms = (int)($n * ($n + 1) / 2); // Sum of multiples of 1 is 1 * (1 + 2 + ..)$sum = $multiTerms; // Adding sum of multiples of numbers other// than 1, starting from 2.for ($i=2; $i<=$n; $i++){ // Subtract previous number // from current multiple. $multiTerms = $multiTerms - ($i - 1); // For example, for 2, we get sum // as (2 + 3 + 4 + ....) * 2 $sum = $sum + $multiTerms * $i;}return $sum;} // Driver code $n = 5; echo findSum($n); //This code is contributed by mits?>",
"e": 6893,
"s": 6302,
"text": null
},
{
"code": "<script> // Javascript program to find // sum of given series. function findSum(n) { let multiTerms = n * (n + 1) / 2; // Sum of multiples of 1 is 1 * (1 + 2 + ..) let sum = multiTerms; // Adding sum of multiples // of numbers other // than 1, starting from 2. for (let i = 2; i <= n; i++) { // Subtract previous number // from current multiple. multiTerms = multiTerms - (i - 1); // For example, for 2, we get sum // as (2 + 3 + 4 + ....) * 2 sum = sum + multiTerms*i; } return sum; } let n = 5; document.write(findSum(n)); </script>",
"e": 7674,
"s": 6893,
"text": null
},
{
"code": null,
"e": 7678,
"s": 7674,
"text": "140"
},
{
"code": null,
"e": 8797,
"s": 7680,
"text": "Time Complexity: O(n).Method 3 (Efficient) The whole calculation can be done in the O(1) time as there is a closed-form expression for the sum. Let i and j run from 1 through n. We want to compute S = sum(i*j) overall i and j such that i <= j otherwise we would have duplicates such as 2*3 + ...+3*2; on the other hand, having i = j is OK which gives us 2*2 + ... This is all by the problem specification. (Sorry if my notation is bizarre.)Now, there are two kinds of terms in the sum S: those with i = j (squares, denoted S1) and those with i j always, but the value is the same, by symmetry: 2 * S2 = (sum i)^2 – sum (i^2) . Note that 2*S2 = S3 – S1 as the latter sum is just S1; the former sum (denoted S3) is new here, but there is a closed-form solution for it too. We can now eliminate the mixed term completely: S = S1 + S2 = (S1 + S3) / 2.Since sum(i) = n*(n+1)/2, we get S3 = n*n*(n+1)*(n+1)/4 ; likewise for the sum of squares: S1 = n*(2*n+1)*(n+1)/6. The final expression simplifies to: S = n*(n+1)*(n+2)*(3*n+1)/24 . (As an exercise, you may want to prove that the numerator is indeed divisible by 24.) "
},
{
"code": null,
"e": 8801,
"s": 8797,
"text": "C++"
},
{
"code": null,
"e": 8806,
"s": 8801,
"text": "Java"
},
{
"code": null,
"e": 8814,
"s": 8806,
"text": "Python3"
},
{
"code": null,
"e": 8817,
"s": 8814,
"text": "C#"
},
{
"code": null,
"e": 8821,
"s": 8817,
"text": "PHP"
},
{
"code": null,
"e": 8832,
"s": 8821,
"text": "Javascript"
},
{
"code": "// Efficient CPP program to find sum// of given series.#include <bits/stdc++.h>using namespace std; long long int findSum(int n){ return n*(n+1)*(n+2)*(3*n+1)/24;} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;}",
"e": 9075,
"s": 8832,
"text": null
},
{
"code": "// Efficient Java program to find sum// of given series.class GFG { static int findSum(int n) { return n * (n + 1) * (n + 2) * (3 * n + 1) / 24; } // Driver code public static void main(String[] args) { int n = 5; System.out.println(findSum(n)); }} // This code is contributed by Smitha Dinesh Semwal.",
"e": 9479,
"s": 9075,
"text": null
},
{
"code": "# Efficient Python3 program to find # sum of given series. def findSum(n): return n * (n + 1) * (n + 2) * (3 * n + 1) / 24 # Driver coden = 5print(int(findSum(n))) # This code is contributed by Smitha Dinesh Semwal.",
"e": 9699,
"s": 9479,
"text": null
},
{
"code": "// Efficient C# program// to find sum of given// series.using System; class GFG{static int findSum(int n){ return n * (n + 1) * (n + 2) * (3 * n + 1) / 24;} // Driver codestatic public void Main (){ int n = 5; Console.WriteLine(findSum(n));}} // This code is contributed// by ajit.",
"e": 10011,
"s": 9699,
"text": null
},
{
"code": "<?php// Efficient PHP// program to find sum// of given series. function findSum($n){ return $n * ($n + 1) * ($n + 2) * (3 * $n + 1) / 24;} // Driver code$n = 5;echo findSum($n); // This code is contributed// by akt_mit?>",
"e": 10255,
"s": 10011,
"text": null
},
{
"code": "<script> // Efficient Javascript program // to find sum of given // series. function findSum(n) { return n * (n + 1) * (n + 2) * (3 * n + 1) / 24; } let n = 5; document.write(findSum(n)); </script>",
"e": 10501,
"s": 10255,
"text": null
},
{
"code": null,
"e": 10505,
"s": 10501,
"text": "140"
},
{
"code": null,
"e": 10588,
"s": 10507,
"text": "Time Complexity: O(1).Thanks to diprey1 for suggesting this efficient solution. "
},
{
"code": null,
"e": 10594,
"s": 10588,
"text": "jit_t"
},
{
"code": null,
"e": 10607,
"s": 10594,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 10617,
"s": 10607,
"text": "Code_Mech"
},
{
"code": null,
"e": 10632,
"s": 10617,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 10646,
"s": 10632,
"text": "divyesh072019"
},
{
"code": null,
"e": 10664,
"s": 10646,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 10681,
"s": 10664,
"text": "surinderdawra388"
},
{
"code": null,
"e": 10688,
"s": 10681,
"text": "series"
},
{
"code": null,
"e": 10699,
"s": 10688,
"text": "series-sum"
},
{
"code": null,
"e": 10712,
"s": 10699,
"text": "Mathematical"
},
{
"code": null,
"e": 10725,
"s": 10712,
"text": "Mathematical"
},
{
"code": null,
"e": 10732,
"s": 10725,
"text": "series"
}
] |
Python – tensorflow.math.reduce_max() | 14 May, 2021
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks.
reduce_max() is used to find maximum of elements across dimensions of a tensor.
Syntax: tensorflow.math.reduce_max( input_tensor, axis, keepdims, name)
Parameters:
input_tensor: It is numeric tensor to reduce.
axis(optional): It represent the dimensions to reduce. It’s value should be in range [-rank(input_tensor), rank(input_tensor)). If no value is given for this all dimensions are reduced.
keepdims(optional): It’s default value is False. If it’s set to True it will retain the reduced dimension with length 1.
name(optional): It defines the name for the operation.
Returns: It returns a tensor.
Example 1:
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([1, 2, 3, 4], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_max(a) # Printing the resultprint('Result: ', res)
Output:
Input: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)
Result: tf.Tensor(4.0, shape=(), dtype=float64)
Example 2:
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_max(a, axis = 1, keepdims = True) # Printing the resultprint('Result: ', res)
Output:
Input: tf.Tensor(
[[1. 2.]
[3. 4.]], shape=(2, 2), dtype=float64)
Result: tf.Tensor(
[[2.]
[4.]], shape=(2, 1), dtype=float64)
surinderdawra388
Python Tensorflow-math-functions
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 159,
"s": 28,
"text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks."
},
{
"code": null,
"e": 239,
"s": 159,
"text": "reduce_max() is used to find maximum of elements across dimensions of a tensor."
},
{
"code": null,
"e": 311,
"s": 239,
"text": "Syntax: tensorflow.math.reduce_max( input_tensor, axis, keepdims, name)"
},
{
"code": null,
"e": 323,
"s": 311,
"text": "Parameters:"
},
{
"code": null,
"e": 369,
"s": 323,
"text": "input_tensor: It is numeric tensor to reduce."
},
{
"code": null,
"e": 556,
"s": 369,
"text": "axis(optional): It represent the dimensions to reduce. It’s value should be in range [-rank(input_tensor), rank(input_tensor)). If no value is given for this all dimensions are reduced."
},
{
"code": null,
"e": 677,
"s": 556,
"text": "keepdims(optional): It’s default value is False. If it’s set to True it will retain the reduced dimension with length 1."
},
{
"code": null,
"e": 732,
"s": 677,
"text": "name(optional): It defines the name for the operation."
},
{
"code": null,
"e": 762,
"s": 732,
"text": "Returns: It returns a tensor."
},
{
"code": null,
"e": 773,
"s": 762,
"text": "Example 1:"
},
{
"code": null,
"e": 781,
"s": 773,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([1, 2, 3, 4], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_max(a) # Printing the resultprint('Result: ', res)",
"e": 1048,
"s": 781,
"text": null
},
{
"code": null,
"e": 1056,
"s": 1048,
"text": "Output:"
},
{
"code": null,
"e": 1166,
"s": 1056,
"text": "Input: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)\nResult: tf.Tensor(4.0, shape=(), dtype=float64)"
},
{
"code": null,
"e": 1177,
"s": 1166,
"text": "Example 2:"
},
{
"code": null,
"e": 1185,
"s": 1177,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_max(a, axis = 1, keepdims = True) # Printing the resultprint('Result: ', res)",
"e": 1483,
"s": 1185,
"text": null
},
{
"code": null,
"e": 1491,
"s": 1483,
"text": "Output:"
},
{
"code": null,
"e": 1622,
"s": 1491,
"text": "Input: tf.Tensor(\n[[1. 2.]\n [3. 4.]], shape=(2, 2), dtype=float64)\nResult: tf.Tensor(\n[[2.]\n [4.]], shape=(2, 1), dtype=float64)"
},
{
"code": null,
"e": 1639,
"s": 1622,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1672,
"s": 1639,
"text": "Python Tensorflow-math-functions"
},
{
"code": null,
"e": 1690,
"s": 1672,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 1697,
"s": 1690,
"text": "Python"
}
] |
Count Occurrences of a Given Character using Regex in Java | 15 Nov, 2021
Given a string and a character, the task is to make a function that counts the occurrence of the given character in the string using Regex.
Examples:
Input: str = "geeksforgeeks", c = 'e'
Output: 4
'e' appears four times in str.
Input: str = "abccdefgaa", c = 'a'
Output: 3
'a' appears three times in str.
Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package.
Get the String in which it is to be matched
Find all occurrences of the given character using Matcher.find() function (in Java)
For each found occurrence, increment the counter by 1
Below is the implementation of the above approach:
Java
// Java program to count occurrences// of a character using Regex import java.util.regex.*; class GFG { // Method that returns the count of the given // character in the string public static long count(String s, char ch) { // Use Matcher class of java.util.regex // to match the character Matcher matcher = Pattern.compile(String.valueOf(ch)) .matcher(s); int res = 0; // for every presence of character ch // increment the counter res by 1 while (matcher.find()) { res++; } return res; } // Driver method public static void main(String args[]) { String str = "geeksforgeeks"; char c = 'e'; System.out.println("The occurrence of " + c + " in " + str + " is " + count(str, c)); }}
The occurrence of e in geeksforgeeks is 4
Related Article:
Program to count the occurrence of a given character in a string
Count occurrence of a given character in a string using Stream API in Java
nishkarshgandhi
gabaa406
java-regular-expression
Java-String-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 193,
"s": 53,
"text": "Given a string and a character, the task is to make a function that counts the occurrence of the given character in the string using Regex."
},
{
"code": null,
"e": 203,
"s": 193,
"text": "Examples:"
},
{
"code": null,
"e": 361,
"s": 203,
"text": "Input: str = \"geeksforgeeks\", c = 'e'\nOutput: 4\n'e' appears four times in str.\n\nInput: str = \"abccdefgaa\", c = 'a' \nOutput: 3\n'a' appears three times in str."
},
{
"code": null,
"e": 682,
"s": 361,
"text": "Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package. "
},
{
"code": null,
"e": 726,
"s": 682,
"text": "Get the String in which it is to be matched"
},
{
"code": null,
"e": 810,
"s": 726,
"text": "Find all occurrences of the given character using Matcher.find() function (in Java)"
},
{
"code": null,
"e": 864,
"s": 810,
"text": "For each found occurrence, increment the counter by 1"
},
{
"code": null,
"e": 915,
"s": 864,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 920,
"s": 915,
"text": "Java"
},
{
"code": "// Java program to count occurrences// of a character using Regex import java.util.regex.*; class GFG { // Method that returns the count of the given // character in the string public static long count(String s, char ch) { // Use Matcher class of java.util.regex // to match the character Matcher matcher = Pattern.compile(String.valueOf(ch)) .matcher(s); int res = 0; // for every presence of character ch // increment the counter res by 1 while (matcher.find()) { res++; } return res; } // Driver method public static void main(String args[]) { String str = \"geeksforgeeks\"; char c = 'e'; System.out.println(\"The occurrence of \" + c + \" in \" + str + \" is \" + count(str, c)); }}",
"e": 1790,
"s": 920,
"text": null
},
{
"code": null,
"e": 1832,
"s": 1790,
"text": "The occurrence of e in geeksforgeeks is 4"
},
{
"code": null,
"e": 1850,
"s": 1832,
"text": "Related Article: "
},
{
"code": null,
"e": 1915,
"s": 1850,
"text": "Program to count the occurrence of a given character in a string"
},
{
"code": null,
"e": 1990,
"s": 1915,
"text": "Count occurrence of a given character in a string using Stream API in Java"
},
{
"code": null,
"e": 2006,
"s": 1990,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 2015,
"s": 2006,
"text": "gabaa406"
},
{
"code": null,
"e": 2039,
"s": 2015,
"text": "java-regular-expression"
},
{
"code": null,
"e": 2060,
"s": 2039,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 2065,
"s": 2060,
"text": "Java"
},
{
"code": null,
"e": 2079,
"s": 2065,
"text": "Java Programs"
},
{
"code": null,
"e": 2084,
"s": 2079,
"text": "Java"
}
] |
Python | Return new list on element insertion | 28 Jan, 2019
The usual append method adds the new element in the original sequence and does not return any value. But sometimes we require to have a new list each time we add a new element to the list. This kind of problem is common in web development. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using + operatorThis task can be performed if we make a single element list and concatenate original list with this newly made single element list.
# Python3 code to demonstrate # returning new list on element insertion# using + operator # initializing listtest_list = [5, 6, 2, 3, 9] # printing original listprint ("The original list is : " + str(test_list)) # element to add K = 10 # using + operator# returning new list on element insertionres = test_list + [K] # printing result print ("The newly returned added list : " + str(res))
Output :
The original list is : [5, 6, 2, 3, 9]
The newly returned added list : [5, 6, 2, 3, 9, 10]
Method #2 : Using * operatorSimilar kind of task can be used using * operator in which we use * operator to take all the elements and also add the new element to output the new list.
# Python3 code to demonstrate # returning new list on element insertion# using * operator # initializing listtest_list = [5, 6, 2, 3, 9] # printing original listprint ("The original list is : " + str(test_list)) # element to add K = 10 # using * operator# returning new list on element insertionres = [*test_list, K] # printing result print ("The newly returned added list : " + str(res))
Output :
The original list is : [5, 6, 2, 3, 9]
The newly returned added list : [5, 6, 2, 3, 9, 10]
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "The usual append method adds the new element in the original sequence and does not return any value. But sometimes we require to have a new list each time we add a new element to the list. This kind of problem is common in web development. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 492,
"s": 332,
"text": "Method #1 : Using + operatorThis task can be performed if we make a single element list and concatenate original list with this newly made single element list."
},
{
"code": "# Python3 code to demonstrate # returning new list on element insertion# using + operator # initializing listtest_list = [5, 6, 2, 3, 9] # printing original listprint (\"The original list is : \" + str(test_list)) # element to add K = 10 # using + operator# returning new list on element insertionres = test_list + [K] # printing result print (\"The newly returned added list : \" + str(res))",
"e": 887,
"s": 492,
"text": null
},
{
"code": null,
"e": 896,
"s": 887,
"text": "Output :"
},
{
"code": null,
"e": 988,
"s": 896,
"text": "The original list is : [5, 6, 2, 3, 9]\nThe newly returned added list : [5, 6, 2, 3, 9, 10]\n"
},
{
"code": null,
"e": 1172,
"s": 988,
"text": " Method #2 : Using * operatorSimilar kind of task can be used using * operator in which we use * operator to take all the elements and also add the new element to output the new list."
},
{
"code": "# Python3 code to demonstrate # returning new list on element insertion# using * operator # initializing listtest_list = [5, 6, 2, 3, 9] # printing original listprint (\"The original list is : \" + str(test_list)) # element to add K = 10 # using * operator# returning new list on element insertionres = [*test_list, K] # printing result print (\"The newly returned added list : \" + str(res))",
"e": 1567,
"s": 1172,
"text": null
},
{
"code": null,
"e": 1576,
"s": 1567,
"text": "Output :"
},
{
"code": null,
"e": 1668,
"s": 1576,
"text": "The original list is : [5, 6, 2, 3, 9]\nThe newly returned added list : [5, 6, 2, 3, 9, 10]\n"
},
{
"code": null,
"e": 1689,
"s": 1668,
"text": "Python list-programs"
},
{
"code": null,
"e": 1701,
"s": 1689,
"text": "python-list"
},
{
"code": null,
"e": 1708,
"s": 1701,
"text": "Python"
},
{
"code": null,
"e": 1724,
"s": 1708,
"text": "Python Programs"
},
{
"code": null,
"e": 1736,
"s": 1724,
"text": "python-list"
}
] |
How to clear previous appended data on change the dropdown menu in JavaScript ? | 22 Nov, 2019
To clear the previously appended data on change the drop-down is carried out by using jQuery. Appended data must be cleared on change or on toggling the drop-down menu, otherwise previously appended data append with current menu item data. To avoid this issue, jQuery or JavaScript is implemented with help of add(), remove(), addClass(), and removeClass() methods.
The Following Approaches will explain clearly:
Approach 1: Initially use removeClass() method to remove active class of previously appended data menu item. Then followed by addClass() method to add active class of currently appended data menu item. Now use each() function to append data with respect active class added or removed on click.
Example: Below Alert choosing example illustrate to clear the previously appended data on change the drop-down using remove(), add() methods.<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="pt-3 text-success font-weight-bold text-center"> GeeksforGeeks </h1> <div class="m-3 dropdown"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> Alert Menu </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Success</a> <a class="dropdown-item" href="#">Warning</a> <a class="dropdown-item" href="#">Danger</a> </div> </div> <p id="alert" class="alert alert-dismissible"> <button type="button" class="close" data-dismiss="alert">× </button><i id="demo"></i> Alert ! ...</p> </div> <script> $("a").click(function() { // removeClass active of previously selected menu item $('a.dropdown-item.active').removeClass("active"); // Add class active to current selected menu item $(this).addClass("active"); // Getting text from within selected elements var msg = $('a.dropdown-item.active').text(); // If condition to check selected alert message if (msg == "Success") { $("#alert").removeClass("alert-warning"); $("#alert").removeClass("alert-danger"); $("#alert").addClass("alert-success"); } else if (msg == "Warning") { $("#alert").removeClass("alert-success"); $("#alert").removeClass("alert-danger"); $("#alert").addClass("alert-warning"); } else { $("#alert").removeClass("alert-success"); $("#alert").removeClass("alert-warning"); $("#alert").addClass("alert-danger"); } var str = ""; $(".active").each(function() { // Using html() to append html data str += $(this).html() + " "; }); $("#demo").html(str); }).click(); </script></body> </html>
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="pt-3 text-success font-weight-bold text-center"> GeeksforGeeks </h1> <div class="m-3 dropdown"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> Alert Menu </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Success</a> <a class="dropdown-item" href="#">Warning</a> <a class="dropdown-item" href="#">Danger</a> </div> </div> <p id="alert" class="alert alert-dismissible"> <button type="button" class="close" data-dismiss="alert">× </button><i id="demo"></i> Alert ! ...</p> </div> <script> $("a").click(function() { // removeClass active of previously selected menu item $('a.dropdown-item.active').removeClass("active"); // Add class active to current selected menu item $(this).addClass("active"); // Getting text from within selected elements var msg = $('a.dropdown-item.active').text(); // If condition to check selected alert message if (msg == "Success") { $("#alert").removeClass("alert-warning"); $("#alert").removeClass("alert-danger"); $("#alert").addClass("alert-success"); } else if (msg == "Warning") { $("#alert").removeClass("alert-success"); $("#alert").removeClass("alert-danger"); $("#alert").addClass("alert-warning"); } else { $("#alert").removeClass("alert-success"); $("#alert").removeClass("alert-warning"); $("#alert").addClass("alert-danger"); } var str = ""; $(".active").each(function() { // Using html() to append html data str += $(this).html() + " "; }); $("#demo").html(str); }).click(); </script></body> </html>
Output:
Approach 2: Initially use for loop remove active class of previously appended data menu item, here loop condition based on length of item listed with help of remove() method. Then followed by add() method to add active class of currently appended data menu item listed. Now use each() function to append data with respect to active class added or removed while toggling listed items.
Example: Below active courses selection example illustrate to clear the previously appended data onchange the dropdown using addClass(), removeClass() methods.<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="pt-3 text-success font-weight-bold text-center"> GeeksforGeeks </h1> <div class="m-3 dropdown"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> Active Courses Menu </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#"> JAVA Backend Development </a> <a class="dropdown-item" href="#"> DSA Foundation </a> <a class="dropdown-item" href="#"> GEEK Class </a> <a class="dropdown-item" href="#"> Machine Learning Foundation With Python & AI </a> <a class="dropdown-item" href="#"> Competitive Programming </a> </div> </div> <div class="card"> <div class="card-header bg-primary text-light"> Selected Courses</div> <div class="card-body p-3 bg-light text-dark border border-primary"> <h4 id="demo"></h4> </div> <div class="card-footer bg-primary text-light"> Available @ GeeksforGeeks </div> </div> </div> <script> $(".dropdown-item").click(function() { // Select all list items var dropItems = $(".dropdown-item"); var str = ""; // Remove 'active' tag for all list items // based on iteration for (let i = 0; i < dropItems.length; i++) { dropItems[i].classList.remove("active"); } // Add 'active' tag for currently selected item this.classList.add("active"); $(".active").each(function() { // Using text() to append text data str += $(this).text() + " "; }); $("#demo").text(str); }); </script></body> </html>
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="pt-3 text-success font-weight-bold text-center"> GeeksforGeeks </h1> <div class="m-3 dropdown"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> Active Courses Menu </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#"> JAVA Backend Development </a> <a class="dropdown-item" href="#"> DSA Foundation </a> <a class="dropdown-item" href="#"> GEEK Class </a> <a class="dropdown-item" href="#"> Machine Learning Foundation With Python & AI </a> <a class="dropdown-item" href="#"> Competitive Programming </a> </div> </div> <div class="card"> <div class="card-header bg-primary text-light"> Selected Courses</div> <div class="card-body p-3 bg-light text-dark border border-primary"> <h4 id="demo"></h4> </div> <div class="card-footer bg-primary text-light"> Available @ GeeksforGeeks </div> </div> </div> <script> $(".dropdown-item").click(function() { // Select all list items var dropItems = $(".dropdown-item"); var str = ""; // Remove 'active' tag for all list items // based on iteration for (let i = 0; i < dropItems.length; i++) { dropItems[i].classList.remove("active"); } // Add 'active' tag for currently selected item this.classList.add("active"); $(".active").each(function() { // Using text() to append text data str += $(this).text() + " "; }); $("#demo").text(str); }); </script></body> </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
jQuery-Misc
Picked
Bootstrap
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2019"
},
{
"code": null,
"e": 394,
"s": 28,
"text": "To clear the previously appended data on change the drop-down is carried out by using jQuery. Appended data must be cleared on change or on toggling the drop-down menu, otherwise previously appended data append with current menu item data. To avoid this issue, jQuery or JavaScript is implemented with help of add(), remove(), addClass(), and removeClass() methods."
},
{
"code": null,
"e": 441,
"s": 394,
"text": "The Following Approaches will explain clearly:"
},
{
"code": null,
"e": 735,
"s": 441,
"text": "Approach 1: Initially use removeClass() method to remove active class of previously appended data menu item. Then followed by addClass() method to add active class of currently appended data menu item. Now use each() function to append data with respect active class added or removed on click."
},
{
"code": null,
"e": 3549,
"s": 735,
"text": "Example: Below Alert choosing example illustrate to clear the previously appended data on change the drop-down using remove(), add() methods.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"pt-3 text-success font-weight-bold text-center\"> GeeksforGeeks </h1> <div class=\"m-3 dropdown\"> <button type=\"button\" class=\"btn btn-primary dropdown-toggle\" data-toggle=\"dropdown\"> Alert Menu </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Success</a> <a class=\"dropdown-item\" href=\"#\">Warning</a> <a class=\"dropdown-item\" href=\"#\">Danger</a> </div> </div> <p id=\"alert\" class=\"alert alert-dismissible\"> <button type=\"button\" class=\"close\" data-dismiss=\"alert\">× </button><i id=\"demo\"></i> Alert ! ...</p> </div> <script> $(\"a\").click(function() { // removeClass active of previously selected menu item $('a.dropdown-item.active').removeClass(\"active\"); // Add class active to current selected menu item $(this).addClass(\"active\"); // Getting text from within selected elements var msg = $('a.dropdown-item.active').text(); // If condition to check selected alert message if (msg == \"Success\") { $(\"#alert\").removeClass(\"alert-warning\"); $(\"#alert\").removeClass(\"alert-danger\"); $(\"#alert\").addClass(\"alert-success\"); } else if (msg == \"Warning\") { $(\"#alert\").removeClass(\"alert-success\"); $(\"#alert\").removeClass(\"alert-danger\"); $(\"#alert\").addClass(\"alert-warning\"); } else { $(\"#alert\").removeClass(\"alert-success\"); $(\"#alert\").removeClass(\"alert-warning\"); $(\"#alert\").addClass(\"alert-danger\"); } var str = \"\"; $(\".active\").each(function() { // Using html() to append html data str += $(this).html() + \" \"; }); $(\"#demo\").html(str); }).click(); </script></body> </html>"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"pt-3 text-success font-weight-bold text-center\"> GeeksforGeeks </h1> <div class=\"m-3 dropdown\"> <button type=\"button\" class=\"btn btn-primary dropdown-toggle\" data-toggle=\"dropdown\"> Alert Menu </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Success</a> <a class=\"dropdown-item\" href=\"#\">Warning</a> <a class=\"dropdown-item\" href=\"#\">Danger</a> </div> </div> <p id=\"alert\" class=\"alert alert-dismissible\"> <button type=\"button\" class=\"close\" data-dismiss=\"alert\">× </button><i id=\"demo\"></i> Alert ! ...</p> </div> <script> $(\"a\").click(function() { // removeClass active of previously selected menu item $('a.dropdown-item.active').removeClass(\"active\"); // Add class active to current selected menu item $(this).addClass(\"active\"); // Getting text from within selected elements var msg = $('a.dropdown-item.active').text(); // If condition to check selected alert message if (msg == \"Success\") { $(\"#alert\").removeClass(\"alert-warning\"); $(\"#alert\").removeClass(\"alert-danger\"); $(\"#alert\").addClass(\"alert-success\"); } else if (msg == \"Warning\") { $(\"#alert\").removeClass(\"alert-success\"); $(\"#alert\").removeClass(\"alert-danger\"); $(\"#alert\").addClass(\"alert-warning\"); } else { $(\"#alert\").removeClass(\"alert-success\"); $(\"#alert\").removeClass(\"alert-warning\"); $(\"#alert\").addClass(\"alert-danger\"); } var str = \"\"; $(\".active\").each(function() { // Using html() to append html data str += $(this).html() + \" \"; }); $(\"#demo\").html(str); }).click(); </script></body> </html>",
"e": 6222,
"s": 3549,
"text": null
},
{
"code": null,
"e": 6230,
"s": 6222,
"text": "Output:"
},
{
"code": null,
"e": 6614,
"s": 6230,
"text": "Approach 2: Initially use for loop remove active class of previously appended data menu item, here loop condition based on length of item listed with help of remove() method. Then followed by add() method to add active class of currently appended data menu item listed. Now use each() function to append data with respect to active class added or removed while toggling listed items."
},
{
"code": null,
"e": 9471,
"s": 6614,
"text": "Example: Below active courses selection example illustrate to clear the previously appended data onchange the dropdown using addClass(), removeClass() methods.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"pt-3 text-success font-weight-bold text-center\"> GeeksforGeeks </h1> <div class=\"m-3 dropdown\"> <button type=\"button\" class=\"btn btn-primary dropdown-toggle\" data-toggle=\"dropdown\"> Active Courses Menu </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\"> JAVA Backend Development </a> <a class=\"dropdown-item\" href=\"#\"> DSA Foundation </a> <a class=\"dropdown-item\" href=\"#\"> GEEK Class </a> <a class=\"dropdown-item\" href=\"#\"> Machine Learning Foundation With Python & AI </a> <a class=\"dropdown-item\" href=\"#\"> Competitive Programming </a> </div> </div> <div class=\"card\"> <div class=\"card-header bg-primary text-light\"> Selected Courses</div> <div class=\"card-body p-3 bg-light text-dark border border-primary\"> <h4 id=\"demo\"></h4> </div> <div class=\"card-footer bg-primary text-light\"> Available @ GeeksforGeeks </div> </div> </div> <script> $(\".dropdown-item\").click(function() { // Select all list items var dropItems = $(\".dropdown-item\"); var str = \"\"; // Remove 'active' tag for all list items // based on iteration for (let i = 0; i < dropItems.length; i++) { dropItems[i].classList.remove(\"active\"); } // Add 'active' tag for currently selected item this.classList.add(\"active\"); $(\".active\").each(function() { // Using text() to append text data str += $(this).text() + \" \"; }); $(\"#demo\").text(str); }); </script></body> </html>"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"pt-3 text-success font-weight-bold text-center\"> GeeksforGeeks </h1> <div class=\"m-3 dropdown\"> <button type=\"button\" class=\"btn btn-primary dropdown-toggle\" data-toggle=\"dropdown\"> Active Courses Menu </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\"> JAVA Backend Development </a> <a class=\"dropdown-item\" href=\"#\"> DSA Foundation </a> <a class=\"dropdown-item\" href=\"#\"> GEEK Class </a> <a class=\"dropdown-item\" href=\"#\"> Machine Learning Foundation With Python & AI </a> <a class=\"dropdown-item\" href=\"#\"> Competitive Programming </a> </div> </div> <div class=\"card\"> <div class=\"card-header bg-primary text-light\"> Selected Courses</div> <div class=\"card-body p-3 bg-light text-dark border border-primary\"> <h4 id=\"demo\"></h4> </div> <div class=\"card-footer bg-primary text-light\"> Available @ GeeksforGeeks </div> </div> </div> <script> $(\".dropdown-item\").click(function() { // Select all list items var dropItems = $(\".dropdown-item\"); var str = \"\"; // Remove 'active' tag for all list items // based on iteration for (let i = 0; i < dropItems.length; i++) { dropItems[i].classList.remove(\"active\"); } // Add 'active' tag for currently selected item this.classList.add(\"active\"); $(\".active\").each(function() { // Using text() to append text data str += $(this).text() + \" \"; }); $(\"#demo\").text(str); }); </script></body> </html>",
"e": 12169,
"s": 9471,
"text": null
},
{
"code": null,
"e": 12177,
"s": 12169,
"text": "Output:"
},
{
"code": null,
"e": 12186,
"s": 12177,
"text": "CSS-Misc"
},
{
"code": null,
"e": 12196,
"s": 12186,
"text": "HTML-Misc"
},
{
"code": null,
"e": 12212,
"s": 12196,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 12224,
"s": 12212,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 12231,
"s": 12224,
"text": "Picked"
},
{
"code": null,
"e": 12241,
"s": 12231,
"text": "Bootstrap"
},
{
"code": null,
"e": 12248,
"s": 12241,
"text": "JQuery"
},
{
"code": null,
"e": 12265,
"s": 12248,
"text": "Web Technologies"
},
{
"code": null,
"e": 12292,
"s": 12265,
"text": "Web technologies Questions"
}
] |
String Constant Pool in Java | 21 Jun, 2020
Consider the following two Java programs, the first program produces output as “Yes”, but the second program produces output “No”. Can you guess the reason?
// Program 1: Comparing two references to objects// created using literals.import java.util.*; class GFG { public static void main(String[] args) { String s1 = "abc"; String s2 = "abc"; // Note that this == compares whether // s1 and s2 refer to same object or not if (s1 == s2) System.out.println("Yes"); else System.out.println("No"); }}
Yes
// Program 2: Comparing two references to objects// created using new operator.import java.util.*; class GFG { public static void main(String[] args) { String s1 = new String("abc"); String s2 = new String("abc"); // Note that this == compares whether // s1 and s2 refer to same object or not if (s1 == s2) System.out.println("Yes"); else System.out.println("No"); }}
No
Let us understand why we get different output with below explanation.
String is a sequence of characters. One of the most important characteristics of a string in Java is that they are immutable. In other words, once created, the internal state of a string remains the same throughout the execution of the program. This immutability is achieved through the use of a special string constant pool in the heap. In this article, we will understand about the storage of the strings.
A string constant pool is a separate place in the heap memory where the values of all the strings which are defined in the program are stored. When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap. On standard assignment of a value to a string variable, the variable is allocated stack, while the value is stored in the heap in the string constant pool. For example, let’s assign some value to a string str1. In java, a string is defined and the value is assigned as:
String str1 = "Hello";
The following illustration explains the memory allocation for the above declaration:
In the above scenario, a string object is created in the stack, and the value “Hello” is created and stored in the heap. Since we have normally assigned the value, it is stored in the constant pool area of the heap. A pointer points towards the value stored in the heap from the object in the stack. Now, let’s take the same example with multiple string variables having the same value as follows:
String str1 = "Hello";
String str2 = "Hello";
The following illustration explains the memory allocation for the above declaration:
In this case, both the string objects get created in the stack, but another instance of the value “Hello” is not created in the heap. Instead, the previous instance of “Hello” is re-used. The string constant pool is a small cache that resides within the heap. Java stores all the values inside the string constant pool on direct allocation. This way, if a similar value needs to be accessed again, a new string object created in the stack can reference it directly with the help of a pointer. In other words, the string constant pool exists mainly to reduce memory usage and improve the re-use of existing instances in memory. When a string object is assigned a different value, the new value will be registered in the string constant pool as a separate instance. Lets understand this with the following example:
String str1 = "Hello";
String str2 = "Hello";
String str3 = "Class";
The following illustration explains the memory allocation for the above declaration:
One way to skip this memory allocation is to use the new keyword while creating a new string object. The ‘new’ keyword forces a new instance to always be created regardless of whether the same value was used previously or not. Using ‘new’ forces the instance to be created in the heap outside the string constant pool which is clear, since caching and re-using of instances isn’t allowed here. Let’s understand this with an example:
String str1 = new String("John");
String str2 = new String("Doe");
The following illustration explains the memory allocation for the above declaration:
Java-Strings
Java
Strings
Java-Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Jun, 2020"
},
{
"code": null,
"e": 210,
"s": 53,
"text": "Consider the following two Java programs, the first program produces output as “Yes”, but the second program produces output “No”. Can you guess the reason?"
},
{
"code": "// Program 1: Comparing two references to objects// created using literals.import java.util.*; class GFG { public static void main(String[] args) { String s1 = \"abc\"; String s2 = \"abc\"; // Note that this == compares whether // s1 and s2 refer to same object or not if (s1 == s2) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 624,
"s": 210,
"text": null
},
{
"code": null,
"e": 629,
"s": 624,
"text": "Yes\n"
},
{
"code": "// Program 2: Comparing two references to objects// created using new operator.import java.util.*; class GFG { public static void main(String[] args) { String s1 = new String(\"abc\"); String s2 = new String(\"abc\"); // Note that this == compares whether // s1 and s2 refer to same object or not if (s1 == s2) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 1071,
"s": 629,
"text": null
},
{
"code": null,
"e": 1075,
"s": 1071,
"text": "No\n"
},
{
"code": null,
"e": 1145,
"s": 1075,
"text": "Let us understand why we get different output with below explanation."
},
{
"code": null,
"e": 1553,
"s": 1145,
"text": "String is a sequence of characters. One of the most important characteristics of a string in Java is that they are immutable. In other words, once created, the internal state of a string remains the same throughout the execution of the program. This immutability is achieved through the use of a special string constant pool in the heap. In this article, we will understand about the storage of the strings."
},
{
"code": null,
"e": 2113,
"s": 1553,
"text": "A string constant pool is a separate place in the heap memory where the values of all the strings which are defined in the program are stored. When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap. On standard assignment of a value to a string variable, the variable is allocated stack, while the value is stored in the heap in the string constant pool. For example, let’s assign some value to a string str1. In java, a string is defined and the value is assigned as:"
},
{
"code": null,
"e": 2137,
"s": 2113,
"text": "String str1 = \"Hello\";\n"
},
{
"code": null,
"e": 2222,
"s": 2137,
"text": "The following illustration explains the memory allocation for the above declaration:"
},
{
"code": null,
"e": 2620,
"s": 2222,
"text": "In the above scenario, a string object is created in the stack, and the value “Hello” is created and stored in the heap. Since we have normally assigned the value, it is stored in the constant pool area of the heap. A pointer points towards the value stored in the heap from the object in the stack. Now, let’s take the same example with multiple string variables having the same value as follows:"
},
{
"code": null,
"e": 2667,
"s": 2620,
"text": "String str1 = \"Hello\";\nString str2 = \"Hello\";\n"
},
{
"code": null,
"e": 2752,
"s": 2667,
"text": "The following illustration explains the memory allocation for the above declaration:"
},
{
"code": null,
"e": 3565,
"s": 2752,
"text": "In this case, both the string objects get created in the stack, but another instance of the value “Hello” is not created in the heap. Instead, the previous instance of “Hello” is re-used. The string constant pool is a small cache that resides within the heap. Java stores all the values inside the string constant pool on direct allocation. This way, if a similar value needs to be accessed again, a new string object created in the stack can reference it directly with the help of a pointer. In other words, the string constant pool exists mainly to reduce memory usage and improve the re-use of existing instances in memory. When a string object is assigned a different value, the new value will be registered in the string constant pool as a separate instance. Lets understand this with the following example:"
},
{
"code": null,
"e": 3635,
"s": 3565,
"text": "String str1 = \"Hello\";\nString str2 = \"Hello\";\nString str3 = \"Class\";\n"
},
{
"code": null,
"e": 3720,
"s": 3635,
"text": "The following illustration explains the memory allocation for the above declaration:"
},
{
"code": null,
"e": 4153,
"s": 3720,
"text": "One way to skip this memory allocation is to use the new keyword while creating a new string object. The ‘new’ keyword forces a new instance to always be created regardless of whether the same value was used previously or not. Using ‘new’ forces the instance to be created in the heap outside the string constant pool which is clear, since caching and re-using of instances isn’t allowed here. Let’s understand this with an example:"
},
{
"code": null,
"e": 4221,
"s": 4153,
"text": "String str1 = new String(\"John\");\nString str2 = new String(\"Doe\");\n"
},
{
"code": null,
"e": 4306,
"s": 4221,
"text": "The following illustration explains the memory allocation for the above declaration:"
},
{
"code": null,
"e": 4319,
"s": 4306,
"text": "Java-Strings"
},
{
"code": null,
"e": 4324,
"s": 4319,
"text": "Java"
},
{
"code": null,
"e": 4332,
"s": 4324,
"text": "Strings"
},
{
"code": null,
"e": 4345,
"s": 4332,
"text": "Java-Strings"
},
{
"code": null,
"e": 4353,
"s": 4345,
"text": "Strings"
},
{
"code": null,
"e": 4358,
"s": 4353,
"text": "Java"
}
] |
Sort mixed list in Python | 11 May, 2020
Sometimes, while working with Python, we can have a problem in which we need to sort a particular list which has mixed data types. That it contains integers and strings and we need to sort each of them accordingly. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using sort() + comparator
This problem can be solved using sort functionality provided by Python. We can construct our own custom comparator to complete the task of mixed sort.
# Python3 code to demonstrate working of# Sort Mixed List# using sort() + comparator # comparator function for sortdef mixs(num): try: ele = int(num) return (0, ele, '') except ValueError: return (1, num, '') # initialize list test_list = [4, 'gfg', 2, 'best', 'is', 3] # printing original list print("The original list : " + str(test_list)) # Sort Mixed List# using sort() + comparatortest_list.sort(key = mixs) # printing resultprint("List after mixed sorting : " + str(test_list))
The original list : [4, 'gfg', 2, 'best', 'is', 3]
List after mixed sorting : [2, 3, 4, 'best', 'gfg', 'is']
Method #2 : Using sorted() + key + lambda + isdigit()
The combination of above functionalities can also be used to achieve solution to this problem. In this, we just sort the list using sorted() using key functionality using lambda function to segregate digits using isdigit().
# Python3 code to demonstrate working of# Sort Mixed List# using sorted() + key + lambda + isdigit() # initialize list test_list = ['4', 'gfg', '2', 'best', 'is', '3'] # printing original list print("The original list : " + str(test_list)) # Sort Mixed List# using sorted() + key + lambda + isdigit()res = sorted(test_list, key = lambda ele: (0, int(ele)) if ele.isdigit() else (1, ele)) # printing resultprint("List after mixed sorting : " + str(res))
The original list : ['4', 'gfg', '2', 'best', 'is', '3']
List after mixed sorting : ['2', '3', '4', 'best', 'gfg', 'is']
Python list-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 307,
"s": 28,
"text": "Sometimes, while working with Python, we can have a problem in which we need to sort a particular list which has mixed data types. That it contains integers and strings and we need to sort each of them accordingly. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 345,
"s": 307,
"text": "Method #1 : Using sort() + comparator"
},
{
"code": null,
"e": 496,
"s": 345,
"text": "This problem can be solved using sort functionality provided by Python. We can construct our own custom comparator to complete the task of mixed sort."
},
{
"code": "# Python3 code to demonstrate working of# Sort Mixed List# using sort() + comparator # comparator function for sortdef mixs(num): try: ele = int(num) return (0, ele, '') except ValueError: return (1, num, '') # initialize list test_list = [4, 'gfg', 2, 'best', 'is', 3] # printing original list print(\"The original list : \" + str(test_list)) # Sort Mixed List# using sort() + comparatortest_list.sort(key = mixs) # printing resultprint(\"List after mixed sorting : \" + str(test_list))",
"e": 1014,
"s": 496,
"text": null
},
{
"code": null,
"e": 1124,
"s": 1014,
"text": "The original list : [4, 'gfg', 2, 'best', 'is', 3]\nList after mixed sorting : [2, 3, 4, 'best', 'gfg', 'is']\n"
},
{
"code": null,
"e": 1180,
"s": 1126,
"text": "Method #2 : Using sorted() + key + lambda + isdigit()"
},
{
"code": null,
"e": 1404,
"s": 1180,
"text": "The combination of above functionalities can also be used to achieve solution to this problem. In this, we just sort the list using sorted() using key functionality using lambda function to segregate digits using isdigit()."
},
{
"code": "# Python3 code to demonstrate working of# Sort Mixed List# using sorted() + key + lambda + isdigit() # initialize list test_list = ['4', 'gfg', '2', 'best', 'is', '3'] # printing original list print(\"The original list : \" + str(test_list)) # Sort Mixed List# using sorted() + key + lambda + isdigit()res = sorted(test_list, key = lambda ele: (0, int(ele)) if ele.isdigit() else (1, ele)) # printing resultprint(\"List after mixed sorting : \" + str(res))",
"e": 1884,
"s": 1404,
"text": null
},
{
"code": null,
"e": 2006,
"s": 1884,
"text": "The original list : ['4', 'gfg', '2', 'best', 'is', '3']\nList after mixed sorting : ['2', '3', '4', 'best', 'gfg', 'is']\n"
},
{
"code": null,
"e": 2027,
"s": 2006,
"text": "Python list-programs"
},
{
"code": null,
"e": 2039,
"s": 2027,
"text": "Python-sort"
},
{
"code": null,
"e": 2046,
"s": 2039,
"text": "Python"
},
{
"code": null,
"e": 2062,
"s": 2046,
"text": "Python Programs"
}
] |
Unused local variable in Python | 01 Oct, 2020
A variable defined inside a function block or a looping block loses its scope outside that block is called ad local variable to that block. A local variable cannot be accessed outside the block it is defined.
Example:
Python3
# simple display functiondef func(num): # local variable a = num print("The number is :", str(a)) func(10) # generates errorprint(a)
Output:
NameError: name 'a' is not defined
Here we get an error because ‘a’ is local to the function func() and it loses its scope outside that block. Here the local variable ‘a’ is used to hold the number passed and it is utilized in the printing statement. But in some cases, the local variables wl be declared by assigning some value and left utilized for any process. Just assigning some value is not utilizing the variable, the value in it must be read and used for some computation.
Garbage collection is automatic in Python and when the reference count of an object comes to zero the object will be cleared. We all know that a variable local to a certain block of code loses its scope outside the block. The garbage collection is automatically invoked when the difference between the allocation of objects and the deallocation of objects crosses a certain threshold value. If the script is a few lines of code, then memory management is not a tedious process. If the script is very long with complex tasks and there are many unused local variables, it has a considerable effect on the code execution time and memory management. However, issues with memory management are very less.
The main issue that arises due to these unused variables is it decreases readability. When the code is thousands of lines, when another programmer is required to work with it, he may have to spend a long time analyzing what for the variable is used which is actually left unused. One may forget the unused variable declared and may use it in the later part which can result in undesirable output. It is always good practice to remove the unused local variables.
A code with many unused local variables, unused imports, or unused line of codes is considered to be dead code. When there are situations where you are ambiguous that a local variable may have a role later in the code, then there are some naming conventions that can be used to distinguish it from the rest of the variables. Naming the variable as ‘dummy’, ‘unused’ or any name that conveys that this variable is currently not used anywhere.
Some editors like VScode, PyCharm, Eclipse, PyDev will raise warnings sometimes regarding these unused variables. The warnings won’t interrupt the program execution. To suppress the warning, one can simply name the variable with an underscore (‘_‘) alone. Python treats it as an unused variable and ignores it without giving the warning message.
Python
# unused functiondef my_func(): # unused local variable _ = 5 b=2 c=b+10 print(b,c) for i in range(0, 5): print(i)
0
1
2
3
4
There are packages that can be used to find the dead code in the scripts. One such package is Vulture. The vulture package finds the unused local variables, unused imports, and unused cord parts and gives out the report. To install this package, type the following command in the anaconda prompt.
pip install vulture
Now type a python script and save it with .py extension. The file shall be stored either in the directory that opens by default in the anaconda prompt or in some specific location. In case of storing the file in some other location, one has to then move to that directory. Now consider the following script as an example. It is saved as trial1.py
Python
# unused functiondef my_func(): # unused local variables a = 5 b=2 c=b+10 print(b,c) for i in range(0, 5): print(i)
0
1
2
3
4
Once the file is saved in the desired directory, then type the following command in the anaconda prompt to find the dead code.
C:\user>>vulture trial1.py
Output:
The vulture package understands the naming convention explained below to avoid warning. Thus, when an underscore alone is used as a variable name, the warning message is suppressed. Consider the trial1.py, where the name of the unused local variable is changed to underscore(‘_’).
Python3
# unused functiondef my_func(): # unused local variables _ = 5 b=2 c=b+10 print(b,c) for i in range(0, 5): print(i)
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 238,
"s": 28,
"text": "A variable defined inside a function block or a looping block loses its scope outside that block is called ad local variable to that block. A local variable cannot be accessed outside the block it is defined."
},
{
"code": null,
"e": 247,
"s": 238,
"text": "Example:"
},
{
"code": null,
"e": 255,
"s": 247,
"text": "Python3"
},
{
"code": "# simple display functiondef func(num): # local variable a = num print(\"The number is :\", str(a)) func(10) # generates errorprint(a)",
"e": 401,
"s": 255,
"text": null
},
{
"code": null,
"e": 409,
"s": 401,
"text": "Output:"
},
{
"code": null,
"e": 445,
"s": 409,
"text": "NameError: name 'a' is not defined\n"
},
{
"code": null,
"e": 892,
"s": 445,
"text": "Here we get an error because ‘a’ is local to the function func() and it loses its scope outside that block. Here the local variable ‘a’ is used to hold the number passed and it is utilized in the printing statement. But in some cases, the local variables wl be declared by assigning some value and left utilized for any process. Just assigning some value is not utilizing the variable, the value in it must be read and used for some computation. "
},
{
"code": null,
"e": 1592,
"s": 892,
"text": "Garbage collection is automatic in Python and when the reference count of an object comes to zero the object will be cleared. We all know that a variable local to a certain block of code loses its scope outside the block. The garbage collection is automatically invoked when the difference between the allocation of objects and the deallocation of objects crosses a certain threshold value. If the script is a few lines of code, then memory management is not a tedious process. If the script is very long with complex tasks and there are many unused local variables, it has a considerable effect on the code execution time and memory management. However, issues with memory management are very less."
},
{
"code": null,
"e": 2054,
"s": 1592,
"text": "The main issue that arises due to these unused variables is it decreases readability. When the code is thousands of lines, when another programmer is required to work with it, he may have to spend a long time analyzing what for the variable is used which is actually left unused. One may forget the unused variable declared and may use it in the later part which can result in undesirable output. It is always good practice to remove the unused local variables."
},
{
"code": null,
"e": 2496,
"s": 2054,
"text": "A code with many unused local variables, unused imports, or unused line of codes is considered to be dead code. When there are situations where you are ambiguous that a local variable may have a role later in the code, then there are some naming conventions that can be used to distinguish it from the rest of the variables. Naming the variable as ‘dummy’, ‘unused’ or any name that conveys that this variable is currently not used anywhere."
},
{
"code": null,
"e": 2842,
"s": 2496,
"text": "Some editors like VScode, PyCharm, Eclipse, PyDev will raise warnings sometimes regarding these unused variables. The warnings won’t interrupt the program execution. To suppress the warning, one can simply name the variable with an underscore (‘_‘) alone. Python treats it as an unused variable and ignores it without giving the warning message."
},
{
"code": null,
"e": 2849,
"s": 2842,
"text": "Python"
},
{
"code": "# unused functiondef my_func(): # unused local variable _ = 5 b=2 c=b+10 print(b,c) for i in range(0, 5): print(i)",
"e": 2993,
"s": 2849,
"text": null
},
{
"code": null,
"e": 3004,
"s": 2993,
"text": "0\n1\n2\n3\n4\n"
},
{
"code": null,
"e": 3301,
"s": 3004,
"text": "There are packages that can be used to find the dead code in the scripts. One such package is Vulture. The vulture package finds the unused local variables, unused imports, and unused cord parts and gives out the report. To install this package, type the following command in the anaconda prompt."
},
{
"code": null,
"e": 3321,
"s": 3301,
"text": "pip install vulture"
},
{
"code": null,
"e": 3669,
"s": 3321,
"text": "Now type a python script and save it with .py extension. The file shall be stored either in the directory that opens by default in the anaconda prompt or in some specific location. In case of storing the file in some other location, one has to then move to that directory. Now consider the following script as an example. It is saved as trial1.py"
},
{
"code": null,
"e": 3676,
"s": 3669,
"text": "Python"
},
{
"code": "# unused functiondef my_func(): # unused local variables a = 5 b=2 c=b+10 print(b,c) for i in range(0, 5): print(i)",
"e": 3821,
"s": 3676,
"text": null
},
{
"code": null,
"e": 3832,
"s": 3821,
"text": "0\n1\n2\n3\n4\n"
},
{
"code": null,
"e": 3959,
"s": 3832,
"text": "Once the file is saved in the desired directory, then type the following command in the anaconda prompt to find the dead code."
},
{
"code": null,
"e": 3986,
"s": 3959,
"text": "C:\\user>>vulture trial1.py"
},
{
"code": null,
"e": 3994,
"s": 3986,
"text": "Output:"
},
{
"code": null,
"e": 4276,
"s": 3994,
"text": "The vulture package understands the naming convention explained below to avoid warning. Thus, when an underscore alone is used as a variable name, the warning message is suppressed. Consider the trial1.py, where the name of the unused local variable is changed to underscore(‘_’)."
},
{
"code": null,
"e": 4284,
"s": 4276,
"text": "Python3"
},
{
"code": "# unused functiondef my_func(): # unused local variables _ = 5 b=2 c=b+10 print(b,c) for i in range(0, 5): print(i)",
"e": 4429,
"s": 4284,
"text": null
},
{
"code": null,
"e": 4443,
"s": 4429,
"text": "python-basics"
},
{
"code": null,
"e": 4450,
"s": 4443,
"text": "Python"
}
] |
Structures in C | 22 Jun, 2022
What is a structure? A structure is a key word that create user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.
How to create a structure? ‘struct’ keyword is used to create a structure. Following is an example.
C
struct address{ char name[50]; char street[100]; char city[50]; char state[20]; int pin;};
How to declare structure variables? A structure variable can either be declared with structure declaration or as a separate declaration like basic types.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C
// A variable declaration with structure declaration.struct Point{ int x, y;} p1; // The variable p1 is declared with 'Point' // A variable declaration like basic data typesstruct Point{ int x, y;}; int main(){ struct Point p1; // The variable p1 is declared like a normal variable}
Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory.
How to initialize structure members? Structure members cannot be initialized with declaration. For example the following C program fails in compilation.
C
struct Point{ int x = 0; // COMPILER ERROR: cannot initialize members here int y = 0; // COMPILER ERROR: cannot initialize members here};
The reason for above error is simple, when a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.
C
struct Point{ int x, y;}; int main(){ // A valid initialization. member x gets value 0 and y // gets value 1. The order of declaration is followed. struct Point p1 = {0, 1};}
How to access structure elements? Structure members are accessed using dot (.) operator.
C
#include<stdio.h> struct Point{ int x, y;}; int main(){ struct Point p1 = {0, 1}; // Accessing members of point p1 p1.x = 20; printf ("x = %d, y = %d", p1.x, p1.y); return 0;}
x = 20, y = 1
What is designated Initialization? Designated Initialization allows structure members to be initialized in any order. This feature has been added in C99 standard.
C
#include<stdio.h> struct Point{ int x, y, z;}; int main(){ // Examples of initialization using designated initialization struct Point p1 = {.y = 0, .z = 1, .x = 2}; struct Point p2 = {.x = 20}; printf ("x = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z); printf ("x = %d", p2.x); return 0;}
x = 2, y = 0, z = 1
x = 20
This feature is not available in C++ and works only in C. What is an array of structures? Like other primitive data types, we can create an array of structures.
C
#include<stdio.h> struct Point{ int x, y;}; int main(){ // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; printf("%d %d", arr[0].x, arr[0].y); return 0;}
10 20
What is a structure pointer? Like primitive types, we can have pointer to a structure. If we have a pointer to structure, members are accessed using arrow ( -> ) operator.
C
#include<stdio.h> struct Point{ int x, y;}; int main(){ struct Point p1 = {1, 2}; // p2 is a pointer to structure p1 struct Point *p2 = &p1; // Accessing structure members using structure pointer printf("%d %d", p2->x, p2->y); return 0;}
1 2
What is structure member alignment? See https://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/Limitations of C StructuresIn C language, Structures provide a method for packing together data of different types. A Structure is a helpful tool to handle a group of logically related data items. However, C structures have some limitations.
The C structure does not allow the struct data type to be treated like built-in data types:
We cannot use operators like +,- etc. on Structure variables. For example, consider the following code:
C
struct number{ float x;};int main(){ struct number n1,n2,n3; n1.x=4; n2.x=3; n3=n1+n2; return 0;} /*Output: prog.c: In function 'main':prog.c:10:7: error:invalid operands to binary + (have 'struct number' and 'struct number') n3=n1+n2; */
But we can use arithmetic operation on structure variables like this.
C
// Use of airthmatic operator in sturcture #include <stdio.h> struct number { float x;};int main(){ struct number n1,n2,n3; n1.x=4; n2.x=3; n3.x=(n1.x)+(n2.x); printf("\n%f",n3.x); return 0;}
No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by any function, anywhere in the scope of the Structure.
Functions inside Structure: C structures do not permit functions inside Structure
Static Members: C Structures cannot have static members inside their body
Access Modifiers: C Programming language do not support access modifiers. So they cannot be used in C Structures.
Construction creation in Structure: Structures in C cannot have constructor inside Structures.
Related Article : C Structures vs C++ Structures
RajeetGoyal
mxp
RishabhPrabhu
SidharthSunil
shubham_singh
vishalyadav3
shikharg1110
C Basics
C-Struct-Union-Enum
CBSE - Class 11
cpp-structure
school-programming
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
std::string class in C++
Function Pointer in C
rand() and srand() in C/C++
Different Methods to Reverse a String in C++
Enumeration (or enum) in C | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 258,
"s": 52,
"text": "What is a structure? A structure is a key word that create user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. "
},
{
"code": null,
"e": 362,
"s": 258,
"text": " How to create a structure? ‘struct’ keyword is used to create a structure. Following is an example. "
},
{
"code": null,
"e": 364,
"s": 362,
"text": "C"
},
{
"code": "struct address{ char name[50]; char street[100]; char city[50]; char state[20]; int pin;};",
"e": 465,
"s": 364,
"text": null
},
{
"code": null,
"e": 623,
"s": 465,
"text": " How to declare structure variables? A structure variable can either be declared with structure declaration or as a separate declaration like basic types. "
},
{
"code": null,
"e": 632,
"s": 623,
"text": "Chapters"
},
{
"code": null,
"e": 659,
"s": 632,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 709,
"s": 659,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 732,
"s": 709,
"text": "captions off, selected"
},
{
"code": null,
"e": 740,
"s": 732,
"text": "English"
},
{
"code": null,
"e": 764,
"s": 740,
"text": "This is a modal window."
},
{
"code": null,
"e": 833,
"s": 764,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 855,
"s": 833,
"text": "End of dialog window."
},
{
"code": null,
"e": 857,
"s": 855,
"text": "C"
},
{
"code": "// A variable declaration with structure declaration.struct Point{ int x, y;} p1; // The variable p1 is declared with 'Point' // A variable declaration like basic data typesstruct Point{ int x, y;}; int main(){ struct Point p1; // The variable p1 is declared like a normal variable}",
"e": 1149,
"s": 857,
"text": null
},
{
"code": null,
"e": 1255,
"s": 1149,
"text": "Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory. "
},
{
"code": null,
"e": 1410,
"s": 1255,
"text": "How to initialize structure members? Structure members cannot be initialized with declaration. For example the following C program fails in compilation. "
},
{
"code": null,
"e": 1412,
"s": 1410,
"text": "C"
},
{
"code": "struct Point{ int x = 0; // COMPILER ERROR: cannot initialize members here int y = 0; // COMPILER ERROR: cannot initialize members here};",
"e": 1558,
"s": 1412,
"text": null
},
{
"code": null,
"e": 1822,
"s": 1558,
"text": "The reason for above error is simple, when a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization. "
},
{
"code": null,
"e": 1824,
"s": 1822,
"text": "C"
},
{
"code": "struct Point{ int x, y;}; int main(){ // A valid initialization. member x gets value 0 and y // gets value 1. The order of declaration is followed. struct Point p1 = {0, 1};}",
"e": 2008,
"s": 1824,
"text": null
},
{
"code": null,
"e": 2101,
"s": 2008,
"text": " How to access structure elements? Structure members are accessed using dot (.) operator. "
},
{
"code": null,
"e": 2103,
"s": 2101,
"text": "C"
},
{
"code": "#include<stdio.h> struct Point{ int x, y;}; int main(){ struct Point p1 = {0, 1}; // Accessing members of point p1 p1.x = 20; printf (\"x = %d, y = %d\", p1.x, p1.y); return 0;}",
"e": 2293,
"s": 2103,
"text": null
},
{
"code": null,
"e": 2307,
"s": 2293,
"text": "x = 20, y = 1"
},
{
"code": null,
"e": 2476,
"s": 2309,
"text": " What is designated Initialization? Designated Initialization allows structure members to be initialized in any order. This feature has been added in C99 standard. "
},
{
"code": null,
"e": 2478,
"s": 2476,
"text": "C"
},
{
"code": "#include<stdio.h> struct Point{ int x, y, z;}; int main(){ // Examples of initialization using designated initialization struct Point p1 = {.y = 0, .z = 1, .x = 2}; struct Point p2 = {.x = 20}; printf (\"x = %d, y = %d, z = %d\\n\", p1.x, p1.y, p1.z); printf (\"x = %d\", p2.x); return 0;}",
"e": 2778,
"s": 2478,
"text": null
},
{
"code": null,
"e": 2805,
"s": 2778,
"text": "x = 2, y = 0, z = 1\nx = 20"
},
{
"code": null,
"e": 2971,
"s": 2807,
"text": "This feature is not available in C++ and works only in C. What is an array of structures? Like other primitive data types, we can create an array of structures. "
},
{
"code": null,
"e": 2973,
"s": 2971,
"text": "C"
},
{
"code": "#include<stdio.h> struct Point{ int x, y;}; int main(){ // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; printf(\"%d %d\", arr[0].x, arr[0].y); return 0;}",
"e": 3204,
"s": 2973,
"text": null
},
{
"code": null,
"e": 3210,
"s": 3204,
"text": "10 20"
},
{
"code": null,
"e": 3387,
"s": 3212,
"text": " What is a structure pointer? Like primitive types, we can have pointer to a structure. If we have a pointer to structure, members are accessed using arrow ( -> ) operator. "
},
{
"code": null,
"e": 3389,
"s": 3387,
"text": "C"
},
{
"code": "#include<stdio.h> struct Point{ int x, y;}; int main(){ struct Point p1 = {1, 2}; // p2 is a pointer to structure p1 struct Point *p2 = &p1; // Accessing structure members using structure pointer printf(\"%d %d\", p2->x, p2->y); return 0;}",
"e": 3643,
"s": 3389,
"text": null
},
{
"code": null,
"e": 3647,
"s": 3643,
"text": "1 2"
},
{
"code": null,
"e": 4014,
"s": 3649,
"text": "What is structure member alignment? See https://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/Limitations of C StructuresIn C language, Structures provide a method for packing together data of different types. A Structure is a helpful tool to handle a group of logically related data items. However, C structures have some limitations. "
},
{
"code": null,
"e": 4106,
"s": 4014,
"text": "The C structure does not allow the struct data type to be treated like built-in data types:"
},
{
"code": null,
"e": 4213,
"s": 4108,
"text": "We cannot use operators like +,- etc. on Structure variables. For example, consider the following code: "
},
{
"code": null,
"e": 4215,
"s": 4213,
"text": "C"
},
{
"code": "struct number{ float x;};int main(){ struct number n1,n2,n3; n1.x=4; n2.x=3; n3=n1+n2; return 0;} /*Output: prog.c: In function 'main':prog.c:10:7: error:invalid operands to binary + (have 'struct number' and 'struct number') n3=n1+n2; */",
"e": 4473,
"s": 4215,
"text": null
},
{
"code": null,
"e": 4545,
"s": 4475,
"text": "But we can use arithmetic operation on structure variables like this."
},
{
"code": null,
"e": 4547,
"s": 4545,
"text": "C"
},
{
"code": "// Use of airthmatic operator in sturcture #include <stdio.h> struct number { float x;};int main(){ struct number n1,n2,n3; n1.x=4; n2.x=3; n3.x=(n1.x)+(n2.x); printf(\"\\n%f\",n3.x); return 0;}",
"e": 4760,
"s": 4547,
"text": null
},
{
"code": null,
"e": 4907,
"s": 4760,
"text": "No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by any function, anywhere in the scope of the Structure."
},
{
"code": null,
"e": 4991,
"s": 4909,
"text": "Functions inside Structure: C structures do not permit functions inside Structure"
},
{
"code": null,
"e": 5067,
"s": 4993,
"text": "Static Members: C Structures cannot have static members inside their body"
},
{
"code": null,
"e": 5183,
"s": 5069,
"text": "Access Modifiers: C Programming language do not support access modifiers. So they cannot be used in C Structures."
},
{
"code": null,
"e": 5280,
"s": 5185,
"text": "Construction creation in Structure: Structures in C cannot have constructor inside Structures."
},
{
"code": null,
"e": 5330,
"s": 5280,
"text": "Related Article : C Structures vs C++ Structures "
},
{
"code": null,
"e": 5344,
"s": 5332,
"text": "RajeetGoyal"
},
{
"code": null,
"e": 5348,
"s": 5344,
"text": "mxp"
},
{
"code": null,
"e": 5362,
"s": 5348,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 5376,
"s": 5362,
"text": "SidharthSunil"
},
{
"code": null,
"e": 5390,
"s": 5376,
"text": "shubham_singh"
},
{
"code": null,
"e": 5403,
"s": 5390,
"text": "vishalyadav3"
},
{
"code": null,
"e": 5416,
"s": 5403,
"text": "shikharg1110"
},
{
"code": null,
"e": 5425,
"s": 5416,
"text": "C Basics"
},
{
"code": null,
"e": 5445,
"s": 5425,
"text": "C-Struct-Union-Enum"
},
{
"code": null,
"e": 5461,
"s": 5445,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 5475,
"s": 5461,
"text": "cpp-structure"
},
{
"code": null,
"e": 5494,
"s": 5475,
"text": "school-programming"
},
{
"code": null,
"e": 5505,
"s": 5494,
"text": "C Language"
},
{
"code": null,
"e": 5603,
"s": 5505,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5620,
"s": 5603,
"text": "Substring in C++"
},
{
"code": null,
"e": 5655,
"s": 5620,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 5701,
"s": 5655,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 5749,
"s": 5701,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 5794,
"s": 5749,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 5819,
"s": 5794,
"text": "std::string class in C++"
},
{
"code": null,
"e": 5841,
"s": 5819,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 5869,
"s": 5841,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 5914,
"s": 5869,
"text": "Different Methods to Reverse a String in C++"
}
] |
Kibana - Create Dashboard | In our previous chapters, we have seen how to create visualization in the form of vertical bar, horizontal bar, pie chart etc. In this chapter, let us learn how to combine them together in the form of Dashboard. A dashboard is collection of your visualizations created, so that you can take a look at it all together at a time.
To create Dashboard in Kibana, click on the Dashboard option available as shown below −
Now, click on Create new dashboard button as shown above. It will take us to the screen as shown below −
Observe that we do not have any dashboard created so far. There are options at the top where we can Save, Cancel, Add, Options, Share, Auto-refresh and also change the time to get the data on our dashboard. We will create a new dashboard, by clicking on the Add button shown above.
When we click the Add button (top left corner), it displays us the visualization we created as shown below −
Select the visualization you want to add to your dashboard. We will select the first three visualizations as shown below −
This is how it is seen on the screen together −
Thus, as a user you are able to get the overall details about the data we have uploaded – country wise with fields country-name, regionname, area and population.
So now we know all the regions available, the max population country wise in descending order, the max area etc.
This is just the sample data visualization we uploaded, but in real world it becomes very easy to track the details of your business like for example you have a website which gets millions of hits monthly or daily, you want to keep a track on the sales done every day, hour, minute, seconds and if you have your ELK stack in place Kibana can show you your sales visualization right in front of your eyes every hour, minute, seconds as you want to see. It displays the real time data as it is happening in the real world.
Kibana, on the whole, plays a very important role in extracting the accurate details about your business transaction day wise, hourly or every minute, so the company knows how the progress is going on.
You can save your dashboard by using the save button at the top.
There is a title and description where you can enter the name of the dashboard and a short description which tells what the dashboard does. Now, click on Confirm Save to save the dashboard.
At present you can see the data shown is of Last 15 minutes. Please note this is a static data without any time field so the data displayed will not change. When you have the data connected to real time system changing the time, will also show the data reflecting.
By default, you will see Last 15 minutes as shown below −
Click on the Last 15 minutes and it will display you the time range which you can select as per your choice.
Observe that there are Quick, Relative, Absolute and Recent options. The following screenshot shows the details for Quick option −
Now, click on Relative to see the option available −
Here you can specify the From and To date in minutes , hours, seconds, months, years ago.
The Absolute option has the following details −
You can see the calendar option and can select a date range.
The recent option will give back the Last 15 minutes option and also other option which you have selected recently. Choosing the time range will update the data coming within that time range.
We can also use search and filter on the dashboard. In search suppose if we want to get the details of a particular region, we can add a search as shown below −
In the above search, we have used the field Region and want to display the details of region:OCEANIA.
We get following results −
Looking at the above data we can say that in OCEANIA region, Australia has the max population and Area.
Similarly, we can add a filter as shown below −
Next, click on Add a filter button and it will display the details of the field available in your index as shown below −
Choose the field you want to filter on. I will use Region field to get the details of ASIA region as shown below −
Save the filter and you should see the filter as follows −
The data will now be shown as per the filter added −
You can also add more filters as shown below −
You can disable the filter by clicking on the disable checkbox as shown below.
You can activate the filter by clicking on the same checkbox to activate it. Observe that there is delete button to delete the filter. Edit button to edit the filter or change the filter options.
For the visualization displayed, you will notice three dots as shown below −
Click on it and it will display options as shown below −
Click on Inspect and it gives the details of the region in tabular format as shown below −
There is an option to download the visualization in CSV format in-case you want to see it in excel sheet.
The next option fullscreen will get the visualization in a fullscreenmode as shown below −
You can use the same button to exit the fullscreen mode.
We can share the dashboard using the share button. Onclick of share button, you will get display as follows −
You can also use embed code to show the dashboard on your site or use permalinks which will be a link to share with others.
The url will be as follows −
http://localhost:5601/goto/519c1a088d5d0f8703937d754923b84b
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2433,
"s": 2105,
"text": "In our previous chapters, we have seen how to create visualization in the form of vertical bar, horizontal bar, pie chart etc. In this chapter, let us learn how to combine them together in the form of Dashboard. A dashboard is collection of your visualizations created, so that you can take a look at it all together at a time."
},
{
"code": null,
"e": 2521,
"s": 2433,
"text": "To create Dashboard in Kibana, click on the Dashboard option available as shown below −"
},
{
"code": null,
"e": 2626,
"s": 2521,
"text": "Now, click on Create new dashboard button as shown above. It will take us to the screen as shown below −"
},
{
"code": null,
"e": 2908,
"s": 2626,
"text": "Observe that we do not have any dashboard created so far. There are options at the top where we can Save, Cancel, Add, Options, Share, Auto-refresh and also change the time to get the data on our dashboard. We will create a new dashboard, by clicking on the Add button shown above."
},
{
"code": null,
"e": 3017,
"s": 2908,
"text": "When we click the Add button (top left corner), it displays us the visualization we created as shown below −"
},
{
"code": null,
"e": 3140,
"s": 3017,
"text": "Select the visualization you want to add to your dashboard. We will select the first three visualizations as shown below −"
},
{
"code": null,
"e": 3188,
"s": 3140,
"text": "This is how it is seen on the screen together −"
},
{
"code": null,
"e": 3350,
"s": 3188,
"text": "Thus, as a user you are able to get the overall details about the data we have uploaded – country wise with fields country-name, regionname, area and population."
},
{
"code": null,
"e": 3463,
"s": 3350,
"text": "So now we know all the regions available, the max population country wise in descending order, the max area etc."
},
{
"code": null,
"e": 3984,
"s": 3463,
"text": "This is just the sample data visualization we uploaded, but in real world it becomes very easy to track the details of your business like for example you have a website which gets millions of hits monthly or daily, you want to keep a track on the sales done every day, hour, minute, seconds and if you have your ELK stack in place Kibana can show you your sales visualization right in front of your eyes every hour, minute, seconds as you want to see. It displays the real time data as it is happening in the real world."
},
{
"code": null,
"e": 4186,
"s": 3984,
"text": "Kibana, on the whole, plays a very important role in extracting the accurate details about your business transaction day wise, hourly or every minute, so the company knows how the progress is going on."
},
{
"code": null,
"e": 4251,
"s": 4186,
"text": "You can save your dashboard by using the save button at the top."
},
{
"code": null,
"e": 4441,
"s": 4251,
"text": "There is a title and description where you can enter the name of the dashboard and a short description which tells what the dashboard does. Now, click on Confirm Save to save the dashboard."
},
{
"code": null,
"e": 4706,
"s": 4441,
"text": "At present you can see the data shown is of Last 15 minutes. Please note this is a static data without any time field so the data displayed will not change. When you have the data connected to real time system changing the time, will also show the data reflecting."
},
{
"code": null,
"e": 4764,
"s": 4706,
"text": "By default, you will see Last 15 minutes as shown below −"
},
{
"code": null,
"e": 4873,
"s": 4764,
"text": "Click on the Last 15 minutes and it will display you the time range which you can select as per your choice."
},
{
"code": null,
"e": 5004,
"s": 4873,
"text": "Observe that there are Quick, Relative, Absolute and Recent options. The following screenshot shows the details for Quick option −"
},
{
"code": null,
"e": 5057,
"s": 5004,
"text": "Now, click on Relative to see the option available −"
},
{
"code": null,
"e": 5147,
"s": 5057,
"text": "Here you can specify the From and To date in minutes , hours, seconds, months, years ago."
},
{
"code": null,
"e": 5195,
"s": 5147,
"text": "The Absolute option has the following details −"
},
{
"code": null,
"e": 5256,
"s": 5195,
"text": "You can see the calendar option and can select a date range."
},
{
"code": null,
"e": 5448,
"s": 5256,
"text": "The recent option will give back the Last 15 minutes option and also other option which you have selected recently. Choosing the time range will update the data coming within that time range."
},
{
"code": null,
"e": 5609,
"s": 5448,
"text": "We can also use search and filter on the dashboard. In search suppose if we want to get the details of a particular region, we can add a search as shown below −"
},
{
"code": null,
"e": 5711,
"s": 5609,
"text": "In the above search, we have used the field Region and want to display the details of region:OCEANIA."
},
{
"code": null,
"e": 5738,
"s": 5711,
"text": "We get following results −"
},
{
"code": null,
"e": 5842,
"s": 5738,
"text": "Looking at the above data we can say that in OCEANIA region, Australia has the max population and Area."
},
{
"code": null,
"e": 5890,
"s": 5842,
"text": "Similarly, we can add a filter as shown below −"
},
{
"code": null,
"e": 6011,
"s": 5890,
"text": "Next, click on Add a filter button and it will display the details of the field available in your index as shown below −"
},
{
"code": null,
"e": 6126,
"s": 6011,
"text": "Choose the field you want to filter on. I will use Region field to get the details of ASIA region as shown below −"
},
{
"code": null,
"e": 6185,
"s": 6126,
"text": "Save the filter and you should see the filter as follows −"
},
{
"code": null,
"e": 6238,
"s": 6185,
"text": "The data will now be shown as per the filter added −"
},
{
"code": null,
"e": 6285,
"s": 6238,
"text": "You can also add more filters as shown below −"
},
{
"code": null,
"e": 6364,
"s": 6285,
"text": "You can disable the filter by clicking on the disable checkbox as shown below."
},
{
"code": null,
"e": 6560,
"s": 6364,
"text": "You can activate the filter by clicking on the same checkbox to activate it. Observe that there is delete button to delete the filter. Edit button to edit the filter or change the filter options."
},
{
"code": null,
"e": 6637,
"s": 6560,
"text": "For the visualization displayed, you will notice three dots as shown below −"
},
{
"code": null,
"e": 6694,
"s": 6637,
"text": "Click on it and it will display options as shown below −"
},
{
"code": null,
"e": 6785,
"s": 6694,
"text": "Click on Inspect and it gives the details of the region in tabular format as shown below −"
},
{
"code": null,
"e": 6891,
"s": 6785,
"text": "There is an option to download the visualization in CSV format in-case you want to see it in excel sheet."
},
{
"code": null,
"e": 6982,
"s": 6891,
"text": "The next option fullscreen will get the visualization in a fullscreenmode as shown below −"
},
{
"code": null,
"e": 7039,
"s": 6982,
"text": "You can use the same button to exit the fullscreen mode."
},
{
"code": null,
"e": 7149,
"s": 7039,
"text": "We can share the dashboard using the share button. Onclick of share button, you will get display as follows −"
},
{
"code": null,
"e": 7273,
"s": 7149,
"text": "You can also use embed code to show the dashboard on your site or use permalinks which will be a link to share with others."
},
{
"code": null,
"e": 7302,
"s": 7273,
"text": "The url will be as follows −"
},
{
"code": null,
"e": 7363,
"s": 7302,
"text": "http://localhost:5601/goto/519c1a088d5d0f8703937d754923b84b\n"
},
{
"code": null,
"e": 7370,
"s": 7363,
"text": " Print"
},
{
"code": null,
"e": 7381,
"s": 7370,
"text": " Add Notes"
}
] |
The What, Why, and How of Sankey Diagrams | by Allison Stafford | Towards Data Science | Sankey diagrams show the flow of resources. They communicate sources and uses of the resources, materials, or costs represented.
The key to reading and interpreting Sankey Diagrams is remembering that the width is proportional to the quantity represented. In the example below, the audience quickly sees that largest destination for water is terrestrial evaporation, among other features of the hydrologic cycle.
When presented with a Sankey diagram, remember that the only rule (ok, the main rule) is that the width of the lines and arrows represent amounts or volumes of resources. If the arrows don’t appear representative, it likely means the constructor made a mistake, does not understand the purpose of the tool, or is trying to hide an inconvenient truth. If something appears off, make sure to ask questions to make sure you are understanding the visualization.
Sankey diagrams allow you to show complex processes visually, with a focus on a single aspect or resource that you want to highlight. If your team is making a decision about energy, time, or money, then that’s a great time to consider a Sankey diagram.Sankeys offer the added benefit of supporting multiple viewing levels. Viewers can get a high level view, see specific details, or generate interactive views. If you have a teammate that likes to drill down, many tools will let you share that functionality, without any extra work by the creator. You can also predetermine the level of depth that works best for your purpose.Sankey diagrams make dominant contributors or consumers stand out, and they help your audience see relative magnitudes and/or areas with the largest opportunities.
Sankey diagrams allow you to show complex processes visually, with a focus on a single aspect or resource that you want to highlight. If your team is making a decision about energy, time, or money, then that’s a great time to consider a Sankey diagram.
Sankeys offer the added benefit of supporting multiple viewing levels. Viewers can get a high level view, see specific details, or generate interactive views. If you have a teammate that likes to drill down, many tools will let you share that functionality, without any extra work by the creator. You can also predetermine the level of depth that works best for your purpose.
Sankey diagrams make dominant contributors or consumers stand out, and they help your audience see relative magnitudes and/or areas with the largest opportunities.
Sometimes, Sankey diagrams aren’t the right tool for your situation:
They can appear overly complex and hard for your audience to digest.
Poorly made Sankey diagrams and hide instead of highlight the actionable insight.
Since not everyone is familiar with this visualization type, complex Sankey diagrams may require explanation that takes more time and energy than they are worth
Sankey diagrams can make it difficult to differentiate and compare flows with similar values (widths). If these comparisons are essential for your purpose, consider a (stacked) bar graph.
First, solidify your purpose and the most important take-away for your audience. To avoid wasting time rebuilding your diagram or building an ineffective Sankey diagram, here are some questions I would recommend asking yourself before you start:
Are you using this Sankey for exploratory data analysis?
Are you using it to tell a story, promote a particular action, change minds?
Who is your audience?
What is your audience’s experience level with data visualizations?
What will your audience be looking for and convinced by — ROI, efficiency, effectiveness, profitability, comparisons by region or by city?
From here, it’s a good idea to start with an outline of how you want your visualization to look before you start coding. As you sketch, consider the following:
Alternative ways to communicate your point
Group related inputs or outputs in space and/or with color
Using color to indicate transition from one state to another
Emphasizing the main takeaway for your audience using color saturation or intensity, position, length, angle, direction, shape. (Anything but width!)
Cutting minuscule flows or grouping them into an “other” category to reduce clutter
from matplotlib.sankey import Sankeyfrom matplotlib import pyplot as pltfig = plt.figure(figsize=(15,10))ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Flow Refugees from the Syrian Civil War")sankey = Sankey(ax=ax, scale=0.0000001, offset= 0.1, format = '%d')sankey.add(flows=[6918000, -3600000, -950000, -670000, -250000, -130000, -1300000, -18000], labels = ['Syria', 'Turkey', 'Lebanon', 'Jordan', 'Iraq', 'Egypt', 'Europe', 'USA'], orientations=[0, 0, 1, 1, 1, 1, -1, -1],#arrow directions edgecolor = '#027368', facecolor = '#027368')sankey.finish();
Pathlength — use this argument to adjust the lengths of the arrows once they separate from the main flow with a list of floats.
Trunklength — use this argument to adjust the length of the space between the inputs and outputs
Originally, I got this not very Sankey-like visualization. I was completely confused as to what was going wrong — I see some numbers and labels and widths, but definitely not what I expected.
Digging into the documentation, I decided to adjust the trunk length, which helped my Sankey begin to emerge from its geometric artwork cocoon. As my husband pointed out, it went from Pollock to Dali.
Then I found it — scale factor. It turns out that the scale factor is key for working with large values! After a little experimentation, I got the Sankey looking much better.
It seems like the defaults work great for percent values, but be prepared to scale for any other data magnitudes.
fig = plt.figure(figsize = (15,8))ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Household Budget")sankey = Sankey(ax=ax, scale=.1, offset=1, unit='%')sankey.add(flows=[100, -50, -30, -20], labels=['household budget', 'necessities', 'fun', 'saving'], orientations=[0, 0, 1, -1], trunklength = 10, edgecolor = '#027368', facecolor = '#027368')sankey.add(flows=[50, -30, -10, -10], labels=['','rent', 'groceries', 'other'], trunklength = 2, pathlengths = [3,3,3,3], orientations=[0, 1, 0, -1], prior=0, #which sankey are you connecting to (0-indexed) connect=(1, 0), #flow number to connect: (prior, this) edgecolor = '#58A4B0', facecolor = '#58A4B0')diagrams = sankey.finish()for diagram in diagrams: for text in diagram.texts: text.set_fontsize(16);
Matplotlib’s sankey package doesn’t seem to do everything you might hope to do with Sankey diagrams. For example, it does not seem to track flows across nodes using color to indicate the origin or a third property. If you want to make more complex Sankey diagrams, especially with color functionality, I recommend using other tools such as floweaver [how to use post here].
Their choice of subject — the movement of apples and bananas from farms to gendered consumers — feels a little contrived. I find it hard to believe that no women consume apples from farm2, and only women consume apples from farm3. At the same time, I see how this tool could be a good choice, depending on your needs and style preference.
Sankey diagrams aren’t the perfect tool for every situation. They are definitely not the quickest and simplest visualization to create or digest. But when they are done well, they work as a powerful conversation starter. Just make sure that you are using them because they are the best way to communicate your message, not only to show off your visualization skills. | [
{
"code": null,
"e": 301,
"s": 172,
"text": "Sankey diagrams show the flow of resources. They communicate sources and uses of the resources, materials, or costs represented."
},
{
"code": null,
"e": 585,
"s": 301,
"text": "The key to reading and interpreting Sankey Diagrams is remembering that the width is proportional to the quantity represented. In the example below, the audience quickly sees that largest destination for water is terrestrial evaporation, among other features of the hydrologic cycle."
},
{
"code": null,
"e": 1043,
"s": 585,
"text": "When presented with a Sankey diagram, remember that the only rule (ok, the main rule) is that the width of the lines and arrows represent amounts or volumes of resources. If the arrows don’t appear representative, it likely means the constructor made a mistake, does not understand the purpose of the tool, or is trying to hide an inconvenient truth. If something appears off, make sure to ask questions to make sure you are understanding the visualization."
},
{
"code": null,
"e": 1834,
"s": 1043,
"text": "Sankey diagrams allow you to show complex processes visually, with a focus on a single aspect or resource that you want to highlight. If your team is making a decision about energy, time, or money, then that’s a great time to consider a Sankey diagram.Sankeys offer the added benefit of supporting multiple viewing levels. Viewers can get a high level view, see specific details, or generate interactive views. If you have a teammate that likes to drill down, many tools will let you share that functionality, without any extra work by the creator. You can also predetermine the level of depth that works best for your purpose.Sankey diagrams make dominant contributors or consumers stand out, and they help your audience see relative magnitudes and/or areas with the largest opportunities."
},
{
"code": null,
"e": 2087,
"s": 1834,
"text": "Sankey diagrams allow you to show complex processes visually, with a focus on a single aspect or resource that you want to highlight. If your team is making a decision about energy, time, or money, then that’s a great time to consider a Sankey diagram."
},
{
"code": null,
"e": 2463,
"s": 2087,
"text": "Sankeys offer the added benefit of supporting multiple viewing levels. Viewers can get a high level view, see specific details, or generate interactive views. If you have a teammate that likes to drill down, many tools will let you share that functionality, without any extra work by the creator. You can also predetermine the level of depth that works best for your purpose."
},
{
"code": null,
"e": 2627,
"s": 2463,
"text": "Sankey diagrams make dominant contributors or consumers stand out, and they help your audience see relative magnitudes and/or areas with the largest opportunities."
},
{
"code": null,
"e": 2696,
"s": 2627,
"text": "Sometimes, Sankey diagrams aren’t the right tool for your situation:"
},
{
"code": null,
"e": 2765,
"s": 2696,
"text": "They can appear overly complex and hard for your audience to digest."
},
{
"code": null,
"e": 2847,
"s": 2765,
"text": "Poorly made Sankey diagrams and hide instead of highlight the actionable insight."
},
{
"code": null,
"e": 3008,
"s": 2847,
"text": "Since not everyone is familiar with this visualization type, complex Sankey diagrams may require explanation that takes more time and energy than they are worth"
},
{
"code": null,
"e": 3196,
"s": 3008,
"text": "Sankey diagrams can make it difficult to differentiate and compare flows with similar values (widths). If these comparisons are essential for your purpose, consider a (stacked) bar graph."
},
{
"code": null,
"e": 3442,
"s": 3196,
"text": "First, solidify your purpose and the most important take-away for your audience. To avoid wasting time rebuilding your diagram or building an ineffective Sankey diagram, here are some questions I would recommend asking yourself before you start:"
},
{
"code": null,
"e": 3499,
"s": 3442,
"text": "Are you using this Sankey for exploratory data analysis?"
},
{
"code": null,
"e": 3576,
"s": 3499,
"text": "Are you using it to tell a story, promote a particular action, change minds?"
},
{
"code": null,
"e": 3598,
"s": 3576,
"text": "Who is your audience?"
},
{
"code": null,
"e": 3665,
"s": 3598,
"text": "What is your audience’s experience level with data visualizations?"
},
{
"code": null,
"e": 3804,
"s": 3665,
"text": "What will your audience be looking for and convinced by — ROI, efficiency, effectiveness, profitability, comparisons by region or by city?"
},
{
"code": null,
"e": 3964,
"s": 3804,
"text": "From here, it’s a good idea to start with an outline of how you want your visualization to look before you start coding. As you sketch, consider the following:"
},
{
"code": null,
"e": 4007,
"s": 3964,
"text": "Alternative ways to communicate your point"
},
{
"code": null,
"e": 4066,
"s": 4007,
"text": "Group related inputs or outputs in space and/or with color"
},
{
"code": null,
"e": 4127,
"s": 4066,
"text": "Using color to indicate transition from one state to another"
},
{
"code": null,
"e": 4277,
"s": 4127,
"text": "Emphasizing the main takeaway for your audience using color saturation or intensity, position, length, angle, direction, shape. (Anything but width!)"
},
{
"code": null,
"e": 4361,
"s": 4277,
"text": "Cutting minuscule flows or grouping them into an “other” category to reduce clutter"
},
{
"code": null,
"e": 5077,
"s": 4361,
"text": "from matplotlib.sankey import Sankeyfrom matplotlib import pyplot as pltfig = plt.figure(figsize=(15,10))ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title=\"Flow Refugees from the Syrian Civil War\")sankey = Sankey(ax=ax, scale=0.0000001, offset= 0.1, format = '%d')sankey.add(flows=[6918000, -3600000, -950000, -670000, -250000, -130000, -1300000, -18000], labels = ['Syria', 'Turkey', 'Lebanon', 'Jordan', 'Iraq', 'Egypt', 'Europe', 'USA'], orientations=[0, 0, 1, 1, 1, 1, -1, -1],#arrow directions edgecolor = '#027368', facecolor = '#027368')sankey.finish();"
},
{
"code": null,
"e": 5205,
"s": 5077,
"text": "Pathlength — use this argument to adjust the lengths of the arrows once they separate from the main flow with a list of floats."
},
{
"code": null,
"e": 5302,
"s": 5205,
"text": "Trunklength — use this argument to adjust the length of the space between the inputs and outputs"
},
{
"code": null,
"e": 5494,
"s": 5302,
"text": "Originally, I got this not very Sankey-like visualization. I was completely confused as to what was going wrong — I see some numbers and labels and widths, but definitely not what I expected."
},
{
"code": null,
"e": 5695,
"s": 5494,
"text": "Digging into the documentation, I decided to adjust the trunk length, which helped my Sankey begin to emerge from its geometric artwork cocoon. As my husband pointed out, it went from Pollock to Dali."
},
{
"code": null,
"e": 5870,
"s": 5695,
"text": "Then I found it — scale factor. It turns out that the scale factor is key for working with large values! After a little experimentation, I got the Sankey looking much better."
},
{
"code": null,
"e": 5984,
"s": 5870,
"text": "It seems like the defaults work great for percent values, but be prepared to scale for any other data magnitudes."
},
{
"code": null,
"e": 6928,
"s": 5984,
"text": "fig = plt.figure(figsize = (15,8))ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title=\"Household Budget\")sankey = Sankey(ax=ax, scale=.1, offset=1, unit='%')sankey.add(flows=[100, -50, -30, -20], labels=['household budget', 'necessities', 'fun', 'saving'], orientations=[0, 0, 1, -1], trunklength = 10, edgecolor = '#027368', facecolor = '#027368')sankey.add(flows=[50, -30, -10, -10], labels=['','rent', 'groceries', 'other'], trunklength = 2, pathlengths = [3,3,3,3], orientations=[0, 1, 0, -1], prior=0, #which sankey are you connecting to (0-indexed) connect=(1, 0), #flow number to connect: (prior, this) edgecolor = '#58A4B0', facecolor = '#58A4B0')diagrams = sankey.finish()for diagram in diagrams: for text in diagram.texts: text.set_fontsize(16);"
},
{
"code": null,
"e": 7302,
"s": 6928,
"text": "Matplotlib’s sankey package doesn’t seem to do everything you might hope to do with Sankey diagrams. For example, it does not seem to track flows across nodes using color to indicate the origin or a third property. If you want to make more complex Sankey diagrams, especially with color functionality, I recommend using other tools such as floweaver [how to use post here]."
},
{
"code": null,
"e": 7641,
"s": 7302,
"text": "Their choice of subject — the movement of apples and bananas from farms to gendered consumers — feels a little contrived. I find it hard to believe that no women consume apples from farm2, and only women consume apples from farm3. At the same time, I see how this tool could be a good choice, depending on your needs and style preference."
}
] |
MATLAB - The Nested if Statements | It is always legal in MATLAB to nest if-else statements which means you can use one if or elseif statement inside another if or elseif statement(s).
The syntax for a nested if statement is as follows −
if <expression 1>
% Executes when the boolean expression 1 is true
if <expression 2>
% Executes when the boolean expression 2 is true
end
end
You can nest elseif...else in the similar way as you have nested if statement.
Create a script file and type the following code in it −
a = 100;
b = 200;
% check the boolean condition
if( a == 100 )
% if condition is true then check the following
if( b == 200 )
% if condition is true then print the following
fprintf('Value of a is 100 and b is 200\n' );
end
end
fprintf('Exact value of a is : %d\n', a );
fprintf('Exact value of b is : %d\n', b );
When you run the file, it displays −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
30 Lectures
4 hours
Nouman Azam
127 Lectures
12 hours
Nouman Azam
17 Lectures
3 hours
Sanjeev
37 Lectures
5 hours
TELCOMA Global
22 Lectures
4 hours
TELCOMA Global
18 Lectures
3 hours
Phinite Academy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2290,
"s": 2141,
"text": "It is always legal in MATLAB to nest if-else statements which means you can use one if or elseif statement inside another if or elseif statement(s)."
},
{
"code": null,
"e": 2343,
"s": 2290,
"text": "The syntax for a nested if statement is as follows −"
},
{
"code": null,
"e": 2506,
"s": 2343,
"text": "if <expression 1>\n % Executes when the boolean expression 1 is true \n if <expression 2>\n % Executes when the boolean expression 2 is true \n end\nend\n"
},
{
"code": null,
"e": 2585,
"s": 2506,
"text": "You can nest elseif...else in the similar way as you have nested if statement."
},
{
"code": null,
"e": 2642,
"s": 2585,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 3030,
"s": 2642,
"text": "a = 100;\nb = 200;\n % check the boolean condition \n if( a == 100 )\n \n % if condition is true then check the following \n if( b == 200 )\n \n % if condition is true then print the following \n fprintf('Value of a is 100 and b is 200\\n' );\n end\n \n end\n fprintf('Exact value of a is : %d\\n', a );\n fprintf('Exact value of b is : %d\\n', b );"
},
{
"code": null,
"e": 3067,
"s": 3030,
"text": "When you run the file, it displays −"
},
{
"code": null,
"e": 3151,
"s": 3067,
"text": "Value of a is 100 and b is 200\nExact value of a is : 100\nExact value of b is : 200\n"
},
{
"code": null,
"e": 3184,
"s": 3151,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3197,
"s": 3184,
"text": " Nouman Azam"
},
{
"code": null,
"e": 3232,
"s": 3197,
"text": "\n 127 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 3245,
"s": 3232,
"text": " Nouman Azam"
},
{
"code": null,
"e": 3278,
"s": 3245,
"text": "\n 17 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3287,
"s": 3278,
"text": " Sanjeev"
},
{
"code": null,
"e": 3320,
"s": 3287,
"text": "\n 37 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3336,
"s": 3320,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3369,
"s": 3336,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3385,
"s": 3369,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3418,
"s": 3385,
"text": "\n 18 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3435,
"s": 3418,
"text": " Phinite Academy"
},
{
"code": null,
"e": 3442,
"s": 3435,
"text": " Print"
},
{
"code": null,
"e": 3453,
"s": 3442,
"text": " Add Notes"
}
] |
Tryit Editor v3.7 | CSS Grid Intro
Tryit: The column-gap property | [
{
"code": null,
"e": 24,
"s": 9,
"text": "CSS Grid Intro"
}
] |
How can I delete MySQL temporary table? | As we know that MySQL temporary table would be deleted if the current session is terminated. But of still in between the session we want to delete the temporary table than with the help of the DROP statement we can delete the temporary table. It can be understood with the help of the following example −
In this example, we are deleting the temporary table named ‘SalesSummary’ −
mysql> DROP TABLE SalesSummary;
Query OK, 0 rows affected (0.00 sec)
The above query will delete the table and it can be confirmed from the query below −
mysql> Select * from SalesSummary;
ERROR 1146 (42S02): Table 'query.SalesSummary doesn't exist | [
{
"code": null,
"e": 1367,
"s": 1062,
"text": "As we know that MySQL temporary table would be deleted if the current session is terminated. But of still in between the session we want to delete the temporary table than with the help of the DROP statement we can delete the temporary table. It can be understood with the help of the following example −"
},
{
"code": null,
"e": 1443,
"s": 1367,
"text": "In this example, we are deleting the temporary table named ‘SalesSummary’ −"
},
{
"code": null,
"e": 1512,
"s": 1443,
"text": "mysql> DROP TABLE SalesSummary;\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1597,
"s": 1512,
"text": "The above query will delete the table and it can be confirmed from the query below −"
},
{
"code": null,
"e": 1692,
"s": 1597,
"text": "mysql> Select * from SalesSummary;\nERROR 1146 (42S02): Table 'query.SalesSummary doesn't exist"
}
] |
Counting the number of words in a Trie - GeeksforGeeks | 25 Feb, 2019
A Trie is used to store dictionary words so that they can be searched efficiently and prefix search can be done. The task is to write a function to count the number of words.
Example :
Input : root
/ \ \
t a b
| | |
h n y
| | \ |
e s y e
/ | |
i r w
| | |
r e e
|
r
Output : 8
Explanation : Words formed in the Trie :
"the", "a", "there", "answer", "any", "by",
"bye", "their".
In Trie structure, we have a field to store end of word marker, we call it isLeaf in below implementation. To count words, we need to simply traverse the Trie and count all nodes where isLeaf is set.
C++
Java
C#
// C++ implementation to count words in a trie#include <bits/stdc++.h>using namespace std; #define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) // Alphabet size (# of symbols)#define ALPHABET_SIZE (26) // Converts key current character into index// use only 'a' through 'z' and lower case#define CHAR_TO_INDEX(c) ((int)c - (int)'a') // Trie nodestruct TrieNode{ struct TrieNode *children[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word bool isLeaf;}; // Returns new trie node (initialized to NULLs)struct TrieNode *getNode(void){ struct TrieNode *pNode = new TrieNode; pNode->isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node, just// marks leaf nodevoid insert(struct TrieNode *root, const char *key){ int length = strlen(key); struct TrieNode *pCrawl = root; for (int level = 0; level < length; level++) { int index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isLeaf = true;} // Function to count number of wordsint wordCount(struct TrieNode *root){ int result = 0; // Leaf denotes end of a word if (root -> isLeaf) result++; for (int i = 0; i < ALPHABET_SIZE; i++) if (root -> children[i]) result += wordCount(root -> children[i]); return result; } // Driverint main(){ // Input keys (use only 'a' through 'z' // and lower case) char keys[][8] = {"the", "a", "there", "answer", "any", "by", "bye", "their"}; struct TrieNode *root = getNode(); // Construct Trie for (int i = 0; i < ARRAY_SIZE(keys); i++) insert(root, keys[i]); cout << wordCount(root); return 0;}
// Java implementation to count words in a triepublic class Words_in_trie { // Alphabet size (# of symbols) static final int ALPHABET_SIZE = 26; // Trie node static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word boolean isLeaf; TrieNode(){ isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; // If not present, inserts key into trie // If the key is prefix of trie node, just // marks leaf node static void insert(String key) { int length = key.length(); TrieNode pCrawl = root; for (int level = 0; level < length; level++) { int index = key.charAt(level) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; } // Function to count number of words static int wordCount(TrieNode root) { int result = 0; // Leaf denotes end of a word if (root.isLeaf) result++; for (int i = 0; i < ALPHABET_SIZE; i++) if (root.children[i] != null ) result += wordCount(root.children[i]); return result; } // Driver Program public static void main(String args[]) { // Input keys (use only 'a' through 'z' // and lower case) String keys[] = {"the", "a", "there", "answer", "any", "by", "bye", "their"}; root = new TrieNode(); // Construct Trie for (int i = 0; i < keys.length; i++) insert(keys[i]); System.out.println(wordCount(root)); }}// This code is contributed by Sumit Ghosh
// C# implementation to count words in a trie using System; public class Words_in_trie { // Alphabet size (# of symbols) static readonly int ALPHABET_SIZE = 26; // Trie node public class TrieNode { public TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word public bool isLeaf; public TrieNode() { isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; // If not present, inserts key into trie // If the key is prefix of trie node, just // marks leaf node static void insert(String key) { int length = key.Length; TrieNode pCrawl = root; for (int level = 0; level < length; level++) { int index = key[level] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; } // Function to count number of words static int wordCount(TrieNode root) { int result = 0; // Leaf denotes end of a word if (root.isLeaf) result++; for (int i = 0; i < ALPHABET_SIZE; i++) if (root.children[i] != null ) result += wordCount(root.children[i]); return result; } // Driver code public static void Main() { // Input keys (use only 'a' through 'z' // and lower case) String []keys = {"the", "a", "there", "answer", "any", "by", "bye", "their"}; root = new TrieNode(); // Construct Trie for (int i = 0; i < keys.Length; i++) insert(keys[i]); Console.WriteLine(wordCount(root)); } } /* This code contributed by PrinciRaj1992 */
8
This article is contributed by Rohit Thapliyal. 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.
princiraj1992
Trie
Advanced Data Structure
Tree
Tree
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Proof that Dominant Set of a Graph is NP-Complete
Extendible Hashing (Dynamic approach to DBMS)
2-3 Trees | (Search, Insert and Deletion)
Cartesian Tree
Advantages of Trie Data Structure
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree) | [
{
"code": null,
"e": 24241,
"s": 24213,
"text": "\n25 Feb, 2019"
},
{
"code": null,
"e": 24416,
"s": 24241,
"text": "A Trie is used to store dictionary words so that they can be searched efficiently and prefix search can be done. The task is to write a function to count the number of words."
},
{
"code": null,
"e": 24426,
"s": 24416,
"text": "Example :"
},
{
"code": null,
"e": 24792,
"s": 24426,
"text": "Input : root\n / \\ \\\n t a b\n | | |\n h n y\n | | \\ |\n e s y e\n / | |\n i r w\n | | |\n r e e\n |\n r\nOutput : 8\nExplanation : Words formed in the Trie : \n\"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \n\"bye\", \"their\".\n"
},
{
"code": null,
"e": 24992,
"s": 24792,
"text": "In Trie structure, we have a field to store end of word marker, we call it isLeaf in below implementation. To count words, we need to simply traverse the Trie and count all nodes where isLeaf is set."
},
{
"code": null,
"e": 24996,
"s": 24992,
"text": "C++"
},
{
"code": null,
"e": 25001,
"s": 24996,
"text": "Java"
},
{
"code": null,
"e": 25004,
"s": 25001,
"text": "C#"
},
{
"code": "// C++ implementation to count words in a trie#include <bits/stdc++.h>using namespace std; #define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) // Alphabet size (# of symbols)#define ALPHABET_SIZE (26) // Converts key current character into index// use only 'a' through 'z' and lower case#define CHAR_TO_INDEX(c) ((int)c - (int)'a') // Trie nodestruct TrieNode{ struct TrieNode *children[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word bool isLeaf;}; // Returns new trie node (initialized to NULLs)struct TrieNode *getNode(void){ struct TrieNode *pNode = new TrieNode; pNode->isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node, just// marks leaf nodevoid insert(struct TrieNode *root, const char *key){ int length = strlen(key); struct TrieNode *pCrawl = root; for (int level = 0; level < length; level++) { int index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isLeaf = true;} // Function to count number of wordsint wordCount(struct TrieNode *root){ int result = 0; // Leaf denotes end of a word if (root -> isLeaf) result++; for (int i = 0; i < ALPHABET_SIZE; i++) if (root -> children[i]) result += wordCount(root -> children[i]); return result; } // Driverint main(){ // Input keys (use only 'a' through 'z' // and lower case) char keys[][8] = {\"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \"bye\", \"their\"}; struct TrieNode *root = getNode(); // Construct Trie for (int i = 0; i < ARRAY_SIZE(keys); i++) insert(root, keys[i]); cout << wordCount(root); return 0;}",
"e": 26982,
"s": 25004,
"text": null
},
{
"code": "// Java implementation to count words in a triepublic class Words_in_trie { // Alphabet size (# of symbols) static final int ALPHABET_SIZE = 26; // Trie node static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word boolean isLeaf; TrieNode(){ isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; // If not present, inserts key into trie // If the key is prefix of trie node, just // marks leaf node static void insert(String key) { int length = key.length(); TrieNode pCrawl = root; for (int level = 0; level < length; level++) { int index = key.charAt(level) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; } // Function to count number of words static int wordCount(TrieNode root) { int result = 0; // Leaf denotes end of a word if (root.isLeaf) result++; for (int i = 0; i < ALPHABET_SIZE; i++) if (root.children[i] != null ) result += wordCount(root.children[i]); return result; } // Driver Program public static void main(String args[]) { // Input keys (use only 'a' through 'z' // and lower case) String keys[] = {\"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \"bye\", \"their\"}; root = new TrieNode(); // Construct Trie for (int i = 0; i < keys.length; i++) insert(keys[i]); System.out.println(wordCount(root)); }}// This code is contributed by Sumit Ghosh",
"e": 29017,
"s": 26982,
"text": null
},
{
"code": "// C# implementation to count words in a trie using System; public class Words_in_trie { // Alphabet size (# of symbols) static readonly int ALPHABET_SIZE = 26; // Trie node public class TrieNode { public TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word public bool isLeaf; public TrieNode() { isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; // If not present, inserts key into trie // If the key is prefix of trie node, just // marks leaf node static void insert(String key) { int length = key.Length; TrieNode pCrawl = root; for (int level = 0; level < length; level++) { int index = key[level] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isLeaf = true; } // Function to count number of words static int wordCount(TrieNode root) { int result = 0; // Leaf denotes end of a word if (root.isLeaf) result++; for (int i = 0; i < ALPHABET_SIZE; i++) if (root.children[i] != null ) result += wordCount(root.children[i]); return result; } // Driver code public static void Main() { // Input keys (use only 'a' through 'z' // and lower case) String []keys = {\"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \"bye\", \"their\"}; root = new TrieNode(); // Construct Trie for (int i = 0; i < keys.Length; i++) insert(keys[i]); Console.WriteLine(wordCount(root)); } } /* This code contributed by PrinciRaj1992 */",
"e": 31122,
"s": 29017,
"text": null
},
{
"code": null,
"e": 31125,
"s": 31122,
"text": "8\n"
},
{
"code": null,
"e": 31428,
"s": 31125,
"text": "This article is contributed by Rohit Thapliyal. 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": 31553,
"s": 31428,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31567,
"s": 31553,
"text": "princiraj1992"
},
{
"code": null,
"e": 31572,
"s": 31567,
"text": "Trie"
},
{
"code": null,
"e": 31596,
"s": 31572,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 31601,
"s": 31596,
"text": "Tree"
},
{
"code": null,
"e": 31606,
"s": 31601,
"text": "Tree"
},
{
"code": null,
"e": 31611,
"s": 31606,
"text": "Trie"
},
{
"code": null,
"e": 31709,
"s": 31611,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31718,
"s": 31709,
"text": "Comments"
},
{
"code": null,
"e": 31731,
"s": 31718,
"text": "Old Comments"
},
{
"code": null,
"e": 31781,
"s": 31731,
"text": "Proof that Dominant Set of a Graph is NP-Complete"
},
{
"code": null,
"e": 31827,
"s": 31781,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 31869,
"s": 31827,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 31884,
"s": 31869,
"text": "Cartesian Tree"
},
{
"code": null,
"e": 31918,
"s": 31884,
"text": "Advantages of Trie Data Structure"
},
{
"code": null,
"e": 31968,
"s": 31918,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 32003,
"s": 31968,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 32037,
"s": 32003,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 32078,
"s": 32037,
"text": "Inorder Tree Traversal without Recursion"
}
] |
Node.js os.networkInterfaces() Method - GeeksforGeeks | 12 Oct, 2021
The os.networkInterfaces() method is an inbuilt application programming interface of the os module which is used to get the information about network interfaces of the computer.
Syntax:
os.networkInterfaces()
Parameters: This method does not accept any parameters.
Return Value: This method returns an object containing information about each network interfaces. The returned object will contain the array of network interfaces which again consists of the following attributes:
address: A string that specifies the assigned network address i.e. IPv4 or IPv6/
netmask: A string that specifies the IPv4 or IPv6 network mask.
family: A string that specifies the Family, value is one of IPv4 or IPv6.
mac: A string that specifies the MAC address of the network interface.
internal: A boolean value, true if interface is loopback one, false otherwise.
scopeid: A number that specifies the scope ID for IPv6.
cidr: A string that specifies the assigned IPv4 or IPv6 address with the routing prefix in CIDR notation. It is set to null if netmask is invalid.
Below examples illustrate the use of os.networkInterfaces() method in Node.js:
Example 1:
// Node.js program to demonstrate the // os.networkInterfaces() Method // Allocating os moduleconst os = require('os'); // Print os.networkInterfaces() valueconsole.log(os.networkInterfaces());
Output:
{ 'Wi-Fi':
[ { address: 'fe80::242a:3451:7fb2:3ab1',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: 'b3:52:16:13:de:b9',
scopeid: 3,
internal: false,
cidr: 'fe80::242a:3451:7fb2:3ab1/64' },
{ address: '192.168.0.5',
netmask: '255.255.255.0',
family: 'IPv4',
mac: 'b3:52:16:13:de:b9',
internal: false,
cidr: '192.168.0.5/24' } ],
'Loopback Pseudo-Interface 1':
[ { address: '::1',
netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
family: 'IPv6',
mac: '00:00:00:00:00:00',
scopeid: 0,
internal: true,
cidr: '::1/128' },
{ address: '127.0.0.1',
netmask: '255.0.0.0',
family: 'IPv4',
mac: '00:00:00:00:00:00',
internal: true,
cidr: '127.0.0.1/8' } ] }
Example 2:
// Node.js program to demonstrate the // os.networkInterfaces() Method // Allocating os moduleconst os = require('os'); // Print os.networkInterfaces() valuevar net_int = os.networkInterfaces(); var no_of_network_interfaces = 0; for (var key in net_int) { console.log(key); var net_infos=net_int[key]; net_infos.forEach(element => { no_of_network_interfaces++; console.log("\tinterface:"); for (var attr in element){ console.log("\t\t" + attr + " : " + element[attr] ); } }); } console.log("total number of Network " + "interfaces is " + no_of_network_interfaces);
Output:
Wi-Fi
interface:
address : fe80::242a:3451:7fb2:3ab1
netmask : ffff:ffff:ffff:ffff::
family : IPv6
mac : b3:52:16:13:de:b9
scopeid : 3
internal : false
cidr : fe80::242a:3451:7fb2:3ab1/64
interface:
address : 192.168.0.5
netmask : 255.255.255.0
family : IPv4
mac : b3:52:16:13:de:b9
internal : false
cidr : 192.168.0.5/24
Loopback Pseudo-Interface 1
interface:
address : ::1
netmask : ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
family : IPv6
mac : 00:00:00:00:00:00
scopeid : 0
internal : true
cidr : ::1/128
interface:
address : 127.0.0.1
netmask : 255.0.0.0
family : IPv4
mac : 00:00:00:00:00:00
internal : true
cidr : 127.0.0.1/8
total number of Network interfaces is 4
Note: The above program will compile and run by using the node filename.js command.
Reference: https://nodejs.org/api/os.html#os_os_networkinterfaces
Node.js-os-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25002,
"s": 24974,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 25180,
"s": 25002,
"text": "The os.networkInterfaces() method is an inbuilt application programming interface of the os module which is used to get the information about network interfaces of the computer."
},
{
"code": null,
"e": 25188,
"s": 25180,
"text": "Syntax:"
},
{
"code": null,
"e": 25211,
"s": 25188,
"text": "os.networkInterfaces()"
},
{
"code": null,
"e": 25267,
"s": 25211,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 25480,
"s": 25267,
"text": "Return Value: This method returns an object containing information about each network interfaces. The returned object will contain the array of network interfaces which again consists of the following attributes:"
},
{
"code": null,
"e": 25561,
"s": 25480,
"text": "address: A string that specifies the assigned network address i.e. IPv4 or IPv6/"
},
{
"code": null,
"e": 25625,
"s": 25561,
"text": "netmask: A string that specifies the IPv4 or IPv6 network mask."
},
{
"code": null,
"e": 25699,
"s": 25625,
"text": "family: A string that specifies the Family, value is one of IPv4 or IPv6."
},
{
"code": null,
"e": 25770,
"s": 25699,
"text": "mac: A string that specifies the MAC address of the network interface."
},
{
"code": null,
"e": 25849,
"s": 25770,
"text": "internal: A boolean value, true if interface is loopback one, false otherwise."
},
{
"code": null,
"e": 25905,
"s": 25849,
"text": "scopeid: A number that specifies the scope ID for IPv6."
},
{
"code": null,
"e": 26052,
"s": 25905,
"text": "cidr: A string that specifies the assigned IPv4 or IPv6 address with the routing prefix in CIDR notation. It is set to null if netmask is invalid."
},
{
"code": null,
"e": 26131,
"s": 26052,
"text": "Below examples illustrate the use of os.networkInterfaces() method in Node.js:"
},
{
"code": null,
"e": 26142,
"s": 26131,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // os.networkInterfaces() Method // Allocating os moduleconst os = require('os'); // Print os.networkInterfaces() valueconsole.log(os.networkInterfaces());",
"e": 26340,
"s": 26142,
"text": null
},
{
"code": null,
"e": 26348,
"s": 26340,
"text": "Output:"
},
{
"code": null,
"e": 27180,
"s": 26348,
"text": "{ 'Wi-Fi':\n [ { address: 'fe80::242a:3451:7fb2:3ab1',\n netmask: 'ffff:ffff:ffff:ffff::',\n family: 'IPv6',\n mac: 'b3:52:16:13:de:b9',\n scopeid: 3,\n internal: false,\n cidr: 'fe80::242a:3451:7fb2:3ab1/64' },\n { address: '192.168.0.5',\n netmask: '255.255.255.0',\n family: 'IPv4',\n mac: 'b3:52:16:13:de:b9',\n internal: false,\n cidr: '192.168.0.5/24' } ],\n 'Loopback Pseudo-Interface 1':\n [ { address: '::1',\n netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',\n family: 'IPv6',\n mac: '00:00:00:00:00:00',\n scopeid: 0,\n internal: true,\n cidr: '::1/128' },\n { address: '127.0.0.1',\n netmask: '255.0.0.0',\n family: 'IPv4',\n mac: '00:00:00:00:00:00',\n internal: true,\n cidr: '127.0.0.1/8' } ] }\n"
},
{
"code": null,
"e": 27191,
"s": 27180,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the // os.networkInterfaces() Method // Allocating os moduleconst os = require('os'); // Print os.networkInterfaces() valuevar net_int = os.networkInterfaces(); var no_of_network_interfaces = 0; for (var key in net_int) { console.log(key); var net_infos=net_int[key]; net_infos.forEach(element => { no_of_network_interfaces++; console.log(\"\\tinterface:\"); for (var attr in element){ console.log(\"\\t\\t\" + attr + \" : \" + element[attr] ); } }); } console.log(\"total number of Network \" + \"interfaces is \" + no_of_network_interfaces);",
"e": 27805,
"s": 27191,
"text": null
},
{
"code": null,
"e": 27813,
"s": 27805,
"text": "Output:"
},
{
"code": null,
"e": 28932,
"s": 27813,
"text": "Wi-Fi\n interface:\n address : fe80::242a:3451:7fb2:3ab1\n netmask : ffff:ffff:ffff:ffff::\n family : IPv6\n mac : b3:52:16:13:de:b9\n scopeid : 3\n internal : false\n cidr : fe80::242a:3451:7fb2:3ab1/64\n interface:\n address : 192.168.0.5\n netmask : 255.255.255.0\n family : IPv4\n mac : b3:52:16:13:de:b9\n internal : false\n cidr : 192.168.0.5/24\nLoopback Pseudo-Interface 1\n interface:\n address : ::1\n netmask : ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff\n family : IPv6\n mac : 00:00:00:00:00:00\n scopeid : 0\n internal : true\n cidr : ::1/128\n interface:\n address : 127.0.0.1\n netmask : 255.0.0.0\n family : IPv4\n mac : 00:00:00:00:00:00\n internal : true\n cidr : 127.0.0.1/8\ntotal number of Network interfaces is 4\n"
},
{
"code": null,
"e": 29016,
"s": 28932,
"text": "Note: The above program will compile and run by using the node filename.js command."
},
{
"code": null,
"e": 29082,
"s": 29016,
"text": "Reference: https://nodejs.org/api/os.html#os_os_networkinterfaces"
},
{
"code": null,
"e": 29100,
"s": 29082,
"text": "Node.js-os-module"
},
{
"code": null,
"e": 29108,
"s": 29100,
"text": "Node.js"
},
{
"code": null,
"e": 29125,
"s": 29108,
"text": "Web Technologies"
},
{
"code": null,
"e": 29223,
"s": 29125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29260,
"s": 29223,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 29292,
"s": 29260,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 29323,
"s": 29292,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 29350,
"s": 29323,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 29397,
"s": 29350,
"text": "Difference between npm i and npm ci in Node.js"
},
{
"code": null,
"e": 29439,
"s": 29397,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29482,
"s": 29439,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29544,
"s": 29482,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29594,
"s": 29544,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python List Comprehensions in 5-minutes | by Daniel Bourke | Towards Data Science | Just show me the code! Quick link: Jupyter Notebook on GitHub
Why would you want to do a Python list comprehension?
To save lines of code.
There’s might be more to it than that but in my experience, this is the only reason — if you have a better one, leave a comment and I’ll update the article.
You can get the exact same thing done with a couple extra lines. But browse any Python Stack Overflow question and chances are you’ll find someone asking for a Pythonic version or a Pythonic one-liner.
List comprehensions are a way of achieving Pythonic one-liners with iterables (lists).
One-line definitions:
List = a Python object which can be iterated over (an iterable).
Iterated over = going through something one-by-one.
A good example is emptying your shopping cart at the cashier, you pull each item out one by one and put it on the counter, your shopping cart could be considered an iterable.
We’ll use this example to look at some code. We’re shopping at a math store so all we’re buying is numbers.
# Create a list of numbers (our shopping cart)cart = [3, 4, 12, 17, 19, 21, 23, 26, 30]# Pass items to the cashiercashier = []for item in cart: cashier.append(item)print(cashier)# The output is the same as the cartOutput: [3, 4, 12, 17, 19, 21, 23, 26, 30]
What happened here?
We created a list of items in the cartWe created an empty cashierlist (the cashierdidn’t have any of our items yet)We used a for loop to iterate over each itemin our cartFor each itemwe added it to the cashier list with .append()Then we checked what items the cashier had with print()
We created a list of items in the cart
We created an empty cashierlist (the cashierdidn’t have any of our items yet)
We used a for loop to iterate over each itemin our cart
For each itemwe added it to the cashier list with .append()
Then we checked what items the cashier had with print()
How could we do this same thing a list comprehension?
# Pass items to second cashier but with a list comprehensioncashier_2 = [item for item in cart]print(cashier_2)# The output is the same as cashier (and the same as cart)Output: [3, 4, 12, 17, 19, 21, 23, 26, 30]
What happened here?
The exact same steps as above, only written in a different way. Let’s compare.
cashier is created in blue. On the left, it’s created on its own line. On the right, it’s created at the same time everything else is being created.cart is being iterated over in green. item is created as the for loop runs. This step is the same as grabbing one item at a time out of your shopping cart and passing it to the cashier.cashier is updated in the red with each item. The only difference is on the left, an .append() statement is required. The list comprehension on the right negates the need for an .append() statement
cashier is created in blue. On the left, it’s created on its own line. On the right, it’s created at the same time everything else is being created.
cart is being iterated over in green. item is created as the for loop runs. This step is the same as grabbing one item at a time out of your shopping cart and passing it to the cashier.
cashier is updated in the red with each item. The only difference is on the left, an .append() statement is required. The list comprehension on the right negates the need for an .append() statement
We accomplished the same steps in 1 line of code instead of 3. This may not seem like much but say you had a 1000 line Python project. You could potentially reduce your project from 1000 lines to 300. This kind of reduction won’t always happen but it’s an example of how to get the same task done with a Pythonic one-liner.
Now you’ve got a little bit of an intuition, let’s look at a few more examples.
cashier_3 only deals with even numbers. How could we deal with this?
By using a conditional.
Conditional = another way of saying, do something if True, stop if False.
# Make a new cartcart = [5, 7, 9, 10, 12, 15, 19, 20, 22]# Only give cashier_3 even numberscashier_3 = []for item in cart: if item % 2 == 0: cashier_3.append(item)print(cashier_3)# Thanks to the conditional the output is only the even numbersOutput: [10, 12, 20, 22]
How about with a list comprehension?
cashier_3 = [item for item in cart if item % 2 == 0]print(cashier_3)# The output is the same as aboveOutput: [10, 12, 20, 22]
What’s happening here?
This is similar to the above example except for the conditional in yellow.
cashier_3 is created in blue.cart is being iterated over in green. item is being created as the for loop runs.As each item is passed to cashier_3, it’s being checked to see if it matches up with the conditional in yellow.cashier_3 is updated in the red with each item as long as it fulfils the conditional in yellow.
cashier_3 is created in blue.
cart is being iterated over in green. item is being created as the for loop runs.
As each item is passed to cashier_3, it’s being checked to see if it matches up with the conditional in yellow.
cashier_3 is updated in the red with each item as long as it fulfils the conditional in yellow.
cashier_4 only accepts numbers over 100 and are odd. How could you do this?
# Reminder of what cart looks likecart = [5, 7, 9, 10, 12, 15, 19, 20, 22]# Non-list comprehension for cashier_4cashier_4 = []for item in cart: item += 100 # add 100 to each item to bring them over 100 if item % 2 == 1: # check to see if they're odd or not cashier_4.append(item)print(cashier_4)# The output is all odd numbers over 100Output: [105, 107, 109, 115, 119]
Now with a list comprehension.
# List comprehension for cashier_4cashier_4 = [item+100 for item in cart if item % 2 == 1]print(cashier_4)# The output is all odd numbers over 100 (same as above)Output: [105, 107, 109, 115, 119]
This tutorial only scratches the surface of what’s possible with Python list comprehensions. Once you start to get the hang of them, you’ll start to realise how valuable they are for writing succinct and powerful Pythonic code.
If you’re looking for more, I recommend checking out the Python list comprehension tutorial on DataCamp.
All the code in this article is available on GitHub and a video version of this article is available on YouTube.
Have advice for the next article? Feel free to leave a response or reach out via Twitter, LinkedIn, Email. | [
{
"code": null,
"e": 233,
"s": 171,
"text": "Just show me the code! Quick link: Jupyter Notebook on GitHub"
},
{
"code": null,
"e": 287,
"s": 233,
"text": "Why would you want to do a Python list comprehension?"
},
{
"code": null,
"e": 310,
"s": 287,
"text": "To save lines of code."
},
{
"code": null,
"e": 467,
"s": 310,
"text": "There’s might be more to it than that but in my experience, this is the only reason — if you have a better one, leave a comment and I’ll update the article."
},
{
"code": null,
"e": 669,
"s": 467,
"text": "You can get the exact same thing done with a couple extra lines. But browse any Python Stack Overflow question and chances are you’ll find someone asking for a Pythonic version or a Pythonic one-liner."
},
{
"code": null,
"e": 756,
"s": 669,
"text": "List comprehensions are a way of achieving Pythonic one-liners with iterables (lists)."
},
{
"code": null,
"e": 778,
"s": 756,
"text": "One-line definitions:"
},
{
"code": null,
"e": 843,
"s": 778,
"text": "List = a Python object which can be iterated over (an iterable)."
},
{
"code": null,
"e": 895,
"s": 843,
"text": "Iterated over = going through something one-by-one."
},
{
"code": null,
"e": 1070,
"s": 895,
"text": "A good example is emptying your shopping cart at the cashier, you pull each item out one by one and put it on the counter, your shopping cart could be considered an iterable."
},
{
"code": null,
"e": 1178,
"s": 1070,
"text": "We’ll use this example to look at some code. We’re shopping at a math store so all we’re buying is numbers."
},
{
"code": null,
"e": 1438,
"s": 1178,
"text": "# Create a list of numbers (our shopping cart)cart = [3, 4, 12, 17, 19, 21, 23, 26, 30]# Pass items to the cashiercashier = []for item in cart: cashier.append(item)print(cashier)# The output is the same as the cartOutput: [3, 4, 12, 17, 19, 21, 23, 26, 30]"
},
{
"code": null,
"e": 1458,
"s": 1438,
"text": "What happened here?"
},
{
"code": null,
"e": 1743,
"s": 1458,
"text": "We created a list of items in the cartWe created an empty cashierlist (the cashierdidn’t have any of our items yet)We used a for loop to iterate over each itemin our cartFor each itemwe added it to the cashier list with .append()Then we checked what items the cashier had with print()"
},
{
"code": null,
"e": 1782,
"s": 1743,
"text": "We created a list of items in the cart"
},
{
"code": null,
"e": 1860,
"s": 1782,
"text": "We created an empty cashierlist (the cashierdidn’t have any of our items yet)"
},
{
"code": null,
"e": 1916,
"s": 1860,
"text": "We used a for loop to iterate over each itemin our cart"
},
{
"code": null,
"e": 1976,
"s": 1916,
"text": "For each itemwe added it to the cashier list with .append()"
},
{
"code": null,
"e": 2032,
"s": 1976,
"text": "Then we checked what items the cashier had with print()"
},
{
"code": null,
"e": 2086,
"s": 2032,
"text": "How could we do this same thing a list comprehension?"
},
{
"code": null,
"e": 2298,
"s": 2086,
"text": "# Pass items to second cashier but with a list comprehensioncashier_2 = [item for item in cart]print(cashier_2)# The output is the same as cashier (and the same as cart)Output: [3, 4, 12, 17, 19, 21, 23, 26, 30]"
},
{
"code": null,
"e": 2318,
"s": 2298,
"text": "What happened here?"
},
{
"code": null,
"e": 2397,
"s": 2318,
"text": "The exact same steps as above, only written in a different way. Let’s compare."
},
{
"code": null,
"e": 2928,
"s": 2397,
"text": "cashier is created in blue. On the left, it’s created on its own line. On the right, it’s created at the same time everything else is being created.cart is being iterated over in green. item is created as the for loop runs. This step is the same as grabbing one item at a time out of your shopping cart and passing it to the cashier.cashier is updated in the red with each item. The only difference is on the left, an .append() statement is required. The list comprehension on the right negates the need for an .append() statement"
},
{
"code": null,
"e": 3077,
"s": 2928,
"text": "cashier is created in blue. On the left, it’s created on its own line. On the right, it’s created at the same time everything else is being created."
},
{
"code": null,
"e": 3263,
"s": 3077,
"text": "cart is being iterated over in green. item is created as the for loop runs. This step is the same as grabbing one item at a time out of your shopping cart and passing it to the cashier."
},
{
"code": null,
"e": 3461,
"s": 3263,
"text": "cashier is updated in the red with each item. The only difference is on the left, an .append() statement is required. The list comprehension on the right negates the need for an .append() statement"
},
{
"code": null,
"e": 3785,
"s": 3461,
"text": "We accomplished the same steps in 1 line of code instead of 3. This may not seem like much but say you had a 1000 line Python project. You could potentially reduce your project from 1000 lines to 300. This kind of reduction won’t always happen but it’s an example of how to get the same task done with a Pythonic one-liner."
},
{
"code": null,
"e": 3865,
"s": 3785,
"text": "Now you’ve got a little bit of an intuition, let’s look at a few more examples."
},
{
"code": null,
"e": 3934,
"s": 3865,
"text": "cashier_3 only deals with even numbers. How could we deal with this?"
},
{
"code": null,
"e": 3958,
"s": 3934,
"text": "By using a conditional."
},
{
"code": null,
"e": 4032,
"s": 3958,
"text": "Conditional = another way of saying, do something if True, stop if False."
},
{
"code": null,
"e": 4309,
"s": 4032,
"text": "# Make a new cartcart = [5, 7, 9, 10, 12, 15, 19, 20, 22]# Only give cashier_3 even numberscashier_3 = []for item in cart: if item % 2 == 0: cashier_3.append(item)print(cashier_3)# Thanks to the conditional the output is only the even numbersOutput: [10, 12, 20, 22]"
},
{
"code": null,
"e": 4346,
"s": 4309,
"text": "How about with a list comprehension?"
},
{
"code": null,
"e": 4472,
"s": 4346,
"text": "cashier_3 = [item for item in cart if item % 2 == 0]print(cashier_3)# The output is the same as aboveOutput: [10, 12, 20, 22]"
},
{
"code": null,
"e": 4495,
"s": 4472,
"text": "What’s happening here?"
},
{
"code": null,
"e": 4570,
"s": 4495,
"text": "This is similar to the above example except for the conditional in yellow."
},
{
"code": null,
"e": 4887,
"s": 4570,
"text": "cashier_3 is created in blue.cart is being iterated over in green. item is being created as the for loop runs.As each item is passed to cashier_3, it’s being checked to see if it matches up with the conditional in yellow.cashier_3 is updated in the red with each item as long as it fulfils the conditional in yellow."
},
{
"code": null,
"e": 4917,
"s": 4887,
"text": "cashier_3 is created in blue."
},
{
"code": null,
"e": 4999,
"s": 4917,
"text": "cart is being iterated over in green. item is being created as the for loop runs."
},
{
"code": null,
"e": 5111,
"s": 4999,
"text": "As each item is passed to cashier_3, it’s being checked to see if it matches up with the conditional in yellow."
},
{
"code": null,
"e": 5207,
"s": 5111,
"text": "cashier_3 is updated in the red with each item as long as it fulfils the conditional in yellow."
},
{
"code": null,
"e": 5283,
"s": 5207,
"text": "cashier_4 only accepts numbers over 100 and are odd. How could you do this?"
},
{
"code": null,
"e": 5665,
"s": 5283,
"text": "# Reminder of what cart looks likecart = [5, 7, 9, 10, 12, 15, 19, 20, 22]# Non-list comprehension for cashier_4cashier_4 = []for item in cart: item += 100 # add 100 to each item to bring them over 100 if item % 2 == 1: # check to see if they're odd or not cashier_4.append(item)print(cashier_4)# The output is all odd numbers over 100Output: [105, 107, 109, 115, 119]"
},
{
"code": null,
"e": 5696,
"s": 5665,
"text": "Now with a list comprehension."
},
{
"code": null,
"e": 5892,
"s": 5696,
"text": "# List comprehension for cashier_4cashier_4 = [item+100 for item in cart if item % 2 == 1]print(cashier_4)# The output is all odd numbers over 100 (same as above)Output: [105, 107, 109, 115, 119]"
},
{
"code": null,
"e": 6120,
"s": 5892,
"text": "This tutorial only scratches the surface of what’s possible with Python list comprehensions. Once you start to get the hang of them, you’ll start to realise how valuable they are for writing succinct and powerful Pythonic code."
},
{
"code": null,
"e": 6225,
"s": 6120,
"text": "If you’re looking for more, I recommend checking out the Python list comprehension tutorial on DataCamp."
},
{
"code": null,
"e": 6338,
"s": 6225,
"text": "All the code in this article is available on GitHub and a video version of this article is available on YouTube."
}
] |
Rendering elegant stock trading agents using Matplotlib and Gym | by Adam King | Towards Data Science | We are going to be extending the code we wrote in the last tutorial to render an insightful visualization of the environment using Matplotlib. If you haven’t read my first article on Creating custom Gym environments from scratch, you should stop here and read that first.
If you are unfamiliar with the matplotlib library, don’t worry. We will be going over every line so you can create your own custom visualizations of your gym environments. As always, the code for this tutorial will be available on my Github.
Here is a sneak preview of what we will be creating in this article:
If it looks complicated, it’s actually not that bad. Just a couple of graphs updating on each step, annotated with some key information. Let’s get started!
We're so pumped to have you!
Already have an account? Sign In
In our last tutorial, we wrote a simple render method using print statements to display the agent’s net worth and other important metrics. Let’s move that logic to a new method called _render_to_file, so we can save a session’s trading metrics to a file, if necessary.
def _render_to_file(self, filename='render.txt'): profit = self.net_worth - INITIAL_ACCOUNT_BALANCE file = open(filename, 'a+') file.write(f'Step: {self.current_step}\n') file.write(f'Balance: {self.balance}\n') file.write(f'Shares held: {self.shares_held} (Total sold: {self.total_shares_sold})\n') file.write(f'Avg cost for held shares: {self.cost_basis} (Total sales value: {self.total_sales_value})\n') file.write(f'Net worth: {self.net_worth} (Max net worth: {self.max_net_worth})\n') file.write(f'Profit: {profit}\n\n') file.close()
Now, let’s move onto creating our new render method. It’s going to utilize our new StockTradingGraph class, that we haven’t written yet. We’ll get to that next.
def render(self, mode='live', title=None, **kwargs): # Render the environment to the screen if mode == 'file': self._render_to_file(kwargs.get('filename', 'render.txt')) elif mode == 'live': if self.visualization == None: self.visualization = StockTradingGraph(self.df, title) if self.current_step > LOOKBACK_WINDOW_SIZE: self.visualization.render(self.current_step, self.net_worth, self.trades, window_size=LOOKBACK_WINDOW_SIZE)
We are using kwargs here to pass the optional filename and title to the StockTradingGraph. If you are unfamiliar with kwargs, it is basically a dictionary for passing optional keyword arguments to functions.
We also pass self.trades for the visualization to render, but have not defined it yet, so let’s do that. Back in our _take_action method, whenever we buy or sell shares, we are now going to add the details of that transaction to the self.trades object, which we’ve initialized to [] in our reset method.
def _take_action(self, action): ... if action_type < 1: ... if shares_bought > 0: self.trades.append({'step': self.current_step, 'shares': shares_bought, 'total': additional_cost, 'type': "buy"}) elif action_type < 2: ... if shares_sold > 0: self.trades.append({'step': self.current_step, 'shares': shares_sold, 'total': shares_sold * current_price, 'type': "sell"})
Now our StockTradingGraph has all of the information it needs to render the stock’s price history and trade volume, along with our agent’s net worth and any trades its made. Let’s get started rendering our visualization.
First, we’ll define our StockTradingGraph and its __init__ method. Here is where we will create our pyplot figure, and set up each of the subplots to be rendered to. The date2num function is used to reformat dates into timestamps, necessary later in the rendering process.
import numpy as npimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesdef date2num(date): converter = mdates.strpdate2num('%Y-%m-%d') return converter(date)class StockTradingGraph: """A stock trading visualization using matplotlib made to render OpenAI gym environments""" def __init__(self, df, title=None): self.df = df self.net_worths = np.zeros(len(df['Date'])) # Create a figure on screen and set the title fig = plt.figure() fig.suptitle(title) # Create top subplot for net worth axis self.net_worth_ax = plt.subplot2grid((6, 1), (0, 0), rowspan=2, colspan=1) # Create bottom subplot for shared price/volume axis self.price_ax = plt.subplot2grid((6, 1), (2, 0), rowspan=8, colspan=1, sharex=self.net_worth_ax) # Create a new axis for volume which shares its x-axis with price self.volume_ax = self.price_ax.twinx() # Add padding to make graph easier to view plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0) # Show the graph without blocking the rest of the program plt.show(block=False)
We use the plt.subplot2grid(...) method to first create a subplot at the top of our figure to render our net worth grid, and then create another subplot below it for our price grid. The first argument of subplot2grid is the size of the subplot and the second is the location within the figure.
To render our trade volume bars, we call the twinx() method on self.price_ax, which allows us to overlay another grid on top that will share the same x-axis. Finally, and most importantly, we will render our figure to the screen using plt.show(block=False). If you forget to pass block=False, you will only ever see the first step rendered, after which the agent will be blocked from continuing.
Next, let’s write our render method. This will take all of the information from the current time step and render a live representation to the screen.
def render(self, current_step, net_worth, trades, window_size=40): self.net_worths[current_step] = net_worth window_start = max(current_step - window_size, 0) step_range = range(window_start, current_step + 1) # Format dates as timestamps, necessary for candlestick graph dates = np.array([date2num(x) for x in self.df['Date'].values[step_range]]) self._render_net_worth(current_step, net_worth, window_size, dates) self._render_price(current_step, net_worth, dates, step_range) self._render_volume(current_step, net_worth, dates, step_range) self._render_trades(current_step, trades, step_range) # Format the date ticks to be more easily read self.price_ax.set_xticklabels(self.df['Date'].values[step_range], rotation=45, horizontalalignment='right') # Hide duplicate net worth date labels plt.setp(self.net_worth_ax.get_xticklabels(), visible=False) # Necessary to view frames before they are unrendered plt.pause(0.001)
Here, we save the net_worth, and then render each graph from top to bottom. We’re also going to annotate the price graph with the trades the agent has taken in theself.render_trades method. It’s important to call plt.pause() here, otherwise each frame will be cleared by the next call to render, before the last frame was actually shown on screen.
Now, let’s look at each of the graph’s render methods, starting with net worth.
def _render_net_worth(self, current_step, net_worth, step_range, dates): # Clear the frame rendered last step self.net_worth_ax.clear() # Plot net worths self.net_worth_ax.plot_date(dates, self.net_worths[step_range], '- ', label='Net Worth') # Show legend, which uses the label we defined for the plot above self.net_worth_ax.legend() legend = self.net_worth_ax.legend(loc=2, ncol=2, prop={'size': 8}) legend.get_frame().set_alpha(0.4) last_date = date2num(self.df['Date'].values[current_step]) last_net_worth = self.net_worths[current_step] # Annotate the current net worth on the net worth graph self.net_worth_ax.annotate('{0:.2f}'.format(net_worth), (last_date, last_net_worth), xytext=(last_date, last_net_worth), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color="black", fontsize="small") # Add space above and below min/max net worth self.net_worth_ax.set_ylim( min(self.net_worths[np.nonzero(self.net_worths)]) / 1.25, max(self.net_worths) * 1.25)
We just call plot_date(...) on our net worth subplot to plot a simple line graph, then annotate it with the agent’s current net_worth, and add a legend.
Rendering the price graph is a bit more complicated. To keep things simple, we are going to render the OHCL bars in a separate method from the volume bars. First, you need to pip install mpl_finance if you don’t already have it, as this package is needed for the candlestick graphs we’ll be using. Then add this line to the top of your file.
from mpl_finance import candlestick_ochl as candlestick
Great, let’s clear the previous frame, zip up the OHCL data, and render a candlestick graph to the self.price_ax subplot.
def _render_price(self, current_step, net_worth, dates, step_range): self.price_ax.clear() # Format data for OHCL candlestick graph candlesticks = zip(dates, self.df['Open'].values[step_range], self.df['Close'].values[step_range], self.df['High'].values[step_range], self.df['Low'].values[step_range]) # Plot price using candlestick graph from mpl_finance candlestick(self.price_ax, candlesticks, width=1, colorup=UP_COLOR, colordown=DOWN_COLOR) last_date = date2num(self.df['Date'].values[current_step]) last_close = self.df['Close'].values[current_step] last_high = self.df['High'].values[current_step] # Print the current price to the price axis self.price_ax.annotate('{0:.2f}'.format(last_close), (last_date, last_close), xytext=(last_date, last_high), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color="black", fontsize="small") # Shift price axis up to give volume chart space ylim = self.price_ax.get_ylim() self.price_ax.set_ylim(ylim[0] - (ylim[1] - ylim[0]) * VOLUME_CHART_HEIGHT, ylim[1])
We’ve annotated the graph with the stock’s current price, and shifted the chart up to prevent it from overlapping with the volume bars. Next let’s look at the volume render method, which is much simpler as there are no annotations.
def _render_volume(self, current_step, net_worth, dates, step_range): self.volume_ax.clear() volume = np.array(self.df['Volume'].values[step_range]) pos = self.df['Open'].values[step_range] - \ self.df['Close'].values[step_range] < 0 neg = self.df['Open'].values[step_range] - \ self.df['Close'].values[step_range] > 0 # Color volume bars based on price direction on that date self.volume_ax.bar(dates[pos], volume[pos], color=UP_COLOR, alpha=0.4, width=1, align='center') self.volume_ax.bar(dates[neg], volume[neg], color=DOWN_COLOR, alpha=0.4, width=1, align='center') # Cap volume axis height below price chart and hide ticks self.volume_ax.set_ylim(0, max(volume) / VOLUME_CHART_HEIGHT) self.volume_ax.yaxis.set_ticks([])
Just a simple bar graph, with each bar colored either green or red, depending on whether the price moved up or down in that time step.
Finally, let’s get to the fun part: _render_trades. In this method, we’ll render an arrow on the price graph where the agent has made a trade, annotated with the total amount transacted.
def _render_trades(self, current_step, trades, step_range): for trade in trades: if trade['step'] in step_range: date = date2num(self.df['Date'].values[trade['step']]) high = self.df['High'].values[trade['step']] low = self.df['Low'].values[trade['step']] if trade['type'] == 'buy': high_low = low color = UP_TEXT_COLOR else: high_low = high color = DOWN_TEXT_COLOR total = '{0:.2f}'.format(trade['total']) # Print the current price to the price axis self.price_ax.annotate(f'${total}', (date, high_low), xytext=(date, high_low), color=color, fontsize=8, arrowprops=(dict(color=color)))
And that’s it! We now have a beautiful, live rendering visualization of our stock trading environment we created in the last article! It’s too bad we still haven’t put much time into teaching the agent how to make money... We’ll leave that for next time!
Not too shabby! Next week we are going to build upon the code from this tutorial to create Bitcoin trading bots that don’t lose money.
towardsdatascience.com
Thanks for reading! As always, all of the code for this tutorial can be found on my Github. Leave a comment below if you have any questions or feedback, I’d love to hear from you! I can also be reached on Twitter at @notadamking.
You can also sponsor me on Github Sponsors or Patreon via the links below.
github.com
Github Sponsors is currently matching all donations 1:1 up to $5,000! | [
{
"code": null,
"e": 444,
"s": 172,
"text": "We are going to be extending the code we wrote in the last tutorial to render an insightful visualization of the environment using Matplotlib. If you haven’t read my first article on Creating custom Gym environments from scratch, you should stop here and read that first."
},
{
"code": null,
"e": 686,
"s": 444,
"text": "If you are unfamiliar with the matplotlib library, don’t worry. We will be going over every line so you can create your own custom visualizations of your gym environments. As always, the code for this tutorial will be available on my Github."
},
{
"code": null,
"e": 755,
"s": 686,
"text": "Here is a sneak preview of what we will be creating in this article:"
},
{
"code": null,
"e": 911,
"s": 755,
"text": "If it looks complicated, it’s actually not that bad. Just a couple of graphs updating on each step, annotated with some key information. Let’s get started!"
},
{
"code": null,
"e": 940,
"s": 911,
"text": "We're so pumped to have you!"
},
{
"code": null,
"e": 975,
"s": 940,
"text": "\nAlready have an account? Sign In\n"
},
{
"code": null,
"e": 1244,
"s": 975,
"text": "In our last tutorial, we wrote a simple render method using print statements to display the agent’s net worth and other important metrics. Let’s move that logic to a new method called _render_to_file, so we can save a session’s trading metrics to a file, if necessary."
},
{
"code": null,
"e": 1806,
"s": 1244,
"text": "def _render_to_file(self, filename='render.txt'): profit = self.net_worth - INITIAL_ACCOUNT_BALANCE file = open(filename, 'a+') file.write(f'Step: {self.current_step}\\n') file.write(f'Balance: {self.balance}\\n') file.write(f'Shares held: {self.shares_held} (Total sold: {self.total_shares_sold})\\n') file.write(f'Avg cost for held shares: {self.cost_basis} (Total sales value: {self.total_sales_value})\\n') file.write(f'Net worth: {self.net_worth} (Max net worth: {self.max_net_worth})\\n') file.write(f'Profit: {profit}\\n\\n') file.close()"
},
{
"code": null,
"e": 1967,
"s": 1806,
"text": "Now, let’s move onto creating our new render method. It’s going to utilize our new StockTradingGraph class, that we haven’t written yet. We’ll get to that next."
},
{
"code": null,
"e": 2439,
"s": 1967,
"text": "def render(self, mode='live', title=None, **kwargs): # Render the environment to the screen if mode == 'file': self._render_to_file(kwargs.get('filename', 'render.txt')) elif mode == 'live': if self.visualization == None: self.visualization = StockTradingGraph(self.df, title) if self.current_step > LOOKBACK_WINDOW_SIZE: self.visualization.render(self.current_step, self.net_worth, self.trades, window_size=LOOKBACK_WINDOW_SIZE)"
},
{
"code": null,
"e": 2647,
"s": 2439,
"text": "We are using kwargs here to pass the optional filename and title to the StockTradingGraph. If you are unfamiliar with kwargs, it is basically a dictionary for passing optional keyword arguments to functions."
},
{
"code": null,
"e": 2951,
"s": 2647,
"text": "We also pass self.trades for the visualization to render, but have not defined it yet, so let’s do that. Back in our _take_action method, whenever we buy or sell shares, we are now going to add the details of that transaction to the self.trades object, which we’ve initialized to [] in our reset method."
},
{
"code": null,
"e": 3377,
"s": 2951,
"text": "def _take_action(self, action): ... if action_type < 1: ... if shares_bought > 0: self.trades.append({'step': self.current_step, 'shares': shares_bought, 'total': additional_cost, 'type': \"buy\"}) elif action_type < 2: ... if shares_sold > 0: self.trades.append({'step': self.current_step, 'shares': shares_sold, 'total': shares_sold * current_price, 'type': \"sell\"})"
},
{
"code": null,
"e": 3598,
"s": 3377,
"text": "Now our StockTradingGraph has all of the information it needs to render the stock’s price history and trade volume, along with our agent’s net worth and any trades its made. Let’s get started rendering our visualization."
},
{
"code": null,
"e": 3871,
"s": 3598,
"text": "First, we’ll define our StockTradingGraph and its __init__ method. Here is where we will create our pyplot figure, and set up each of the subplots to be rendered to. The date2num function is used to reformat dates into timestamps, necessary later in the rendering process."
},
{
"code": null,
"e": 5015,
"s": 3871,
"text": "import numpy as npimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesdef date2num(date): converter = mdates.strpdate2num('%Y-%m-%d') return converter(date)class StockTradingGraph: \"\"\"A stock trading visualization using matplotlib made to render OpenAI gym environments\"\"\" def __init__(self, df, title=None): self.df = df self.net_worths = np.zeros(len(df['Date'])) # Create a figure on screen and set the title fig = plt.figure() fig.suptitle(title) # Create top subplot for net worth axis self.net_worth_ax = plt.subplot2grid((6, 1), (0, 0), rowspan=2, colspan=1) # Create bottom subplot for shared price/volume axis self.price_ax = plt.subplot2grid((6, 1), (2, 0), rowspan=8, colspan=1, sharex=self.net_worth_ax) # Create a new axis for volume which shares its x-axis with price self.volume_ax = self.price_ax.twinx() # Add padding to make graph easier to view plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0) # Show the graph without blocking the rest of the program plt.show(block=False)"
},
{
"code": null,
"e": 5309,
"s": 5015,
"text": "We use the plt.subplot2grid(...) method to first create a subplot at the top of our figure to render our net worth grid, and then create another subplot below it for our price grid. The first argument of subplot2grid is the size of the subplot and the second is the location within the figure."
},
{
"code": null,
"e": 5705,
"s": 5309,
"text": "To render our trade volume bars, we call the twinx() method on self.price_ax, which allows us to overlay another grid on top that will share the same x-axis. Finally, and most importantly, we will render our figure to the screen using plt.show(block=False). If you forget to pass block=False, you will only ever see the first step rendered, after which the agent will be blocked from continuing."
},
{
"code": null,
"e": 5855,
"s": 5705,
"text": "Next, let’s write our render method. This will take all of the information from the current time step and render a live representation to the screen."
},
{
"code": null,
"e": 6814,
"s": 5855,
"text": "def render(self, current_step, net_worth, trades, window_size=40): self.net_worths[current_step] = net_worth window_start = max(current_step - window_size, 0) step_range = range(window_start, current_step + 1) # Format dates as timestamps, necessary for candlestick graph dates = np.array([date2num(x) for x in self.df['Date'].values[step_range]]) self._render_net_worth(current_step, net_worth, window_size, dates) self._render_price(current_step, net_worth, dates, step_range) self._render_volume(current_step, net_worth, dates, step_range) self._render_trades(current_step, trades, step_range) # Format the date ticks to be more easily read self.price_ax.set_xticklabels(self.df['Date'].values[step_range], rotation=45, horizontalalignment='right') # Hide duplicate net worth date labels plt.setp(self.net_worth_ax.get_xticklabels(), visible=False) # Necessary to view frames before they are unrendered plt.pause(0.001)"
},
{
"code": null,
"e": 7162,
"s": 6814,
"text": "Here, we save the net_worth, and then render each graph from top to bottom. We’re also going to annotate the price graph with the trades the agent has taken in theself.render_trades method. It’s important to call plt.pause() here, otherwise each frame will be cleared by the next call to render, before the last frame was actually shown on screen."
},
{
"code": null,
"e": 7242,
"s": 7162,
"text": "Now, let’s look at each of the graph’s render methods, starting with net worth."
},
{
"code": null,
"e": 8276,
"s": 7242,
"text": "def _render_net_worth(self, current_step, net_worth, step_range, dates): # Clear the frame rendered last step self.net_worth_ax.clear() # Plot net worths self.net_worth_ax.plot_date(dates, self.net_worths[step_range], '- ', label='Net Worth') # Show legend, which uses the label we defined for the plot above self.net_worth_ax.legend() legend = self.net_worth_ax.legend(loc=2, ncol=2, prop={'size': 8}) legend.get_frame().set_alpha(0.4) last_date = date2num(self.df['Date'].values[current_step]) last_net_worth = self.net_worths[current_step] # Annotate the current net worth on the net worth graph self.net_worth_ax.annotate('{0:.2f}'.format(net_worth), (last_date, last_net_worth), xytext=(last_date, last_net_worth), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color=\"black\", fontsize=\"small\") # Add space above and below min/max net worth self.net_worth_ax.set_ylim( min(self.net_worths[np.nonzero(self.net_worths)]) / 1.25, max(self.net_worths) * 1.25)"
},
{
"code": null,
"e": 8429,
"s": 8276,
"text": "We just call plot_date(...) on our net worth subplot to plot a simple line graph, then annotate it with the agent’s current net_worth, and add a legend."
},
{
"code": null,
"e": 8771,
"s": 8429,
"text": "Rendering the price graph is a bit more complicated. To keep things simple, we are going to render the OHCL bars in a separate method from the volume bars. First, you need to pip install mpl_finance if you don’t already have it, as this package is needed for the candlestick graphs we’ll be using. Then add this line to the top of your file."
},
{
"code": null,
"e": 8827,
"s": 8771,
"text": "from mpl_finance import candlestick_ochl as candlestick"
},
{
"code": null,
"e": 8949,
"s": 8827,
"text": "Great, let’s clear the previous frame, zip up the OHCL data, and render a candlestick graph to the self.price_ax subplot."
},
{
"code": null,
"e": 10006,
"s": 8949,
"text": "def _render_price(self, current_step, net_worth, dates, step_range): self.price_ax.clear() # Format data for OHCL candlestick graph candlesticks = zip(dates, self.df['Open'].values[step_range], self.df['Close'].values[step_range], self.df['High'].values[step_range], self.df['Low'].values[step_range]) # Plot price using candlestick graph from mpl_finance candlestick(self.price_ax, candlesticks, width=1, colorup=UP_COLOR, colordown=DOWN_COLOR) last_date = date2num(self.df['Date'].values[current_step]) last_close = self.df['Close'].values[current_step] last_high = self.df['High'].values[current_step] # Print the current price to the price axis self.price_ax.annotate('{0:.2f}'.format(last_close), (last_date, last_close), xytext=(last_date, last_high), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color=\"black\", fontsize=\"small\") # Shift price axis up to give volume chart space ylim = self.price_ax.get_ylim() self.price_ax.set_ylim(ylim[0] - (ylim[1] - ylim[0]) * VOLUME_CHART_HEIGHT, ylim[1])"
},
{
"code": null,
"e": 10238,
"s": 10006,
"text": "We’ve annotated the graph with the stock’s current price, and shifted the chart up to prevent it from overlapping with the volume bars. Next let’s look at the volume render method, which is much simpler as there are no annotations."
},
{
"code": null,
"e": 11007,
"s": 10238,
"text": "def _render_volume(self, current_step, net_worth, dates, step_range): self.volume_ax.clear() volume = np.array(self.df['Volume'].values[step_range]) pos = self.df['Open'].values[step_range] - \\ self.df['Close'].values[step_range] < 0 neg = self.df['Open'].values[step_range] - \\ self.df['Close'].values[step_range] > 0 # Color volume bars based on price direction on that date self.volume_ax.bar(dates[pos], volume[pos], color=UP_COLOR, alpha=0.4, width=1, align='center') self.volume_ax.bar(dates[neg], volume[neg], color=DOWN_COLOR, alpha=0.4, width=1, align='center') # Cap volume axis height below price chart and hide ticks self.volume_ax.set_ylim(0, max(volume) / VOLUME_CHART_HEIGHT) self.volume_ax.yaxis.set_ticks([])"
},
{
"code": null,
"e": 11142,
"s": 11007,
"text": "Just a simple bar graph, with each bar colored either green or red, depending on whether the price moved up or down in that time step."
},
{
"code": null,
"e": 11329,
"s": 11142,
"text": "Finally, let’s get to the fun part: _render_trades. In this method, we’ll render an arrow on the price graph where the agent has made a trade, annotated with the total amount transacted."
},
{
"code": null,
"e": 12019,
"s": 11329,
"text": "def _render_trades(self, current_step, trades, step_range): for trade in trades: if trade['step'] in step_range: date = date2num(self.df['Date'].values[trade['step']]) high = self.df['High'].values[trade['step']] low = self.df['Low'].values[trade['step']] if trade['type'] == 'buy': high_low = low color = UP_TEXT_COLOR else: high_low = high color = DOWN_TEXT_COLOR total = '{0:.2f}'.format(trade['total']) # Print the current price to the price axis self.price_ax.annotate(f'${total}', (date, high_low), xytext=(date, high_low), color=color, fontsize=8, arrowprops=(dict(color=color)))"
},
{
"code": null,
"e": 12274,
"s": 12019,
"text": "And that’s it! We now have a beautiful, live rendering visualization of our stock trading environment we created in the last article! It’s too bad we still haven’t put much time into teaching the agent how to make money... We’ll leave that for next time!"
},
{
"code": null,
"e": 12409,
"s": 12274,
"text": "Not too shabby! Next week we are going to build upon the code from this tutorial to create Bitcoin trading bots that don’t lose money."
},
{
"code": null,
"e": 12432,
"s": 12409,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12662,
"s": 12432,
"text": "Thanks for reading! As always, all of the code for this tutorial can be found on my Github. Leave a comment below if you have any questions or feedback, I’d love to hear from you! I can also be reached on Twitter at @notadamking."
},
{
"code": null,
"e": 12737,
"s": 12662,
"text": "You can also sponsor me on Github Sponsors or Patreon via the links below."
},
{
"code": null,
"e": 12748,
"s": 12737,
"text": "github.com"
}
] |
How to create a comma separated string from a list of string in C#? | A List of string can be converted to a comma separated string using built in string.Join extension method.
string.Join("," , list);
This type of conversion is really useful when we collect a list of data (Ex: checkbox selected data) from the user and convert the same to a comma separated string and query the database to process further.
Live Demo
using System;
using System.Collections.Generic;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
List<string> fruitsList = new List<string> {
"banana",
"apple",
"mango"
};
string fruits = string.Join(",", fruitsList);
Console.WriteLine(fruits);
Console.ReadLine();
}
}
}
The output of the above code is
banana,apple,mango
Similarly, a property in a list of complex objects can also be converted to a comma separated string like below.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
var studentsList = new List<Student> {
new Student {
Id = 1,
Name = "John"
},
new Student {
Id = 2,
Name = "Jack"
}
};
string students = string.Join(",", studentsList.Select(student => student.Name));
Console.WriteLine(students);
Console.ReadLine();
}
}
public class Student {
public int Id { get; set; }
public string Name { get; set; }
}
}
The output of the above code is
John,Jack | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "A List of string can be converted to a comma separated string using built in string.Join extension method."
},
{
"code": null,
"e": 1194,
"s": 1169,
"text": "string.Join(\",\" , list);"
},
{
"code": null,
"e": 1401,
"s": 1194,
"text": "This type of conversion is really useful when we collect a list of data (Ex: checkbox selected data) from the user and convert the same to a comma separated string and query the database to process further."
},
{
"code": null,
"e": 1412,
"s": 1401,
"text": " Live Demo"
},
{
"code": null,
"e": 1818,
"s": 1412,
"text": "using System;\nusing System.Collections.Generic;\nnamespace DemoApplication {\n public class Program {\n static void Main(string[] args) {\n List<string> fruitsList = new List<string> {\n \"banana\",\n \"apple\",\n \"mango\"\n };\n string fruits = string.Join(\",\", fruitsList);\n Console.WriteLine(fruits);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 1850,
"s": 1818,
"text": "The output of the above code is"
},
{
"code": null,
"e": 1869,
"s": 1850,
"text": "banana,apple,mango"
},
{
"code": null,
"e": 1982,
"s": 1869,
"text": "Similarly, a property in a list of complex objects can also be converted to a comma separated string like below."
},
{
"code": null,
"e": 1993,
"s": 1982,
"text": " Live Demo"
},
{
"code": null,
"e": 2676,
"s": 1993,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace DemoApplication {\n public class Program {\n static void Main(string[] args) {\n var studentsList = new List<Student> {\n new Student {\n Id = 1,\n Name = \"John\"\n },\n new Student {\n Id = 2,\n Name = \"Jack\"\n }\n };\n string students = string.Join(\",\", studentsList.Select(student => student.Name));\n Console.WriteLine(students);\n Console.ReadLine();\n }\n }\n public class Student {\n public int Id { get; set; }\n public string Name { get; set; }\n }\n}"
},
{
"code": null,
"e": 2708,
"s": 2676,
"text": "The output of the above code is"
},
{
"code": null,
"e": 2718,
"s": 2708,
"text": "John,Jack"
}
] |
Development of Genetic Algorithm | Towards Data Science | Many people have heard about the big skepticism in the field of artificial intelligence from final consumers: “We have been on the market for 50 years, so we know better what to do”.
You are talking about your AI, but how does it work? Can you write an algorithm for our sales department? How can we interpret the results?
From these desires, a popular task emerged: “ICP-segmentation for B2B”. ICP — ideal customer profile, target segment in sales. There are parameters of a company at the input: country, amount, income; at the output, we predict some other parameters:
conversion of potential client
what income can give you the client
is this person the one who makes decisions in his company, etc.
Next, we calculate the scoring and, consequently, the probability of getting into one or another group.
The task looks clear enough: we take the input parameters, transform them into the required form, substitute them into the model, and train the model. However, as mentioned earlier, the end-users of our solution will want not only to see the result but also to understand why a certain resulting scheme solves their problem better than a team of professional employees with good intuition. Therefore, in addition to being effective, our decision must be interpretable.
Trying to find a compromise between the efficiency and interpretability of the problem, we came to the following math model:
Or, more simply, a truncated quadratic model with a constraint on the influence of a parameter. The final score is from -100 to 100, and everything is interpreted quite well. You can try to create a model based on intuition (we work with America, which means we will put the most weight on it), or you can find a model based on actual conversion data or profit.
This is where the brute-force problem came from, which was supposed to be solved using a genetic algorithm because the methods of ordinary linear programming (with simplifications) stumble over the amount of data. Each set(x,y)will be briefly referred to as a gene.
At each stage, we calculate the scoring using the formula for each row in the dataset and calculate, using one of several loss functions, how well this gene predicts the result or not.
There are several loss functions that have been investigated:
1 — Matrix: there is a matrix of penalties where we calculate a penalty or a bonus for each row, for example, if we try to split the sample into 2 groups, then in case of errors of the first or second kind, we give a penalty -1, and in case of falling into the correct group, we give a bonus 1
2 — By Average: Calculate the average target parameter for each group and try to find the maximum distance between the groups.
Despite the fact that the results of using the first loss function are easier to interpret, the resulting groups are too heterogeneous. As a result, the effectiveness is grouped when the number of groups is more than two. As a result, the groups are too heterogeneous due to the randomness of the data for groupings, so let’s choose the second option. Sample distribution after PCA (chaotic reference):
A genetic algorithm is a set of transformations of the original sample and, at each stage, discarding the worst results. Initially, the algorithm is naturally multithreaded for large problems, and the growth is not linear. For example, running on 16 cores gives an increase of almost 10 times, in contrast to the algorithm without multithreading. It is also worth looking at optimizing the loss function for sampling. But there are also less obvious ways.
The first thing I want to discuss is reducing the number of map-reduces during parallelization. The genetic algorithm is divided into several phases, namely: reproduction, mutation, calculation of the next generation. All this can be combined into one task with a trigger inside the parameters. That is, instead of:
CURRENT_POPULATION = mutation.Mutation(CURRENT_POPULATION,triggers)CURRENT_POPULATION = reproduction.Reproduction_multythread(CURRENT_POPULATION)
Can be combined into one function:
CURRENT_POPULATION = mut_rep_iteration.Itr(CURRENT_POPULATION,triggers)
Results of comparing the speed of one iteration:
The combined function (new fn) is almost 10 percent better than the previous (old fn). The algorithm itself can count almost a full day, which means that the calculations can take 2–3 hours less.
To begin with, let us recall the mathematical model that we are researching:
Obviously, if we take not random values in the genetic algorithm, but, for example, some valid gene, then the algorithm will need fewer iterations.
Let’s apply several controversial approximations.
1 — Approximate option only yj:
make a random set x, substitute it into the formula and get the usual linear equation in each row
calculate each yj as a system of equations
to fit the conditions, substitute the extreme y values again into the formula, again solve the usual SLAE system already with fewer variables and repeat several times
round each yj
we obtain some initial approximation for each parameter yj
This assumption makes sense since many parameters y are often repeated in different schemes. If some parameter is good (strongly affects the result), then it will have a maximum or minimum value in any scheme.
2 — General approximation variant (gradient descent):
do option 1
we solve the inverse problem: substitute the parameters y and calculate x
repeat N times
Here, in addition to local parameters, we also want to see which group most strongly affects the final result. The speed of the algorithm is low. Therefore, for each variant, five runs were carried out.
Current parameter set:
Generation survivors: 50,000
Number of children: 25,000
Number of mutants: 12,500
Now let’s look at the results:
Variant 1 is the same as a clean launch, which means that the approximation did not lead to positive consequences, but the second one (variant 2) looks promising, but let’s look at the execution time graph.
The time taken to execute is significantly increased due to the time spent on the initial approximation. This is a bit unfair. So, let’s try to compare the usual algorithm with variant 2, giving more resources to the regular algorithm and approximating the time by expanding the sample at each iteration.
Despite the resources being far superior to option number 2 (fp2), achieving a consistently better result is impossible. In theory, this can be corrected by searching for hyperparameters and filtering the next generation to protect against dominance. Research in this direction continues, so the second version of the initial approximation is chosen.
An initial approximation in this problem stabilizes the answer and optimizes resources. The initial approximation was chosen as several iterations of gradient descent:
gen = ret_random_gen(0) #Full random genfor i in range(0,iters): gen = CalculateByGenMG(gen) # calculate only X gen = CalculateByGenML(gen) # calculate only Y
In the end, I would like to provide data from the graphics of model validation in production.
Training is based on the data on the size of the check. Each lead falls into a group from Low to Very High, and as you can see, the higher the rank, the higher the probability of a high check. The incoming data structure has slightly changed, but the differentiation of groups remains stable.
A genetic algorithm is a resource-intensive process, and optimizing this process can become the main task in its creation. The algorithm is easy to use, helps find the optimal solution in brute force problems, and proves its effectiveness. | [
{
"code": null,
"e": 355,
"s": 172,
"text": "Many people have heard about the big skepticism in the field of artificial intelligence from final consumers: “We have been on the market for 50 years, so we know better what to do”."
},
{
"code": null,
"e": 495,
"s": 355,
"text": "You are talking about your AI, but how does it work? Can you write an algorithm for our sales department? How can we interpret the results?"
},
{
"code": null,
"e": 744,
"s": 495,
"text": "From these desires, a popular task emerged: “ICP-segmentation for B2B”. ICP — ideal customer profile, target segment in sales. There are parameters of a company at the input: country, amount, income; at the output, we predict some other parameters:"
},
{
"code": null,
"e": 775,
"s": 744,
"text": "conversion of potential client"
},
{
"code": null,
"e": 811,
"s": 775,
"text": "what income can give you the client"
},
{
"code": null,
"e": 875,
"s": 811,
"text": "is this person the one who makes decisions in his company, etc."
},
{
"code": null,
"e": 979,
"s": 875,
"text": "Next, we calculate the scoring and, consequently, the probability of getting into one or another group."
},
{
"code": null,
"e": 1448,
"s": 979,
"text": "The task looks clear enough: we take the input parameters, transform them into the required form, substitute them into the model, and train the model. However, as mentioned earlier, the end-users of our solution will want not only to see the result but also to understand why a certain resulting scheme solves their problem better than a team of professional employees with good intuition. Therefore, in addition to being effective, our decision must be interpretable."
},
{
"code": null,
"e": 1573,
"s": 1448,
"text": "Trying to find a compromise between the efficiency and interpretability of the problem, we came to the following math model:"
},
{
"code": null,
"e": 1935,
"s": 1573,
"text": "Or, more simply, a truncated quadratic model with a constraint on the influence of a parameter. The final score is from -100 to 100, and everything is interpreted quite well. You can try to create a model based on intuition (we work with America, which means we will put the most weight on it), or you can find a model based on actual conversion data or profit."
},
{
"code": null,
"e": 2201,
"s": 1935,
"text": "This is where the brute-force problem came from, which was supposed to be solved using a genetic algorithm because the methods of ordinary linear programming (with simplifications) stumble over the amount of data. Each set(x,y)will be briefly referred to as a gene."
},
{
"code": null,
"e": 2386,
"s": 2201,
"text": "At each stage, we calculate the scoring using the formula for each row in the dataset and calculate, using one of several loss functions, how well this gene predicts the result or not."
},
{
"code": null,
"e": 2448,
"s": 2386,
"text": "There are several loss functions that have been investigated:"
},
{
"code": null,
"e": 2742,
"s": 2448,
"text": "1 — Matrix: there is a matrix of penalties where we calculate a penalty or a bonus for each row, for example, if we try to split the sample into 2 groups, then in case of errors of the first or second kind, we give a penalty -1, and in case of falling into the correct group, we give a bonus 1"
},
{
"code": null,
"e": 2869,
"s": 2742,
"text": "2 — By Average: Calculate the average target parameter for each group and try to find the maximum distance between the groups."
},
{
"code": null,
"e": 3272,
"s": 2869,
"text": "Despite the fact that the results of using the first loss function are easier to interpret, the resulting groups are too heterogeneous. As a result, the effectiveness is grouped when the number of groups is more than two. As a result, the groups are too heterogeneous due to the randomness of the data for groupings, so let’s choose the second option. Sample distribution after PCA (chaotic reference):"
},
{
"code": null,
"e": 3728,
"s": 3272,
"text": "A genetic algorithm is a set of transformations of the original sample and, at each stage, discarding the worst results. Initially, the algorithm is naturally multithreaded for large problems, and the growth is not linear. For example, running on 16 cores gives an increase of almost 10 times, in contrast to the algorithm without multithreading. It is also worth looking at optimizing the loss function for sampling. But there are also less obvious ways."
},
{
"code": null,
"e": 4044,
"s": 3728,
"text": "The first thing I want to discuss is reducing the number of map-reduces during parallelization. The genetic algorithm is divided into several phases, namely: reproduction, mutation, calculation of the next generation. All this can be combined into one task with a trigger inside the parameters. That is, instead of:"
},
{
"code": null,
"e": 4190,
"s": 4044,
"text": "CURRENT_POPULATION = mutation.Mutation(CURRENT_POPULATION,triggers)CURRENT_POPULATION = reproduction.Reproduction_multythread(CURRENT_POPULATION)"
},
{
"code": null,
"e": 4225,
"s": 4190,
"text": "Can be combined into one function:"
},
{
"code": null,
"e": 4297,
"s": 4225,
"text": "CURRENT_POPULATION = mut_rep_iteration.Itr(CURRENT_POPULATION,triggers)"
},
{
"code": null,
"e": 4346,
"s": 4297,
"text": "Results of comparing the speed of one iteration:"
},
{
"code": null,
"e": 4542,
"s": 4346,
"text": "The combined function (new fn) is almost 10 percent better than the previous (old fn). The algorithm itself can count almost a full day, which means that the calculations can take 2–3 hours less."
},
{
"code": null,
"e": 4619,
"s": 4542,
"text": "To begin with, let us recall the mathematical model that we are researching:"
},
{
"code": null,
"e": 4769,
"s": 4619,
"text": "Obviously, if we take not random values in the genetic algorithm, but, for example, some valid gene, then the algorithm will need fewer iterations."
},
{
"code": null,
"e": 4819,
"s": 4769,
"text": "Let’s apply several controversial approximations."
},
{
"code": null,
"e": 4851,
"s": 4819,
"text": "1 — Approximate option only yj:"
},
{
"code": null,
"e": 4949,
"s": 4851,
"text": "make a random set x, substitute it into the formula and get the usual linear equation in each row"
},
{
"code": null,
"e": 4992,
"s": 4949,
"text": "calculate each yj as a system of equations"
},
{
"code": null,
"e": 5161,
"s": 4992,
"text": "to fit the conditions, substitute the extreme y values again into the formula, again solve the usual SLAE system already with fewer variables and repeat several times"
},
{
"code": null,
"e": 5175,
"s": 5161,
"text": "round each yj"
},
{
"code": null,
"e": 5234,
"s": 5175,
"text": "we obtain some initial approximation for each parameter yj"
},
{
"code": null,
"e": 5444,
"s": 5234,
"text": "This assumption makes sense since many parameters y are often repeated in different schemes. If some parameter is good (strongly affects the result), then it will have a maximum or minimum value in any scheme."
},
{
"code": null,
"e": 5498,
"s": 5444,
"text": "2 — General approximation variant (gradient descent):"
},
{
"code": null,
"e": 5510,
"s": 5498,
"text": "do option 1"
},
{
"code": null,
"e": 5584,
"s": 5510,
"text": "we solve the inverse problem: substitute the parameters y and calculate x"
},
{
"code": null,
"e": 5599,
"s": 5584,
"text": "repeat N times"
},
{
"code": null,
"e": 5802,
"s": 5599,
"text": "Here, in addition to local parameters, we also want to see which group most strongly affects the final result. The speed of the algorithm is low. Therefore, for each variant, five runs were carried out."
},
{
"code": null,
"e": 5825,
"s": 5802,
"text": "Current parameter set:"
},
{
"code": null,
"e": 5854,
"s": 5825,
"text": "Generation survivors: 50,000"
},
{
"code": null,
"e": 5881,
"s": 5854,
"text": "Number of children: 25,000"
},
{
"code": null,
"e": 5907,
"s": 5881,
"text": "Number of mutants: 12,500"
},
{
"code": null,
"e": 5938,
"s": 5907,
"text": "Now let’s look at the results:"
},
{
"code": null,
"e": 6145,
"s": 5938,
"text": "Variant 1 is the same as a clean launch, which means that the approximation did not lead to positive consequences, but the second one (variant 2) looks promising, but let’s look at the execution time graph."
},
{
"code": null,
"e": 6450,
"s": 6145,
"text": "The time taken to execute is significantly increased due to the time spent on the initial approximation. This is a bit unfair. So, let’s try to compare the usual algorithm with variant 2, giving more resources to the regular algorithm and approximating the time by expanding the sample at each iteration."
},
{
"code": null,
"e": 6801,
"s": 6450,
"text": "Despite the resources being far superior to option number 2 (fp2), achieving a consistently better result is impossible. In theory, this can be corrected by searching for hyperparameters and filtering the next generation to protect against dominance. Research in this direction continues, so the second version of the initial approximation is chosen."
},
{
"code": null,
"e": 6969,
"s": 6801,
"text": "An initial approximation in this problem stabilizes the answer and optimizes resources. The initial approximation was chosen as several iterations of gradient descent:"
},
{
"code": null,
"e": 7136,
"s": 6969,
"text": "gen = ret_random_gen(0) #Full random genfor i in range(0,iters): gen = CalculateByGenMG(gen) # calculate only X gen = CalculateByGenML(gen) # calculate only Y"
},
{
"code": null,
"e": 7230,
"s": 7136,
"text": "In the end, I would like to provide data from the graphics of model validation in production."
},
{
"code": null,
"e": 7523,
"s": 7230,
"text": "Training is based on the data on the size of the check. Each lead falls into a group from Low to Very High, and as you can see, the higher the rank, the higher the probability of a high check. The incoming data structure has slightly changed, but the differentiation of groups remains stable."
}
] |
equal_range in C++ - GeeksforGeeks | 28 Sep, 2018
std::equal_range is used to find the sub-range within a given range [first, last) that has all the elements equivalent to a given value. It returns the initial and the final bound of such a sub-range.
This function requires the range to be either sorted or partitioned according to some condition such that all the elements for which the condition evaluates to true are to the left of the given value and rest all are to its right.
It can be used in two ways as shown below:
Comparing elements using <:Syntax:Template
pair
equal_range (ForwardIterator first, ForwardIterator last, const T& val);
first: Forward iterator to the first element in the range.
last: Forward iterator to the last element in the range.
val: Value of the subrange to search for in the range.
Return Value: It returns a pair object, whose member pair::first
is an iterator to the lower bound of the subrange of equivalent
values, and pair::second its upper bound.
If there is no element equivalent to val, then both first and
second points to the nearest element greater than val, or if val is
greater than any other value, then both of them point to last.
// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v sort(v.begin(), v.end()); // v becomes 10 10 10 30 30 30 70 70 80 100 300 300 // Using std::equal_range and comparing the elements // with 30 ip = std::equal_range(v.begin(), v.begin() + 12, 30); // Displaying the subrange bounds cout << "30 is present in the sorted vector from index " << (ip.first - v.begin()) << " till " << (ip.second - v.begin()); return 0;}Output:30 is present in the sorted vector from index 3 till 6
Explanation: After sorting the vector v1, we checked for the bounds within which 30 is present, i.e., from index 3 till index 6.By comparing using a pre-defined function:Syntax: pair
equal_range (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);
Here, first, last and val are the same as previous case.
comp: Binary function that accepts two arguments of the type
pointed by ForwardIterator (and of type T), and returns a
value convertible to bool. The value returned indicates
whether the first argument is considered to go before the
second.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
Return Value: It returns a pair object, whose member
pair::first is an iterator to the lower bound of the subrange
of equivalent values, and pair::second its upper bound.
If there is no element equivalent to val, then both first and
second point to the nearest element greater than val,
or if val is greater than any other value, then both
of them point to last.
// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <algorithm>#include <string>#include <vector>#include <functional>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a > b);}int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v in descending order sort(v.begin(), v.end(), greater<int>()); // v becomes 300 300 100 80 70 70 30 30 30 10 10 10 // Using std::equal_range and comparing the elements // with 10 ip = std::equal_range(v.begin(), v.begin() + 12, 10, comp); // Displaying the subrange bounds cout << "10 is present in the sorted vector from index " << (ip.first - v.begin()) << " till " << (ip.second - v.begin()); return 0;}Output:10 is present in the sorted vector from index 9 till 12
Comparing elements using <:Syntax:Template
pair
equal_range (ForwardIterator first, ForwardIterator last, const T& val);
first: Forward iterator to the first element in the range.
last: Forward iterator to the last element in the range.
val: Value of the subrange to search for in the range.
Return Value: It returns a pair object, whose member pair::first
is an iterator to the lower bound of the subrange of equivalent
values, and pair::second its upper bound.
If there is no element equivalent to val, then both first and
second points to the nearest element greater than val, or if val is
greater than any other value, then both of them point to last.
// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v sort(v.begin(), v.end()); // v becomes 10 10 10 30 30 30 70 70 80 100 300 300 // Using std::equal_range and comparing the elements // with 30 ip = std::equal_range(v.begin(), v.begin() + 12, 30); // Displaying the subrange bounds cout << "30 is present in the sorted vector from index " << (ip.first - v.begin()) << " till " << (ip.second - v.begin()); return 0;}Output:30 is present in the sorted vector from index 3 till 6
Explanation: After sorting the vector v1, we checked for the bounds within which 30 is present, i.e., from index 3 till index 6.
Syntax:
Template
pair
equal_range (ForwardIterator first, ForwardIterator last, const T& val);
first: Forward iterator to the first element in the range.
last: Forward iterator to the last element in the range.
val: Value of the subrange to search for in the range.
Return Value: It returns a pair object, whose member pair::first
is an iterator to the lower bound of the subrange of equivalent
values, and pair::second its upper bound.
If there is no element equivalent to val, then both first and
second points to the nearest element greater than val, or if val is
greater than any other value, then both of them point to last.
// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v sort(v.begin(), v.end()); // v becomes 10 10 10 30 30 30 70 70 80 100 300 300 // Using std::equal_range and comparing the elements // with 30 ip = std::equal_range(v.begin(), v.begin() + 12, 30); // Displaying the subrange bounds cout << "30 is present in the sorted vector from index " << (ip.first - v.begin()) << " till " << (ip.second - v.begin()); return 0;}
Output:
30 is present in the sorted vector from index 3 till 6
Explanation: After sorting the vector v1, we checked for the bounds within which 30 is present, i.e., from index 3 till index 6.
By comparing using a pre-defined function:Syntax: pair
equal_range (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);
Here, first, last and val are the same as previous case.
comp: Binary function that accepts two arguments of the type
pointed by ForwardIterator (and of type T), and returns a
value convertible to bool. The value returned indicates
whether the first argument is considered to go before the
second.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
Return Value: It returns a pair object, whose member
pair::first is an iterator to the lower bound of the subrange
of equivalent values, and pair::second its upper bound.
If there is no element equivalent to val, then both first and
second point to the nearest element greater than val,
or if val is greater than any other value, then both
of them point to last.
// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <algorithm>#include <string>#include <vector>#include <functional>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a > b);}int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v in descending order sort(v.begin(), v.end(), greater<int>()); // v becomes 300 300 100 80 70 70 30 30 30 10 10 10 // Using std::equal_range and comparing the elements // with 10 ip = std::equal_range(v.begin(), v.begin() + 12, 10, comp); // Displaying the subrange bounds cout << "10 is present in the sorted vector from index " << (ip.first - v.begin()) << " till " << (ip.second - v.begin()); return 0;}Output:10 is present in the sorted vector from index 9 till 12
Syntax:
pair
equal_range (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);
Here, first, last and val are the same as previous case.
comp: Binary function that accepts two arguments of the type
pointed by ForwardIterator (and of type T), and returns a
value convertible to bool. The value returned indicates
whether the first argument is considered to go before the
second.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
Return Value: It returns a pair object, whose member
pair::first is an iterator to the lower bound of the subrange
of equivalent values, and pair::second its upper bound.
If there is no element equivalent to val, then both first and
second point to the nearest element greater than val,
or if val is greater than any other value, then both
of them point to last.
// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <algorithm>#include <string>#include <vector>#include <functional>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a > b);}int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v in descending order sort(v.begin(), v.end(), greater<int>()); // v becomes 300 300 100 80 70 70 30 30 30 10 10 10 // Using std::equal_range and comparing the elements // with 10 ip = std::equal_range(v.begin(), v.begin() + 12, 10, comp); // Displaying the subrange bounds cout << "10 is present in the sorted vector from index " << (ip.first - v.begin()) << " till " << (ip.second - v.begin()); return 0;}
Output:
10 is present in the sorted vector from index 9 till 12
Where can it be used ?
std::lower_bound and std::upper_bound at one place: This function can be used if we want to use both std::lower_bound and std::upper_bound at the same time, as its first pointer will be same as std::lower_bound and its second pointer will be same as std::upper_bound. So, there is no use of separately using them, if we have std::equal_range.// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 1, 2, 3, 4, 5, 5, 6, 7 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Using std::equal_range and comparing the elements // with 5 ip = std::equal_range(v.begin(), v.end(), 5); // Displaying the subrange bounds cout << "std::lower_bound should be equal to " << (ip.first - v.begin()) << " and std::upper_bound " << "should be equal to " << (ip.second - v.begin()); vector<int>::iterator i1, i2; // Using std::lower_bound i1 = std::lower_bound(v.begin(), v.end(), 5); cout << "\nstd::lower_bound is = " << (i1 - v.begin()); // Using std::upper_bound i2 = std::upper_bound(v.begin(), v.end(), 5); cout << "\nstd::upper_bound is = " << (i2 - v.begin()); return 0;}Output:std::lower_bound should be equal to 4 and
std::upper_bound should be equal to 6
std::lower_bound is = 4
std::upper_bound is = 6
std::lower_bound and std::upper_bound at one place: This function can be used if we want to use both std::lower_bound and std::upper_bound at the same time, as its first pointer will be same as std::lower_bound and its second pointer will be same as std::upper_bound. So, there is no use of separately using them, if we have std::equal_range.// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 1, 2, 3, 4, 5, 5, 6, 7 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Using std::equal_range and comparing the elements // with 5 ip = std::equal_range(v.begin(), v.end(), 5); // Displaying the subrange bounds cout << "std::lower_bound should be equal to " << (ip.first - v.begin()) << " and std::upper_bound " << "should be equal to " << (ip.second - v.begin()); vector<int>::iterator i1, i2; // Using std::lower_bound i1 = std::lower_bound(v.begin(), v.end(), 5); cout << "\nstd::lower_bound is = " << (i1 - v.begin()); // Using std::upper_bound i2 = std::upper_bound(v.begin(), v.end(), 5); cout << "\nstd::upper_bound is = " << (i2 - v.begin()); return 0;}Output:std::lower_bound should be equal to 4 and
std::upper_bound should be equal to 6
std::lower_bound is = 4
std::upper_bound is = 6
// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 1, 2, 3, 4, 5, 5, 6, 7 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Using std::equal_range and comparing the elements // with 5 ip = std::equal_range(v.begin(), v.end(), 5); // Displaying the subrange bounds cout << "std::lower_bound should be equal to " << (ip.first - v.begin()) << " and std::upper_bound " << "should be equal to " << (ip.second - v.begin()); vector<int>::iterator i1, i2; // Using std::lower_bound i1 = std::lower_bound(v.begin(), v.end(), 5); cout << "\nstd::lower_bound is = " << (i1 - v.begin()); // Using std::upper_bound i2 = std::upper_bound(v.begin(), v.end(), 5); cout << "\nstd::upper_bound is = " << (i2 - v.begin()); return 0;}
Output:
std::lower_bound should be equal to 4 and
std::upper_bound should be equal to 6
std::lower_bound is = 4
std::upper_bound is = 6
This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [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.
cpp-algorithm-library
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
List in C++ Standard Template Library (STL)
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
new and delete operators in C++ for dynamic memory
Destructors in C++
Queue in C++ Standard Template Library (STL) | [
{
"code": null,
"e": 23731,
"s": 23703,
"text": "\n28 Sep, 2018"
},
{
"code": null,
"e": 23932,
"s": 23731,
"text": "std::equal_range is used to find the sub-range within a given range [first, last) that has all the elements equivalent to a given value. It returns the initial and the final bound of such a sub-range."
},
{
"code": null,
"e": 24163,
"s": 23932,
"text": "This function requires the range to be either sorted or partitioned according to some condition such that all the elements for which the condition evaluates to true are to the left of the given value and rest all are to its right."
},
{
"code": null,
"e": 24206,
"s": 24163,
"text": "It can be used in two ways as shown below:"
},
{
"code": null,
"e": 27921,
"s": 24206,
"text": "Comparing elements using <:Syntax:Template\npair \n equal_range (ForwardIterator first, ForwardIterator last, const T& val);\n\nfirst: Forward iterator to the first element in the range.\nlast: Forward iterator to the last element in the range.\nval: Value of the subrange to search for in the range.\n\nReturn Value: It returns a pair object, whose member pair::first \nis an iterator to the lower bound of the subrange of equivalent \nvalues, and pair::second its upper bound.\nIf there is no element equivalent to val, then both first and \nsecond points to the nearest element greater than val, or if val is\ngreater than any other value, then both of them point to last.\n// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v sort(v.begin(), v.end()); // v becomes 10 10 10 30 30 30 70 70 80 100 300 300 // Using std::equal_range and comparing the elements // with 30 ip = std::equal_range(v.begin(), v.begin() + 12, 30); // Displaying the subrange bounds cout << \"30 is present in the sorted vector from index \" << (ip.first - v.begin()) << \" till \" << (ip.second - v.begin()); return 0;}Output:30 is present in the sorted vector from index 3 till 6\nExplanation: After sorting the vector v1, we checked for the bounds within which 30 is present, i.e., from index 3 till index 6.By comparing using a pre-defined function:Syntax: pair \n equal_range (ForwardIterator first, ForwardIterator last, \n const T& val, Compare comp);\n\nHere, first, last and val are the same as previous case.\n\ncomp: Binary function that accepts two arguments of the type \npointed by ForwardIterator (and of type T), and returns a\nvalue convertible to bool. The value returned indicates \nwhether the first argument is considered to go before the\nsecond. \nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\nReturn Value: It returns a pair object, whose member \npair::first is an iterator to the lower bound of the subrange \nof equivalent values, and pair::second its upper bound. \nIf there is no element equivalent to val, then both first and\nsecond point to the nearest element greater than val,\nor if val is greater than any other value, then both\nof them point to last.\n// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <algorithm>#include <string>#include <vector>#include <functional>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a > b);}int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v in descending order sort(v.begin(), v.end(), greater<int>()); // v becomes 300 300 100 80 70 70 30 30 30 10 10 10 // Using std::equal_range and comparing the elements // with 10 ip = std::equal_range(v.begin(), v.begin() + 12, 10, comp); // Displaying the subrange bounds cout << \"10 is present in the sorted vector from index \" << (ip.first - v.begin()) << \" till \" << (ip.second - v.begin()); return 0;}Output:10 is present in the sorted vector from index 9 till 12\n"
},
{
"code": null,
"e": 29624,
"s": 27921,
"text": "Comparing elements using <:Syntax:Template\npair \n equal_range (ForwardIterator first, ForwardIterator last, const T& val);\n\nfirst: Forward iterator to the first element in the range.\nlast: Forward iterator to the last element in the range.\nval: Value of the subrange to search for in the range.\n\nReturn Value: It returns a pair object, whose member pair::first \nis an iterator to the lower bound of the subrange of equivalent \nvalues, and pair::second its upper bound.\nIf there is no element equivalent to val, then both first and \nsecond points to the nearest element greater than val, or if val is\ngreater than any other value, then both of them point to last.\n// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v sort(v.begin(), v.end()); // v becomes 10 10 10 30 30 30 70 70 80 100 300 300 // Using std::equal_range and comparing the elements // with 30 ip = std::equal_range(v.begin(), v.begin() + 12, 30); // Displaying the subrange bounds cout << \"30 is present in the sorted vector from index \" << (ip.first - v.begin()) << \" till \" << (ip.second - v.begin()); return 0;}Output:30 is present in the sorted vector from index 3 till 6\nExplanation: After sorting the vector v1, we checked for the bounds within which 30 is present, i.e., from index 3 till index 6."
},
{
"code": null,
"e": 29632,
"s": 29624,
"text": "Syntax:"
},
{
"code": null,
"e": 30265,
"s": 29632,
"text": "Template\npair \n equal_range (ForwardIterator first, ForwardIterator last, const T& val);\n\nfirst: Forward iterator to the first element in the range.\nlast: Forward iterator to the last element in the range.\nval: Value of the subrange to search for in the range.\n\nReturn Value: It returns a pair object, whose member pair::first \nis an iterator to the lower bound of the subrange of equivalent \nvalues, and pair::second its upper bound.\nIf there is no element equivalent to val, then both first and \nsecond points to the nearest element greater than val, or if val is\ngreater than any other value, then both of them point to last.\n"
},
{
"code": "// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v sort(v.begin(), v.end()); // v becomes 10 10 10 30 30 30 70 70 80 100 300 300 // Using std::equal_range and comparing the elements // with 30 ip = std::equal_range(v.begin(), v.begin() + 12, 30); // Displaying the subrange bounds cout << \"30 is present in the sorted vector from index \" << (ip.first - v.begin()) << \" till \" << (ip.second - v.begin()); return 0;}",
"e": 31112,
"s": 30265,
"text": null
},
{
"code": null,
"e": 31120,
"s": 31112,
"text": "Output:"
},
{
"code": null,
"e": 31176,
"s": 31120,
"text": "30 is present in the sorted vector from index 3 till 6\n"
},
{
"code": null,
"e": 31305,
"s": 31176,
"text": "Explanation: After sorting the vector v1, we checked for the bounds within which 30 is present, i.e., from index 3 till index 6."
},
{
"code": null,
"e": 33318,
"s": 31305,
"text": "By comparing using a pre-defined function:Syntax: pair \n equal_range (ForwardIterator first, ForwardIterator last, \n const T& val, Compare comp);\n\nHere, first, last and val are the same as previous case.\n\ncomp: Binary function that accepts two arguments of the type \npointed by ForwardIterator (and of type T), and returns a\nvalue convertible to bool. The value returned indicates \nwhether the first argument is considered to go before the\nsecond. \nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\nReturn Value: It returns a pair object, whose member \npair::first is an iterator to the lower bound of the subrange \nof equivalent values, and pair::second its upper bound. \nIf there is no element equivalent to val, then both first and\nsecond point to the nearest element greater than val,\nor if val is greater than any other value, then both\nof them point to last.\n// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <algorithm>#include <string>#include <vector>#include <functional>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a > b);}int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v in descending order sort(v.begin(), v.end(), greater<int>()); // v becomes 300 300 100 80 70 70 30 30 30 10 10 10 // Using std::equal_range and comparing the elements // with 10 ip = std::equal_range(v.begin(), v.begin() + 12, 10, comp); // Displaying the subrange bounds cout << \"10 is present in the sorted vector from index \" << (ip.first - v.begin()) << \" till \" << (ip.second - v.begin()); return 0;}Output:10 is present in the sorted vector from index 9 till 12\n"
},
{
"code": null,
"e": 33326,
"s": 33318,
"text": "Syntax:"
},
{
"code": null,
"e": 34225,
"s": 33326,
"text": " pair \n equal_range (ForwardIterator first, ForwardIterator last, \n const T& val, Compare comp);\n\nHere, first, last and val are the same as previous case.\n\ncomp: Binary function that accepts two arguments of the type \npointed by ForwardIterator (and of type T), and returns a\nvalue convertible to bool. The value returned indicates \nwhether the first argument is considered to go before the\nsecond. \nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\nReturn Value: It returns a pair object, whose member \npair::first is an iterator to the lower bound of the subrange \nof equivalent values, and pair::second its upper bound. \nIf there is no element equivalent to val, then both first and\nsecond point to the nearest element greater than val,\nor if val is greater than any other value, then both\nof them point to last.\n"
},
{
"code": "// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <algorithm>#include <string>#include <vector>#include <functional>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a > b);}int main(){ vector<int> v = { 10, 10, 30, 30, 30, 100, 10, 300, 300, 70, 70, 80 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Sorting the vector v in descending order sort(v.begin(), v.end(), greater<int>()); // v becomes 300 300 100 80 70 70 30 30 30 10 10 10 // Using std::equal_range and comparing the elements // with 10 ip = std::equal_range(v.begin(), v.begin() + 12, 10, comp); // Displaying the subrange bounds cout << \"10 is present in the sorted vector from index \" << (ip.first - v.begin()) << \" till \" << (ip.second - v.begin()); return 0;}",
"e": 35228,
"s": 34225,
"text": null
},
{
"code": null,
"e": 35236,
"s": 35228,
"text": "Output:"
},
{
"code": null,
"e": 35293,
"s": 35236,
"text": "10 is present in the sorted vector from index 9 till 12\n"
},
{
"code": null,
"e": 35316,
"s": 35293,
"text": "Where can it be used ?"
},
{
"code": null,
"e": 36815,
"s": 35316,
"text": "std::lower_bound and std::upper_bound at one place: This function can be used if we want to use both std::lower_bound and std::upper_bound at the same time, as its first pointer will be same as std::lower_bound and its second pointer will be same as std::upper_bound. So, there is no use of separately using them, if we have std::equal_range.// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 1, 2, 3, 4, 5, 5, 6, 7 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Using std::equal_range and comparing the elements // with 5 ip = std::equal_range(v.begin(), v.end(), 5); // Displaying the subrange bounds cout << \"std::lower_bound should be equal to \" << (ip.first - v.begin()) << \" and std::upper_bound \" << \"should be equal to \" << (ip.second - v.begin()); vector<int>::iterator i1, i2; // Using std::lower_bound i1 = std::lower_bound(v.begin(), v.end(), 5); cout << \"\\nstd::lower_bound is = \" << (i1 - v.begin()); // Using std::upper_bound i2 = std::upper_bound(v.begin(), v.end(), 5); cout << \"\\nstd::upper_bound is = \" << (i2 - v.begin()); return 0;}Output:std::lower_bound should be equal to 4 and \nstd::upper_bound should be equal to 6\nstd::lower_bound is = 4\nstd::upper_bound is = 6\n"
},
{
"code": null,
"e": 38314,
"s": 36815,
"text": "std::lower_bound and std::upper_bound at one place: This function can be used if we want to use both std::lower_bound and std::upper_bound at the same time, as its first pointer will be same as std::lower_bound and its second pointer will be same as std::upper_bound. So, there is no use of separately using them, if we have std::equal_range.// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 1, 2, 3, 4, 5, 5, 6, 7 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Using std::equal_range and comparing the elements // with 5 ip = std::equal_range(v.begin(), v.end(), 5); // Displaying the subrange bounds cout << \"std::lower_bound should be equal to \" << (ip.first - v.begin()) << \" and std::upper_bound \" << \"should be equal to \" << (ip.second - v.begin()); vector<int>::iterator i1, i2; // Using std::lower_bound i1 = std::lower_bound(v.begin(), v.end(), 5); cout << \"\\nstd::lower_bound is = \" << (i1 - v.begin()); // Using std::upper_bound i2 = std::upper_bound(v.begin(), v.end(), 5); cout << \"\\nstd::upper_bound is = \" << (i2 - v.begin()); return 0;}Output:std::lower_bound should be equal to 4 and \nstd::upper_bound should be equal to 6\nstd::lower_bound is = 4\nstd::upper_bound is = 6\n"
},
{
"code": "// C++ program to demonstrate the use of std::equal_range#include <iostream>#include <vector>#include <algorithm>using namespace std;int main(){ vector<int> v = { 1, 2, 3, 4, 5, 5, 6, 7 }; // Declaring an iterator to store the // return value of std::equal_range std::pair<std::vector<int>::iterator, std::vector<int>::iterator> ip; // Using std::equal_range and comparing the elements // with 5 ip = std::equal_range(v.begin(), v.end(), 5); // Displaying the subrange bounds cout << \"std::lower_bound should be equal to \" << (ip.first - v.begin()) << \" and std::upper_bound \" << \"should be equal to \" << (ip.second - v.begin()); vector<int>::iterator i1, i2; // Using std::lower_bound i1 = std::lower_bound(v.begin(), v.end(), 5); cout << \"\\nstd::lower_bound is = \" << (i1 - v.begin()); // Using std::upper_bound i2 = std::upper_bound(v.begin(), v.end(), 5); cout << \"\\nstd::upper_bound is = \" << (i2 - v.begin()); return 0;}",
"e": 39335,
"s": 38314,
"text": null
},
{
"code": null,
"e": 39343,
"s": 39335,
"text": "Output:"
},
{
"code": null,
"e": 39473,
"s": 39343,
"text": "std::lower_bound should be equal to 4 and \nstd::upper_bound should be equal to 6\nstd::lower_bound is = 4\nstd::upper_bound is = 6\n"
},
{
"code": null,
"e": 39776,
"s": 39473,
"text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 39901,
"s": 39776,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 39923,
"s": 39901,
"text": "cpp-algorithm-library"
},
{
"code": null,
"e": 39934,
"s": 39923,
"text": "cpp-vector"
},
{
"code": null,
"e": 39938,
"s": 39934,
"text": "STL"
},
{
"code": null,
"e": 39942,
"s": 39938,
"text": "C++"
},
{
"code": null,
"e": 39946,
"s": 39942,
"text": "STL"
},
{
"code": null,
"e": 39950,
"s": 39946,
"text": "CPP"
},
{
"code": null,
"e": 40048,
"s": 39950,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40057,
"s": 40048,
"text": "Comments"
},
{
"code": null,
"e": 40070,
"s": 40057,
"text": "Old Comments"
},
{
"code": null,
"e": 40098,
"s": 40070,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 40122,
"s": 40098,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 40142,
"s": 40122,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 40175,
"s": 40142,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 40219,
"s": 40175,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 40263,
"s": 40219,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 40299,
"s": 40263,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 40350,
"s": 40299,
"text": "new and delete operators in C++ for dynamic memory"
},
{
"code": null,
"e": 40369,
"s": 40350,
"text": "Destructors in C++"
}
] |
IDE | GeeksforGeeks | A computer science portal for geeks | Please enter your email address or userHandle. | [] |
Cartesian Tree - GeeksforGeeks | 18 Feb, 2022
A Cartesian tree is a tree data structure created from a set of data that obeys the following structural invariants:
The tree obeys in the min (or max) heap property – each node is less (or greater) than its children.An inorder traversal of the nodes yields the values in the same order in which they appear in the initial sequence.
The tree obeys in the min (or max) heap property – each node is less (or greater) than its children.
An inorder traversal of the nodes yields the values in the same order in which they appear in the initial sequence.
Suppose we have an input array- {5,10,40,30,28}. Then the max-heap Cartesian Tree would be.
A min-heap Cartesian Tree of the above input array will be-
Note:
Cartesian Tree is not a height-balanced tree.Cartesian tree of a sequence of distinct numbers is always unique.
Cartesian Tree is not a height-balanced tree.
Cartesian tree of a sequence of distinct numbers is always unique.
Cartesian tree of a sequence of distinct numbers is always unique. We will prove this using induction. As a base case, empty tree is always unique. For the inductive case, assume that for all trees containing n’ < n elements, there is a unique Cartesian tree for each sequence of n’ nodes. Now take any sequence of n elements. Because a Cartesian tree is a min-heap, the smallest element of the sequence must be the root of the Cartesian tree. Because an inorder traversal of the elements must yield the input sequence, we know that all nodes to the left of the min element must be in its left subtree and similarly for the nodes to the right. Since the left and right subtree are both Cartesian trees with at most n-1 elements in them (since the min element is at the root), by the induction hypothesis there is a unique Cartesian tree that could be the left or right subtree. Since all our decisions were forced, we end up with a unique tree, completing the induction.How to construct Cartesian Tree? A O(n2) solution for construction of Cartesian Tree is discussed here (Note that the above program here constructs the “special binary tree” (which is nothing but a Cartesian tree)A O(nlogn) Algorithm : It’s possible to build a Cartesian tree from a sequence of data in O(NlogN) time on average. Beginning with the empty tree,Scan the given sequence from left to right adding new nodes as follows:
Position the node as the right child of the rightmost node.Scan upward from the node’s parent up to the root of the tree until a node is found whose value is greater than the current value.If such a node is found, set its right child to be the new node, and set the new node’s left child to be the previous right child.If no such node is found, set the new child to be the root, and set the new node’s left child to be the previous tree.
Position the node as the right child of the rightmost node.
Scan upward from the node’s parent up to the root of the tree until a node is found whose value is greater than the current value.
If such a node is found, set its right child to be the new node, and set the new node’s left child to be the previous right child.
If no such node is found, set the new child to be the root, and set the new node’s left child to be the previous tree.
CPP
Java
C#
Javascript
// A O(n) C++ program to construct cartesian tree// from a given array#include<bits/stdc++.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; Node *left, *right;}; /* This function is here just to test buildTree() */void printInorder (Node* node){ if (node == NULL) return; printInorder (node->left); cout << node->data << " "; printInorder (node->right);} // Recursively construct subtree under given root using// leftChild[] and rightchildNode * buildCartesianTreeUtil (int root, int arr[], int parent[], int leftchild[], int rightchild[]){ if (root == -1) return NULL; // Create a new node with root's data Node *temp = new Node; temp->data = arr[root] ; // Recursively construct left and right subtrees temp->left = buildCartesianTreeUtil( leftchild[root], arr, parent, leftchild, rightchild ); temp->right = buildCartesianTreeUtil( rightchild[root], arr, parent, leftchild, rightchild ); return temp ;} // A function to create the Cartesian Tree in O(N) timeNode * buildCartesianTree (int arr[], int n){ // Arrays to hold the index of parent, left-child, // right-child of each number in the input array int parent[n],leftchild[n],rightchild[n]; // Initialize all array values as -1 memset(parent, -1, sizeof(parent)); memset(leftchild, -1, sizeof(leftchild)); memset(rightchild, -1, sizeof(rightchild)); // 'root' and 'last' stores the index of the root and the // last processed of the Cartesian Tree. // Initially we take root of the Cartesian Tree as the // first element of the input array. This can change // according to the algorithm int root = 0, last; // Starting from the second element of the input array // to the last on scan across the elements, adding them // one at a time. for (int i=1; i<=n-1; i++) { last = i-1; rightchild[i] = -1; // Scan upward from the node's parent up to // the root of the tree until a node is found // whose value is greater than the current one // This is the same as Step 2 mentioned in the // algorithm while (arr[last] <= arr[i] && last != root) last = parent[last]; // arr[i] is the largest element yet; make it // new root if (arr[last] <= arr[i]) { parent[root] = i; leftchild[i] = root; root = i; } // Just insert it else if (rightchild[last] == -1) { rightchild[last] = i; parent[i] = last; leftchild[i] = -1; } // Reconfigure links else { parent[rightchild[last]] = i; leftchild[i] = rightchild[last]; rightchild[last] = i; parent[i] = last; } } // Since the root of the Cartesian Tree has no // parent, so we assign it -1 parent[root] = -1; return (buildCartesianTreeUtil (root, arr, parent, leftchild, rightchild));} /* Driver program to test above functions */int main(){ /* Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 */ int arr[] = {5, 10, 40, 30, 28}; int n = sizeof(arr)/sizeof(arr[0]); Node *root = buildCartesianTree(arr, n); /* Let us test the built tree by printing Inorder traversal */ printf("Inorder traversal of the constructed tree : \n"); printInorder(root); return(0);}
// A O(n) Java program to construct cartesian tree// from a given array /* A binary tree node has data, pointer to leftchild and a pointer to right child */class GFG{static class Node{ int data; Node left, right;}; /* This function is here just to test buildTree() */static void printInorder (Node node){ if (node == null) return; printInorder (node.left); System.out.print(node.data + " "); printInorder (node.right);} // Recursively construct subtree under given root using// leftChild[] and rightchildstatic Node buildCartesianTreeUtil (int root, int arr[], int parent[], int leftchild[], int rightchild[]){ if (root == -1) return null; // Create a new node with root's data Node temp = new Node(); temp.data = arr[root] ; // Recursively construct left and right subtrees temp.left = buildCartesianTreeUtil( leftchild[root], arr, parent, leftchild, rightchild ); temp.right = buildCartesianTreeUtil( rightchild[root], arr, parent, leftchild, rightchild ); return temp ;} // A function to create the Cartesian Tree in O(N) timestatic Node buildCartesianTree (int arr[], int n){ // Arrays to hold the index of parent, left-child, // right-child of each number in the input array int []parent = new int[n]; int []leftchild = new int[n]; int []rightchild = new int[n]; // Initialize all array values as -1 memset(parent, -1); memset(leftchild, -1); memset(rightchild, -1); // 'root' and 'last' stores the index of the root and the // last processed of the Cartesian Tree. // Initially we take root of the Cartesian Tree as the // first element of the input array. This can change // according to the algorithm int root = 0, last; // Starting from the second element of the input array // to the last on scan across the elements, adding them // one at a time. for (int i = 1; i <= n - 1; i++) { last = i - 1; rightchild[i] = -1; // Scan upward from the node's parent up to // the root of the tree until a node is found // whose value is greater than the current one // This is the same as Step 2 mentioned in the // algorithm while (arr[last] <= arr[i] && last != root) last = parent[last]; // arr[i] is the largest element yet; make it // new root if (arr[last] <= arr[i]) { parent[root] = i; leftchild[i] = root; root = i; } // Just insert it else if (rightchild[last] == -1) { rightchild[last] = i; parent[i] = last; leftchild[i] = -1; } // Reconfigure links else { parent[rightchild[last]] = i; leftchild[i] = rightchild[last]; rightchild[last] = i; parent[i] = last; } } // Since the root of the Cartesian Tree has no // parent, so we assign it -1 parent[root] = -1; return (buildCartesianTreeUtil (root, arr, parent, leftchild, rightchild));} static void memset(int[] arr, int value){ for (int i = 0; i < arr.length; i++) { arr[i] = value; } } /* Driver code */public static void main(String[] args){ /* Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 */ int arr[] = {5, 10, 40, 30, 28}; int n = arr.length; Node root = buildCartesianTree(arr, n); /* Let us test the built tree by printing Inorder traversal */ System.out.printf("Inorder traversal of the" + " constructed tree : \n"); printInorder(root);}} // This code is contributed by PrinciRaj1992
// A O(n) C# program to construct cartesian tree// from a given array /* A binary tree node has data, pointer to leftchild and a pointer to right child */using System; class GFG{ class Node{ public int data; public Node left, right;}; /* This function is here just to test buildTree() */static void printInorder (Node node){ if (node == null) return; printInorder (node.left); Console.Write(node.data + " "); printInorder (node.right);} // Recursively construct subtree under given root using// leftChild[] and rightchildstatic Node buildCartesianTreeUtil (int root, int []arr, int []parent, int []leftchild, int []rightchild){ if (root == -1) return null; // Create a new node with root's data Node temp = new Node(); temp.data = arr[root] ; // Recursively construct left and right subtrees temp.left = buildCartesianTreeUtil( leftchild[root], arr, parent, leftchild, rightchild ); temp.right = buildCartesianTreeUtil( rightchild[root], arr, parent, leftchild, rightchild ); return temp ;} // A function to create the Cartesian Tree in O(N) timestatic Node buildCartesianTree (int []arr, int n){ // Arrays to hold the index of parent, left-child, // right-child of each number in the input array int []parent = new int[n]; int []leftchild = new int[n]; int []rightchild = new int[n]; // Initialize all array values as -1 memset(parent, -1); memset(leftchild, -1); memset(rightchild, -1); // 'root' and 'last' stores the index of the root and the // last processed of the Cartesian Tree. // Initially we take root of the Cartesian Tree as the // first element of the input array. This can change // according to the algorithm int root = 0, last; // Starting from the second element of the input array // to the last on scan across the elements, adding them // one at a time. for (int i = 1; i <= n - 1; i++) { last = i - 1; rightchild[i] = -1; // Scan upward from the node's parent up to // the root of the tree until a node is found // whose value is greater than the current one // This is the same as Step 2 mentioned in the // algorithm while (arr[last] <= arr[i] && last != root) last = parent[last]; // arr[i] is the largest element yet; make it // new root if (arr[last] <= arr[i]) { parent[root] = i; leftchild[i] = root; root = i; } // Just insert it else if (rightchild[last] == -1) { rightchild[last] = i; parent[i] = last; leftchild[i] = -1; } // Reconfigure links else { parent[rightchild[last]] = i; leftchild[i] = rightchild[last]; rightchild[last] = i; parent[i] = last; } } // Since the root of the Cartesian Tree has no // parent, so we assign it -1 parent[root] = -1; return (buildCartesianTreeUtil (root, arr, parent, leftchild, rightchild));} static void memset(int[] arr, int value){ for (int i = 0; i < arr.Length; i++) { arr[i] = value; } } /* Driver code */public static void Main(String[] args){ /* Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 */ int []arr = {5, 10, 40, 30, 28}; int n = arr.Length; Node root = buildCartesianTree(arr, n); /* Let us test the built tree by printing Inorder traversal */ Console.Write("Inorder traversal of the" + " constructed tree : \n"); printInorder(root);}} // This code is contributed by 29AjayKumar
<script>// A O(n) Javascript program to construct cartesian tree// from a given array /* A binary tree node has data, pointer to leftchild and a pointer to right child */class Node{ constructor(data) { this.data=data; this.left=this.right=null; }} /* This function is here just to test buildTree() */function printInorder (node){ if (node == null) return; printInorder (node.left); document.write(node.data + " "); printInorder (node.right);} // Recursively construct subtree under given root using// leftChild[] and rightchildfunction buildCartesianTreeUtil(root,arr,parent,leftchild,rightchild){ if (root == -1) return null; // Create a new node with root's data let temp = new Node(); temp.data = arr[root] ; // Recursively construct left and right subtrees temp.left = buildCartesianTreeUtil( leftchild[root], arr, parent, leftchild, rightchild ); temp.right = buildCartesianTreeUtil( rightchild[root], arr, parent, leftchild, rightchild ); return temp ;} // A function to create the Cartesian Tree in O(N) timefunction buildCartesianTree (arr,n){ // Arrays to hold the index of parent, left-child, // right-child of each number in the input array let parent = new Array(n); let leftchild = new Array(n); let rightchild = new Array(n); // Initialize all array values as -1 memset(parent, -1); memset(leftchild, -1); memset(rightchild, -1); // 'root' and 'last' stores the index of the root and the // last processed of the Cartesian Tree. // Initially we take root of the Cartesian Tree as the // first element of the input array. This can change // according to the algorithm let root = 0, last; // Starting from the second element of the input array // to the last on scan across the elements, adding them // one at a time. for (let i = 1; i <= n - 1; i++) { last = i - 1; rightchild[i] = -1; // Scan upward from the node's parent up to // the root of the tree until a node is found // whose value is greater than the current one // This is the same as Step 2 mentioned in the // algorithm while (arr[last] <= arr[i] && last != root) last = parent[last]; // arr[i] is the largest element yet; make it // new root if (arr[last] <= arr[i]) { parent[root] = i; leftchild[i] = root; root = i; } // Just insert it else if (rightchild[last] == -1) { rightchild[last] = i; parent[i] = last; leftchild[i] = -1; } // Reconfigure links else { parent[rightchild[last]] = i; leftchild[i] = rightchild[last]; rightchild[last] = i; parent[i] = last; } } // Since the root of the Cartesian Tree has no // parent, so we assign it -1 parent[root] = -1; return (buildCartesianTreeUtil (root, arr, parent, leftchild, rightchild));} function memset(arr,value){ for (let i = 0; i < arr.length; i++) { arr[i] = value; }} /* Driver code *//* Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 */ let arr = [5, 10, 40, 30, 28];let n = arr.length; let root = buildCartesianTree(arr, n); /* Let us test the built tree by printing Inorder traversal */document.write("Inorder traversal of the" + " constructed tree : <br>");printInorder(root); // This code is contributed by rag2127</script>
Output:
Inorder traversal of the constructed tree :
5 10 40 30 28
Time Complexity : At first look, the code seems to be taking O(n2) time as there are two loop in buildCartesianTree(). But actually, it takes O(NlogN) time in average and O(n^2) for sorted preorder traversal.Auxiliary Space: We declare a structure for every node as well as three extra arrays- leftchild[], rightchild[], parent[] to hold the indices of left-child, right-child, parent of each value in the input array. Hence the overall O(4*n) = O(n) extra space.Application of Cartesian Tree
Cartesian Tree Sorting
A range minimum query on a sequence is equivalent to a lowest common ancestor query on the sequence’s Cartesian tree. Hence, RMQ may be reduced to LCA using the sequence’s Cartesian tree.
Treap, a balanced binary search tree structure, is a Cartesian tree of (key,priority) pairs; it is heap-ordered according to the priority values, and an inorder traversal gives the keys in sorted order.
Suffix tree of a string may be constructed from the suffix array and the longest common prefix array. The first step is to compute the Cartesian tree of the longest common prefix array.
References: http://wcipeg.com/wiki/Cartesian_treeThis article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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
DivyanshuShekhar1
princiraj1992
29AjayKumar
rag2127
varshagumber28
simmytarika5
surinderdawra388
Advanced Data Structure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Decision Tree Introduction with example
Red-Black Tree | Set 2 (Insert)
Disjoint Set Data Structures
How to design a tiny URL or URL shortener?
Design a Chess Game
Binomial Heap
Red-Black Tree | Set 3 (Delete)
Design a data structure that supports insert, delete, search and getRandom in constant time
Binary Indexed Tree or Fenwick Tree
Difference between B tree and B+ tree | [
{
"code": null,
"e": 24011,
"s": 23983,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 24130,
"s": 24011,
"text": "A Cartesian tree is a tree data structure created from a set of data that obeys the following structural invariants: "
},
{
"code": null,
"e": 24346,
"s": 24130,
"text": "The tree obeys in the min (or max) heap property – each node is less (or greater) than its children.An inorder traversal of the nodes yields the values in the same order in which they appear in the initial sequence."
},
{
"code": null,
"e": 24447,
"s": 24346,
"text": "The tree obeys in the min (or max) heap property – each node is less (or greater) than its children."
},
{
"code": null,
"e": 24563,
"s": 24447,
"text": "An inorder traversal of the nodes yields the values in the same order in which they appear in the initial sequence."
},
{
"code": null,
"e": 24656,
"s": 24563,
"text": "Suppose we have an input array- {5,10,40,30,28}. Then the max-heap Cartesian Tree would be. "
},
{
"code": null,
"e": 24718,
"s": 24656,
"text": "A min-heap Cartesian Tree of the above input array will be- "
},
{
"code": null,
"e": 24726,
"s": 24718,
"text": "Note: "
},
{
"code": null,
"e": 24838,
"s": 24726,
"text": "Cartesian Tree is not a height-balanced tree.Cartesian tree of a sequence of distinct numbers is always unique."
},
{
"code": null,
"e": 24884,
"s": 24838,
"text": "Cartesian Tree is not a height-balanced tree."
},
{
"code": null,
"e": 24951,
"s": 24884,
"text": "Cartesian tree of a sequence of distinct numbers is always unique."
},
{
"code": null,
"e": 26354,
"s": 24951,
"text": "Cartesian tree of a sequence of distinct numbers is always unique. We will prove this using induction. As a base case, empty tree is always unique. For the inductive case, assume that for all trees containing n’ < n elements, there is a unique Cartesian tree for each sequence of n’ nodes. Now take any sequence of n elements. Because a Cartesian tree is a min-heap, the smallest element of the sequence must be the root of the Cartesian tree. Because an inorder traversal of the elements must yield the input sequence, we know that all nodes to the left of the min element must be in its left subtree and similarly for the nodes to the right. Since the left and right subtree are both Cartesian trees with at most n-1 elements in them (since the min element is at the root), by the induction hypothesis there is a unique Cartesian tree that could be the left or right subtree. Since all our decisions were forced, we end up with a unique tree, completing the induction.How to construct Cartesian Tree? A O(n2) solution for construction of Cartesian Tree is discussed here (Note that the above program here constructs the “special binary tree” (which is nothing but a Cartesian tree)A O(nlogn) Algorithm : It’s possible to build a Cartesian tree from a sequence of data in O(NlogN) time on average. Beginning with the empty tree,Scan the given sequence from left to right adding new nodes as follows: "
},
{
"code": null,
"e": 26792,
"s": 26354,
"text": "Position the node as the right child of the rightmost node.Scan upward from the node’s parent up to the root of the tree until a node is found whose value is greater than the current value.If such a node is found, set its right child to be the new node, and set the new node’s left child to be the previous right child.If no such node is found, set the new child to be the root, and set the new node’s left child to be the previous tree."
},
{
"code": null,
"e": 26852,
"s": 26792,
"text": "Position the node as the right child of the rightmost node."
},
{
"code": null,
"e": 26983,
"s": 26852,
"text": "Scan upward from the node’s parent up to the root of the tree until a node is found whose value is greater than the current value."
},
{
"code": null,
"e": 27114,
"s": 26983,
"text": "If such a node is found, set its right child to be the new node, and set the new node’s left child to be the previous right child."
},
{
"code": null,
"e": 27233,
"s": 27114,
"text": "If no such node is found, set the new child to be the root, and set the new node’s left child to be the previous tree."
},
{
"code": null,
"e": 27239,
"s": 27235,
"text": "CPP"
},
{
"code": null,
"e": 27244,
"s": 27239,
"text": "Java"
},
{
"code": null,
"e": 27247,
"s": 27244,
"text": "C#"
},
{
"code": null,
"e": 27258,
"s": 27247,
"text": "Javascript"
},
{
"code": "// A O(n) C++ program to construct cartesian tree// from a given array#include<bits/stdc++.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; Node *left, *right;}; /* This function is here just to test buildTree() */void printInorder (Node* node){ if (node == NULL) return; printInorder (node->left); cout << node->data << \" \"; printInorder (node->right);} // Recursively construct subtree under given root using// leftChild[] and rightchildNode * buildCartesianTreeUtil (int root, int arr[], int parent[], int leftchild[], int rightchild[]){ if (root == -1) return NULL; // Create a new node with root's data Node *temp = new Node; temp->data = arr[root] ; // Recursively construct left and right subtrees temp->left = buildCartesianTreeUtil( leftchild[root], arr, parent, leftchild, rightchild ); temp->right = buildCartesianTreeUtil( rightchild[root], arr, parent, leftchild, rightchild ); return temp ;} // A function to create the Cartesian Tree in O(N) timeNode * buildCartesianTree (int arr[], int n){ // Arrays to hold the index of parent, left-child, // right-child of each number in the input array int parent[n],leftchild[n],rightchild[n]; // Initialize all array values as -1 memset(parent, -1, sizeof(parent)); memset(leftchild, -1, sizeof(leftchild)); memset(rightchild, -1, sizeof(rightchild)); // 'root' and 'last' stores the index of the root and the // last processed of the Cartesian Tree. // Initially we take root of the Cartesian Tree as the // first element of the input array. This can change // according to the algorithm int root = 0, last; // Starting from the second element of the input array // to the last on scan across the elements, adding them // one at a time. for (int i=1; i<=n-1; i++) { last = i-1; rightchild[i] = -1; // Scan upward from the node's parent up to // the root of the tree until a node is found // whose value is greater than the current one // This is the same as Step 2 mentioned in the // algorithm while (arr[last] <= arr[i] && last != root) last = parent[last]; // arr[i] is the largest element yet; make it // new root if (arr[last] <= arr[i]) { parent[root] = i; leftchild[i] = root; root = i; } // Just insert it else if (rightchild[last] == -1) { rightchild[last] = i; parent[i] = last; leftchild[i] = -1; } // Reconfigure links else { parent[rightchild[last]] = i; leftchild[i] = rightchild[last]; rightchild[last] = i; parent[i] = last; } } // Since the root of the Cartesian Tree has no // parent, so we assign it -1 parent[root] = -1; return (buildCartesianTreeUtil (root, arr, parent, leftchild, rightchild));} /* Driver program to test above functions */int main(){ /* Assume that inorder traversal of following tree is given 40 / \\ 10 30 / \\ 5 28 */ int arr[] = {5, 10, 40, 30, 28}; int n = sizeof(arr)/sizeof(arr[0]); Node *root = buildCartesianTree(arr, n); /* Let us test the built tree by printing Inorder traversal */ printf(\"Inorder traversal of the constructed tree : \\n\"); printInorder(root); return(0);}",
"e": 30878,
"s": 27258,
"text": null
},
{
"code": "// A O(n) Java program to construct cartesian tree// from a given array /* A binary tree node has data, pointer to leftchild and a pointer to right child */class GFG{static class Node{ int data; Node left, right;}; /* This function is here just to test buildTree() */static void printInorder (Node node){ if (node == null) return; printInorder (node.left); System.out.print(node.data + \" \"); printInorder (node.right);} // Recursively construct subtree under given root using// leftChild[] and rightchildstatic Node buildCartesianTreeUtil (int root, int arr[], int parent[], int leftchild[], int rightchild[]){ if (root == -1) return null; // Create a new node with root's data Node temp = new Node(); temp.data = arr[root] ; // Recursively construct left and right subtrees temp.left = buildCartesianTreeUtil( leftchild[root], arr, parent, leftchild, rightchild ); temp.right = buildCartesianTreeUtil( rightchild[root], arr, parent, leftchild, rightchild ); return temp ;} // A function to create the Cartesian Tree in O(N) timestatic Node buildCartesianTree (int arr[], int n){ // Arrays to hold the index of parent, left-child, // right-child of each number in the input array int []parent = new int[n]; int []leftchild = new int[n]; int []rightchild = new int[n]; // Initialize all array values as -1 memset(parent, -1); memset(leftchild, -1); memset(rightchild, -1); // 'root' and 'last' stores the index of the root and the // last processed of the Cartesian Tree. // Initially we take root of the Cartesian Tree as the // first element of the input array. This can change // according to the algorithm int root = 0, last; // Starting from the second element of the input array // to the last on scan across the elements, adding them // one at a time. for (int i = 1; i <= n - 1; i++) { last = i - 1; rightchild[i] = -1; // Scan upward from the node's parent up to // the root of the tree until a node is found // whose value is greater than the current one // This is the same as Step 2 mentioned in the // algorithm while (arr[last] <= arr[i] && last != root) last = parent[last]; // arr[i] is the largest element yet; make it // new root if (arr[last] <= arr[i]) { parent[root] = i; leftchild[i] = root; root = i; } // Just insert it else if (rightchild[last] == -1) { rightchild[last] = i; parent[i] = last; leftchild[i] = -1; } // Reconfigure links else { parent[rightchild[last]] = i; leftchild[i] = rightchild[last]; rightchild[last] = i; parent[i] = last; } } // Since the root of the Cartesian Tree has no // parent, so we assign it -1 parent[root] = -1; return (buildCartesianTreeUtil (root, arr, parent, leftchild, rightchild));} static void memset(int[] arr, int value){ for (int i = 0; i < arr.length; i++) { arr[i] = value; } } /* Driver code */public static void main(String[] args){ /* Assume that inorder traversal of following tree is given 40 / \\ 10 30 / \\ 5 28 */ int arr[] = {5, 10, 40, 30, 28}; int n = arr.length; Node root = buildCartesianTree(arr, n); /* Let us test the built tree by printing Inorder traversal */ System.out.printf(\"Inorder traversal of the\" + \" constructed tree : \\n\"); printInorder(root);}} // This code is contributed by PrinciRaj1992",
"e": 34669,
"s": 30878,
"text": null
},
{
"code": "// A O(n) C# program to construct cartesian tree// from a given array /* A binary tree node has data, pointer to leftchild and a pointer to right child */using System; class GFG{ class Node{ public int data; public Node left, right;}; /* This function is here just to test buildTree() */static void printInorder (Node node){ if (node == null) return; printInorder (node.left); Console.Write(node.data + \" \"); printInorder (node.right);} // Recursively construct subtree under given root using// leftChild[] and rightchildstatic Node buildCartesianTreeUtil (int root, int []arr, int []parent, int []leftchild, int []rightchild){ if (root == -1) return null; // Create a new node with root's data Node temp = new Node(); temp.data = arr[root] ; // Recursively construct left and right subtrees temp.left = buildCartesianTreeUtil( leftchild[root], arr, parent, leftchild, rightchild ); temp.right = buildCartesianTreeUtil( rightchild[root], arr, parent, leftchild, rightchild ); return temp ;} // A function to create the Cartesian Tree in O(N) timestatic Node buildCartesianTree (int []arr, int n){ // Arrays to hold the index of parent, left-child, // right-child of each number in the input array int []parent = new int[n]; int []leftchild = new int[n]; int []rightchild = new int[n]; // Initialize all array values as -1 memset(parent, -1); memset(leftchild, -1); memset(rightchild, -1); // 'root' and 'last' stores the index of the root and the // last processed of the Cartesian Tree. // Initially we take root of the Cartesian Tree as the // first element of the input array. This can change // according to the algorithm int root = 0, last; // Starting from the second element of the input array // to the last on scan across the elements, adding them // one at a time. for (int i = 1; i <= n - 1; i++) { last = i - 1; rightchild[i] = -1; // Scan upward from the node's parent up to // the root of the tree until a node is found // whose value is greater than the current one // This is the same as Step 2 mentioned in the // algorithm while (arr[last] <= arr[i] && last != root) last = parent[last]; // arr[i] is the largest element yet; make it // new root if (arr[last] <= arr[i]) { parent[root] = i; leftchild[i] = root; root = i; } // Just insert it else if (rightchild[last] == -1) { rightchild[last] = i; parent[i] = last; leftchild[i] = -1; } // Reconfigure links else { parent[rightchild[last]] = i; leftchild[i] = rightchild[last]; rightchild[last] = i; parent[i] = last; } } // Since the root of the Cartesian Tree has no // parent, so we assign it -1 parent[root] = -1; return (buildCartesianTreeUtil (root, arr, parent, leftchild, rightchild));} static void memset(int[] arr, int value){ for (int i = 0; i < arr.Length; i++) { arr[i] = value; } } /* Driver code */public static void Main(String[] args){ /* Assume that inorder traversal of following tree is given 40 / \\ 10 30 / \\ 5 28 */ int []arr = {5, 10, 40, 30, 28}; int n = arr.Length; Node root = buildCartesianTree(arr, n); /* Let us test the built tree by printing Inorder traversal */ Console.Write(\"Inorder traversal of the\" + \" constructed tree : \\n\"); printInorder(root);}} // This code is contributed by 29AjayKumar",
"e": 38475,
"s": 34669,
"text": null
},
{
"code": "<script>// A O(n) Javascript program to construct cartesian tree// from a given array /* A binary tree node has data, pointer to leftchild and a pointer to right child */class Node{ constructor(data) { this.data=data; this.left=this.right=null; }} /* This function is here just to test buildTree() */function printInorder (node){ if (node == null) return; printInorder (node.left); document.write(node.data + \" \"); printInorder (node.right);} // Recursively construct subtree under given root using// leftChild[] and rightchildfunction buildCartesianTreeUtil(root,arr,parent,leftchild,rightchild){ if (root == -1) return null; // Create a new node with root's data let temp = new Node(); temp.data = arr[root] ; // Recursively construct left and right subtrees temp.left = buildCartesianTreeUtil( leftchild[root], arr, parent, leftchild, rightchild ); temp.right = buildCartesianTreeUtil( rightchild[root], arr, parent, leftchild, rightchild ); return temp ;} // A function to create the Cartesian Tree in O(N) timefunction buildCartesianTree (arr,n){ // Arrays to hold the index of parent, left-child, // right-child of each number in the input array let parent = new Array(n); let leftchild = new Array(n); let rightchild = new Array(n); // Initialize all array values as -1 memset(parent, -1); memset(leftchild, -1); memset(rightchild, -1); // 'root' and 'last' stores the index of the root and the // last processed of the Cartesian Tree. // Initially we take root of the Cartesian Tree as the // first element of the input array. This can change // according to the algorithm let root = 0, last; // Starting from the second element of the input array // to the last on scan across the elements, adding them // one at a time. for (let i = 1; i <= n - 1; i++) { last = i - 1; rightchild[i] = -1; // Scan upward from the node's parent up to // the root of the tree until a node is found // whose value is greater than the current one // This is the same as Step 2 mentioned in the // algorithm while (arr[last] <= arr[i] && last != root) last = parent[last]; // arr[i] is the largest element yet; make it // new root if (arr[last] <= arr[i]) { parent[root] = i; leftchild[i] = root; root = i; } // Just insert it else if (rightchild[last] == -1) { rightchild[last] = i; parent[i] = last; leftchild[i] = -1; } // Reconfigure links else { parent[rightchild[last]] = i; leftchild[i] = rightchild[last]; rightchild[last] = i; parent[i] = last; } } // Since the root of the Cartesian Tree has no // parent, so we assign it -1 parent[root] = -1; return (buildCartesianTreeUtil (root, arr, parent, leftchild, rightchild));} function memset(arr,value){ for (let i = 0; i < arr.length; i++) { arr[i] = value; }} /* Driver code *//* Assume that inorder traversal of following tree is given 40 / \\ 10 30 / \\ 5 28 */ let arr = [5, 10, 40, 30, 28];let n = arr.length; let root = buildCartesianTree(arr, n); /* Let us test the built tree by printing Inorder traversal */document.write(\"Inorder traversal of the\" + \" constructed tree : <br>\");printInorder(root); // This code is contributed by rag2127</script>",
"e": 42188,
"s": 38475,
"text": null
},
{
"code": null,
"e": 42198,
"s": 42188,
"text": "Output: "
},
{
"code": null,
"e": 42256,
"s": 42198,
"text": "Inorder traversal of the constructed tree :\n5 10 40 30 28"
},
{
"code": null,
"e": 42751,
"s": 42256,
"text": "Time Complexity : At first look, the code seems to be taking O(n2) time as there are two loop in buildCartesianTree(). But actually, it takes O(NlogN) time in average and O(n^2) for sorted preorder traversal.Auxiliary Space: We declare a structure for every node as well as three extra arrays- leftchild[], rightchild[], parent[] to hold the indices of left-child, right-child, parent of each value in the input array. Hence the overall O(4*n) = O(n) extra space.Application of Cartesian Tree "
},
{
"code": null,
"e": 42774,
"s": 42751,
"text": "Cartesian Tree Sorting"
},
{
"code": null,
"e": 42962,
"s": 42774,
"text": "A range minimum query on a sequence is equivalent to a lowest common ancestor query on the sequence’s Cartesian tree. Hence, RMQ may be reduced to LCA using the sequence’s Cartesian tree."
},
{
"code": null,
"e": 43165,
"s": 42962,
"text": "Treap, a balanced binary search tree structure, is a Cartesian tree of (key,priority) pairs; it is heap-ordered according to the priority values, and an inorder traversal gives the keys in sorted order."
},
{
"code": null,
"e": 43351,
"s": 43165,
"text": "Suffix tree of a string may be constructed from the suffix array and the longest common prefix array. The first step is to compute the Cartesian tree of the longest common prefix array."
},
{
"code": null,
"e": 43795,
"s": 43351,
"text": "References: http://wcipeg.com/wiki/Cartesian_treeThis article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 43813,
"s": 43795,
"text": "DivyanshuShekhar1"
},
{
"code": null,
"e": 43827,
"s": 43813,
"text": "princiraj1992"
},
{
"code": null,
"e": 43839,
"s": 43827,
"text": "29AjayKumar"
},
{
"code": null,
"e": 43847,
"s": 43839,
"text": "rag2127"
},
{
"code": null,
"e": 43862,
"s": 43847,
"text": "varshagumber28"
},
{
"code": null,
"e": 43875,
"s": 43862,
"text": "simmytarika5"
},
{
"code": null,
"e": 43892,
"s": 43875,
"text": "surinderdawra388"
},
{
"code": null,
"e": 43916,
"s": 43892,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 44014,
"s": 43916,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44023,
"s": 44014,
"text": "Comments"
},
{
"code": null,
"e": 44036,
"s": 44023,
"text": "Old Comments"
},
{
"code": null,
"e": 44076,
"s": 44036,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 44108,
"s": 44076,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 44137,
"s": 44108,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 44180,
"s": 44137,
"text": "How to design a tiny URL or URL shortener?"
},
{
"code": null,
"e": 44200,
"s": 44180,
"text": "Design a Chess Game"
},
{
"code": null,
"e": 44214,
"s": 44200,
"text": "Binomial Heap"
},
{
"code": null,
"e": 44246,
"s": 44214,
"text": "Red-Black Tree | Set 3 (Delete)"
},
{
"code": null,
"e": 44338,
"s": 44246,
"text": "Design a data structure that supports insert, delete, search and getRandom in constant time"
},
{
"code": null,
"e": 44374,
"s": 44338,
"text": "Binary Indexed Tree or Fenwick Tree"
}
] |
MS Project - Quick Guide | Each one of you might be using a different setting for MS Project 2013. To ensure the results are not different from what is shown in this tutorials, ensure the settings as follows. Remember all these are the default settings you will have when you first install MS Project 2013 on your computer.
Step 1 − File → Options → General tab → Project view → Default view.
Select “Gantt with Timeline” from the dropdown box.
Step 2 − File → Options → Display tab → Show Indicators and Options Buttons For.
Check all options.
Step 3 − File → Options → Schedule tab → Schedule → Show Assignment Units.
Choose “percentage” from the dropdown box.
Step 4 − File → Options → Schedule tab → Calculation → Calculate Project after Each Edit.
Check the On button.
Step 5 − File → Options → Save tab → Save projects → Save Files In this format.
Select Project (*.mpp).
Step 6 − File → Options → Advanced tab → Edit.
Check all options.
Step 7 − File → Options → Advanced tab → Display → Show Status Bar → Show Scroll Bar.
Both options, Status Bar and Scroll Bar should be checked.
Step 8 Resources → Level → Leveling Options → Leveling Calculations.
Set to manual.
Step 9 − Resources → Level → Leveling Options → Leveling calculations → Look for Overallocations.
Select “Day By Day” from dropdown box.
Microsoft Project is a project management software program developed and sold by Microsoft, designed to assist a project manager in developing a schedule, assigning resources to tasks, tracking progress, managing the budget, and analyzing workloads.
Project creates budgets based on assignment work and resource rates. As resources are assigned to tasks and assignment work estimated, the program calculates the cost, equal to the work times the rate, which rolls up to the task level and then to any summary task, and finally to the project level.
Each resource can have its own calendar, which defines what days and shifts a resource is available. Microsoft Project is not suitable for solving problems of available materials (resources) constrained production. Additional software is necessary to manage a complex facility that produces physical goods.
MS Project is feature rich, but project management techniques are required to drive a project effectively. A lot of project managers get confused between a schedule and a plan. MS Project can help you in creating a Schedule for the project even with the provided constraints. It cannot Plan for you. As a project manager you should be able to answer the following specific questions as part of the planning process to develop a schedule. MS Project cannot answer these for you.
What tasks need to be performed to create the deliverables of the project and in what order? This relates to the scope of the project.
What tasks need to be performed to create the deliverables of the project and in what order? This relates to the scope of the project.
What are the time constraints and deadlines if any, for different tasks and for the project as a whole? This relates to the schedule of the project.
What are the time constraints and deadlines if any, for different tasks and for the project as a whole? This relates to the schedule of the project.
What kind of resources (man/machine/material) are needed to perform each task?
What kind of resources (man/machine/material) are needed to perform each task?
How much will each task cost to accomplish? This would relate to the cost of the project.
How much will each task cost to accomplish? This would relate to the cost of the project.
What kind of risk do we have associated with a particular schedule for the project? This might affect the scope, cost and time constraints of your project.
What kind of risk do we have associated with a particular schedule for the project? This might affect the scope, cost and time constraints of your project.
Strictly speaking, from the perspective of Project Management Methodology, a Plan and Schedule are not the same. A plan is a detailed action-oriented, experience and knowledge-based exercise which considers all elements of strategy, scope, cost, time, resources, quality and risk for the project.
Scheduling is the science of using mathematical calculations and logic to generate time effective sequence of task considering any resource and cost constraints. Schedule is part of the Plan. In Project Management Methodology, schedule would only mean listing of a project's milestones, tasks/activities, and deliverables, with start and finish dates. Of course the schedule is linked with resources, budgets and dependencies.
However, in this tutorial for MS Project (and in all available help for MS Project) the word ‘Plan’ is used as a ‘Schedule’ being created in MS Project. This is because of two reasons.
One, MS Project does more than just create a schedule it can establish dependencies among tasks, it can create constraints, it can resolve resource conflicts, and it can also help in reviewing cost and schedule performance over the duration of the project. So it does help in more than just creating a Schedule. This it makes sense for Microsoft to market MS Project as a Plan Creator rather than over-simplifying it as just a schedule creator.
Two, it is due to limitation of generally accepted form of English language, where a schedule can be both in a noun as well as verb form. As a noun, a Schedule is like a time table or a series of things to be done or of events to occur at or during a particular time or period. And in the verb form, schedule is to plan for a certain date. Therefore it is much easier to say that, “One can schedule a plan from a start date” but very awkward to say, “One can schedule a schedule from a start date”. The distinction is important for you as a project manager, but as far as MS project is concerned the noun form of Schedule is a Plan.
Of course, a project manager should also be able to answer other project-related questions as well. For example −
Why this project needs to be run by the organization?
What’s the best way to communicate project details to the stakeholders?
What is the risk management plan?
How the vendors are going to be managed?
How the project is tracked and monitored?
How the quality is measured and qualified?
MS Project can help you −
Visualize your project plan in standard defined formats.
Schedule tasks and resources consistently and effectively.
Track information about the work, duration, and resource requirements for your project.
Generate reports to share in progress meetings.
In this chapter, we will take a close look at the user interface of MS Project.
Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013.
Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013.
Windows 8 − On the Start screen, tap or click Project 2013.
Windows 8 − On the Start screen, tap or click Project 2013.
Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013.
Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013.
The following screen is the Project’s start screen. Here you have options to open a new plan, some other plans, and even a new plan template.
Click the Blank Project Tab. The following screen pops up.
The screen should have the MS Project interface displayed. The major part of this interface are −
Quick Access Toolbar − A customizable area where you can add the frequently used commands.
Quick Access Toolbar − A customizable area where you can add the frequently used commands.
Tabs on the Ribbon, Groups − With the release of Microsoft Office 2007 came the "Fluent User Interface" or "Fluent UI", which replaced menus and customizable toolbars with a single "Office menu", a miniature toolbar known as "quick-access toolbar" and what came to be known as the ribbon having multiple tabs, each holding a toolbar bearing buttons and occasionally other controls. Toolbar controls have heterogeneous sizes and are classified in visually distinguishable Groups. Groups are collections of related commands. Each tab is divided into multiple groups.
Tabs on the Ribbon, Groups − With the release of Microsoft Office 2007 came the "Fluent User Interface" or "Fluent UI", which replaced menus and customizable toolbars with a single "Office menu", a miniature toolbar known as "quick-access toolbar" and what came to be known as the ribbon having multiple tabs, each holding a toolbar bearing buttons and occasionally other controls. Toolbar controls have heterogeneous sizes and are classified in visually distinguishable Groups. Groups are collections of related commands. Each tab is divided into multiple groups.
Commands − The specific features you use to perform actions in Project. Each tab contains several commands. If you point at a command you will see a description in a tooltip.
Commands − The specific features you use to perform actions in Project. Each tab contains several commands. If you point at a command you will see a description in a tooltip.
View Label − This appears along the left edge of the active view. Active view is the one you can see in the main window at a given point in time. Project includes lots of views like Gantt Chart view, Network Diagram view, Task Usage view, etc. The View label just tells you about the view you are using currently. Project can display a single view or multiple views in separate panes.
View Label − This appears along the left edge of the active view. Active view is the one you can see in the main window at a given point in time. Project includes lots of views like Gantt Chart view, Network Diagram view, Task Usage view, etc. The View label just tells you about the view you are using currently. Project can display a single view or multiple views in separate panes.
View Shortcuts − This lets you switch between frequently used views in Project.
View Shortcuts − This lets you switch between frequently used views in Project.
Zoom Slider − Simply zooms the active view in or out.
Zoom Slider − Simply zooms the active view in or out.
Status bar − Displays details like the scheduling mode of new tasks (manual or automatic) and details of filter applied to the active view.
Status bar − Displays details like the scheduling mode of new tasks (manual or automatic) and details of filter applied to the active view.
When working with MS Project you either specify a start date or a finish date. Because once you enter one of the two, and other project tasks, constraints and dependencies, MS Project will calculate the other date. It is always a good practice to use a start date even if you know the deadline for the project.
Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013.
Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013.
Windows 8 − On the Start screen, tap or click Project 2013.
Windows 8 − On the Start screen, tap or click Project 2013.
Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013.
Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013.
MS Project 2013 will display a list of options. In the list of available templates, click Blank Project.
Project sets the plan’s start date to current date, a thin green vertical line in the chart portion of the Gantt Chart View indicates this current date.
Let us change the project start date and add some more information.
Click Project tab → Properties Group → Project Information.
A dialog box appears. In the start date box, type 11/5/15, or click the down arrow to display the calendar, select November 5, 2015 (or any date of your choice).
Click OK to accept the start date.
Click Project tab → Properties Group → Project Information.
Click the arrow on the Current Date dropdown box. A list appears containing three base calendars.
24 Hour − A calendar with no non-working time.
24 Hour − A calendar with no non-working time.
Night Shift − Covers 11 PM to 8 AM, night shifts covering all nights from Monday to Friday, with one hour breaks.
Night Shift − Covers 11 PM to 8 AM, night shifts covering all nights from Monday to Friday, with one hour breaks.
Standard − Regular working hours, Monday to Friday between 8 AM to 5 PM, with one hour breaks.
Standard − Regular working hours, Monday to Friday between 8 AM to 5 PM, with one hour breaks.
Select a Standard Calendar as your project Calendar. Click “Cancel” or “OK” to close the dialog box.
Now let us add exceptions.
Exceptions are used to modify a Project calendar to have a non-standard workday or a non-working day. You can also allot unique working hours for a particular resource as well.
Here is an example to create a non-working day, which could be because of a holiday or office celebrations or events other than the standard office work effort.
Click Project tab → Properties Group → Change Working Time.
Change Working Time dialog box appears. Under Exceptions Tab click on the Name Field, enter event as “Office Anniversary”. In the Start field enter 11/22/15, and then enter the same date in the Finish field. This date is now scheduled as a non-working day for the project. You can also verify the changed color indicated in the calendar within the dialog box as below. Click Ok to close.
Just like you can change a Standard Base Calendar, you can change the work and non-working time for each resource. You can modify the resource calendar to accommodate flex-time, vacation time, training time, etc.
Also remember, Resource Calendar can only be applied to work resources and not to material and cost resources.
By default when we create the resources in a plan, the resource calendar matches the Standard base calendar. And any changes you make to the Project Calendar, gets reflected automatically in resource calendars, except when you create an exception in the resource calendar. In that case even if you update the project calendar, the exception in resource calendar is not affected.
Click Project tab → Properties group → Click Change Working Time
Change Working Time dialog box appears.
Click the down arrow for the “For Calendar” drop-down box.
Select the resource for whom you want to create an exception. In example below I have chosen John.
Under Exceptions Tab click on the Name Field, enter event as “Personal holiday”. In the Start field enter the date (example 9/15/2015), and then enter the same date in the Finish field.
Click Project tab → Properties group → Click Change Working Time.
The Change Working Time dialog box appears.
Click the down arrow for the “For Calendar” dropdown box.
Select the resource for whom you want to change work schedule.
In the following screen you can see we have chosen John.
Click “Work Weeks” tab.
Double-click the [default] cell below the Name column heading.
Under “Selected Day(s)” choose any day you want to change the work schedule.
We have chosen Tuesday and Wednesday.
Click Set day(s) to these specific working times. Change the time.
Click Project tab → Properties group → Click Change Working Time.
The Change Working Time dialog box appears.
Click the down arrow for the “For Calendar” dropdown box.
Select the resource for whom you want to change work schedule. We have chosen John again.
Click “Work Weeks” tab.
Double-click the [default] cell below the Name column heading.
Under “Selected Day(s)” choose any day you want to change the work schedule.
Click any day (we have chosen Friday) and use the radio button “Set days to nonworking time”.
Click OK to close the Dialog box. You will now see all Fridays are greyed out in the calendar.
With Microsoft Windows Operating system, right clicking a file and selecting “Properties” brings up the file properties dialog box that contains version, security and other file details. You can record some top level information for your .mpp project file as well. This can be done as follows −
Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013.
Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013.
Windows 8 − On the Start screen, tap or click Project 2013.
Windows 8 − On the Start screen, tap or click Project 2013.
Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013.
Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013.
Click File Tab. Under Info Tab go to Project Information. Click arrow near Project Information to click Advanced Properties. A dialog box opens, you can type in the changes as required. Click OK and don’t forget to save by clicking on Save.
Before we start, let us assume you already have a Work Breakdown Structure (WBS). In context of WBS, “Work” refers to “Deliverables” and not effort.
WBS identifies the deliverable at the lowest level as work package. This work package is decomposed into smaller tasks/activities, which is the effort necessary to complete the work package. So a task is action-oriented, and the work package is the deliverable or a result of one or more tasks being performed.
There is a significant amount of confusion between what constitutes an activity and what constitutes a task within the project management community. But for MS Project, a task is the effort and action required to produce a particular project deliverable. MS Project does not use the term “activity”.
This is simple. In Gantt Chart View, just click a cell directly below the Task Name column. Enter the task name. In the following screen, we have entered 5 different tasks.
A duration of the task is the estimated amount of time it will take to complete a task. As a project manager you can estimate a task duration using expert judgment, historical information, analogous estimates or parametric estimates.
You can enter task duration in terms of different dimensional units of time, namely minutes, hours, days, weeks, and months. You can use abbreviations for simplicity and ease as shown in the following table.
Remember, Project default values depend on your work hours. So 1 day is not equivalent to 24 hours but has 8 hours of work for the day. Of course, you can change these defaults anytime you want.
Click Project tab → Properties Group → Click Change Working Time → Click Options.
You can apply this to all projects or a specific project that you are working on currently.
One of the neat tricks MS Project possesses is, it considers duration of the task in workday sense. So if you have a non-working day in between, it accommodates this and ensures a task that takes 16 hours to complete to end on the 3rd day. In other words, if you have a task that needs 16 hours to complete starting on Monday 8:00 AM (if this is the time your work day starts, and 8 hours being total work hours in a day), and Tuesday being a holiday, the task will logically end on the evening of Wednesday.
Tip − With manually scheduled tasks, if you are not sure about a task duration, you can just enter text such as “Check with Manager/Engineer” to come back to this later.
This is simple in Gantt Chart View, click the cell below Duration column heading. Enter the duration. (Task 1 in the following screenshot)
You can also enter Start and Finish date and MS Project will calculate the duration on its own. (Task 2 in the following screenshot)
You can enter text as well when you don’t have a duration metric currently. (Task 3 and Task 4 in the following screenshot)
Note − In the above screenshot, Task 6 is scheduled to start on Sunday, which is a nonworking day and ends on Wednesday. So essentially, one would believe that with these 3 days Monday, Tuesday, Wednesday, the duration calculated would be 3 days. But MS Project 2013 calculates it as 4 days. So one needs to be careful when choosing the start date of the task. Because for any successive operation, MS Project 2013 considers that Task 6 will take 4 days. The next time, you change the start date, the Finish date changes to reflect this 4-day duration.
Elapsed Duration is the time that elapses while some event is occurring which does not require any resources. Elapsed duration for a task can be used in instances where a task will go on round-the-clock without any stoppage. A normal workday has 8 hours, and an elapsed day duration will have 24 hours. The task also continues over non-working (holidays and vacations) and working days.
You can enter elapsed duration by preceding any duration abbreviation with an “e”. So 1ew is seven 24-hour days.
For example, when you are ‘Waiting for the paint to dry’. And it takes 4 days for this to happen. It does not need a resource or a work effort, and all you are doing is waiting for it to dry. You can use 4ed as the time duration, which signifies 4 elapsed days, the paint can dry regardless of whether it is a weekend or if it falls on a holiday. Here in this example, the drying occurs over 24 hours over the weekend.
In Project Management, Milestones are specific points in a project timeline. They are used as major progress points to manage project success and stakeholder expectations. They are primarily used for review, inputs and budgets.
Mathematically, a milestone is a task of zero duration. And they can be put where there is a logical conclusion of a phase of work, or at deadlines imposed by the project plan.
There are two ways you can insert a milestone.
Click name of the Task which you want to insert a Milestone
Click Task tab → Insert group → Click Milestone.
MS Project names the new task as <New Milestone> with zero-day duration.
Click on <New Milestone> to change its name.
You can see the milestone appear with a rhombus symbol in the Gantt Chart View on the right.
Click on any particular task or type in a new task under the Task Name Heading.
Under Duration heading type in “0 days “.
MS Project converts it to a Milestone.
In Method 2, a task was converted to a Milestone of Zero duration. But one can also convert a task of non-zero duration into a Milestone. This is rarely used and causes confusion.
Double-click a particular Task name.
Task Information dialog box opens.
Click Advanced tab → select option “Mark Task as Milestone”.
The project summary task summarizes your whole project.
In Gantt Chart View → Format Tab → Show/Hide → click to check Project Summary Task on.
There can be a huge number of tasks in a project schedule, it is therefore a good idea to have a bunch of related tasks rolled up into a Summary Task to help you organize the plan in a better way. It helps you organize your plan into phases.
In MS Project 2013, you can have several number of sub-tasks under any higher level task. These higher level tasks are called Summary Task. At an even higher level, they are called Phases. The highest level of a plan’s outline structure is called the Project Summary Task, which encompasses the entire project schedule.
Remember because summary task is not a separate task entity but a phase of the project with several sub-tasks in it, the duration of the summary task is from the start of the first sub-task to the finish of the last sub-task. This will be automatically calculated by MS Project.
Of course, you can enter a manual duration of the summary task as well which could be different from the automatically calculated duration. MS Project will keep track of both but this can cause significant confusion.
In most cases, you should ensure that there is no manually entered duration for any task you will be using as a Summary Task.
Let us use the following screenshot as an example. If you would like to group Task 4 and Task 5 into a Summary Task 1. You can do it in two ways.
Select the names of Task 4 and Task 5.
Click Task Tab → group Insert → Click Summary
MS Project creates a <New Summary Task>.
Rename it to Summary Task 1.
You can click Task 4 row.
Select “Insert Task”. A <New Task> is created.
You can rename the Task. Here it is renamed as Summary Task 1. Don’t enter any duration for this task.
Now select Task 4 and Task 5.
Click Task tab → Schedule group → Click Indent Task
Once you have a list of tasks ready to accomplish your project objectives, you need to link them with their task relationships called dependencies. For example, Task 2 can start once Task 1 has finished. These dependencies are called Links. A Guide to the Project Management Body of Knowledge (PMBOK Guide) does not define the term dependency, but refers to it as a logical relationship, which in turn is defined as a dependency between two activities, or between an activity and a milestone.
In MS Project, the first task is called a predecessor because it precedes tasks that depend on it. The following task is called the successor because it succeeds, or follows tasks on which it is dependent. Any task can be a predecessor for one or more successor tasks. Likewise, any task can be a successor to one or more predecessor tasks.
There are only four types of task dependencies, here we present them with examples.
Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used.
Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used.
Finish to Finish (FF) − Cooking all dishes for dinner to finish on time.
Finish to Finish (FF) − Cooking all dishes for dinner to finish on time.
Start To Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey response before starting the tabulation.
Start To Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey response before starting the tabulation.
Start to Finish (SF) − Exam preparation will end when exam begins. Least used.
Start to Finish (SF) − Exam preparation will end when exam begins. Least used.
In MS Project you can identify the Task Links −
Gantt Chart − In Gantt Chart and Network Diagram views, task relationships appear as the links connecting tasks.
Gantt Chart − In Gantt Chart and Network Diagram views, task relationships appear as the links connecting tasks.
Tables − In Tables, task ID numbers of predecessor task appear in the predecessor fields of successor tasks.
Tables − In Tables, task ID numbers of predecessor task appear in the predecessor fields of successor tasks.
Select the two tasks you want to link. In the following screenshot taken as an example, we have selected names, Task 1 and Task 2.
Click Task tab → Schedule group → Link the Selected Tasks.
Task 1 and Task 2 are linked with a Finish-to-Start relationship.
Note − Task 2 will have a Start date of the Next working day from Finish date of Task 1.
Double click a successor task you would like to link.
Here I have clicked Task 4
The Task information dialog box opens
Click Predecessors tab
In the Table, click the empty cell below Task Name column.
A drop down box appears with all Tasks defined in the project.
Choose the predecessor task. Click OK.
Here I have chosen Task 3.
In this method, you will select a group of task, and link them all with Finish-to-Start relationship.
Select multiple tasks with the help of the mouse → Task tab → Schedule group → Link the Selected Tasks.
All tasks get linked. To select non-adjacent tasks, hold down Ctrl key and select each task separately.
If you are in Manually Scheduled mode, any change in duration of the predecessor task will not reflect on Start date of Task 4. For example, Task 4 starts on 9/3/15 which is the next day of Finish date of Task 3.
Now when we change the Duration of Task 3 from 5 to 7 days, the start date is not automatically updated for Task 4 in Manual Scheduling.
You can force MS Project to respect the link (dependency) by doing the following −
Select Task 4.
Click Task tab → Schedule group → Respect Links.
MS Project by default sets new tasks to be manually scheduled. Scheduling is controlled in two ways.
Manual Scheduling − This is done to quickly capture some details without actually scheduling the tasks. You can leave out details for some of the tasks with respect to duration, start and finish dates, if you don’t know them yet.
Automatic Scheduling − This uses the Scheduling engine in MS Project. It calculates values such as task durations, start dates, and finish dates automatically. It takes into accounts all constraints, links and calendars.
For example, at Lucerne Publishing, the new book launch plan has been reviewed by the resources who will carry out the work and by other project stakeholders. Although you expect the plan to change somewhat as you learn more about the book launch, you now have enough confidence in the overall plan to switch from manual to automatic task scheduling.
We have three different methods to convert a task to automatic schedule.
If you want to change the mode for a particular task, say Task 5 in the following example. Click on Task Mode cell in the same row. Then, click the down arrow to open a dropdown box, you can select Auto Scheduled.
Click Task → Tasks group → Auto Schedule.
To switch completely to Auto Schedule mode −
Toggle the scheduling mode of the plan by clicking the New Tasks status bar (at the bottom-left) and then selecting Auto scheduling mode.
You can also change the default scheduling mode that Project applies to all new plans.
Go to File tab and click Options. Then click Schedule tab and under scheduling options for this project select “All New Projects” from the dropdown box. Under new tasks created, select “Auto Scheduled” from the dropdown box.
In project management terminology, resources are required to carry out the project tasks. They can be people, equipment, facilities, funding, or anything (except labor) required for the completion of a project task. Optimum Resource Scheduling is the key to successful project management.
Work resources − People and equipment to complete the tasks.
Work resources − People and equipment to complete the tasks.
Cost resources − Financial cost associated with a task. Travel expenses, food expenses, etc.
Cost resources − Financial cost associated with a task. Travel expenses, food expenses, etc.
Material resources − Consumables used as project proceeds. For example, paint being used while painting a wall.
Material resources − Consumables used as project proceeds. For example, paint being used while painting a wall.
Note − Be aware of the crucial difference between People and Equipment resources. People resources will have limited work hours, say 6, 8 or 12 hours. Equipment resources have different working capacities of 2, 8 or 24 hours and could have maintenance breaks as well. Also note, that it is possible multiple people resources might be using one equipment resource, or one equipment might be accomplishing multiple tasks.
You can enter resource names according to your convenience.
Click View tab → Resource Views group → Click Resource Sheet.
Click the cell directly below the Resource Name heading column.
Enter Resources as an individual person, job function or group.
By default, the Max Units field is set to 100%.
Max Units field represents the maximum capacity of a resource to work on assigned tasks. 100% stands for 100 percent of resource’s working time is available for work on task assigned. The resource is available full-time on each workday. If the resource gets allocated to task or tasks that would require more than his/its work hours, the resource is over allocated and MS Project will indicate this in red formatting.
If a resource does not represent an individual person but a job function, where a group of people with the same skill set can work on the task, we can enter larger Max Units to represent the number of people in the group. So 400% would indicate, 4 individual people working full-time every workday.
Click View tab → Resource Views group → Click Resource Sheet
Click the cell directly below Resource Name heading column
Enter Resources as group, here we take an example of Engineers.
Click the Max. Units field for the Engineers resource.
Type or select 400%. Press Enter.
Entering a value less than 100% in Max.Units would mean you expect the resource capacity to be lower than a full-time resource. So 50% would mean the individual works for half of the normal full capacity, so if a normal work week is 40 hours, this equals 20 hour capacity.
Click View tab → Resource Views group → Click Resource Sheet.
Click the cell directly below Resource Name heading column.
Enter Resource as an individual or job function. Here let’s take an example.
You can enter standard rates and costs per use for work and material resources. You can also enter overtime rates for work resources. Standard rates are calculated on per hour basis. Costs per use on the other hand are costs that do not vary with task. Cost per use is a set fee used up to complete a task. There are three types of resources − work, material, and cost.
Work resources − People and equipment to complete the tasks.
Work resources − People and equipment to complete the tasks.
Cost resources − Financial cost associated with a task. Travel expenses, food expenses, etc.
Cost resources − Financial cost associated with a task. Travel expenses, food expenses, etc.
Material resources − Consumables used as project proceeds. Like paint being used while painting a wall.
Material resources − Consumables used as project proceeds. Like paint being used while painting a wall.
Note − Be aware of the crucial difference between People and Equipment resources. People resources will have limited work hours say 6, 8 or 12 hours. Equipment resources can have different working capacities of 2, 8 or 24 hours and could have maintenance breaks as well. Also note that it is possible multiple people resources might be using one equipment resource, or one equipment might be accomplishing multiple tasks.
Cost resources do not use pay rates. Remember cost per use and cost resources are two different things. Cost resources are financial cost associated with a task, like travel expenses, food expenses, etc. The cost value of cost resource is only assigned when you assign cost resource to a task.
Project calculates the cost of a task by using this formula −
Cost of Task = Work Value (in number of hours) x Resource’s Pay Rate.
You can then see the cost per resource and cost per task (as well as costs rolled up to summary tasks and the entire plan). MS Project will not automatically apply overtime calculations.
To enter standard and overtime pay rates for work resources −
Click View tab → Resource Views group → Resource Sheet.
Click the cell directly below Resource Name heading column to create Resources.
Click the Std. Rate field for each resource to costs in hourly (default), daily, weekly, monthly and yearly rates.
In the following example, the resource Rasmus is left at zero. This is useful when you don’t have to track rate-based costs for some resources.
Click the Ovt. Rate field to enter overtime rates.
Click View tab → Resource Views group → Resource Sheet.
Double-click the Resource, a Resource Information dialog box opens.
Click on Notes tab. Here let’s enter a note for Rasmus as “Rasmus will work parttime”.
Click OK.
A note icon now appears to the left of Rasmus’ name in the Resource Sheet view. Hovering over it will make the note appear.
You can use a cost resource to represent a financial cost associated with a task in a plan. Examples of cost resources are travel, food, entertainment and training. So it is obvious that cost resources do no work on a task and do not affect scheduling of a task.
Cost value of the cost resource is entered when assigning it to a task.
Click View tab → Resource Views group → Resource Sheet.
Click the empty cell in the Resource Name column.
Type Training and press the Tab Key.
In the Type field, click the down arrow to select Cost.
Once the task and resource list are complete, resources need to be assigned to tasks in order to work on them. With MS Project you can track task progress, resource and tasks costs.
Click View Tab → Gantt Chart View → Resource Name column.
Click the box below the Resource Name column for the task you need the resource to be assigned.
From the dropdown, choose the resource name. In the following screenshot as an
example. For Task 1 “PT1”, we have chosen the resource “Celic”.
You can also select multiple resources to work on a single task.
Click Resource tab → Under Assignments group → Assign Resources.
In the Assign Resources dialog box, click the resource name you like to assign.
Here let’s choose “Hitesh”. Now click the Assign button.
You can also select multiple resources to work on a single task.
Click View Tab → Gantt Chart → Task Name column.
Double-click the Task Name. Task Information dialog box opens.
Click the Resources tab.
Click the cell below the Resource Name column. Select the resource from the dropdown list.
You can also select multiple resources to work on a single task.
Click View Tab → Split View group → Details → Task Form.
The window is split in two, Gantt Chart view and Task Form view below it.
In the Task Form view, click under the Resource Name column and select the resource.
You can also select multiple resources to work on a single task.
Click View Tab → Gantt Chart View → Task Name column.
Double-click the Task Name. Task Information dialog box opens.
Click the Resources tab.
Click the cell below the Resource Name column. Select the resource from the dropdown list.
In the following example below, let’s choose “Travel” as cost resource and enter the cost at $800.
We can also assign other material resources to the same task.
After assigning resources to tasks you can view the cost, duration and work required for the plan to complete.
In Gantt Chart View → View Tab → Split View group → Timeline checkbox.
You will be able to see the plan’s start and finish dates.
In the Gantt Chart view, you can also look at the project summary task, to note the duration, start and finish dates of the plan.
In the following example, Assign Resources is the project summary task (identified as Task 0). Duration=53 days, Start date: 1/5/15 and Finish Date: 3/19/15.
One can switch Project Summary Task on by following these steps −
In Gantt Chart View → Format Tab → Show/Hide → To check Project Summary Task on.
Click View tab → Data group → Tables → Cost.
Cost for each task gets rolled up into summary tasks, and then ultimately to project summary task.
Click Report Tab → View Reports group → click Resources → click Resource overview
In Resource status table which appears at the bottom, you will get a summary of resource’s earliest start dates and latest finish dates as well as remaining work.
Click Project Tab → Properties group → Project Information → in
the new dialog box click Statistics...
Once your project plan is ready in MS Project, it becomes essential for a project manager to measure the actuals (in terms of work completed, resources used and costs incurred) and to revise and change information about tasks and resources due to any changes to the plans. A Project Manager should not assume that everything is progressing according to plan and should always keep track of each task. Resistance to formal tracking of project management data is normal. You can overcome resistance to tracking by explaining your expectations, explaining the benefits of tracking, and training people to track the task themselves.
To evaluate project performance you need to create a baseline against which you will compare the progress. One needs to save the baseline, once a plan is fully developed. Of course, due to rolling wave planning or progressive elaboration needed to manage projects one can always add new tasks, resources, constraints and costs to the plan.
Also note, it makes sense to save the baseline before entering any actual values such as percentage of task completion.
Note − With MS Project 2013, you can save up to 11 Baselines in a Single plan. These multiple baselines seem contrary to the definition of baseline. You can use this flexibility when −
You have a baseline plan for the external customer and another for the internal team.
You have a baseline plan for the external customer and another for the internal team.
You are preparing for a risk event. You want to develop separate baseline plans for risk response and recovery.
You are preparing for a risk event. You want to develop separate baseline plans for risk response and recovery.
You are accommodating a big change request, you might still want to keep the original plan for future reference when communicating with a stakeholder.
You are accommodating a big change request, you might still want to keep the original plan for future reference when communicating with a stakeholder.
Click Project Tab → Schedule group → Set Baseline → OK.
Click View Tab → Task Views group → Gantt Chart.
Click Format Tab → Bars and Styles group → Baseline (that you want to display).
You will see Baseline Gantt bars displayed together with the current Gantt bars.
As time and work progresses on a project, you might need to change the baseline as well. You have several options for the same −
Update the baseline.
Update the baseline for selected tasks.
Save multiple baselines.
This simply replaces the original baseline values with the currently scheduled values.
Click Project Tab → Schedule group → Set Baseline → OK.
This does not affect the baseline values for other tasks or resource baseline values in the plan.
Click Project Tab → Schedule group → Set Baseline → For select Selected tasks → OK.
You can save up to 11 baselines in a single plan. The first one is called Baseline, and the rest are Baseline 1 through Baseline 10.
Click Project Tab → Schedule group → Set Baseline → click
the dropdown box to save any baseline you like.
Click OK.
An interim plan saves only two kinds of information for each task − Current start dates and Current finish dates.
It can be used as a project marker. It is visually easy to see how off-track or on-track the project progress is. Because it only specifies dates, it is simple, clear and easy information.
Click Project Tab → Schedule group → Set Baseline → Set interim plan → OK.
If all tasks have started and are finished as scheduled, you can record this in the Update Project dialog box. Most of the times, a seasoned project manager understands that this isn’t true. But sometimes this approach might be fine when the actual work and cost values generated are close enough to your baseline schedule.
Click Project tab → Status group → Update Project.
Switch on the radio button for “Update work as complete through”
option, and then Set 0% -100% complete. Select the current date.
Click OK.
Check marks will appear in the indicators column for tasks that have been completed. On the right in the Chart portion, progress bars are generated in the Gantt bars of each task.
Click any Task → Task Tab → Schedule group → either 0%, 25%, 50%, 75% or 100%.
Click View tab → Data group → Tables → Tracking.
Now for the required Task, click the corresponding % Comp column and enter the required % complete.
You can enter the following actual values for your project −
Actual Start and finish dates − Project moves the schedule accordingly.
Actual Start and finish dates − Project moves the schedule accordingly.
Task’s Actual duration − If equal or greater than schedule duration: task = 100% complete.
Task’s Actual duration − If equal or greater than schedule duration: task = 100% complete.
Click View Tab → Data group → Tables → Work.
You will see the % W. Comp. (% work complete) column.
This table includes Work (Scheduled work), Actual, and Remaining columns.
Click on Task you want to update. In the following example, Task 9’s Actual field is clicked and 24 hours is entered. For this task, initial scheduled Work was 16 hours, because 24 hours is greater. The project marks the task as 100% complete and updates the Work column to 24 hours (from initial 16 hours). In the example, a Baseline is saved, because the Baseline does not change and is used as a comparison. The Baseline is still at 16 hours and a Variance of 8 hours is now calculated by MS Project.
Note − Actual work is rolled up and also reflects on the summary task.
Click Task whose dates you would like to change.
Click Task tab → Schedule group → dropdown menu for Mark on Track → Update Tasks.
Change Start or Finish field in Actual group.
You can fill Actual duration field as well.
There are four types of task dependencies.
Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used.
Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used.
Finish to Finish (FF) − Cooking all the dishes for dinner to finish on time.
Finish to Finish (FF) − Cooking all the dishes for dinner to finish on time.
Start to Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey responses before starting the tabulation.
Start to Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey responses before starting the tabulation.
Start to Finish (SF) − Exam preparation will end when exam begins. Least used.
Start to Finish (SF) − Exam preparation will end when exam begins. Least used.
Click Task Tab → double-click the required task under Task Name column →
Task Information dialog box opens → Predecessors Tab.
Click the box under the Type column and choose the relationship according to your requirement.
By default when you link tasks they are assigned a “Finish to Start” relationship. In this relationship,
Lead − Lead time causes successor task to begin before its predecessor tasks ends.
Lead − Lead time causes successor task to begin before its predecessor tasks ends.
Lag − Lag time causes successor task to start after its predecessor task ends.
Lag − Lag time causes successor task to start after its predecessor task ends.
Click Task Tab → double-click the required Task under Task Name column →
Task Information dialog box opens → Predecessors Tab.
Under Lag heading column, enter the lag in terms of hours, days, weeks, or years. You can also apply lag or lead as a percentage. If you enter 50% for the selected Task which is 6 days long, the task is delayed by 3 days after the predecessor ends.
Lag is entered as positive units and lead in negative units (example,-3d or -50%).
Each task created in MS Project 2013 will be constrained as “As Soon As Possible” by default when Automatic Scheduling is turned ON. As Soon As Possible means the task starts as soon as the project starts, if there are no dependencies that would delay it. So, no fixed start or end dates are imposed by this constraint type, but of course predecessor and successor dependencies are maintained.
When MS Project 2013 performs calculations to save you time in a project that’s running late, constraint settings are enforced.
There are 8 Task Constraints.
Click Task Tab → double-click the required Task under Task Name column →
Task Information dialog box opens → Advanced Tab.
Click dropdown box for Constraint type. Choose the constraint you would like to apply.
If you use Tasks Constraints, you limit your scheduling flexibility, where MS Project 2013 will fix a particular start or finish date of the task according to the constraint. It is a better idea to use a Deadline Date which has no effect on the scheduling of a task or summary task. MS Project will alert you with a red exclamation symbol in the indicators column, if the scheduled completion of the task exceeds its deadline date.
Click Task Tab → double-click the required Task under Task Name column → Task Information dialog box opens → Advanced Tab.
Fixed Cost is associated with a task that is not tied to any resources or amount of work.
Click View Tab → Data group → Tables → Cost.
Enter the cost under the Fixed Cost column for the task of interest. In the following example, we have assigned a fixed cost of $500 to Task 7.
Status meetings, status reports, inspection dates can recur with a particular frequency. In MS Project 2013, you can specify recurring tasks without having to assign tasks each time separately. You can also assign resources to these task.
In Gantt Chart View → Task Tab → Insert group → dropdown box for Task → Recurring Task.
Enter Task Name and choose Recurrence pattern.
You can also choose a specific time for the task to start as well. By default Project schedules a recurring task to start on plan’s default start time. You can add time value in the Start box for Recurring Task Information dialog box to change this. In the following figure, start time of 10:00 AM is entered.
Critical Path is the succession of connected tasks that will take the longest to complete. The word “critical” does not mean that the tasks are complex or important or need to be closely monitored, but the focus is on terms schedule that will affect the project finish date.
So, if you want to shorten the duration of a project, you should first start with activities/tasks on the critical path. Critical path can be a single sequence of tasks (a single critical path) or there can be more than 1 critical paths for a single project. While schedule changes are made, it is also likely that the critical path will change from time to time.
One needs to always focus on the Critical Path first, when one wants to apply fast-tracking or crashing to shorten the project duration.
Slack or Float are key to understanding Critical path. There are two types of Float −
Free Float − It is the amount of time a task can be delayed without delaying another task.
Free Float − It is the amount of time a task can be delayed without delaying another task.
Total Float − It is the amount of time a task can be delayed without delaying the completion of the project.
Total Float − It is the amount of time a task can be delayed without delaying the completion of the project.
In Gantt Chart view → Format Tab → Bar Styles Group → Check the Critical Tasks box ON.
All task bars in the critical path, in the Gantt Chart View on the right, will turn Red in color.
Relationship between a resource’s capacity and task assignments is called allocation.
This can defined by 3 states −
Under allocated − An Engineer who works for 40 hours a week, has work assigned for only 20 hours.
Under allocated − An Engineer who works for 40 hours a week, has work assigned for only 20 hours.
Fully allocated − A skilled worker who works for 40 hours a week, is assigned 40 hours of work in that week.
Fully allocated − A skilled worker who works for 40 hours a week, is assigned 40 hours of work in that week.
Over allocated − A carpenter is assigned 65 hours of work, when he only has a 40 hour work week.
Over allocated − A carpenter is assigned 65 hours of work, when he only has a 40 hour work week.
Click View Tab → Task Views group → Gantt Chart view.
Gantt Chart View displays some limited resource information, as shown in the following screenshot.
It summarizes whether there may be a problem by the red over allocated icon in the indicator column.
Click View Tab → Resource Views group → Resource Usage view.
The Resource Usage view displays resources and all tasks assigned to them underneath the Resource Name. The left-hand side of the screen lists the Resources and the Task Names together with columns of total information for the resource or assignment. The right-hand side shows a time-phased view.
You can also collapse the outline in the table to see total work per resource over time.
Click on Resource Name column heading.
Click View Tab → Data group → Outline → Hide Subtasks.
One would need to either change the scope (reduce the amount of work), assign more resources, or accept a longer schedule to resolve overallocation.
This can be achieved by using some of the following techniques −
By changing its lead or lag time when the resource has more tasks assigned than can be completed during a given time period. If you add delay that is less than or equal to the amount of slack on the task, you will not affect the finish date of the project.
By default when you link tasks, they are assigned a “Finish to Start” relationship. In this relationship,
Lead − Lead time causes successor task to begin before its predecessor tasks ends.
Lead − Lead time causes successor task to begin before its predecessor tasks ends.
Lag − Lag time causes successor task to start after its predecessor task ends.
Lag − Lag time causes successor task to start after its predecessor task ends.
Click Task Tab → double-click the required Task under Task Name column → Task Information dialog box opens → Predecessors Tab.
Under Lag heading column, enter the lag in terms of hours, days, weeks, or years. You can also apply lag or lead as a percentage. If you enter 50% for the selected Task which is 6 days long, the task is delayed by 3 days after the predecessor ends.
Lag is entered as positive units and lead in negative units (example,-3d or -50%).
You can manually allot some other resource to the task.
Click View Tab → Gantt Chart View → Resource Name column.
Click the box below the Resource Name column for the task you need the resource to be assigned.
From the dropdown, choose the resource name. In the following example,
for Task 1 “PT1”, we have chosen the resource “Celic”.
You can also select multiple resources to work on a single task.
Click View Tab → Resource Views group → Resource Usage view.
In the following example, Trish Patrick is over allocated, the Resource Name and Work appear in red.
On View tab → Zoom group → Timescale box → Days.
You can also right-click on the Time-phased grid in the right hand side window to display amount of overallocation by switching on overallocation.
Now you can reduce the assigned hours. In the following example, 8-hour assignment is reduced to 4-hour assignments. Not only is Trish Patrick’s work reduced but total work in the plan has changed. You will also notice a new icon in the indicator column to let you know that the assignment work has been edited.
You can decrease task duration (if no actual work has been entered) to reduce the amount of work required of the resource, who is assigned to complete the task. If actual work has been recorded, you must manually reduce the remaining work on the task.
You can just remove a resource assignment from an overallocated resource.
If resources are overallocated you can use resource-leveling feature in MS Project 2013. It works by either splitting tasks or by adding delay to tasks to ensure the resource is not overloaded. Leveling can delay the individual task finish dates and even the project finish date. Project does not change who is assigned to each task, total work, or assignment unit values.
Project first delays tasks to use up any available slack. Once the slack becomes zero, MS Project 2013 makes changes according to priorities, dependency relationships and task constraints (such as a Finish No Later Than constraint).
It is always better to set task priorities (this is a measure of a task's importance/availability for leveling). You can enter value between 1 and 1000, according to the amount of control you like in the leveling process. A priority level of 1000 will ensure MS Project does not level a particular task. By default, priority is set at 500 or a medium level of control. Tasks that have lower priority are delayed or split before those that have higher priority.
Click View Tab → Task Views → Gantt chart View.
In the Gantt chart table area, scroll to the right to see Add New Column.
Click on the dropdown box and select Priority.
Now you can add priority to each task as required.
Steps in the Leveling process are only a few, but it is important to understand what each option does. The steps are as follows −
Click on View Tab → Resource View group → Resource Sheet.
Click Resource tab → Level group → Leveling Options → Level All.
Project does leveling and overallocated indicators are removed (If leveling is done completely, sometimes this might not happen).
In the following section, we will look at Leveling Options in detail −
Click Resource tab → Level group → Leveling Options.
In Resource Leveling dialog box, under Level calculations, try to use Manual more often. This will ensure MS Project 2013 does the leveling process only when you ask it to, and not as soon as a resource becomes overallocated even if you don’t want it to (when you choose Automatic option). For examples, if a resource is overallocated, for say half an hour more in a week, from 40 hours to 40.5 hours, you wouldn’t want this to inconvenience you by getting automatically leveled.
In Resource Leveling dialog box, under Level calculations, choose Day by Day basis for “Look for overallocations on a” option. Doing so will not level resources, but it will determine when Project displays overallocation indicators next to resource names.
In Resource Leveling dialog box, under Level calculations, use the clear leveling values before leveling checkbox is selected. Doing so will ensure Project removes any existing leveling delays from all tasks and assignments before leveling. And if you previously leveled the plan and then added more assignments, you might want checkbox to be unchecked to ensure you don’t lose the previous leveling results.
In Resource Leveling dialog box, under Leveling range for “.......”, you can choose Level entire project. Here you choose to level either the entire plan or only assignments that fall within a date range you specify.
In Resource Leveling dialog box, under Resolving overallocations, Leveling order dropdown box you can choose Standard. You have 3 options here −
ID only option delays tasks only according to their ID numbers. Numerically higher ID numbers (for example, 10) will be delayed before numerically lower ID numbers. You might want to use this option when your plan has no task relationships or constraints.
ID only option delays tasks only according to their ID numbers. Numerically higher ID numbers (for example, 10) will be delayed before numerically lower ID numbers. You might want to use this option when your plan has no task relationships or constraints.
Standard option delays tasks according to predecessor relationships, start dates, task constraints, slack, priority, and IDs.
Standard option delays tasks according to predecessor relationships, start dates, task constraints, slack, priority, and IDs.
Priority, standard option looks at the task priority value before the other standard criteria (Task priority is a numeric ranking between 0 and 1000).
Priority, standard option looks at the task priority value before the other standard criteria (Task priority is a numeric ranking between 0 and 1000).
In Resource Leveling dialog box, under Resolving overallocations, you have several options that you can select. These are explained as follows −
Level only within available slack. Selecting this checkbox would prevent Project from extending the plan’s finish date. MS Project will use only the free slack within the existing schedule, which could mean that resource overallocations might not be fully resolved.
Level only within available slack. Selecting this checkbox would prevent Project from extending the plan’s finish date. MS Project will use only the free slack within the existing schedule, which could mean that resource overallocations might not be fully resolved.
Leveling can adjust individual assignments. Selecting this checkbox allows Project to add a leveling delay (or split work on assignments if Leveling Can Create Splits in Remaining Work is also selected) independently of any other resources assigned to the same task. This might cause resources to start and finish work on a task at different times.
Leveling can adjust individual assignments. Selecting this checkbox allows Project to add a leveling delay (or split work on assignments if Leveling Can Create Splits in Remaining Work is also selected) independently of any other resources assigned to the same task. This might cause resources to start and finish work on a task at different times.
Leveling can create splits in remaining work checkbox. This allows Project to split work on a task (or on an assignment if Leveling Can Adjust Individual Assignments on a Task is also selected) as a way of resolving overallocation.
Leveling can create splits in remaining work checkbox. This allows Project to split work on a task (or on an assignment if Leveling Can Adjust Individual Assignments on a Task is also selected) as a way of resolving overallocation.
Level manually scheduled tasks. Selecting this allows Project to level a manually scheduled task just as it would an automatically scheduled task.
Level manually scheduled tasks. Selecting this allows Project to level a manually scheduled task just as it would an automatically scheduled task.
Types of cost in a project life cycle includes −
Baseline costs − All planned costs as saved in baseline plan.
Baseline costs − All planned costs as saved in baseline plan.
Actual costs − Costs that have been incurred for tasks, resources or assignments.
Actual costs − Costs that have been incurred for tasks, resources or assignments.
Remaining costs − Difference between baseline/current costs and actual costs.
Remaining costs − Difference between baseline/current costs and actual costs.
Current costs − When plans are changed due to assigning or removing resources, or adding or subtracting tasks, MS Project 2013 will recalculate all costs. This will appear under the fields labeled Cost or Total Cost. If you have started to track actual cost, it will include actual cost + remaining cost per task.
Current costs − When plans are changed due to assigning or removing resources, or adding or subtracting tasks, MS Project 2013 will recalculate all costs. This will appear under the fields labeled Cost or Total Cost. If you have started to track actual cost, it will include actual cost + remaining cost per task.
You can view plan’s cost values in the Project Statistics dialog box.
Click Project tab → Properties Group → Project Information → Statistics...
Click View tab → Task Views group → Other Views → Task Sheet.
Click View tab → Data group → Tables → Cost.
After creating a project plan and baselines, the project begins. At this stage, the project manager would be focusing on collecting, monitoring, analyzing project performance, and updating project status by communicating with the stakeholders.
When there is a difference between what is planned and the actual project performance, it is called a Variance. Variance is mostly measured in terms of Time and Cost.
There are several ways to view task with variance.
Click View tab → Task Views group → Gantt Chart dropdown → Tracking Gantt.
By comparing the currently scheduled Gantt bars with baseline Gantt bars, you can see what tasks started later than planned or took longer to complete.
Click View tab → Task Views group → Other Views → double-click Tracking Gantt.
Click View tab → Data group → Tables → Variance.
Click View tab → Data group → Filters → More
Filters → choose filter as Late tasks, Slipping task, etc.
MS Project 2013 will filter the task list to show only the tasks filtered in this process. So if you select Slipping Task, you will view only incomplete tasks. Any task that is already completed will not show up.
To examine cost in a project life cycle, you should be aware of these terms and what they mean in MS Project 2013 −
Baseline costs − All planned costs as saved in baseline plan.
Baseline costs − All planned costs as saved in baseline plan.
Actual costs − Costs that have been incurred for tasks, resources, or assignments.
Actual costs − Costs that have been incurred for tasks, resources, or assignments.
Remaining costs − Difference between baseline/current costs and actual costs.
Remaining costs − Difference between baseline/current costs and actual costs.
Current costs − When plans are changed due to assigning or removing resources, or adding or subtracting tasks, MS Project 2013 will recalculate all costs. This will appear under the fields labeled Cost or Total Cost. If you have started to track actual cost, it will include actual cost+ remaining cost (uncompleted task) per task.
Current costs − When plans are changed due to assigning or removing resources, or adding or subtracting tasks, MS Project 2013 will recalculate all costs. This will appear under the fields labeled Cost or Total Cost. If you have started to track actual cost, it will include actual cost+ remaining cost (uncompleted task) per task.
Variance − Difference between Baseline Cost and the Total Cost (current or scheduled cost).
Variance − Difference between Baseline Cost and the Total Cost (current or scheduled cost).
Click View Tab → Data group → Tables → Cost.
You will be able to view all relevant information. You can also use filters to see tasks that have run over budget.
Click View tab → Data group → Filters → More Filters → Cost Overbudget → Apply.
For some organizations, resources costs are primary costs, and sometimes the only cost, so these need to be closely watched.
Click View tab → Resource Views group → Resource Sheet.
Click View tab → Data group → Tables → Cost.
We can sort the Cost column to see which resources are the most and least costly.
Click the AutoFilter arrow in Cost column heading, when the drop-down menu appears, click on Sort Largest to Smallest.
You can use the AutoFilter feature for each of the columns, By sorting Variance column, you will be able to see the variance pattern.
Project 2013 comes with a set of predefined reports and dashboards. You’ll find all of these on the Report tab. You can create and customize graphical reports for your project as well.
Click Report → View Reports group → Dashboards.
Click Report → View Reports group → Resources.
Click Report → View Reports group → Costs.
Click Report → View Reports group → In Progress.
Click Report → View Reports group → New Report.
There are four options.
Blank − Creates a blank canvas. Use the Report Tools - Design tab to add charts, tables, text, and images.
Blank − Creates a blank canvas. Use the Report Tools - Design tab to add charts, tables, text, and images.
Chart − Creates a chart comparing Actual Work, Remaining Work, and Work by default. Use the Field List pane to pick different fields to compare. The look of the chart can be changed by clicking on Chart Tools tabs, Design, and Layout tabs.
Chart − Creates a chart comparing Actual Work, Remaining Work, and Work by default. Use the Field List pane to pick different fields to compare. The look of the chart can be changed by clicking on Chart Tools tabs, Design, and Layout tabs.
Table − Creates a table. Use the Field List pane to choose what fields to display in the table (Name, Start, Finish, and % Complete appear by default). Outline level box lets you select how many levels in the project outline the table should show. The look of the table can be changed by clicking on Table Tools tabs, Design, and Layout tabs.
Table − Creates a table. Use the Field List pane to choose what fields to display in the table (Name, Start, Finish, and % Complete appear by default). Outline level box lets you select how many levels in the project outline the table should show. The look of the table can be changed by clicking on Table Tools tabs, Design, and Layout tabs.
Comparison − Creates two charts side-by-side. Charts will have the same data at first. You can click one of the charts and pick the data you want in the Field List pane to begin differentiating them.
Comparison − Creates two charts side-by-side. Charts will have the same data at first. You can click one of the charts and pick the data you want in the Field List pane to begin differentiating them.
32 Lectures
2.5 hours
Pavan Lalwani
18 Lectures
1.5 hours
Dr. Saatya Prasad
102 Lectures
10 hours
Pavan Lalwani
52 Lectures
4 hours
Pavan Lalwani
239 Lectures
33 hours
Gowthami Swarna
53 Lectures
5 hours
Akshay Magre
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2178,
"s": 1881,
"text": "Each one of you might be using a different setting for MS Project 2013. To ensure the results are not different from what is shown in this tutorials, ensure the settings as follows. Remember all these are the default settings you will have when you first install MS Project 2013 on your computer."
},
{
"code": null,
"e": 2247,
"s": 2178,
"text": "Step 1 − File → Options → General tab → Project view → Default view."
},
{
"code": null,
"e": 2299,
"s": 2247,
"text": "Select “Gantt with Timeline” from the dropdown box."
},
{
"code": null,
"e": 2380,
"s": 2299,
"text": "Step 2 − File → Options → Display tab → Show Indicators and Options Buttons For."
},
{
"code": null,
"e": 2399,
"s": 2380,
"text": "Check all options."
},
{
"code": null,
"e": 2474,
"s": 2399,
"text": "Step 3 − File → Options → Schedule tab → Schedule → Show Assignment Units."
},
{
"code": null,
"e": 2517,
"s": 2474,
"text": "Choose “percentage” from the dropdown box."
},
{
"code": null,
"e": 2607,
"s": 2517,
"text": "Step 4 − File → Options → Schedule tab → Calculation → Calculate Project after Each Edit."
},
{
"code": null,
"e": 2628,
"s": 2607,
"text": "Check the On button."
},
{
"code": null,
"e": 2708,
"s": 2628,
"text": "Step 5 − File → Options → Save tab → Save projects → Save Files In this format."
},
{
"code": null,
"e": 2732,
"s": 2708,
"text": "Select Project (*.mpp)."
},
{
"code": null,
"e": 2779,
"s": 2732,
"text": "Step 6 − File → Options → Advanced tab → Edit."
},
{
"code": null,
"e": 2798,
"s": 2779,
"text": "Check all options."
},
{
"code": null,
"e": 2884,
"s": 2798,
"text": "Step 7 − File → Options → Advanced tab → Display → Show Status Bar → Show Scroll Bar."
},
{
"code": null,
"e": 2943,
"s": 2884,
"text": "Both options, Status Bar and Scroll Bar should be checked."
},
{
"code": null,
"e": 3012,
"s": 2943,
"text": "Step 8 Resources → Level → Leveling Options → Leveling Calculations."
},
{
"code": null,
"e": 3027,
"s": 3012,
"text": "Set to manual."
},
{
"code": null,
"e": 3125,
"s": 3027,
"text": "Step 9 − Resources → Level → Leveling Options → Leveling calculations → Look for Overallocations."
},
{
"code": null,
"e": 3164,
"s": 3125,
"text": "Select “Day By Day” from dropdown box."
},
{
"code": null,
"e": 3414,
"s": 3164,
"text": "Microsoft Project is a project management software program developed and sold by Microsoft, designed to assist a project manager in developing a schedule, assigning resources to tasks, tracking progress, managing the budget, and analyzing workloads."
},
{
"code": null,
"e": 3713,
"s": 3414,
"text": "Project creates budgets based on assignment work and resource rates. As resources are assigned to tasks and assignment work estimated, the program calculates the cost, equal to the work times the rate, which rolls up to the task level and then to any summary task, and finally to the project level."
},
{
"code": null,
"e": 4020,
"s": 3713,
"text": "Each resource can have its own calendar, which defines what days and shifts a resource is available. Microsoft Project is not suitable for solving problems of available materials (resources) constrained production. Additional software is necessary to manage a complex facility that produces physical goods."
},
{
"code": null,
"e": 4498,
"s": 4020,
"text": "MS Project is feature rich, but project management techniques are required to drive a project effectively. A lot of project managers get confused between a schedule and a plan. MS Project can help you in creating a Schedule for the project even with the provided constraints. It cannot Plan for you. As a project manager you should be able to answer the following specific questions as part of the planning process to develop a schedule. MS Project cannot answer these for you."
},
{
"code": null,
"e": 4633,
"s": 4498,
"text": "What tasks need to be performed to create the deliverables of the project and in what order? This relates to the scope of the project."
},
{
"code": null,
"e": 4768,
"s": 4633,
"text": "What tasks need to be performed to create the deliverables of the project and in what order? This relates to the scope of the project."
},
{
"code": null,
"e": 4917,
"s": 4768,
"text": "What are the time constraints and deadlines if any, for different tasks and for the project as a whole? This relates to the schedule of the project."
},
{
"code": null,
"e": 5066,
"s": 4917,
"text": "What are the time constraints and deadlines if any, for different tasks and for the project as a whole? This relates to the schedule of the project."
},
{
"code": null,
"e": 5145,
"s": 5066,
"text": "What kind of resources (man/machine/material) are needed to perform each task?"
},
{
"code": null,
"e": 5224,
"s": 5145,
"text": "What kind of resources (man/machine/material) are needed to perform each task?"
},
{
"code": null,
"e": 5314,
"s": 5224,
"text": "How much will each task cost to accomplish? This would relate to the cost of the project."
},
{
"code": null,
"e": 5404,
"s": 5314,
"text": "How much will each task cost to accomplish? This would relate to the cost of the project."
},
{
"code": null,
"e": 5560,
"s": 5404,
"text": "What kind of risk do we have associated with a particular schedule for the project? This might affect the scope, cost and time constraints of your project."
},
{
"code": null,
"e": 5716,
"s": 5560,
"text": "What kind of risk do we have associated with a particular schedule for the project? This might affect the scope, cost and time constraints of your project."
},
{
"code": null,
"e": 6013,
"s": 5716,
"text": "Strictly speaking, from the perspective of Project Management Methodology, a Plan and Schedule are not the same. A plan is a detailed action-oriented, experience and knowledge-based exercise which considers all elements of strategy, scope, cost, time, resources, quality and risk for the project."
},
{
"code": null,
"e": 6440,
"s": 6013,
"text": "Scheduling is the science of using mathematical calculations and logic to generate time effective sequence of task considering any resource and cost constraints. Schedule is part of the Plan. In Project Management Methodology, schedule would only mean listing of a project's milestones, tasks/activities, and deliverables, with start and finish dates. Of course the schedule is linked with resources, budgets and dependencies."
},
{
"code": null,
"e": 6625,
"s": 6440,
"text": "However, in this tutorial for MS Project (and in all available help for MS Project) the word ‘Plan’ is used as a ‘Schedule’ being created in MS Project. This is because of two reasons."
},
{
"code": null,
"e": 7070,
"s": 6625,
"text": "One, MS Project does more than just create a schedule it can establish dependencies among tasks, it can create constraints, it can resolve resource conflicts, and it can also help in reviewing cost and schedule performance over the duration of the project. So it does help in more than just creating a Schedule. This it makes sense for Microsoft to market MS Project as a Plan Creator rather than over-simplifying it as just a schedule creator."
},
{
"code": null,
"e": 7703,
"s": 7070,
"text": "Two, it is due to limitation of generally accepted form of English language, where a schedule can be both in a noun as well as verb form. As a noun, a Schedule is like a time table or a series of things to be done or of events to occur at or during a particular time or period. And in the verb form, schedule is to plan for a certain date. Therefore it is much easier to say that, “One can schedule a plan from a start date” but very awkward to say, “One can schedule a schedule from a start date”. The distinction is important for you as a project manager, but as far as MS project is concerned the noun form of Schedule is a Plan."
},
{
"code": null,
"e": 7817,
"s": 7703,
"text": "Of course, a project manager should also be able to answer other project-related questions as well. For example −"
},
{
"code": null,
"e": 7871,
"s": 7817,
"text": "Why this project needs to be run by the organization?"
},
{
"code": null,
"e": 7943,
"s": 7871,
"text": "What’s the best way to communicate project details to the stakeholders?"
},
{
"code": null,
"e": 7977,
"s": 7943,
"text": "What is the risk management plan?"
},
{
"code": null,
"e": 8018,
"s": 7977,
"text": "How the vendors are going to be managed?"
},
{
"code": null,
"e": 8060,
"s": 8018,
"text": "How the project is tracked and monitored?"
},
{
"code": null,
"e": 8103,
"s": 8060,
"text": "How the quality is measured and qualified?"
},
{
"code": null,
"e": 8129,
"s": 8103,
"text": "MS Project can help you −"
},
{
"code": null,
"e": 8186,
"s": 8129,
"text": "Visualize your project plan in standard defined formats."
},
{
"code": null,
"e": 8245,
"s": 8186,
"text": "Schedule tasks and resources consistently and effectively."
},
{
"code": null,
"e": 8333,
"s": 8245,
"text": "Track information about the work, duration, and resource requirements for your project."
},
{
"code": null,
"e": 8381,
"s": 8333,
"text": "Generate reports to share in progress meetings."
},
{
"code": null,
"e": 8461,
"s": 8381,
"text": "In this chapter, we will take a close look at the user interface of MS Project."
},
{
"code": null,
"e": 8570,
"s": 8461,
"text": "Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013."
},
{
"code": null,
"e": 8679,
"s": 8570,
"text": "Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013."
},
{
"code": null,
"e": 8739,
"s": 8679,
"text": "Windows 8 − On the Start screen, tap or click Project 2013."
},
{
"code": null,
"e": 8799,
"s": 8739,
"text": "Windows 8 − On the Start screen, tap or click Project 2013."
},
{
"code": null,
"e": 8878,
"s": 8799,
"text": "Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013."
},
{
"code": null,
"e": 8957,
"s": 8878,
"text": "Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013."
},
{
"code": null,
"e": 9099,
"s": 8957,
"text": "The following screen is the Project’s start screen. Here you have options to open a new plan, some other plans, and even a new plan template."
},
{
"code": null,
"e": 9158,
"s": 9099,
"text": "Click the Blank Project Tab. The following screen pops up."
},
{
"code": null,
"e": 9256,
"s": 9158,
"text": "The screen should have the MS Project interface displayed. The major part of this interface are −"
},
{
"code": null,
"e": 9347,
"s": 9256,
"text": "Quick Access Toolbar − A customizable area where you can add the frequently used commands."
},
{
"code": null,
"e": 9438,
"s": 9347,
"text": "Quick Access Toolbar − A customizable area where you can add the frequently used commands."
},
{
"code": null,
"e": 10003,
"s": 9438,
"text": "Tabs on the Ribbon, Groups − With the release of Microsoft Office 2007 came the \"Fluent User Interface\" or \"Fluent UI\", which replaced menus and customizable toolbars with a single \"Office menu\", a miniature toolbar known as \"quick-access toolbar\" and what came to be known as the ribbon having multiple tabs, each holding a toolbar bearing buttons and occasionally other controls. Toolbar controls have heterogeneous sizes and are classified in visually distinguishable Groups. Groups are collections of related commands. Each tab is divided into multiple groups."
},
{
"code": null,
"e": 10568,
"s": 10003,
"text": "Tabs on the Ribbon, Groups − With the release of Microsoft Office 2007 came the \"Fluent User Interface\" or \"Fluent UI\", which replaced menus and customizable toolbars with a single \"Office menu\", a miniature toolbar known as \"quick-access toolbar\" and what came to be known as the ribbon having multiple tabs, each holding a toolbar bearing buttons and occasionally other controls. Toolbar controls have heterogeneous sizes and are classified in visually distinguishable Groups. Groups are collections of related commands. Each tab is divided into multiple groups."
},
{
"code": null,
"e": 10743,
"s": 10568,
"text": "Commands − The specific features you use to perform actions in Project. Each tab contains several commands. If you point at a command you will see a description in a tooltip."
},
{
"code": null,
"e": 10918,
"s": 10743,
"text": "Commands − The specific features you use to perform actions in Project. Each tab contains several commands. If you point at a command you will see a description in a tooltip."
},
{
"code": null,
"e": 11303,
"s": 10918,
"text": "View Label − This appears along the left edge of the active view. Active view is the one you can see in the main window at a given point in time. Project includes lots of views like Gantt Chart view, Network Diagram view, Task Usage view, etc. The View label just tells you about the view you are using currently. Project can display a single view or multiple views in separate panes."
},
{
"code": null,
"e": 11688,
"s": 11303,
"text": "View Label − This appears along the left edge of the active view. Active view is the one you can see in the main window at a given point in time. Project includes lots of views like Gantt Chart view, Network Diagram view, Task Usage view, etc. The View label just tells you about the view you are using currently. Project can display a single view or multiple views in separate panes."
},
{
"code": null,
"e": 11768,
"s": 11688,
"text": "View Shortcuts − This lets you switch between frequently used views in Project."
},
{
"code": null,
"e": 11848,
"s": 11768,
"text": "View Shortcuts − This lets you switch between frequently used views in Project."
},
{
"code": null,
"e": 11902,
"s": 11848,
"text": "Zoom Slider − Simply zooms the active view in or out."
},
{
"code": null,
"e": 11956,
"s": 11902,
"text": "Zoom Slider − Simply zooms the active view in or out."
},
{
"code": null,
"e": 12096,
"s": 11956,
"text": "Status bar − Displays details like the scheduling mode of new tasks (manual or automatic) and details of filter applied to the active view."
},
{
"code": null,
"e": 12236,
"s": 12096,
"text": "Status bar − Displays details like the scheduling mode of new tasks (manual or automatic) and details of filter applied to the active view."
},
{
"code": null,
"e": 12547,
"s": 12236,
"text": "When working with MS Project you either specify a start date or a finish date. Because once you enter one of the two, and other project tasks, constraints and dependencies, MS Project will calculate the other date. It is always a good practice to use a start date even if you know the deadline for the project."
},
{
"code": null,
"e": 12656,
"s": 12547,
"text": "Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013."
},
{
"code": null,
"e": 12765,
"s": 12656,
"text": "Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013."
},
{
"code": null,
"e": 12825,
"s": 12765,
"text": "Windows 8 − On the Start screen, tap or click Project 2013."
},
{
"code": null,
"e": 12885,
"s": 12825,
"text": "Windows 8 − On the Start screen, tap or click Project 2013."
},
{
"code": null,
"e": 12964,
"s": 12885,
"text": "Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013."
},
{
"code": null,
"e": 13043,
"s": 12964,
"text": "Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013."
},
{
"code": null,
"e": 13148,
"s": 13043,
"text": "MS Project 2013 will display a list of options. In the list of available templates, click Blank Project."
},
{
"code": null,
"e": 13301,
"s": 13148,
"text": "Project sets the plan’s start date to current date, a thin green vertical line in the chart portion of the Gantt Chart View indicates this current date."
},
{
"code": null,
"e": 13369,
"s": 13301,
"text": "Let us change the project start date and add some more information."
},
{
"code": null,
"e": 13429,
"s": 13369,
"text": "Click Project tab → Properties Group → Project Information."
},
{
"code": null,
"e": 13591,
"s": 13429,
"text": "A dialog box appears. In the start date box, type 11/5/15, or click the down arrow to display the calendar, select November 5, 2015 (or any date of your choice)."
},
{
"code": null,
"e": 13626,
"s": 13591,
"text": "Click OK to accept the start date."
},
{
"code": null,
"e": 13686,
"s": 13626,
"text": "Click Project tab → Properties Group → Project Information."
},
{
"code": null,
"e": 13784,
"s": 13686,
"text": "Click the arrow on the Current Date dropdown box. A list appears containing three base calendars."
},
{
"code": null,
"e": 13831,
"s": 13784,
"text": "24 Hour − A calendar with no non-working time."
},
{
"code": null,
"e": 13878,
"s": 13831,
"text": "24 Hour − A calendar with no non-working time."
},
{
"code": null,
"e": 13992,
"s": 13878,
"text": "Night Shift − Covers 11 PM to 8 AM, night shifts covering all nights from Monday to Friday, with one hour breaks."
},
{
"code": null,
"e": 14106,
"s": 13992,
"text": "Night Shift − Covers 11 PM to 8 AM, night shifts covering all nights from Monday to Friday, with one hour breaks."
},
{
"code": null,
"e": 14201,
"s": 14106,
"text": "Standard − Regular working hours, Monday to Friday between 8 AM to 5 PM, with one hour breaks."
},
{
"code": null,
"e": 14296,
"s": 14201,
"text": "Standard − Regular working hours, Monday to Friday between 8 AM to 5 PM, with one hour breaks."
},
{
"code": null,
"e": 14397,
"s": 14296,
"text": "Select a Standard Calendar as your project Calendar. Click “Cancel” or “OK” to close the dialog box."
},
{
"code": null,
"e": 14424,
"s": 14397,
"text": "Now let us add exceptions."
},
{
"code": null,
"e": 14601,
"s": 14424,
"text": "Exceptions are used to modify a Project calendar to have a non-standard workday or a non-working day. You can also allot unique working hours for a particular resource as well."
},
{
"code": null,
"e": 14762,
"s": 14601,
"text": "Here is an example to create a non-working day, which could be because of a holiday or office celebrations or events other than the standard office work effort."
},
{
"code": null,
"e": 14823,
"s": 14762,
"text": "Click Project tab → Properties Group → Change Working Time.\n"
},
{
"code": null,
"e": 15211,
"s": 14823,
"text": "Change Working Time dialog box appears. Under Exceptions Tab click on the Name Field, enter event as “Office Anniversary”. In the Start field enter 11/22/15, and then enter the same date in the Finish field. This date is now scheduled as a non-working day for the project. You can also verify the changed color indicated in the calendar within the dialog box as below. Click Ok to close."
},
{
"code": null,
"e": 15424,
"s": 15211,
"text": "Just like you can change a Standard Base Calendar, you can change the work and non-working time for each resource. You can modify the resource calendar to accommodate flex-time, vacation time, training time, etc."
},
{
"code": null,
"e": 15535,
"s": 15424,
"text": "Also remember, Resource Calendar can only be applied to work resources and not to material and cost resources."
},
{
"code": null,
"e": 15914,
"s": 15535,
"text": "By default when we create the resources in a plan, the resource calendar matches the Standard base calendar. And any changes you make to the Project Calendar, gets reflected automatically in resource calendars, except when you create an exception in the resource calendar. In that case even if you update the project calendar, the exception in resource calendar is not affected."
},
{
"code": null,
"e": 16181,
"s": 15914,
"text": "Click Project tab → Properties group → Click Change Working Time\n\nChange Working Time dialog box appears. \n\nClick the down arrow for the “For Calendar” drop-down box.\n\nSelect the resource for whom you want to create an exception. In example below I have chosen John."
},
{
"code": null,
"e": 16367,
"s": 16181,
"text": "Under Exceptions Tab click on the Name Field, enter event as “Personal holiday”. In the Start field enter the date (example 9/15/2015), and then enter the same date in the Finish field."
},
{
"code": null,
"e": 16936,
"s": 16367,
"text": "Click Project tab → Properties group → Click Change Working Time.\n\nThe Change Working Time dialog box appears. \n\nClick the down arrow for the “For Calendar” dropdown box.\n\nSelect the resource for whom you want to change work schedule. \nIn the following screen you can see we have chosen John.\n\nClick “Work Weeks” tab.\n\nDouble-click the [default] cell below the Name column heading.\n\nUnder “Selected Day(s)” choose any day you want to change the work schedule. \nWe have chosen Tuesday and Wednesday.\n\t\nClick Set day(s) to these specific working times. Change the time."
},
{
"code": null,
"e": 17555,
"s": 16936,
"text": "Click Project tab → Properties group → Click Change Working Time.\n\nThe Change Working Time dialog box appears.\n\nClick the down arrow for the “For Calendar” dropdown box.\n\nSelect the resource for whom you want to change work schedule. We have chosen John again.\n\nClick “Work Weeks” tab.\n\nDouble-click the [default] cell below the Name column heading.\n\nUnder “Selected Day(s)” choose any day you want to change the work schedule.\n\nClick any day (we have chosen Friday) and use the radio button “Set days to nonworking time”.\n\nClick OK to close the Dialog box. You will now see all Fridays are greyed out in the calendar."
},
{
"code": null,
"e": 17850,
"s": 17555,
"text": "With Microsoft Windows Operating system, right clicking a file and selecting “Properties” brings up the file properties dialog box that contains version, security and other file details. You can record some top level information for your .mpp project file as well. This can be done as follows −"
},
{
"code": null,
"e": 17959,
"s": 17850,
"text": "Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013."
},
{
"code": null,
"e": 18068,
"s": 17959,
"text": "Windows 7 − Click on Start menu, point to All Programs, click Microsoft Office, and then click Project 2013."
},
{
"code": null,
"e": 18128,
"s": 18068,
"text": "Windows 8 − On the Start screen, tap or click Project 2013."
},
{
"code": null,
"e": 18188,
"s": 18128,
"text": "Windows 8 − On the Start screen, tap or click Project 2013."
},
{
"code": null,
"e": 18267,
"s": 18188,
"text": "Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013."
},
{
"code": null,
"e": 18346,
"s": 18267,
"text": "Windows 10 − Click on Start menu → All apps → Microsoft Office → Project 2013."
},
{
"code": null,
"e": 18587,
"s": 18346,
"text": "Click File Tab. Under Info Tab go to Project Information. Click arrow near Project Information to click Advanced Properties. A dialog box opens, you can type in the changes as required. Click OK and don’t forget to save by clicking on Save."
},
{
"code": null,
"e": 18736,
"s": 18587,
"text": "Before we start, let us assume you already have a Work Breakdown Structure (WBS). In context of WBS, “Work” refers to “Deliverables” and not effort."
},
{
"code": null,
"e": 19047,
"s": 18736,
"text": "WBS identifies the deliverable at the lowest level as work package. This work package is decomposed into smaller tasks/activities, which is the effort necessary to complete the work package. So a task is action-oriented, and the work package is the deliverable or a result of one or more tasks being performed."
},
{
"code": null,
"e": 19347,
"s": 19047,
"text": "There is a significant amount of confusion between what constitutes an activity and what constitutes a task within the project management community. But for MS Project, a task is the effort and action required to produce a particular project deliverable. MS Project does not use the term “activity”."
},
{
"code": null,
"e": 19520,
"s": 19347,
"text": "This is simple. In Gantt Chart View, just click a cell directly below the Task Name column. Enter the task name. In the following screen, we have entered 5 different tasks."
},
{
"code": null,
"e": 19754,
"s": 19520,
"text": "A duration of the task is the estimated amount of time it will take to complete a task. As a project manager you can estimate a task duration using expert judgment, historical information, analogous estimates or parametric estimates."
},
{
"code": null,
"e": 19962,
"s": 19754,
"text": "You can enter task duration in terms of different dimensional units of time, namely minutes, hours, days, weeks, and months. You can use abbreviations for simplicity and ease as shown in the following table."
},
{
"code": null,
"e": 20157,
"s": 19962,
"text": "Remember, Project default values depend on your work hours. So 1 day is not equivalent to 24 hours but has 8 hours of work for the day. Of course, you can change these defaults anytime you want."
},
{
"code": null,
"e": 20239,
"s": 20157,
"text": "Click Project tab → Properties Group → Click Change Working Time → Click Options."
},
{
"code": null,
"e": 20331,
"s": 20239,
"text": "You can apply this to all projects or a specific project that you are working on currently."
},
{
"code": null,
"e": 20840,
"s": 20331,
"text": "One of the neat tricks MS Project possesses is, it considers duration of the task in workday sense. So if you have a non-working day in between, it accommodates this and ensures a task that takes 16 hours to complete to end on the 3rd day. In other words, if you have a task that needs 16 hours to complete starting on Monday 8:00 AM (if this is the time your work day starts, and 8 hours being total work hours in a day), and Tuesday being a holiday, the task will logically end on the evening of Wednesday."
},
{
"code": null,
"e": 21010,
"s": 20840,
"text": "Tip − With manually scheduled tasks, if you are not sure about a task duration, you can just enter text such as “Check with Manager/Engineer” to come back to this later."
},
{
"code": null,
"e": 21149,
"s": 21010,
"text": "This is simple in Gantt Chart View, click the cell below Duration column heading. Enter the duration. (Task 1 in the following screenshot)"
},
{
"code": null,
"e": 21282,
"s": 21149,
"text": "You can also enter Start and Finish date and MS Project will calculate the duration on its own. (Task 2 in the following screenshot)"
},
{
"code": null,
"e": 21406,
"s": 21282,
"text": "You can enter text as well when you don’t have a duration metric currently. (Task 3 and Task 4 in the following screenshot)"
},
{
"code": null,
"e": 21959,
"s": 21406,
"text": "Note − In the above screenshot, Task 6 is scheduled to start on Sunday, which is a nonworking day and ends on Wednesday. So essentially, one would believe that with these 3 days Monday, Tuesday, Wednesday, the duration calculated would be 3 days. But MS Project 2013 calculates it as 4 days. So one needs to be careful when choosing the start date of the task. Because for any successive operation, MS Project 2013 considers that Task 6 will take 4 days. The next time, you change the start date, the Finish date changes to reflect this 4-day duration."
},
{
"code": null,
"e": 22346,
"s": 21959,
"text": "Elapsed Duration is the time that elapses while some event is occurring which does not require any resources. Elapsed duration for a task can be used in instances where a task will go on round-the-clock without any stoppage. A normal workday has 8 hours, and an elapsed day duration will have 24 hours. The task also continues over non-working (holidays and vacations) and working days."
},
{
"code": null,
"e": 22459,
"s": 22346,
"text": "You can enter elapsed duration by preceding any duration abbreviation with an “e”. So 1ew is seven 24-hour days."
},
{
"code": null,
"e": 22878,
"s": 22459,
"text": "For example, when you are ‘Waiting for the paint to dry’. And it takes 4 days for this to happen. It does not need a resource or a work effort, and all you are doing is waiting for it to dry. You can use 4ed as the time duration, which signifies 4 elapsed days, the paint can dry regardless of whether it is a weekend or if it falls on a holiday. Here in this example, the drying occurs over 24 hours over the weekend."
},
{
"code": null,
"e": 23106,
"s": 22878,
"text": "In Project Management, Milestones are specific points in a project timeline. They are used as major progress points to manage project success and stakeholder expectations. They are primarily used for review, inputs and budgets."
},
{
"code": null,
"e": 23283,
"s": 23106,
"text": "Mathematically, a milestone is a task of zero duration. And they can be put where there is a logical conclusion of a phase of work, or at deadlines imposed by the project plan."
},
{
"code": null,
"e": 23330,
"s": 23283,
"text": "There are two ways you can insert a milestone."
},
{
"code": null,
"e": 23390,
"s": 23330,
"text": "Click name of the Task which you want to insert a Milestone"
},
{
"code": null,
"e": 23440,
"s": 23390,
"text": "Click Task tab → Insert group → Click Milestone.\n"
},
{
"code": null,
"e": 23513,
"s": 23440,
"text": "MS Project names the new task as <New Milestone> with zero-day duration."
},
{
"code": null,
"e": 23559,
"s": 23513,
"text": "Click on <New Milestone> to change its name.\n"
},
{
"code": null,
"e": 23652,
"s": 23559,
"text": "You can see the milestone appear with a rhombus symbol in the Gantt Chart View on the right."
},
{
"code": null,
"e": 23776,
"s": 23652,
"text": "Click on any particular task or type in a new task under the Task Name Heading.\n\nUnder Duration heading type in “0 days “.\n"
},
{
"code": null,
"e": 23815,
"s": 23776,
"text": "MS Project converts it to a Milestone."
},
{
"code": null,
"e": 23995,
"s": 23815,
"text": "In Method 2, a task was converted to a Milestone of Zero duration. But one can also convert a task of non-zero duration into a Milestone. This is rarely used and causes confusion."
},
{
"code": null,
"e": 24131,
"s": 23995,
"text": "Double-click a particular Task name.\n\nTask Information dialog box opens.\n\nClick Advanced tab → select option “Mark Task as Milestone”.\n"
},
{
"code": null,
"e": 24187,
"s": 24131,
"text": "The project summary task summarizes your whole project."
},
{
"code": null,
"e": 24275,
"s": 24187,
"text": "In Gantt Chart View → Format Tab → Show/Hide → click to check Project Summary Task on.\n"
},
{
"code": null,
"e": 24517,
"s": 24275,
"text": "There can be a huge number of tasks in a project schedule, it is therefore a good idea to have a bunch of related tasks rolled up into a Summary Task to help you organize the plan in a better way. It helps you organize your plan into phases."
},
{
"code": null,
"e": 24837,
"s": 24517,
"text": "In MS Project 2013, you can have several number of sub-tasks under any higher level task. These higher level tasks are called Summary Task. At an even higher level, they are called Phases. The highest level of a plan’s outline structure is called the Project Summary Task, which encompasses the entire project schedule."
},
{
"code": null,
"e": 25116,
"s": 24837,
"text": "Remember because summary task is not a separate task entity but a phase of the project with several sub-tasks in it, the duration of the summary task is from the start of the first sub-task to the finish of the last sub-task. This will be automatically calculated by MS Project."
},
{
"code": null,
"e": 25333,
"s": 25116,
"text": "Of course, you can enter a manual duration of the summary task as well which could be different from the automatically calculated duration. MS Project will keep track of both but this can cause significant confusion."
},
{
"code": null,
"e": 25459,
"s": 25333,
"text": "In most cases, you should ensure that there is no manually entered duration for any task you will be using as a Summary Task."
},
{
"code": null,
"e": 25605,
"s": 25459,
"text": "Let us use the following screenshot as an example. If you would like to group Task 4 and Task 5 into a Summary Task 1. You can do it in two ways."
},
{
"code": null,
"e": 25644,
"s": 25605,
"text": "Select the names of Task 4 and Task 5."
},
{
"code": null,
"e": 25691,
"s": 25644,
"text": "Click Task Tab → group Insert → Click Summary\n"
},
{
"code": null,
"e": 25732,
"s": 25691,
"text": "MS Project creates a <New Summary Task>."
},
{
"code": null,
"e": 25762,
"s": 25732,
"text": "Rename it to Summary Task 1.\n"
},
{
"code": null,
"e": 25788,
"s": 25762,
"text": "You can click Task 4 row."
},
{
"code": null,
"e": 25836,
"s": 25788,
"text": "Select “Insert Task”. A <New Task> is created.\n"
},
{
"code": null,
"e": 25939,
"s": 25836,
"text": "You can rename the Task. Here it is renamed as Summary Task 1. Don’t enter any duration for this task."
},
{
"code": null,
"e": 26023,
"s": 25939,
"text": "Now select Task 4 and Task 5.\n\nClick Task tab → Schedule group → Click Indent Task\n"
},
{
"code": null,
"e": 26516,
"s": 26023,
"text": "Once you have a list of tasks ready to accomplish your project objectives, you need to link them with their task relationships called dependencies. For example, Task 2 can start once Task 1 has finished. These dependencies are called Links. A Guide to the Project Management Body of Knowledge (PMBOK Guide) does not define the term dependency, but refers to it as a logical relationship, which in turn is defined as a dependency between two activities, or between an activity and a milestone."
},
{
"code": null,
"e": 26857,
"s": 26516,
"text": "In MS Project, the first task is called a predecessor because it precedes tasks that depend on it. The following task is called the successor because it succeeds, or follows tasks on which it is dependent. Any task can be a predecessor for one or more successor tasks. Likewise, any task can be a successor to one or more predecessor tasks."
},
{
"code": null,
"e": 26941,
"s": 26857,
"text": "There are only four types of task dependencies, here we present them with examples."
},
{
"code": null,
"e": 27041,
"s": 26941,
"text": "Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used."
},
{
"code": null,
"e": 27141,
"s": 27041,
"text": "Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used."
},
{
"code": null,
"e": 27214,
"s": 27141,
"text": "Finish to Finish (FF) − Cooking all dishes for dinner to finish on time."
},
{
"code": null,
"e": 27287,
"s": 27214,
"text": "Finish to Finish (FF) − Cooking all dishes for dinner to finish on time."
},
{
"code": null,
"e": 27494,
"s": 27287,
"text": "Start To Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey response before starting the tabulation."
},
{
"code": null,
"e": 27701,
"s": 27494,
"text": "Start To Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey response before starting the tabulation."
},
{
"code": null,
"e": 27780,
"s": 27701,
"text": "Start to Finish (SF) − Exam preparation will end when exam begins. Least used."
},
{
"code": null,
"e": 27859,
"s": 27780,
"text": "Start to Finish (SF) − Exam preparation will end when exam begins. Least used."
},
{
"code": null,
"e": 27907,
"s": 27859,
"text": "In MS Project you can identify the Task Links −"
},
{
"code": null,
"e": 28020,
"s": 27907,
"text": "Gantt Chart − In Gantt Chart and Network Diagram views, task relationships appear as the links connecting tasks."
},
{
"code": null,
"e": 28133,
"s": 28020,
"text": "Gantt Chart − In Gantt Chart and Network Diagram views, task relationships appear as the links connecting tasks."
},
{
"code": null,
"e": 28242,
"s": 28133,
"text": "Tables − In Tables, task ID numbers of predecessor task appear in the predecessor fields of successor tasks."
},
{
"code": null,
"e": 28351,
"s": 28242,
"text": "Tables − In Tables, task ID numbers of predecessor task appear in the predecessor fields of successor tasks."
},
{
"code": null,
"e": 28482,
"s": 28351,
"text": "Select the two tasks you want to link. In the following screenshot taken as an example, we have selected names, Task 1 and Task 2."
},
{
"code": null,
"e": 28542,
"s": 28482,
"text": "Click Task tab → Schedule group → Link the Selected Tasks.\n"
},
{
"code": null,
"e": 28608,
"s": 28542,
"text": "Task 1 and Task 2 are linked with a Finish-to-Start relationship."
},
{
"code": null,
"e": 28697,
"s": 28608,
"text": "Note − Task 2 will have a Start date of the Next working day from Finish date of Task 1."
},
{
"code": null,
"e": 28752,
"s": 28697,
"text": "Double click a successor task you would like to link.\n"
},
{
"code": null,
"e": 28779,
"s": 28752,
"text": "Here I have clicked Task 4"
},
{
"code": null,
"e": 28817,
"s": 28779,
"text": "The Task information dialog box opens"
},
{
"code": null,
"e": 28901,
"s": 28817,
"text": "Click Predecessors tab\n\nIn the Table, click the empty cell below Task Name column.\n"
},
{
"code": null,
"e": 28964,
"s": 28901,
"text": "A drop down box appears with all Tasks defined in the project."
},
{
"code": null,
"e": 29004,
"s": 28964,
"text": "Choose the predecessor task. Click OK.\n"
},
{
"code": null,
"e": 29031,
"s": 29004,
"text": "Here I have chosen Task 3."
},
{
"code": null,
"e": 29133,
"s": 29031,
"text": "In this method, you will select a group of task, and link them all with Finish-to-Start relationship."
},
{
"code": null,
"e": 29238,
"s": 29133,
"text": "Select multiple tasks with the help of the mouse → Task tab → Schedule group → Link the Selected Tasks.\n"
},
{
"code": null,
"e": 29342,
"s": 29238,
"text": "All tasks get linked. To select non-adjacent tasks, hold down Ctrl key and select each task separately."
},
{
"code": null,
"e": 29555,
"s": 29342,
"text": "If you are in Manually Scheduled mode, any change in duration of the predecessor task will not reflect on Start date of Task 4. For example, Task 4 starts on 9/3/15 which is the next day of Finish date of Task 3."
},
{
"code": null,
"e": 29692,
"s": 29555,
"text": "Now when we change the Duration of Task 3 from 5 to 7 days, the start date is not automatically updated for Task 4 in Manual Scheduling."
},
{
"code": null,
"e": 29775,
"s": 29692,
"text": "You can force MS Project to respect the link (dependency) by doing the following −"
},
{
"code": null,
"e": 29790,
"s": 29775,
"text": "Select Task 4."
},
{
"code": null,
"e": 29839,
"s": 29790,
"text": "Click Task tab → Schedule group → Respect Links."
},
{
"code": null,
"e": 29940,
"s": 29839,
"text": "MS Project by default sets new tasks to be manually scheduled. Scheduling is controlled in two ways."
},
{
"code": null,
"e": 30170,
"s": 29940,
"text": "Manual Scheduling − This is done to quickly capture some details without actually scheduling the tasks. You can leave out details for some of the tasks with respect to duration, start and finish dates, if you don’t know them yet."
},
{
"code": null,
"e": 30391,
"s": 30170,
"text": "Automatic Scheduling − This uses the Scheduling engine in MS Project. It calculates values such as task durations, start dates, and finish dates automatically. It takes into accounts all constraints, links and calendars."
},
{
"code": null,
"e": 30742,
"s": 30391,
"text": "For example, at Lucerne Publishing, the new book launch plan has been reviewed by the resources who will carry out the work and by other project stakeholders. Although you expect the plan to change somewhat as you learn more about the book launch, you now have enough confidence in the overall plan to switch from manual to automatic task scheduling."
},
{
"code": null,
"e": 30815,
"s": 30742,
"text": "We have three different methods to convert a task to automatic schedule."
},
{
"code": null,
"e": 31029,
"s": 30815,
"text": "If you want to change the mode for a particular task, say Task 5 in the following example. Click on Task Mode cell in the same row. Then, click the down arrow to open a dropdown box, you can select Auto Scheduled."
},
{
"code": null,
"e": 31071,
"s": 31029,
"text": "Click Task → Tasks group → Auto Schedule."
},
{
"code": null,
"e": 31116,
"s": 31071,
"text": "To switch completely to Auto Schedule mode −"
},
{
"code": null,
"e": 31254,
"s": 31116,
"text": "Toggle the scheduling mode of the plan by clicking the New Tasks status bar (at the bottom-left) and then selecting Auto scheduling mode."
},
{
"code": null,
"e": 31341,
"s": 31254,
"text": "You can also change the default scheduling mode that Project applies to all new plans."
},
{
"code": null,
"e": 31566,
"s": 31341,
"text": "Go to File tab and click Options. Then click Schedule tab and under scheduling options for this project select “All New Projects” from the dropdown box. Under new tasks created, select “Auto Scheduled” from the dropdown box."
},
{
"code": null,
"e": 31855,
"s": 31566,
"text": "In project management terminology, resources are required to carry out the project tasks. They can be people, equipment, facilities, funding, or anything (except labor) required for the completion of a project task. Optimum Resource Scheduling is the key to successful project management."
},
{
"code": null,
"e": 31916,
"s": 31855,
"text": "Work resources − People and equipment to complete the tasks."
},
{
"code": null,
"e": 31977,
"s": 31916,
"text": "Work resources − People and equipment to complete the tasks."
},
{
"code": null,
"e": 32070,
"s": 31977,
"text": "Cost resources − Financial cost associated with a task. Travel expenses, food expenses, etc."
},
{
"code": null,
"e": 32163,
"s": 32070,
"text": "Cost resources − Financial cost associated with a task. Travel expenses, food expenses, etc."
},
{
"code": null,
"e": 32275,
"s": 32163,
"text": "Material resources − Consumables used as project proceeds. For example, paint being used while painting a wall."
},
{
"code": null,
"e": 32387,
"s": 32275,
"text": "Material resources − Consumables used as project proceeds. For example, paint being used while painting a wall."
},
{
"code": null,
"e": 32807,
"s": 32387,
"text": "Note − Be aware of the crucial difference between People and Equipment resources. People resources will have limited work hours, say 6, 8 or 12 hours. Equipment resources have different working capacities of 2, 8 or 24 hours and could have maintenance breaks as well. Also note, that it is possible multiple people resources might be using one equipment resource, or one equipment might be accomplishing multiple tasks."
},
{
"code": null,
"e": 32867,
"s": 32807,
"text": "You can enter resource names according to your convenience."
},
{
"code": null,
"e": 33060,
"s": 32867,
"text": "Click View tab → Resource Views group → Click Resource Sheet.\n\nClick the cell directly below the Resource Name heading column.\n\nEnter Resources as an individual person, job function or group.\n"
},
{
"code": null,
"e": 33108,
"s": 33060,
"text": "By default, the Max Units field is set to 100%."
},
{
"code": null,
"e": 33526,
"s": 33108,
"text": "Max Units field represents the maximum capacity of a resource to work on assigned tasks. 100% stands for 100 percent of resource’s working time is available for work on task assigned. The resource is available full-time on each workday. If the resource gets allocated to task or tasks that would require more than his/its work hours, the resource is over allocated and MS Project will indicate this in red formatting."
},
{
"code": null,
"e": 33825,
"s": 33526,
"text": "If a resource does not represent an individual person but a job function, where a group of people with the same skill set can work on the task, we can enter larger Max Units to represent the number of people in the group. So 400% would indicate, 4 individual people working full-time every workday."
},
{
"code": null,
"e": 34068,
"s": 33825,
"text": "Click View tab → Resource Views group → Click Resource Sheet\n\nClick the cell directly below Resource Name heading column\n\nEnter Resources as group, here we take an example of Engineers.\n\nClick the Max. Units field for the Engineers resource.\n"
},
{
"code": null,
"e": 34102,
"s": 34068,
"text": "Type or select 400%. Press Enter."
},
{
"code": null,
"e": 34375,
"s": 34102,
"text": "Entering a value less than 100% in Max.Units would mean you expect the resource capacity to be lower than a full-time resource. So 50% would mean the individual works for half of the normal full capacity, so if a normal work week is 40 hours, this equals 20 hour capacity."
},
{
"code": null,
"e": 34577,
"s": 34375,
"text": "Click View tab → Resource Views group → Click Resource Sheet.\n\nClick the cell directly below Resource Name heading column.\n\nEnter Resource as an individual or job function. Here let’s take an example.\n"
},
{
"code": null,
"e": 34947,
"s": 34577,
"text": "You can enter standard rates and costs per use for work and material resources. You can also enter overtime rates for work resources. Standard rates are calculated on per hour basis. Costs per use on the other hand are costs that do not vary with task. Cost per use is a set fee used up to complete a task. There are three types of resources − work, material, and cost."
},
{
"code": null,
"e": 35008,
"s": 34947,
"text": "Work resources − People and equipment to complete the tasks."
},
{
"code": null,
"e": 35069,
"s": 35008,
"text": "Work resources − People and equipment to complete the tasks."
},
{
"code": null,
"e": 35162,
"s": 35069,
"text": "Cost resources − Financial cost associated with a task. Travel expenses, food expenses, etc."
},
{
"code": null,
"e": 35255,
"s": 35162,
"text": "Cost resources − Financial cost associated with a task. Travel expenses, food expenses, etc."
},
{
"code": null,
"e": 35359,
"s": 35255,
"text": "Material resources − Consumables used as project proceeds. Like paint being used while painting a wall."
},
{
"code": null,
"e": 35463,
"s": 35359,
"text": "Material resources − Consumables used as project proceeds. Like paint being used while painting a wall."
},
{
"code": null,
"e": 35885,
"s": 35463,
"text": "Note − Be aware of the crucial difference between People and Equipment resources. People resources will have limited work hours say 6, 8 or 12 hours. Equipment resources can have different working capacities of 2, 8 or 24 hours and could have maintenance breaks as well. Also note that it is possible multiple people resources might be using one equipment resource, or one equipment might be accomplishing multiple tasks."
},
{
"code": null,
"e": 36179,
"s": 35885,
"text": "Cost resources do not use pay rates. Remember cost per use and cost resources are two different things. Cost resources are financial cost associated with a task, like travel expenses, food expenses, etc. The cost value of cost resource is only assigned when you assign cost resource to a task."
},
{
"code": null,
"e": 36241,
"s": 36179,
"text": "Project calculates the cost of a task by using this formula −"
},
{
"code": null,
"e": 36312,
"s": 36241,
"text": "Cost of Task = Work Value (in number of hours) x Resource’s Pay Rate.\n"
},
{
"code": null,
"e": 36499,
"s": 36312,
"text": "You can then see the cost per resource and cost per task (as well as costs rolled up to summary tasks and the entire plan). MS Project will not automatically apply overtime calculations."
},
{
"code": null,
"e": 36561,
"s": 36499,
"text": "To enter standard and overtime pay rates for work resources −"
},
{
"code": null,
"e": 36815,
"s": 36561,
"text": "Click View tab → Resource Views group → Resource Sheet.\n\nClick the cell directly below Resource Name heading column to create Resources.\n\nClick the Std. Rate field for each resource to costs in hourly (default), daily, weekly, monthly and yearly rates.\n"
},
{
"code": null,
"e": 36959,
"s": 36815,
"text": "In the following example, the resource Rasmus is left at zero. This is useful when you don’t have to track rate-based costs for some resources."
},
{
"code": null,
"e": 37010,
"s": 36959,
"text": "Click the Ovt. Rate field to enter overtime rates."
},
{
"code": null,
"e": 37234,
"s": 37010,
"text": "Click View tab → Resource Views group → Resource Sheet.\n\nDouble-click the Resource, a Resource Information dialog box opens.\n\nClick on Notes tab. Here let’s enter a note for Rasmus as “Rasmus will work parttime”.\nClick OK.\n"
},
{
"code": null,
"e": 37358,
"s": 37234,
"text": "A note icon now appears to the left of Rasmus’ name in the Resource Sheet view. Hovering over it will make the note appear."
},
{
"code": null,
"e": 37621,
"s": 37358,
"text": "You can use a cost resource to represent a financial cost associated with a task in a plan. Examples of cost resources are travel, food, entertainment and training. So it is obvious that cost resources do no work on a task and do not affect scheduling of a task."
},
{
"code": null,
"e": 37693,
"s": 37621,
"text": "Cost value of the cost resource is entered when assigning it to a task."
},
{
"code": null,
"e": 37898,
"s": 37693,
"text": "Click View tab → Resource Views group → Resource Sheet.\n\nClick the empty cell in the Resource Name column. \n\nType Training and press the Tab Key.\n\nIn the Type field, click the down arrow to select Cost.\n"
},
{
"code": null,
"e": 38080,
"s": 37898,
"text": "Once the task and resource list are complete, resources need to be assigned to tasks in order to work on them. With MS Project you can track task progress, resource and tasks costs."
},
{
"code": null,
"e": 38384,
"s": 38080,
"text": "Click View Tab → Gantt Chart View → Resource Name column.\n\nClick the box below the Resource Name column for the task you need the resource to be assigned.\n\nFrom the dropdown, choose the resource name. In the following screenshot as an \n example. For Task 1 “PT1”, we have chosen the resource “Celic”.\n"
},
{
"code": null,
"e": 38449,
"s": 38384,
"text": "You can also select multiple resources to work on a single task."
},
{
"code": null,
"e": 38596,
"s": 38449,
"text": "Click Resource tab → Under Assignments group → Assign Resources.\n\nIn the Assign Resources dialog box, click the resource name you like to assign.\n"
},
{
"code": null,
"e": 38653,
"s": 38596,
"text": "Here let’s choose “Hitesh”. Now click the Assign button."
},
{
"code": null,
"e": 38718,
"s": 38653,
"text": "You can also select multiple resources to work on a single task."
},
{
"code": null,
"e": 38950,
"s": 38718,
"text": "Click View Tab → Gantt Chart → Task Name column.\n\nDouble-click the Task Name. Task Information dialog box opens.\n\nClick the Resources tab.\n\nClick the cell below the Resource Name column. Select the resource from the dropdown list.\n"
},
{
"code": null,
"e": 39015,
"s": 38950,
"text": "You can also select multiple resources to work on a single task."
},
{
"code": null,
"e": 39073,
"s": 39015,
"text": "Click View Tab → Split View group → Details → Task Form.\n"
},
{
"code": null,
"e": 39147,
"s": 39073,
"text": "The window is split in two, Gantt Chart view and Task Form view below it."
},
{
"code": null,
"e": 39233,
"s": 39147,
"text": "In the Task Form view, click under the Resource Name column and select the resource.\n"
},
{
"code": null,
"e": 39298,
"s": 39233,
"text": "You can also select multiple resources to work on a single task."
},
{
"code": null,
"e": 39535,
"s": 39298,
"text": "Click View Tab → Gantt Chart View → Task Name column.\n\nDouble-click the Task Name. Task Information dialog box opens.\n\nClick the Resources tab.\n\nClick the cell below the Resource Name column. Select the resource from the dropdown list.\n"
},
{
"code": null,
"e": 39634,
"s": 39535,
"text": "In the following example below, let’s choose “Travel” as cost resource and enter the cost at $800."
},
{
"code": null,
"e": 39696,
"s": 39634,
"text": "We can also assign other material resources to the same task."
},
{
"code": null,
"e": 39807,
"s": 39696,
"text": "After assigning resources to tasks you can view the cost, duration and work required for the plan to complete."
},
{
"code": null,
"e": 39879,
"s": 39807,
"text": "In Gantt Chart View → View Tab → Split View group → Timeline checkbox.\n"
},
{
"code": null,
"e": 39938,
"s": 39879,
"text": "You will be able to see the plan’s start and finish dates."
},
{
"code": null,
"e": 40068,
"s": 39938,
"text": "In the Gantt Chart view, you can also look at the project summary task, to note the duration, start and finish dates of the plan."
},
{
"code": null,
"e": 40226,
"s": 40068,
"text": "In the following example, Assign Resources is the project summary task (identified as Task 0). Duration=53 days, Start date: 1/5/15 and Finish Date: 3/19/15."
},
{
"code": null,
"e": 40292,
"s": 40226,
"text": "One can switch Project Summary Task on by following these steps −"
},
{
"code": null,
"e": 40374,
"s": 40292,
"text": "In Gantt Chart View → Format Tab → Show/Hide → To check Project Summary Task on.\n"
},
{
"code": null,
"e": 40420,
"s": 40374,
"text": "Click View tab → Data group → Tables → Cost.\n"
},
{
"code": null,
"e": 40519,
"s": 40420,
"text": "Cost for each task gets rolled up into summary tasks, and then ultimately to project summary task."
},
{
"code": null,
"e": 40602,
"s": 40519,
"text": "Click Report Tab → View Reports group → click Resources → click Resource overview\n"
},
{
"code": null,
"e": 40765,
"s": 40602,
"text": "In Resource status table which appears at the bottom, you will get a summary of resource’s earliest start dates and latest finish dates as well as remaining work."
},
{
"code": null,
"e": 40872,
"s": 40765,
"text": "Click Project Tab → Properties group → Project Information → in\n the new dialog box click Statistics...\n"
},
{
"code": null,
"e": 41501,
"s": 40872,
"text": "Once your project plan is ready in MS Project, it becomes essential for a project manager to measure the actuals (in terms of work completed, resources used and costs incurred) and to revise and change information about tasks and resources due to any changes to the plans. A Project Manager should not assume that everything is progressing according to plan and should always keep track of each task. Resistance to formal tracking of project management data is normal. You can overcome resistance to tracking by explaining your expectations, explaining the benefits of tracking, and training people to track the task themselves."
},
{
"code": null,
"e": 41841,
"s": 41501,
"text": "To evaluate project performance you need to create a baseline against which you will compare the progress. One needs to save the baseline, once a plan is fully developed. Of course, due to rolling wave planning or progressive elaboration needed to manage projects one can always add new tasks, resources, constraints and costs to the plan."
},
{
"code": null,
"e": 41961,
"s": 41841,
"text": "Also note, it makes sense to save the baseline before entering any actual values such as percentage of task completion."
},
{
"code": null,
"e": 42146,
"s": 41961,
"text": "Note − With MS Project 2013, you can save up to 11 Baselines in a Single plan. These multiple baselines seem contrary to the definition of baseline. You can use this flexibility when −"
},
{
"code": null,
"e": 42232,
"s": 42146,
"text": "You have a baseline plan for the external customer and another for the internal team."
},
{
"code": null,
"e": 42318,
"s": 42232,
"text": "You have a baseline plan for the external customer and another for the internal team."
},
{
"code": null,
"e": 42430,
"s": 42318,
"text": "You are preparing for a risk event. You want to develop separate baseline plans for risk response and recovery."
},
{
"code": null,
"e": 42542,
"s": 42430,
"text": "You are preparing for a risk event. You want to develop separate baseline plans for risk response and recovery."
},
{
"code": null,
"e": 42693,
"s": 42542,
"text": "You are accommodating a big change request, you might still want to keep the original plan for future reference when communicating with a stakeholder."
},
{
"code": null,
"e": 42844,
"s": 42693,
"text": "You are accommodating a big change request, you might still want to keep the original plan for future reference when communicating with a stakeholder."
},
{
"code": null,
"e": 42901,
"s": 42844,
"text": "Click Project Tab → Schedule group → Set Baseline → OK.\n"
},
{
"code": null,
"e": 43032,
"s": 42901,
"text": "Click View Tab → Task Views group → Gantt Chart.\n\nClick Format Tab → Bars and Styles group → Baseline (that you want to display).\n"
},
{
"code": null,
"e": 43113,
"s": 43032,
"text": "You will see Baseline Gantt bars displayed together with the current Gantt bars."
},
{
"code": null,
"e": 43242,
"s": 43113,
"text": "As time and work progresses on a project, you might need to change the baseline as well. You have several options for the same −"
},
{
"code": null,
"e": 43263,
"s": 43242,
"text": "Update the baseline."
},
{
"code": null,
"e": 43303,
"s": 43263,
"text": "Update the baseline for selected tasks."
},
{
"code": null,
"e": 43328,
"s": 43303,
"text": "Save multiple baselines."
},
{
"code": null,
"e": 43415,
"s": 43328,
"text": "This simply replaces the original baseline values with the currently scheduled values."
},
{
"code": null,
"e": 43472,
"s": 43415,
"text": "Click Project Tab → Schedule group → Set Baseline → OK.\n"
},
{
"code": null,
"e": 43570,
"s": 43472,
"text": "This does not affect the baseline values for other tasks or resource baseline values in the plan."
},
{
"code": null,
"e": 43655,
"s": 43570,
"text": "Click Project Tab → Schedule group → Set Baseline → For select Selected tasks → OK.\n"
},
{
"code": null,
"e": 43788,
"s": 43655,
"text": "You can save up to 11 baselines in a single plan. The first one is called Baseline, and the rest are Baseline 1 through Baseline 10."
},
{
"code": null,
"e": 43911,
"s": 43788,
"text": "Click Project Tab → Schedule group → Set Baseline → click \n the dropdown box to save any baseline you like.\n\t\nClick OK.\n"
},
{
"code": null,
"e": 44025,
"s": 43911,
"text": "An interim plan saves only two kinds of information for each task − Current start dates and Current finish dates."
},
{
"code": null,
"e": 44214,
"s": 44025,
"text": "It can be used as a project marker. It is visually easy to see how off-track or on-track the project progress is. Because it only specifies dates, it is simple, clear and easy information."
},
{
"code": null,
"e": 44290,
"s": 44214,
"text": "Click Project Tab → Schedule group → Set Baseline → Set interim plan → OK.\n"
},
{
"code": null,
"e": 44614,
"s": 44290,
"text": "If all tasks have started and are finished as scheduled, you can record this in the Update Project dialog box. Most of the times, a seasoned project manager understands that this isn’t true. But sometimes this approach might be fine when the actual work and cost values generated are close enough to your baseline schedule."
},
{
"code": null,
"e": 44812,
"s": 44614,
"text": "Click Project tab → Status group → Update Project.\n\nSwitch on the radio button for “Update work as complete through”\n option, and then Set 0% -100% complete. Select the current date.\n\t\nClick OK.\n"
},
{
"code": null,
"e": 44992,
"s": 44812,
"text": "Check marks will appear in the indicators column for tasks that have been completed. On the right in the Chart portion, progress bars are generated in the Gantt bars of each task."
},
{
"code": null,
"e": 45072,
"s": 44992,
"text": "Click any Task → Task Tab → Schedule group → either 0%, 25%, 50%, 75% or 100%.\n"
},
{
"code": null,
"e": 45122,
"s": 45072,
"text": "Click View tab → Data group → Tables → Tracking.\n"
},
{
"code": null,
"e": 45222,
"s": 45122,
"text": "Now for the required Task, click the corresponding % Comp column and enter the required % complete."
},
{
"code": null,
"e": 45283,
"s": 45222,
"text": "You can enter the following actual values for your project −"
},
{
"code": null,
"e": 45355,
"s": 45283,
"text": "Actual Start and finish dates − Project moves the schedule accordingly."
},
{
"code": null,
"e": 45427,
"s": 45355,
"text": "Actual Start and finish dates − Project moves the schedule accordingly."
},
{
"code": null,
"e": 45518,
"s": 45427,
"text": "Task’s Actual duration − If equal or greater than schedule duration: task = 100% complete."
},
{
"code": null,
"e": 45609,
"s": 45518,
"text": "Task’s Actual duration − If equal or greater than schedule duration: task = 100% complete."
},
{
"code": null,
"e": 45655,
"s": 45609,
"text": "Click View Tab → Data group → Tables → Work.\n"
},
{
"code": null,
"e": 45709,
"s": 45655,
"text": "You will see the % W. Comp. (% work complete) column."
},
{
"code": null,
"e": 45783,
"s": 45709,
"text": "This table includes Work (Scheduled work), Actual, and Remaining columns."
},
{
"code": null,
"e": 46287,
"s": 45783,
"text": "Click on Task you want to update. In the following example, Task 9’s Actual field is clicked and 24 hours is entered. For this task, initial scheduled Work was 16 hours, because 24 hours is greater. The project marks the task as 100% complete and updates the Work column to 24 hours (from initial 16 hours). In the example, a Baseline is saved, because the Baseline does not change and is used as a comparison. The Baseline is still at 16 hours and a Variance of 8 hours is now calculated by MS Project."
},
{
"code": null,
"e": 46358,
"s": 46287,
"text": "Note − Actual work is rolled up and also reflects on the summary task."
},
{
"code": null,
"e": 46407,
"s": 46358,
"text": "Click Task whose dates you would like to change."
},
{
"code": null,
"e": 46537,
"s": 46407,
"text": "Click Task tab → Schedule group → dropdown menu for Mark on Track → Update Tasks.\n\nChange Start or Finish field in Actual group.\n"
},
{
"code": null,
"e": 46581,
"s": 46537,
"text": "You can fill Actual duration field as well."
},
{
"code": null,
"e": 46624,
"s": 46581,
"text": "There are four types of task dependencies."
},
{
"code": null,
"e": 46725,
"s": 46624,
"text": "Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used."
},
{
"code": null,
"e": 46826,
"s": 46725,
"text": "Finish to Start (FS) − Finish the first floor before starting to build the second floor. Most used."
},
{
"code": null,
"e": 46903,
"s": 46826,
"text": "Finish to Finish (FF) − Cooking all the dishes for dinner to finish on time."
},
{
"code": null,
"e": 46980,
"s": 46903,
"text": "Finish to Finish (FF) − Cooking all the dishes for dinner to finish on time."
},
{
"code": null,
"e": 47188,
"s": 46980,
"text": "Start to Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey responses before starting the tabulation."
},
{
"code": null,
"e": 47396,
"s": 47188,
"text": "Start to Start (SS) − When doing a survey, we would seek survey responses but will also start tabulating the responses. One does not have to finish collecting survey responses before starting the tabulation."
},
{
"code": null,
"e": 47475,
"s": 47396,
"text": "Start to Finish (SF) − Exam preparation will end when exam begins. Least used."
},
{
"code": null,
"e": 47554,
"s": 47475,
"text": "Start to Finish (SF) − Exam preparation will end when exam begins. Least used."
},
{
"code": null,
"e": 47781,
"s": 47554,
"text": "Click Task Tab → double-click the required task under Task Name column →\n Task Information dialog box opens → Predecessors Tab.\n\nClick the box under the Type column and choose the relationship according to your requirement.\n"
},
{
"code": null,
"e": 47886,
"s": 47781,
"text": "By default when you link tasks they are assigned a “Finish to Start” relationship. In this relationship,"
},
{
"code": null,
"e": 47969,
"s": 47886,
"text": "Lead − Lead time causes successor task to begin before its predecessor tasks ends."
},
{
"code": null,
"e": 48052,
"s": 47969,
"text": "Lead − Lead time causes successor task to begin before its predecessor tasks ends."
},
{
"code": null,
"e": 48131,
"s": 48052,
"text": "Lag − Lag time causes successor task to start after its predecessor task ends."
},
{
"code": null,
"e": 48210,
"s": 48131,
"text": "Lag − Lag time causes successor task to start after its predecessor task ends."
},
{
"code": null,
"e": 48341,
"s": 48210,
"text": "Click Task Tab → double-click the required Task under Task Name column →\n Task Information dialog box opens → Predecessors Tab.\n"
},
{
"code": null,
"e": 48590,
"s": 48341,
"text": "Under Lag heading column, enter the lag in terms of hours, days, weeks, or years. You can also apply lag or lead as a percentage. If you enter 50% for the selected Task which is 6 days long, the task is delayed by 3 days after the predecessor ends."
},
{
"code": null,
"e": 48673,
"s": 48590,
"text": "Lag is entered as positive units and lead in negative units (example,-3d or -50%)."
},
{
"code": null,
"e": 49067,
"s": 48673,
"text": "Each task created in MS Project 2013 will be constrained as “As Soon As Possible” by default when Automatic Scheduling is turned ON. As Soon As Possible means the task starts as soon as the project starts, if there are no dependencies that would delay it. So, no fixed start or end dates are imposed by this constraint type, but of course predecessor and successor dependencies are maintained."
},
{
"code": null,
"e": 49195,
"s": 49067,
"text": "When MS Project 2013 performs calculations to save you time in a project that’s running late, constraint settings are enforced."
},
{
"code": null,
"e": 49225,
"s": 49195,
"text": "There are 8 Task Constraints."
},
{
"code": null,
"e": 49440,
"s": 49225,
"text": "Click Task Tab → double-click the required Task under Task Name column →\n Task Information dialog box opens → Advanced Tab.\n\nClick dropdown box for Constraint type. Choose the constraint you would like to apply.\n"
},
{
"code": null,
"e": 49872,
"s": 49440,
"text": "If you use Tasks Constraints, you limit your scheduling flexibility, where MS Project 2013 will fix a particular start or finish date of the task according to the constraint. It is a better idea to use a Deadline Date which has no effect on the scheduling of a task or summary task. MS Project will alert you with a red exclamation symbol in the indicators column, if the scheduled completion of the task exceeds its deadline date."
},
{
"code": null,
"e": 49995,
"s": 49872,
"text": "Click Task Tab → double-click the required Task under Task Name column → Task Information dialog box opens → Advanced Tab."
},
{
"code": null,
"e": 50085,
"s": 49995,
"text": "Fixed Cost is associated with a task that is not tied to any resources or amount of work."
},
{
"code": null,
"e": 50130,
"s": 50085,
"text": "Click View Tab → Data group → Tables → Cost."
},
{
"code": null,
"e": 50274,
"s": 50130,
"text": "Enter the cost under the Fixed Cost column for the task of interest. In the following example, we have assigned a fixed cost of $500 to Task 7."
},
{
"code": null,
"e": 50513,
"s": 50274,
"text": "Status meetings, status reports, inspection dates can recur with a particular frequency. In MS Project 2013, you can specify recurring tasks without having to assign tasks each time separately. You can also assign resources to these task."
},
{
"code": null,
"e": 50601,
"s": 50513,
"text": "In Gantt Chart View → Task Tab → Insert group → dropdown box for Task → Recurring Task."
},
{
"code": null,
"e": 50648,
"s": 50601,
"text": "Enter Task Name and choose Recurrence pattern."
},
{
"code": null,
"e": 50958,
"s": 50648,
"text": "You can also choose a specific time for the task to start as well. By default Project schedules a recurring task to start on plan’s default start time. You can add time value in the Start box for Recurring Task Information dialog box to change this. In the following figure, start time of 10:00 AM is entered."
},
{
"code": null,
"e": 51236,
"s": 50960,
"text": "Critical Path is the succession of connected tasks that will take the longest to complete. The word “critical” does not mean that the tasks are complex or important or need to be closely monitored, but the focus is on terms schedule that will affect the project finish date."
},
{
"code": null,
"e": 51600,
"s": 51236,
"text": "So, if you want to shorten the duration of a project, you should first start with activities/tasks on the critical path. Critical path can be a single sequence of tasks (a single critical path) or there can be more than 1 critical paths for a single project. While schedule changes are made, it is also likely that the critical path will change from time to time."
},
{
"code": null,
"e": 51737,
"s": 51600,
"text": "One needs to always focus on the Critical Path first, when one wants to apply fast-tracking or crashing to shorten the project duration."
},
{
"code": null,
"e": 51823,
"s": 51737,
"text": "Slack or Float are key to understanding Critical path. There are two types of Float −"
},
{
"code": null,
"e": 51914,
"s": 51823,
"text": "Free Float − It is the amount of time a task can be delayed without delaying another task."
},
{
"code": null,
"e": 52005,
"s": 51914,
"text": "Free Float − It is the amount of time a task can be delayed without delaying another task."
},
{
"code": null,
"e": 52114,
"s": 52005,
"text": "Total Float − It is the amount of time a task can be delayed without delaying the completion of the project."
},
{
"code": null,
"e": 52223,
"s": 52114,
"text": "Total Float − It is the amount of time a task can be delayed without delaying the completion of the project."
},
{
"code": null,
"e": 52311,
"s": 52223,
"text": "In Gantt Chart view → Format Tab → Bar Styles Group → Check the Critical Tasks box ON.\n"
},
{
"code": null,
"e": 52409,
"s": 52311,
"text": "All task bars in the critical path, in the Gantt Chart View on the right, will turn Red in color."
},
{
"code": null,
"e": 52495,
"s": 52409,
"text": "Relationship between a resource’s capacity and task assignments is called allocation."
},
{
"code": null,
"e": 52526,
"s": 52495,
"text": "This can defined by 3 states −"
},
{
"code": null,
"e": 52624,
"s": 52526,
"text": "Under allocated − An Engineer who works for 40 hours a week, has work assigned for only 20 hours."
},
{
"code": null,
"e": 52722,
"s": 52624,
"text": "Under allocated − An Engineer who works for 40 hours a week, has work assigned for only 20 hours."
},
{
"code": null,
"e": 52831,
"s": 52722,
"text": "Fully allocated − A skilled worker who works for 40 hours a week, is assigned 40 hours of work in that week."
},
{
"code": null,
"e": 52940,
"s": 52831,
"text": "Fully allocated − A skilled worker who works for 40 hours a week, is assigned 40 hours of work in that week."
},
{
"code": null,
"e": 53037,
"s": 52940,
"text": "Over allocated − A carpenter is assigned 65 hours of work, when he only has a 40 hour work week."
},
{
"code": null,
"e": 53134,
"s": 53037,
"text": "Over allocated − A carpenter is assigned 65 hours of work, when he only has a 40 hour work week."
},
{
"code": null,
"e": 53189,
"s": 53134,
"text": "Click View Tab → Task Views group → Gantt Chart view.\n"
},
{
"code": null,
"e": 53288,
"s": 53189,
"text": "Gantt Chart View displays some limited resource information, as shown in the following screenshot."
},
{
"code": null,
"e": 53389,
"s": 53288,
"text": "It summarizes whether there may be a problem by the red over allocated icon in the indicator column."
},
{
"code": null,
"e": 53451,
"s": 53389,
"text": "Click View Tab → Resource Views group → Resource Usage view.\n"
},
{
"code": null,
"e": 53748,
"s": 53451,
"text": "The Resource Usage view displays resources and all tasks assigned to them underneath the Resource Name. The left-hand side of the screen lists the Resources and the Task Names together with columns of total information for the resource or assignment. The right-hand side shows a time-phased view."
},
{
"code": null,
"e": 53837,
"s": 53748,
"text": "You can also collapse the outline in the table to see total work per resource over time."
},
{
"code": null,
"e": 53876,
"s": 53837,
"text": "Click on Resource Name column heading."
},
{
"code": null,
"e": 53932,
"s": 53876,
"text": "Click View Tab → Data group → Outline → Hide Subtasks.\n"
},
{
"code": null,
"e": 54081,
"s": 53932,
"text": "One would need to either change the scope (reduce the amount of work), assign more resources, or accept a longer schedule to resolve overallocation."
},
{
"code": null,
"e": 54146,
"s": 54081,
"text": "This can be achieved by using some of the following techniques −"
},
{
"code": null,
"e": 54403,
"s": 54146,
"text": "By changing its lead or lag time when the resource has more tasks assigned than can be completed during a given time period. If you add delay that is less than or equal to the amount of slack on the task, you will not affect the finish date of the project."
},
{
"code": null,
"e": 54510,
"s": 54403,
"text": "By default when you link tasks, they are assigned a “Finish to Start” relationship. In this relationship,"
},
{
"code": null,
"e": 54593,
"s": 54510,
"text": "Lead − Lead time causes successor task to begin before its predecessor tasks ends."
},
{
"code": null,
"e": 54676,
"s": 54593,
"text": "Lead − Lead time causes successor task to begin before its predecessor tasks ends."
},
{
"code": null,
"e": 54756,
"s": 54676,
"text": "Lag − Lag time causes successor task to start after its predecessor task ends."
},
{
"code": null,
"e": 54836,
"s": 54756,
"text": "Lag − Lag time causes successor task to start after its predecessor task ends."
},
{
"code": null,
"e": 54963,
"s": 54836,
"text": "Click Task Tab → double-click the required Task under Task Name column → Task Information dialog box opens → Predecessors Tab."
},
{
"code": null,
"e": 55212,
"s": 54963,
"text": "Under Lag heading column, enter the lag in terms of hours, days, weeks, or years. You can also apply lag or lead as a percentage. If you enter 50% for the selected Task which is 6 days long, the task is delayed by 3 days after the predecessor ends."
},
{
"code": null,
"e": 55295,
"s": 55212,
"text": "Lag is entered as positive units and lead in negative units (example,-3d or -50%)."
},
{
"code": null,
"e": 55351,
"s": 55295,
"text": "You can manually allot some other resource to the task."
},
{
"code": null,
"e": 55637,
"s": 55351,
"text": "Click View Tab → Gantt Chart View → Resource Name column.\n\nClick the box below the Resource Name column for the task you need the resource to be assigned.\n\nFrom the dropdown, choose the resource name. In the following example,\n for Task 1 “PT1”, we have chosen the resource “Celic”.\n"
},
{
"code": null,
"e": 55702,
"s": 55637,
"text": "You can also select multiple resources to work on a single task."
},
{
"code": null,
"e": 55764,
"s": 55702,
"text": "Click View Tab → Resource Views group → Resource Usage view.\n"
},
{
"code": null,
"e": 55865,
"s": 55764,
"text": "In the following example, Trish Patrick is over allocated, the Resource Name and Work appear in red."
},
{
"code": null,
"e": 55915,
"s": 55865,
"text": "On View tab → Zoom group → Timescale box → Days.\n"
},
{
"code": null,
"e": 56062,
"s": 55915,
"text": "You can also right-click on the Time-phased grid in the right hand side window to display amount of overallocation by switching on overallocation."
},
{
"code": null,
"e": 56375,
"s": 56062,
"text": "Now you can reduce the assigned hours. In the following example, 8-hour assignment is reduced to 4-hour assignments. Not only is Trish Patrick’s work reduced but total work in the plan has changed. You will also notice a new icon in the indicator column to let you know that the assignment work has been edited."
},
{
"code": null,
"e": 56627,
"s": 56375,
"text": "You can decrease task duration (if no actual work has been entered) to reduce the amount of work required of the resource, who is assigned to complete the task. If actual work has been recorded, you must manually reduce the remaining work on the task."
},
{
"code": null,
"e": 56701,
"s": 56627,
"text": "You can just remove a resource assignment from an overallocated resource."
},
{
"code": null,
"e": 57074,
"s": 56701,
"text": "If resources are overallocated you can use resource-leveling feature in MS Project 2013. It works by either splitting tasks or by adding delay to tasks to ensure the resource is not overloaded. Leveling can delay the individual task finish dates and even the project finish date. Project does not change who is assigned to each task, total work, or assignment unit values."
},
{
"code": null,
"e": 57307,
"s": 57074,
"text": "Project first delays tasks to use up any available slack. Once the slack becomes zero, MS Project 2013 makes changes according to priorities, dependency relationships and task constraints (such as a Finish No Later Than constraint)."
},
{
"code": null,
"e": 57768,
"s": 57307,
"text": "It is always better to set task priorities (this is a measure of a task's importance/availability for leveling). You can enter value between 1 and 1000, according to the amount of control you like in the leveling process. A priority level of 1000 will ensure MS Project does not level a particular task. By default, priority is set at 500 or a medium level of control. Tasks that have lower priority are delayed or split before those that have higher priority."
},
{
"code": null,
"e": 57940,
"s": 57768,
"text": "Click View Tab → Task Views → Gantt chart View.\n\nIn the Gantt chart table area, scroll to the right to see Add New Column.\n\nClick on the dropdown box and select Priority.\n"
},
{
"code": null,
"e": 57991,
"s": 57940,
"text": "Now you can add priority to each task as required."
},
{
"code": null,
"e": 58121,
"s": 57991,
"text": "Steps in the Leveling process are only a few, but it is important to understand what each option does. The steps are as follows −"
},
{
"code": null,
"e": 58246,
"s": 58121,
"text": "Click on View Tab → Resource View group → Resource Sheet.\n\nClick Resource tab → Level group → Leveling Options → Level All.\n"
},
{
"code": null,
"e": 58376,
"s": 58246,
"text": "Project does leveling and overallocated indicators are removed (If leveling is done completely, sometimes this might not happen)."
},
{
"code": null,
"e": 58447,
"s": 58376,
"text": "In the following section, we will look at Leveling Options in detail −"
},
{
"code": null,
"e": 58501,
"s": 58447,
"text": "Click Resource tab → Level group → Leveling Options.\n"
},
{
"code": null,
"e": 58981,
"s": 58501,
"text": "In Resource Leveling dialog box, under Level calculations, try to use Manual more often. This will ensure MS Project 2013 does the leveling process only when you ask it to, and not as soon as a resource becomes overallocated even if you don’t want it to (when you choose Automatic option). For examples, if a resource is overallocated, for say half an hour more in a week, from 40 hours to 40.5 hours, you wouldn’t want this to inconvenience you by getting automatically leveled."
},
{
"code": null,
"e": 59237,
"s": 58981,
"text": "In Resource Leveling dialog box, under Level calculations, choose Day by Day basis for “Look for overallocations on a” option. Doing so will not level resources, but it will determine when Project displays overallocation indicators next to resource names."
},
{
"code": null,
"e": 59646,
"s": 59237,
"text": "In Resource Leveling dialog box, under Level calculations, use the clear leveling values before leveling checkbox is selected. Doing so will ensure Project removes any existing leveling delays from all tasks and assignments before leveling. And if you previously leveled the plan and then added more assignments, you might want checkbox to be unchecked to ensure you don’t lose the previous leveling results."
},
{
"code": null,
"e": 59863,
"s": 59646,
"text": "In Resource Leveling dialog box, under Leveling range for “.......”, you can choose Level entire project. Here you choose to level either the entire plan or only assignments that fall within a date range you specify."
},
{
"code": null,
"e": 60009,
"s": 59863,
"text": "In Resource Leveling dialog box, under Resolving overallocations, Leveling order dropdown box you can choose Standard. You have 3 options here −"
},
{
"code": null,
"e": 60265,
"s": 60009,
"text": "ID only option delays tasks only according to their ID numbers. Numerically higher ID numbers (for example, 10) will be delayed before numerically lower ID numbers. You might want to use this option when your plan has no task relationships or constraints."
},
{
"code": null,
"e": 60521,
"s": 60265,
"text": "ID only option delays tasks only according to their ID numbers. Numerically higher ID numbers (for example, 10) will be delayed before numerically lower ID numbers. You might want to use this option when your plan has no task relationships or constraints."
},
{
"code": null,
"e": 60647,
"s": 60521,
"text": "Standard option delays tasks according to predecessor relationships, start dates, task constraints, slack, priority, and IDs."
},
{
"code": null,
"e": 60773,
"s": 60647,
"text": "Standard option delays tasks according to predecessor relationships, start dates, task constraints, slack, priority, and IDs."
},
{
"code": null,
"e": 60924,
"s": 60773,
"text": "Priority, standard option looks at the task priority value before the other standard criteria (Task priority is a numeric ranking between 0 and 1000)."
},
{
"code": null,
"e": 61075,
"s": 60924,
"text": "Priority, standard option looks at the task priority value before the other standard criteria (Task priority is a numeric ranking between 0 and 1000)."
},
{
"code": null,
"e": 61220,
"s": 61075,
"text": "In Resource Leveling dialog box, under Resolving overallocations, you have several options that you can select. These are explained as follows −"
},
{
"code": null,
"e": 61486,
"s": 61220,
"text": "Level only within available slack. Selecting this checkbox would prevent Project from extending the plan’s finish date. MS Project will use only the free slack within the existing schedule, which could mean that resource overallocations might not be fully resolved."
},
{
"code": null,
"e": 61752,
"s": 61486,
"text": "Level only within available slack. Selecting this checkbox would prevent Project from extending the plan’s finish date. MS Project will use only the free slack within the existing schedule, which could mean that resource overallocations might not be fully resolved."
},
{
"code": null,
"e": 62101,
"s": 61752,
"text": "Leveling can adjust individual assignments. Selecting this checkbox allows Project to add a leveling delay (or split work on assignments if Leveling Can Create Splits in Remaining Work is also selected) independently of any other resources assigned to the same task. This might cause resources to start and finish work on a task at different times."
},
{
"code": null,
"e": 62450,
"s": 62101,
"text": "Leveling can adjust individual assignments. Selecting this checkbox allows Project to add a leveling delay (or split work on assignments if Leveling Can Create Splits in Remaining Work is also selected) independently of any other resources assigned to the same task. This might cause resources to start and finish work on a task at different times."
},
{
"code": null,
"e": 62682,
"s": 62450,
"text": "Leveling can create splits in remaining work checkbox. This allows Project to split work on a task (or on an assignment if Leveling Can Adjust Individual Assignments on a Task is also selected) as a way of resolving overallocation."
},
{
"code": null,
"e": 62914,
"s": 62682,
"text": "Leveling can create splits in remaining work checkbox. This allows Project to split work on a task (or on an assignment if Leveling Can Adjust Individual Assignments on a Task is also selected) as a way of resolving overallocation."
},
{
"code": null,
"e": 63061,
"s": 62914,
"text": "Level manually scheduled tasks. Selecting this allows Project to level a manually scheduled task just as it would an automatically scheduled task."
},
{
"code": null,
"e": 63208,
"s": 63061,
"text": "Level manually scheduled tasks. Selecting this allows Project to level a manually scheduled task just as it would an automatically scheduled task."
},
{
"code": null,
"e": 63257,
"s": 63208,
"text": "Types of cost in a project life cycle includes −"
},
{
"code": null,
"e": 63319,
"s": 63257,
"text": "Baseline costs − All planned costs as saved in baseline plan."
},
{
"code": null,
"e": 63381,
"s": 63319,
"text": "Baseline costs − All planned costs as saved in baseline plan."
},
{
"code": null,
"e": 63463,
"s": 63381,
"text": "Actual costs − Costs that have been incurred for tasks, resources or assignments."
},
{
"code": null,
"e": 63545,
"s": 63463,
"text": "Actual costs − Costs that have been incurred for tasks, resources or assignments."
},
{
"code": null,
"e": 63623,
"s": 63545,
"text": "Remaining costs − Difference between baseline/current costs and actual costs."
},
{
"code": null,
"e": 63701,
"s": 63623,
"text": "Remaining costs − Difference between baseline/current costs and actual costs."
},
{
"code": null,
"e": 64015,
"s": 63701,
"text": "Current costs − When plans are changed due to assigning or removing resources, or adding or subtracting tasks, MS Project 2013 will recalculate all costs. This will appear under the fields labeled Cost or Total Cost. If you have started to track actual cost, it will include actual cost + remaining cost per task."
},
{
"code": null,
"e": 64329,
"s": 64015,
"text": "Current costs − When plans are changed due to assigning or removing resources, or adding or subtracting tasks, MS Project 2013 will recalculate all costs. This will appear under the fields labeled Cost or Total Cost. If you have started to track actual cost, it will include actual cost + remaining cost per task."
},
{
"code": null,
"e": 64399,
"s": 64329,
"text": "You can view plan’s cost values in the Project Statistics dialog box."
},
{
"code": null,
"e": 64475,
"s": 64399,
"text": "Click Project tab → Properties Group → Project Information → Statistics...\n"
},
{
"code": null,
"e": 64584,
"s": 64475,
"text": "Click View tab → Task Views group → Other Views → Task Sheet.\n\nClick View tab → Data group → Tables → Cost.\n"
},
{
"code": null,
"e": 64828,
"s": 64584,
"text": "After creating a project plan and baselines, the project begins. At this stage, the project manager would be focusing on collecting, monitoring, analyzing project performance, and updating project status by communicating with the stakeholders."
},
{
"code": null,
"e": 64995,
"s": 64828,
"text": "When there is a difference between what is planned and the actual project performance, it is called a Variance. Variance is mostly measured in terms of Time and Cost."
},
{
"code": null,
"e": 65046,
"s": 64995,
"text": "There are several ways to view task with variance."
},
{
"code": null,
"e": 65122,
"s": 65046,
"text": "Click View tab → Task Views group → Gantt Chart dropdown → Tracking Gantt.\n"
},
{
"code": null,
"e": 65274,
"s": 65122,
"text": "By comparing the currently scheduled Gantt bars with baseline Gantt bars, you can see what tasks started later than planned or took longer to complete."
},
{
"code": null,
"e": 65354,
"s": 65274,
"text": "Click View tab → Task Views group → Other Views → double-click Tracking Gantt.\n"
},
{
"code": null,
"e": 65404,
"s": 65354,
"text": "Click View tab → Data group → Tables → Variance.\n"
},
{
"code": null,
"e": 65513,
"s": 65404,
"text": "Click View tab → Data group → Filters → More \n Filters → choose filter as Late tasks, Slipping task, etc.\n"
},
{
"code": null,
"e": 65726,
"s": 65513,
"text": "MS Project 2013 will filter the task list to show only the tasks filtered in this process. So if you select Slipping Task, you will view only incomplete tasks. Any task that is already completed will not show up."
},
{
"code": null,
"e": 65842,
"s": 65726,
"text": "To examine cost in a project life cycle, you should be aware of these terms and what they mean in MS Project 2013 −"
},
{
"code": null,
"e": 65904,
"s": 65842,
"text": "Baseline costs − All planned costs as saved in baseline plan."
},
{
"code": null,
"e": 65966,
"s": 65904,
"text": "Baseline costs − All planned costs as saved in baseline plan."
},
{
"code": null,
"e": 66049,
"s": 65966,
"text": "Actual costs − Costs that have been incurred for tasks, resources, or assignments."
},
{
"code": null,
"e": 66132,
"s": 66049,
"text": "Actual costs − Costs that have been incurred for tasks, resources, or assignments."
},
{
"code": null,
"e": 66210,
"s": 66132,
"text": "Remaining costs − Difference between baseline/current costs and actual costs."
},
{
"code": null,
"e": 66288,
"s": 66210,
"text": "Remaining costs − Difference between baseline/current costs and actual costs."
},
{
"code": null,
"e": 66620,
"s": 66288,
"text": "Current costs − When plans are changed due to assigning or removing resources, or adding or subtracting tasks, MS Project 2013 will recalculate all costs. This will appear under the fields labeled Cost or Total Cost. If you have started to track actual cost, it will include actual cost+ remaining cost (uncompleted task) per task."
},
{
"code": null,
"e": 66952,
"s": 66620,
"text": "Current costs − When plans are changed due to assigning or removing resources, or adding or subtracting tasks, MS Project 2013 will recalculate all costs. This will appear under the fields labeled Cost or Total Cost. If you have started to track actual cost, it will include actual cost+ remaining cost (uncompleted task) per task."
},
{
"code": null,
"e": 67044,
"s": 66952,
"text": "Variance − Difference between Baseline Cost and the Total Cost (current or scheduled cost)."
},
{
"code": null,
"e": 67136,
"s": 67044,
"text": "Variance − Difference between Baseline Cost and the Total Cost (current or scheduled cost)."
},
{
"code": null,
"e": 67182,
"s": 67136,
"text": "Click View Tab → Data group → Tables → Cost.\n"
},
{
"code": null,
"e": 67298,
"s": 67182,
"text": "You will be able to view all relevant information. You can also use filters to see tasks that have run over budget."
},
{
"code": null,
"e": 67379,
"s": 67298,
"text": "Click View tab → Data group → Filters → More Filters → Cost Overbudget → Apply.\n"
},
{
"code": null,
"e": 67504,
"s": 67379,
"text": "For some organizations, resources costs are primary costs, and sometimes the only cost, so these need to be closely watched."
},
{
"code": null,
"e": 67607,
"s": 67504,
"text": "Click View tab → Resource Views group → Resource Sheet.\n\nClick View tab → Data group → Tables → Cost.\n"
},
{
"code": null,
"e": 67689,
"s": 67607,
"text": "We can sort the Cost column to see which resources are the most and least costly."
},
{
"code": null,
"e": 67808,
"s": 67689,
"text": "Click the AutoFilter arrow in Cost column heading, when the drop-down menu appears, click on Sort Largest to Smallest."
},
{
"code": null,
"e": 67942,
"s": 67808,
"text": "You can use the AutoFilter feature for each of the columns, By sorting Variance column, you will be able to see the variance pattern."
},
{
"code": null,
"e": 68127,
"s": 67942,
"text": "Project 2013 comes with a set of predefined reports and dashboards. You’ll find all of these on the Report tab. You can create and customize graphical reports for your project as well."
},
{
"code": null,
"e": 68176,
"s": 68127,
"text": "Click Report → View Reports group → Dashboards.\n"
},
{
"code": null,
"e": 68224,
"s": 68176,
"text": "Click Report → View Reports group → Resources.\n"
},
{
"code": null,
"e": 68268,
"s": 68224,
"text": "Click Report → View Reports group → Costs.\n"
},
{
"code": null,
"e": 68318,
"s": 68268,
"text": "Click Report → View Reports group → In Progress.\n"
},
{
"code": null,
"e": 68367,
"s": 68318,
"text": "Click Report → View Reports group → New Report.\n"
},
{
"code": null,
"e": 68391,
"s": 68367,
"text": "There are four options."
},
{
"code": null,
"e": 68498,
"s": 68391,
"text": "Blank − Creates a blank canvas. Use the Report Tools - Design tab to add charts, tables, text, and images."
},
{
"code": null,
"e": 68605,
"s": 68498,
"text": "Blank − Creates a blank canvas. Use the Report Tools - Design tab to add charts, tables, text, and images."
},
{
"code": null,
"e": 68845,
"s": 68605,
"text": "Chart − Creates a chart comparing Actual Work, Remaining Work, and Work by default. Use the Field List pane to pick different fields to compare. The look of the chart can be changed by clicking on Chart Tools tabs, Design, and Layout tabs."
},
{
"code": null,
"e": 69085,
"s": 68845,
"text": "Chart − Creates a chart comparing Actual Work, Remaining Work, and Work by default. Use the Field List pane to pick different fields to compare. The look of the chart can be changed by clicking on Chart Tools tabs, Design, and Layout tabs."
},
{
"code": null,
"e": 69428,
"s": 69085,
"text": "Table − Creates a table. Use the Field List pane to choose what fields to display in the table (Name, Start, Finish, and % Complete appear by default). Outline level box lets you select how many levels in the project outline the table should show. The look of the table can be changed by clicking on Table Tools tabs, Design, and Layout tabs."
},
{
"code": null,
"e": 69771,
"s": 69428,
"text": "Table − Creates a table. Use the Field List pane to choose what fields to display in the table (Name, Start, Finish, and % Complete appear by default). Outline level box lets you select how many levels in the project outline the table should show. The look of the table can be changed by clicking on Table Tools tabs, Design, and Layout tabs."
},
{
"code": null,
"e": 69971,
"s": 69771,
"text": "Comparison − Creates two charts side-by-side. Charts will have the same data at first. You can click one of the charts and pick the data you want in the Field List pane to begin differentiating them."
},
{
"code": null,
"e": 70171,
"s": 69971,
"text": "Comparison − Creates two charts side-by-side. Charts will have the same data at first. You can click one of the charts and pick the data you want in the Field List pane to begin differentiating them."
},
{
"code": null,
"e": 70206,
"s": 70171,
"text": "\n 32 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 70221,
"s": 70206,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 70256,
"s": 70221,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 70275,
"s": 70256,
"text": " Dr. Saatya Prasad"
},
{
"code": null,
"e": 70310,
"s": 70275,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 70325,
"s": 70310,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 70358,
"s": 70325,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 70373,
"s": 70358,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 70408,
"s": 70373,
"text": "\n 239 Lectures \n 33 hours \n"
},
{
"code": null,
"e": 70425,
"s": 70408,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 70458,
"s": 70425,
"text": "\n 53 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 70472,
"s": 70458,
"text": " Akshay Magre"
},
{
"code": null,
"e": 70479,
"s": 70472,
"text": " Print"
},
{
"code": null,
"e": 70490,
"s": 70479,
"text": " Add Notes"
}
] |
Write a Java program to capitalize each word in the string? | You can capitalize words in a string using the toUpperCase() method of the String class. This method converts the contents of the current string to Upper case letters.
Live Demo
public class StringToUpperCaseEmp {
public static void main(String[] args) {
String str = "string abc touppercase ";
String strUpper = str.toUpperCase();
System.out.println("Original String: " + str);
System.out.println("String changed to upper case: " + strUpper);
}
}
Original String: string abc touppercase
String changed to upper case: STRING ABC TOUPPERCASE | [
{
"code": null,
"e": 1230,
"s": 1062,
"text": "You can capitalize words in a string using the toUpperCase() method of the String class. This method converts the contents of the current string to Upper case letters."
},
{
"code": null,
"e": 1241,
"s": 1230,
"text": " Live Demo"
},
{
"code": null,
"e": 1541,
"s": 1241,
"text": "public class StringToUpperCaseEmp {\n public static void main(String[] args) {\n String str = \"string abc touppercase \";\n String strUpper = str.toUpperCase();\n System.out.println(\"Original String: \" + str);\n System.out.println(\"String changed to upper case: \" + strUpper);\n }\n}"
},
{
"code": null,
"e": 1634,
"s": 1541,
"text": "Original String: string abc touppercase\nString changed to upper case: STRING ABC TOUPPERCASE"
}
] |
Aurelia - Quick Guide | The best definition of the framework can be found in Aurelia official docs −
Well, it's actually simple. Aurelia is just JavaScript. However, it's not yesterday's JavaScript, but the JavaScript of tomorrow. By using modern tooling we've been able to write Aurelia from the ground up in ECMAScript 2016. This means we have native modules, classes, decorators and more at our disposal...and you have them too.
Not only is Aurelia written in modern and future JavaScript, but it also takes a modern approach to architecture. In the past, frameworks have been monolithic beasts. Not Aurelia though. It's built as a series of collaborating libraries. Taken together, they form a powerful and robust framework for building Single Page Apps (SPAs). However, Aurelia's libraries can often be used individually, in traditional web sites or even on the server-side through technologies such as NodeJS.
Components − Components are building blocks of Aurelia framework. It is composed of HTML view and JavaScript view-model pairs.
Components − Components are building blocks of Aurelia framework. It is composed of HTML view and JavaScript view-model pairs.
Web Standards − This is one of the cleanest modern frameworks, completely focused on web standards without unnecessary abstractions.
Web Standards − This is one of the cleanest modern frameworks, completely focused on web standards without unnecessary abstractions.
Extensible − The framework offers an easy way to integrate with the other needed tools.
Extensible − The framework offers an easy way to integrate with the other needed tools.
Commercial Support − Aurelia offers commercial and enterprise support. It is an official product of Durandal Inc.
Commercial Support − Aurelia offers commercial and enterprise support. It is an official product of Durandal Inc.
License − Aurelia is open sourced and licensed under MIT license.
License − Aurelia is open sourced and licensed under MIT license.
Aurelia is very clean. If you follow the frameworks conventions, you can focus on your app without the framework getting in your way.
Aurelia is very clean. If you follow the frameworks conventions, you can focus on your app without the framework getting in your way.
It is also easily extensible. You can add or remove any tools that the framework offers and you can also add any other tools that aren't part of the framework.
It is also easily extensible. You can add or remove any tools that the framework offers and you can also add any other tools that aren't part of the framework.
Aurelia is very easy to work with. It is directed towards developers’ experience. It saves you lots of time.
Aurelia is very easy to work with. It is directed towards developers’ experience. It saves you lots of time.
The framework itself is directed towards web standards so you will always stay up to date with modern concepts.
The framework itself is directed towards web standards so you will always stay up to date with modern concepts.
Aurelia doesn’t have the largest community out there, but it is very agile, knowledgeable and willing to help within short notice.
Aurelia doesn’t have the largest community out there, but it is very agile, knowledgeable and willing to help within short notice.
There are no major limitations. The Framework is powerful and easy to work with.
There are no major limitations. The Framework is powerful and easy to work with.
In this chapter, you will learn how to get started with Aurelia framework. Before you do that, you will need NodeJS installed on your system.
NodeJS and NPM
NodeJS is the platform needed for Aurelia development. Checkout our NodeJS Environment Setup.
Before we download Aurelia package, let's create a folder on desktop where our app will be placed.
C:\Users\username\Desktop>mkdir aureliaApp
Now we can download the package from official Aurelia website.
Aurelia supports ES2016 and TypeScript. We will use ES2016. Extract the downloaded files inside the aureliaApp folder that we created above.
First we need to install the web server from command prompt window.
C:\Users\username\Desktop\aureliaApp>npm install http-server -g
To start the web server, we need to run the following code in command prompt.
C:\Users\username\Desktop\aureliaApp>http-server -o -c-1
We can see our first Aurelia app in the browser.
In this chapter, we will explain Aurelia starting app created in our last chapter. We will also guide you through the folder structure, so you can grasp the core concepts behind Aurelia framework.
package.json represents documentation about npm packages installed. It also shows the version of those packages and provides an easy way to add, delete, change version or automatically install all packages when the app needs to be shared between developers.
package.json represents documentation about npm packages installed. It also shows the version of those packages and provides an easy way to add, delete, change version or automatically install all packages when the app needs to be shared between developers.
index.html is the default page of the app like in most of the HTML based apps. It is a place where scripts and stylesheets are loaded.
index.html is the default page of the app like in most of the HTML based apps. It is a place where scripts and stylesheets are loaded.
config.js is Aurelia loader configuration file. You will not spend much time working with this file.
config.js is Aurelia loader configuration file. You will not spend much time working with this file.
jspm_packages is the directory for the SystemJS loaded modules.
jspm_packages is the directory for the SystemJS loaded modules.
styles is the default styling directory. You can always change the place where you keep your styling files.
styles is the default styling directory. You can always change the place where you keep your styling files.
src folder is a place where you will spend most of your development time. It keeps HTML and js files.
src folder is a place where you will spend most of your development time. It keeps HTML and js files.
As we already stated, the src directory is the place where your app logic will be held. If you look at the default app you can see that app.js and app.html are very simple.
Aurelia allows us to use JavaScript core language for class definitions. Following default example shows EC6 class.
export class App {
message = 'Welcome to Aurelia!';
}
The message property is bound to the HTML template using ${message}syntax. This syntax represents one-way binding converted into string and showed inside the template view.
<template>
<h1>${message}</h1>
</template>
As we already discussed in the last chapter, we can start the server by running the following command in the command prompt window.
C:\Users\username\Desktop\aureliaApp>http-server -o -c-1
Application will be rendered on the screen.
Components are the main building blocks of Aurelia framework. In this chapter, you will learn how to create simple components.
As already discussed in the previous chapter, each component contains view-model which is written in JavaScript, and view written in HTML. You can see the following view-model definition. It is an ES6 example but you can also use TypeScript.
export class MyComponent {
header = "This is Header";
content = "This is content";
}
We can bind our values to the view as shown in the following example. ${header}syntax will bind the defined header value from MyComponent. The same concept is applied for content.
<template>
<h1>${header}</h1>
<p>${content}</p>
</template>
The above code will produce the following output.
If you want to update the header and footer when the user clicks the button, you can use the following example. This time we are defining header and footer inside EC6 class constructor.
export class App{
constructor() {
this.header = 'This is Header';
this.content = 'This is content';
}
updateContent() {
this.header = 'This is NEW header...'
this.content = 'This is NEW content...';
}
}
We can add click.delegate() to connect updateContent() function with the button. More on this in one of our subsequent chapters.
<template>
<h1>${header}</h1>
<p>${content}</p>
<button click.delegate = "updateContent()">Update Content</button>
</template>
When the button is clicked, the header and content will be updated.
Aurelia uses component lifecycle methods to manipulate the component lifecycle. In this chapter, we will show you those methods and explain the component lifecycle.
constructor() − Constructor method is used for initializing an object created with a class. This method is called first. If you don't specify this method, the default constructor will be used.
constructor() − Constructor method is used for initializing an object created with a class. This method is called first. If you don't specify this method, the default constructor will be used.
created(owningView, myView) − This is called once the view and view-model are created and connected to the controller. This method takes two arguments. The first one is the view where the component is declared (owningView). The second one is the component view (myView).
created(owningView, myView) − This is called once the view and view-model are created and connected to the controller. This method takes two arguments. The first one is the view where the component is declared (owningView). The second one is the component view (myView).
bind(bindingContext, overrideContext) − At this point of time, the binding has started. The first argument represents the binding context of the component. The second one is overrideContext. This argument is used for adding additional contextual properties.
bind(bindingContext, overrideContext) − At this point of time, the binding has started. The first argument represents the binding context of the component. The second one is overrideContext. This argument is used for adding additional contextual properties.
attached() − Attached method is invoked once the component is attached to the DOM.
attached() − Attached method is invoked once the component is attached to the DOM.
detached() − This method is opposite to attached. It is invoked when the component is removed from the DOM.
detached() − This method is opposite to attached. It is invoked when the component is removed from the DOM.
unbind() − The last lifecycle method is unbind. It is called when the component is unbound.
unbind() − The last lifecycle method is unbind. It is called when the component is unbound.
The lifecycle methods are useful when you want to have higher control over your component. You can use them when you need to trigger some functionalities at certain point of component lifecycle.
All lifecycle methods are shown below.
export class App {
constructor(argument) {
// Create and initialize your class object here...
}
created(owningView, myView) {
// Invoked once the component is created...
}
bind(bindingContext, overrideContext) {
// Invoked once the databinding is activated...
}
attached(argument) {
// Invoked once the component is attached to the DOM...
}
detached(argument) {
// Invoked when component is detached from the dom
}
unbind(argument) {
// Invoked when component is unbound...
}
}
Aurelia offers a way to add components dynamically. You can reuse a single component on different parts of your app without the need to include HTML multiple times. In this chapter, you will learn how to achieve this.
Let's create new components directory inside src folder.
C:\Users\username\Desktop\aureliaApp\src>mkdir components
Inside this directory, we will create custom-component.html. This component will be inserted later in the HTML page.
<template>
<p>This is some text from dynamic component...</p>
</template>
We will create simple component in app.js. It will be used to render header and footer text on screen.
export class MyComponent {
header = "This is Header";
content = "This is content";
}
Inside our app.html file, we need to require the custom-component.html to be able to insert it dynamically. Once we do that, we can add a new element custom-component.
<template>
<require from = "./components/custom-component.html"></require>
<h1>${header}</h1>
<p>${content}</p>
<custom-component></custom-component>
</template>
Following is the output. Header and Footer text is rendered from myComponent inside app.js. The additional text is rendered from the custom-component.js.
In this chapter, you will learn how to use Aurelia dependency injection library.
First, we need to create new file dependency-test.js inside src folder. In this file, we will create a simple class DependencyTest. This class will be later injected as a dependency.
export class DependencyTest {
constructor() {
this.test = "Test is succesfull!!!";
}
}
In our app.js file, we are importing inject library and DependencyTest class that we created above. To inject the class we are using @inject() function. Our App class will just log it to the developer console.
import {inject} from 'aurelia-framework';
import {DependencyTest} from './dependency-test';
@inject(DependencyTest)
export class App {
constructor(DependencyTest) {
console.log(DependencyTest);
}
}
We can check the console to see that the DependencyTest class is injected.
There will more examples of Aurelia dependency injection in the next chapters.
In this chapter, we will show you how to configure Aurelia framework for your needs. Sometimes you will need to set an initial configuration or run some code before the app is rendered to the users.
Let's create main.js file inside src folder. Inside this file we will configure Aurelia.
You also need to tell Aurelia to load configuration module. You can see the commented part in the following example.
<!DOCTYPE html>
<html>
<head>
<title>Aurelia</title>
<link rel = "stylesheet" href = "styles/styles.css">
<meta name = "viewport" content = "width=device-width, initial-scale = 1">
</head>
<body aurelia-app = "main">
<!--Add "main" value to "aurelia-app" attribute... -->
<script src = "jspm_packages/system.js"></script>
<script src = "config.js"></script>
<script>
SystemJS.import('aurelia-bootstrapper');
</script>
</body>
</html>
The code below shows how to use default configuration. configure function allows to set the configuration manually. We are setting use property to specify what we need.
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging();
aurelia.start().then(() => aurelia.setRoot());
}
There are lots of configuration options we could use. It is out of the scope of this article to show you all of it so we will explain how the configuration works on the following example. We are basically telling Aurelia to use default data binding language, default resources, development logging, router, history and event aggregator. These are standard set of plugins.
export function configure(aurelia) {
aurelia.use
.defaultBindingLanguage()
.defaultResources()
.developmentLogging()
.router()
.history()
.eventAggregator();
aurelia.start().then(() => aurelia.setRoot());
}
Note − These settings will be explained in detail in the next chapter.
When you start building your app, most of the time you will want to use some additional plugins. In this chapter, you will learn how to use plugins in Aurelia framework.
In the last chapter, we saw how to use default configuration in Aurelia framework. If you are using default configuration, standard set of plugins will be available.
defaultBindingLanguage() − This plugin offers an easy way to connect view-model with view. You already saw one-way data-binding syntax (${someValue}). Even though you could use some other binding language, it is a recommended practice to use default binding language.
defaultBindingLanguage() − This plugin offers an easy way to connect view-model with view. You already saw one-way data-binding syntax (${someValue}). Even though you could use some other binding language, it is a recommended practice to use default binding language.
defaultResources() − Default resources give us some primitive constructs such as if, repeat, compose, etc. You can even build these constructs on your own, but since they are so commonly used, Aurelia already created it inside this library.
defaultResources() − Default resources give us some primitive constructs such as if, repeat, compose, etc. You can even build these constructs on your own, but since they are so commonly used, Aurelia already created it inside this library.
Router() − Most of the applications use some kind of routing. Hence, Router is a part of the standard plugins. You can check more about routing in a subsequent chapter.
Router() − Most of the applications use some kind of routing. Hence, Router is a part of the standard plugins. You can check more about routing in a subsequent chapter.
History() − History plugin is usually used together with router.
History() − History plugin is usually used together with router.
eventAggregator() − This plugin is used for cross-component communication. It handles publishing and subscribing to messages or channels inside your app.
eventAggregator() − This plugin is used for cross-component communication. It handles publishing and subscribing to messages or channels inside your app.
These plugins aren't part of the default configuration but are frequently used.
fetch() − Fetch plugin is used for handling HTTP requests. You can use some other AJAX library if you want.
fetch() − Fetch plugin is used for handling HTTP requests. You can use some other AJAX library if you want.
animatorCSS() − This plugin offers a way of handling CSS animations.
animatorCSS() − This plugin offers a way of handling CSS animations.
animator-velocity() − Instead of CSS animations, you can use Velocity animation library. These plugins enable us to use Velocity inside Aurelia apps.
animator-velocity() − Instead of CSS animations, you can use Velocity animation library. These plugins enable us to use Velocity inside Aurelia apps.
dialog() − Dialog plugin offers a highly customizable modal window.
dialog() − Dialog plugin offers a highly customizable modal window.
i18n() − This is the plugin for internalization and localization.
i18n() − This is the plugin for internalization and localization.
ui-virtualization() − Virtualization is a useful library for handling large performance heavy UI tasks.
ui-virtualization() − Virtualization is a useful library for handling large performance heavy UI tasks.
validation() − Use this plugin when you need to validate your data.
validation() − Use this plugin when you need to validate your data.
All plugins explained above are officially maintained by the Aurelia Core Team at the moment of writing this tutorial. There will be some other useful plugins added in future. Following example shows how to configure your app to use plugins.
If, for example, we want to use animator-css and animator-velocity, we need to install it first.
C:\Users\username\Desktop\aureliaApp>jspm install aurelia-animator-css
C:\Users\username\Desktop\aureliaApp>jspm install aurelia-animator-velocity
In the last chapter, you learnt how to use manual configuration. We can add our plugins in main.js file.
export function configure(aurelia) {
aurelia.use
.defaultBindingLanguage()
.defaultResources()
.developmentLogging()
.router()
.history()
.eventAggregator()
.plugin('aurelia-animatorCSS')
.plugin('aurelia-animator-velocity')
aurelia.start().then(() => aurelia.setRoot());
}
Aurelia has its own data-binding system. In this chapter, you will learn how to bind data with Aurelia, and also explain the different binding mechanics.
You already saw simple binding in some of our previous chapters. ${...}syntax is used to link veiw-model and view.
export class App {
constructor() {
this.myData = 'Welcome to Aurelia app!';
}
}
<template>
<h3>${myData}</h3>
</template>
The beauty of Aurelia is in its simplicity. The two-way data binding is automatically set, when we bind to input fields
export class App {
constructor() {
this.myData = 'Enter some text!';
}
}
<template>
<input id = "name" type = "text" value.bind = "myData" />
<h3>${myData}</h3>
</template>
Now, we have our view-model and view linked. Whenever we enter some text inside the input field, the view will be updated.
In this chapter, you will learn how to use behaviors. You can think of binding behavior as a filter that can change the binding data and display it in a different format.
This behavior is used to set how often should some binding update take place. We can use throttle to slow down the rate of updating input view-model. Consider the example from the last chapter. The default rate is 200 ms. We can change that to 2 sec by adding & throttle:2000 to our input.
export class App {
constructor() {
this.myData = 'Enter some text!';
}
}
<template>
<input id = "name" type = "text" value.bind = "myData & throttle:2000" />
<h3>${myData}</h3>
</template>
debounce is almost the same as throttle. The difference being, debounce will update the binding after the user has stopped typing. The following example will update the binding if the user stops typing for two seconds.
export class App {
constructor() {
this.myData = 'Enter some text!';
}
}
<template>
<input id = "name" type = "text" value.bind = "myData & debounce:2000" />
<h3>${myData}</h3>
</template>
oneTime is the most efficient behavior performance wise. You should always use it when you know that data should be bound only once.
export class App {
constructor() {
this.myData = 'Enter some text!';
}
}
<template>
<input id = "name" type = "text" value.bind = "myData & oneTime" />
<h3>${myData}</h3>
</template>
The above example will bind the text to the view. However, if we change the default text, nothing will happen since it is bound only once.
If you need to convert some values in Aurelia app, you can use converters instead of manually converting values to a desired format.
When we want to convert the default date value to some specific format, we can use momentJS library. This is a small library used for manipulating dates.
C:\Users\username\Desktop\aureliaApp>jspm install moment
Let's create a new file converters.js. We will use this file to add converter specific code. Use the following command or create the file manually.
C:\Users\username\Desktop\aureliaApp>touch converters.js
Inside this file, we will import moment library and set DateFormatValueConverter to return only month, day and year values without additional data. Important thing to note is that Aurelia can recognize any class that ends with ValueConverter. This is why our class name is DateFormatValueConverter. This class will be registered as dateFormat and we can later use it inside view.
import moment from 'moment';
export class DateFormatValueConverter {
toView(value) {
return moment(value).format('M/D/YYYY');
}
}
In app.js, we will just use the current date. This will be our view-model.
export class App {
constructor() {
this.currentDate = new Date();
}
}
We already discussed require in custom-elements chapter. The pipe symbol | is used to apply the converter. We are only using dateFormat since this is how Aurelia is registering DateFormatValueConverter.
<template>
<require from = "./converters"></require>
<h3>${currentDate | dateFormat}</h3>
</template>
This is an example of currency formatting. You will notice that the concept is the same as in the above example. First, we need to install numeral library from the command prompt.
C:\Users\username\Desktop\aureliaApp>jspm install numeral
The Converter will set the currency format.
import numeral from 'numeral';
export class CurrencyFormatValueConverter {
toView(value) {
return numeral(value).format('($0,0.00)');
}
}
View-model will just generate a random number. We will use this as currency value and update it every second.
export class App {
constructor() {
this.update();
setInterval(() => this.update(), 1000);
}
update() {
this.myCurrency = Math.random() * 1000;
}
}
Our view will show the randomly generated number transformed as a currency.
<template>
<require from = "./converters"></require>
<h3>${myCurrency | currencyFormat}</h3>
</template>
In this chapter, you will learn about Aurelia events.
Even delegation is a useful concept where the event handler is attached to one top level element instead of multiple elements on the DOM. This will improve the application memory efficiency and should be used whenever possible.
This is a simple example of using event delegation with Aurelia framework. Our view will have a button with click.delegate event attached.
<template>
<button click.delegate = "myFunction()">CLICK ME</button>
</template>
Once the button is clicked, myFunction() will be called.
export class App {
myFunction() {
console.log('The function is triggered...');
}
}
We will get the following output.
There are some cases when you can't use delegation. Some JavaScript events don’t support delegation; IOS supports it for some elements. To find out which events allow delegation, you can search for a bubble property of any event here. In these cases, you can use trigger() method.
The same functionality from the above example can be created with click.trigger.
<template>
<button click.trigger = "myFunction()">CLICK ME</button>
</template>
export class App {
myFunction() {
console.log('The function is triggered...');
}
}
Event aggregator should be used when your events need to be attached to more listeners or when you need to observe some functionality of your app and wait for the data update.
Aurelia event aggregator has three methods. The publish method will fire off events and can be used by multiple subscribers. For subscribing to an event, we can use the subscribe method. And finally, we can use the dispose method to detach the subscribers. The following example demonstrates this.
Our view will just have three buttons for each of the three functionalities.
<template>
<button click.delegate = "publish()">PUBLISH</button><br/>
<button click.delegate = "subscribe()">SUBSCRIBE</button><br/>
<button click.delegate = "dispose()">DISPOSE</button>
</template>
We need to import eventAggregator and inject it before we are able to use it.
import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';
@inject(EventAggregator)
export class App {
constructor(eventAggregator) {
this.eventAggregator = eventAggregator;
}
publish() {
var payload = 'This is some data...';
this.eventAggregator.publish('myEventName', payload);
}
subscribe() {
this.subscriber = this.eventAggregator.subscribe('myEventName', payload => {
console.log(payload);
});
}
dispose() {
this.subscriber.dispose();
console.log('Disposed!!!');
}
}
We need to click the SUBSCRIBE button to listen for data that will be published in future. Once the subscriber is attached, whenever new data is sent, the console will log it. If we click the PUBLISH button five times, we will see that it is logged every time.
We can also detach our subscriber by clicking the DISPOSE button.
In this chapter, you will learn how to use forms in Aurelia framework.
First, we will see how to submit an input form. The view will have two input forms for username and password. We will use value.bind for data binding.
<template>
<form role = "form" submit.delegate = "signup()">
<label for = "email">Email</label>
<input type = "text" value.bind = "email" placeholder = "Email">
<label for = "password">Password</label>
<input type = "password" value.bind = "password" placeholder = "Password">
<button type = "submit">Signup</button>
</form>
</template>
The signup function will just take the username and password values from the inputs and log it in the developer’s console.
export class App {
email = '';
password = '';
signup() {
var myUser = { email: this.email, password: this.password }
console.log(myUser);
};
}
The following example will demonstrate how to submit a checkbox with Aurelia framework. We will create one checkbox and bind the checked value to our view-model.
<template>
<form role = "form" submit.delegate = "submit()">
<label for = "checkbox">Checkbox</label>
<input type = "checkbox" id = "checkbox" checked.bind = "isChecked"><br/>
<button type = "submit">SUBMIT</button>
</form>
</template>
Form submitting will just log the checked value in the console.
export class App {
constructor() {
this.isChecked = false;
}
submit() {
console.log("isChecked: " + this.isChecked);
}
}
The following example will demonstrate how to submit radio buttons. The syntax repeat.for = "option of options" will repeat through an array of objects and create a radio button for each object. This is a neat way of dynamically creating elements in Aurelia framework. Rest is the same as in the previous examples. We are binding the model and the checked values.
<template>
<form role = "form" submit.delegate = "submit()">
<label repeat.for = "option of options">
<input type = "radio" name = "myOptions"
model.bind = "option" checked.bind = "$parent.selectedOption"/>
${option.text}
</label>
<br/>
<button type = "submit">SUBMIT</button>
</form>
</template>
In our view-model, we will create an array of objects this.options and specify that the first radio button is checked. Again, the SUBMIT button will just log in the console which radio button is checked.
export class PeriodPanel {
options = [];
selectedOption = {};
constructor() {
this.options = [
{id:1, text:'First'},
{id:2, text:'Second'},
{id:3, text:'Third'}
];
this.selectedOption = this.options[0];
}
submit() {
console.log('checked: ' + this.selectedOption.id);
}
}
If we check the third radio button and submit our form, the console will show it.
In this chapter, you will learn how to work with HTTP requests in Aurelia framework.
Let's create four buttons that will be used for sending requests to our API.
<template>
<button click.delegate = "getData()">GET</button>
<button click.delegate = "postData()">POST</button>
<button click.delegate = "updateData()">PUT</button>
<button click.delegate = "deleteData()">DEL</button>
</template>
For sending requests to the server, Aurelia recommends fetch client. We are creating functions for every requests we need (GET, POST, PUT and DELETE).
import 'fetch';
import {HttpClient, json} from 'aurelia-fetch-client';
let httpClient = new HttpClient();
export class App {
getData() {
httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => {
console.log(data);
});
}
myPostData = {
id: 101
}
postData(myPostData) {
httpClient.fetch('http://jsonplaceholder.typicode.com/posts', {
method: "POST",
body: JSON.stringify(myPostData)
})
.then(response => response.json())
.then(data => {
console.log(data);
});
}
myUpdateData = {
id: 1
}
updateData(myUpdateData) {
httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1', {
method: "PUT",
body: JSON.stringify(myUpdateData)
})
.then(response => response.json())
.then(data => {
console.log(data);
});
}
deleteData() {
httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1', {
method: "DELETE"
})
.then(response => response.json())
.then(data => {
console.log(data);
});
}
}
We can run the app and click GET, POST, PUT and DEL buttons, respectively. We can see in the console that every request is successful, and the result is logged.
In this chapter, you will see some simple examples of Aurelia refs. You can use it to create a reference to a particular object. You can create a reference to elements or attributes, as seen in the following table.
ref = "myRef"
Used for creating a reference to DOM element.
attribute-name.ref = "myRef"
Used for creating a reference to custom attribute's view-model.
view-model.ref = "myRef
Used for creating a reference to custom element's view-model.
view.ref = "myRef"
Used for creating a reference to custom elements view instance.
rcontroller.ref = "myRef"
Used for creating a reference to custom element's controller instance.
In the following example, we will create a reference to the input element. We will use the default class syntax as a view-model.
export class App { }
We are creating a reference to the input element by adding the ref = "name" attribute.
<template>
<input type = "text" ref = "name"><br/>
<h3>${name.value}</h3>
</template>
When we run the app, we will see that the text entered into the input field is rendered on the screen.
Routing is an important part of every application. In this chapter, you will learn how to use the router in Aurelia framework.
We have already created a components folder in one of the former chapters. If you don't have it created already, you should place it inside the src folder.
C:\Users\username\Desktop\aureliaApp\src>mkdir components
Inside this folder, we will create home and about directories.
C:\Users\username\Desktop\aureliaApp\src\components>mkdir home
C:\Users\username\Desktop\aureliaApp\src\components>mkdir about
Inside the home folder, we need to create view and view-model files.
C:\Users\username\Desktop\aureliaApp\src\components\home>touch home.js
C:\Users\username\Desktop\aureliaApp\src\components\home>touch home.html
We also need view and view-model for about page.
C:\Users\username\Desktop\aureliaApp\src\components\about>touch about.js
C:\Users\username\Desktop\aureliaApp\src\components\about>touch about.html
Note − You can also create all the above folders manually.
Next, we need to add some default code to the files we created.
<template>
<h1>HOME</h1>
</template>
export class Home {}
<template>
<h1>ABOUT</h1>
</template>
export class About {}
We will create view-model for router inside app.js file.
export class App {
configureRouter(config, router) {
config.title = 'Aurelia';
config.map([
{ route: ['','home'], name: 'home',
moduleId: './components/home/home', nav: true, title:'Home' },
{ route: 'about', name: 'about',
moduleId: './components/about/about', nav: true, title:'About' }
]);
this.router = router;
}
}
Our router view will be placed in app.html.
<template>
<nav>
<ul>
<li repeat.for = "row of router.navigation">
<a href.bind = "row.href">${row.title}</a>
</li>
</ul>
</nav>
<router-view></router-view>
</template>
When we run the app, we will can change the routes by clicking home or about links.
In this chapter, you will learn how to use aurelia-history plugin.
This plugin is already available as a part of the standard configuration. If you have set aurelia.use.standardConfiguration() as a part of a manual configuration, you are ready to go.
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging();
aurelia.start().then(() => aurelia.setRoot());
}
We will use an example from the last chapter (Aurelia - Routing). If we want to set the functionality for navigating back or forward, we can use the history object with back() and forward() methods. We will add this after a router configuration.
export class App {
configureRouter(config, router) {
config.title = 'Aurelia';
config.map([
{ route: ['','home'], name: 'home',
moduleId: './pages/home/home', nav: true, title:'Home' },
{ route: 'about', name: 'about',
moduleId: './pages/about/about', nav: true, title:'About' }
]);
this.router = router;
}
goBack() {
history.back();
}
goForward() {
history.forward();
}
}
Now, let's add two buttons to our view.
<template>
<nav>
<ul>
<li repeat.for = "row of router.navigation">
<a href.bind = "row.href">${row.title}</a>
</li>
</ul>
</nav>
<button click.delegate = "goBack()"></button>
//The button used for navigationg back...
<button click.delegate = "goForward()"></button>
//The button used for navigationg forward...
<router-view></router-view>
</template>
The users can navigate back and forward by clicking the buttons we added.
In this chapter, you will learn how to use CSS animations in Aurelia framework.
Our view will have one element that will be animated and a button to trigger the animateElement() function.
<template>
<div class = "myElement"></div>
<button click.delegate = "animateElement()">ANIMATE</button>
</template>
Inside our JavaScript file, we will import CssAnimator plugin and inject it as a dependency. The animateElement function will call the animator to start animation. The animation will be created in the next step.
import {CssAnimator} from 'aurelia-animator-css';
import {inject} from 'aurelia-framework';
@inject(CssAnimator, Element)
export class App {
constructor(animator, element) {
this.animator = animator;
this.element = element;
}
animateElement() {
var myElement = this.element.querySelector('.myElement');
this.animator.animate(myElement, 'myAnimation');
}
}
We will write CSS inside styles/styles.css file. .myAnimation-add is the starting point of an animation while .myAnimation-remove is called when the animation is complete.
.myElement {
width:100px;
height: 100px;
border:1px solid blue;
}
.myAnimation-add {
-webkit-animation: changeBack 3s;
animation: changeBack 3s;
}
.myAnimation-remove {
-webkit-animation: fadeIn 3s;
animation: fadeIn 3s;
}
@-webkit-keyframes changeBack {
0% { background-color: #e6efff; }
25% { background-color: #4d91ff; }
50% { background-color: #0058e6; }
75% { background-color: #003180; }
100% { background-color: #000a1a; }
}
@keyframes changeBack {
0% { background-color: #000a1a; }
25% { background-color: #003180; }
50% { background-color: #0058e6; }
75% { background-color: #4d91ff; }
100% { background-color: #e6efff; }
}
Once the ANIMATE button is clicked, the background color will be changed from light blue to a dark shade. When this animation is complete after three seconds, the element will fade to its starting state.
Aurelia offers a way to implement dialog (modal) window. In this chapter, we will show you how to use it.
Dialog plugin can be installed from the command prompt window.
C:\Users\username\Desktop\aureliaApp>jspm install aurelia-dialog
For this plugin to work, we need to use manual bootstrapping. We covered this in the Configuration chapter. Inside main.js file, we need to add the aurelia-dialog plugin.
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('aurelia-dialog');
aurelia.start().then(() => aurelia.setRoot());
}
First, we will make a new directory called modal. Let's place it inside the components folder. Open the command prompt and run the following code.
C:\Users\username\Desktop\aureliaApp\src\components>mkdir modal
In this folder, we will create two new files. These files will represent view and view-model for our modal.
C:\Users\username\Desktop\aureliaApp\src\components\modal>touch my-modal.html
C:\Users\username\Desktop\aureliaApp\src\components\modal>touch my-modal.js
First, let's add view-model code. We need to import and inject dialog-controller. This controller is used for handling modal specific functionalities. In the following example, we are using it to centralize a modal horizontally.
import {inject} from 'aurelia-framework';
import {DialogController} from 'aurelia-dialog';
@inject(DialogController)
export class Prompt {
constructor(controller) {
this.controller = controller;
this.answer = null;
controller.settings.centerHorizontalOnly = true;
}
activate(message) {
this.message = message;
}
}
The view code will look like this. The buttons when clicked will open or close the modal.
<template>
<ai-dialog>
<ai-dialog-body>
<h2>${message}</h2>
</ai-dialog-body>
<ai-dialog-footer>
<button click.trigger = "controller.cancel()">Cancel</button>
<button click.trigger = "controller.ok(message)">Ok</button>
</ai-dialog-footer>
</ai-dialog>
</template>
The last step is a function for triggering our modal. We need to import and inject DialogService. This service has method open, where we can pass view-model from my-modal file and model, so we can dynamically bind the data.
import {DialogService} from 'aurelia-dialog';
import {inject} from 'aurelia-framework';
import {Prompt} from './components/modal/my-modal';
@inject(DialogService)
export class App {
constructor(dialogService) {
this.dialogService = dialogService;
}
openModal() {
this.dialogService.open( {viewModel: Prompt, model: 'Are you sure?' }).then(response => {
console.log(response);
if (!response.wasCancelled) {
console.log('OK');
} else {
console.log('cancelled');
}
console.log(response.output);
});
}
};
Finally, we will create a button so we can call openModal function.
<template>
<button click.trigger = "openModal()">OPEN MODAL</button>
<template>
If we run the app, we can click the OPEN MODAL button to trigger a new modal window.
Aurelia offers i18n plugin. In this chapter, you will learn how to localize your app using this plugin.
Open the command prompt window and run the following code to install i18n plugin.
C:\Users\username\Desktop\aureliaApp>jspm install aurelia-i18n
We also need to install backend plugin.
C:\Users\username\Desktop\aureliaApp>jspm install npm:i18next-xhr-backend
In the project root folder, we need to create a locale directory.
C:\Users\username\Desktop\aureliaApp>mkdir locale
In this folder, you need to add new folders for any language you want. We will create en with translation.js file inside.
C:\Users\username\Desktop\aureliaApp\locale>mkdir en
C:\Users\username\Desktop\aureliaApp\locale\en>touch translation.json
You need to use manual bootstrapping to be able to use this plugin. Check the Configuration chapter for more information. We need to add i18n plugin to the main.js file.
import {I18N} from 'aurelia-i18n';
import XHR from 'i18next-xhr-backend';
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('aurelia-i18n', (instance) => {
// register backend plugin
instance.i18next.use(XHR);
// adapt options to your needs (see http://i18next.com/docs/options/)
instance.setup({
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
},
lng : 'de',
attributes : ['t','i18n'],
fallbackLng : 'en',
debug : false
});
});
aurelia.start().then(a => a.setRoot());
}
This is the file where you can set translation values. We will use an example from an official documentation. The de-DE folder should actually be used for translating to German language, however we will use English phrases instead, for easier understanding.
{
"score": "Score: {{score}}",
"lives": "{{count}} life remaining",
"lives_plural": "{{count}} lives remaining",
"lives_indefinite": "a life remaining",
"lives_plural_indefinite": "some lives remaining",
"friend": "A friend",
"friend_male": "A boyfriend",
"friend_female": "A girlfriend"
}
We just need to import i18n plugin and set it to use JSON code from de-DE folder.
import {I18N} from 'aurelia-i18n';
export class App {
static inject = [I18N];
constructor(i18n) {
this.i18n = i18n;
this.i18n
.setLocale('de-DE')
.then( () => {
console.log('Locale is ready!');
});
}
}
There are couple of ways to translate data. We will use a custom ValueConverter named t. You can see in the following example various ways of formatting data. Compare this with the translation.json file and you will notice the patterns used for formatting.
<template>
<p>
Translation with Variables: <br />
${ 'score' | t: {'score': 13}}
</p>
<p>
Translation singular: <br />
${ 'lives' | t: { 'count': 1 } }
</p>
<p>
Translation plural: <br />
${ 'lives' | t: { 'count': 2 } }
</p>
<p>
Translation singular indefinite: <br />
${ 'lives' | t: { 'count': 1, indefinite_article: true } }
</p>
<p>
Translation plural indefinite: <br />
${ 'lives' | t: { 'count': 2, indefinite_article: true } }
</p>
<p>
Translation without/with context: <br />
${ 'friend' | t } <br />
${ 'friend' | t: { context: 'male' } } <br />
${ 'friend' | t: { context: 'female' } }
</p>
</template>
When we run the app, we will get the following output.
In this chapter, you will learn how to set up and use aurelia-tools.
Let's create a root folder where we will keep all Aurelia apps.
C:\Users\username\Desktop>mkdir aurelia-projects
Inside aurelia-projects folder, we will clone aurelia-tools repository from github.
C:\Users\username\Desktop\aurelia-projects>git clone https://github.com/aurelia/tools.git
To start a new Aurelia project, the recommended way is to use one of the aurelia-skeletons. Let's clone Aurelia skeletons from git.
C:\Users\username\Desktop\aurelia-projects>git clone https://github.com/aurelia/skeleton-navigation.git
We also need to install packages, modules, and dependencies. You can choose between various skeleton apps. We will use skeleton-es2016.
C:\Users\username\Desktop\aurelia-projects\skeleton-navigation\skeleton-es2016>npm install
C:\Users\username\Desktop\aurelia-projects\skeleton-navigation\skeleton-es2016>jspm install
Finally, we need to run the following code to build the development environment.
C:\Users\username\Desktop\aurelia-projects\skeleton-navigation\skeleton-es2016>gulp build-dev-env
Update local repositories using the following command.
C:\Users\username\Desktop\aurelia-projects\skeleton-navigation\skeleton-es2016>gulp update-own-deps
We can also pull Aurelia dependency without building.
C:\Users\username\Desktop\aurelia-projects\skeleton-navigation\skeleton-es2016>gulp pull-dev-env
In this chapter, you will learn how to use bundling in Aurelia framework.
You can install aurelia-bundler by running the following command in the command prompt.
C:\Users\username\Desktop\aureliaApp>npm install aurelia-bundler --save-dev
If you don't have gulp installed, you can install it by running this code.
C:\Users\username\Desktop\aureliaApp>npm install gulp
You can also install require-dir package from npm.
C:\Users\username\Desktop\aureliaApp>npm install require-dir
First, create gulpfile.js file in apps root directory.
C:\Users\username\Desktop\aureliaApp>touch gulpfile.js
You will need the build folder. In this directory, add another folder named tasks.
C:\Users\username\Desktop\aureliaApp>mkdir build
C:\Users\username\Desktop\aureliaApp\build>mkdir tasks
You need to create bundle.js file inside tasks folder.
C:\Users\username\Desktop\aureliaApp\build\tasks>touch bundle.js
Use gulp as the task runner. You need to tell it to run the code from build\tasks\bundle.js.
require('require-dir')('build/tasks');
Now, create the task that you need. This task will take the app, create dist/appbuild.js and dist/vendor-build.js files. After the bundling process is complete, the config.js file will also be updated. You can include all files and plugins you want to inject and minify.
var gulp = require('gulp');
var bundle = require('aurelia-bundler').bundle;
var config = {
force: true,
baseURL: '.',
configPath: './config.js',
bundles: {
"dist/app-build": {
includes: [
'[*.js]',
'*.html!text',
'*.css!text',
],
options: {
inject: true,
minify: true
}
},
"dist/vendor-build": {
includes: [
'aurelia-bootstrapper',
'aurelia-fetch-client',
'aurelia-router',
'aurelia-animator-css',
],
options: {
inject: true,
minify: true
}
}
}
};
gulp.task('bundle', function() {
return bundle(config);
});
The command prompt will inform us when bundling is complete.
In this chapter, you will learn how to add Aurelia context debugger as a chrome extension.
Note − Before adding the extension, you need to have aurelia-tools files. If you don't have it, you can check Tools chapter.
The easiest way to open chrome extensions is to run the following code in browser’s URL bar.
chrome://extensions
Since this extension isn't yet available from Chrome store, check developermode checkbox and click Load Unpacked Extensions. This will open a small window where you can choose the extension to add.
For this example, let us choose Desktop/aurelia-projects/tools/context-debugger folder and open it.
Now, we can see that the extension is loaded in the browser.
We can also check the developers console. When we click elements tab, we will see aurelia-properties at the bottom right corner.
Community is one of the most important factors to consider when choosing a framework. Aurelia offers fantastic support for its customers. In this chapter, you will learn how you can get help when you are stuck.
You can find Aurelia docs on this link − https://aurelia.io/docs.html
If you need a fast answer, you can always submit a question to aurelia gitter channel. This channel can be found on the following link − https://gitter.im/Aurelia/Discuss
You can also submit an issue to official Aurelia github repository https://github.com/aurelia
If you want to keep track of any updates and changes of Aurelia, you can follow Durandal's official blog http://blog.durandal.io/
You can also follow the official blog of Rob Eisenberg, creator of Aurelia framework http://eisenbergeffect.bluespire.com/
Aurelia offers enterprise support for teams and individuals. If you are interested, send an email to the following address −
[email protected]
You can hire Aurelia Expert Developers by sending an email to this address.
[email protected]
If you want Aurelia official training for your team, you can send an email to this address.
[email protected]
Aurelia is a new framework hence, the best practices are yet to be established. In this chapter, you will find some useful guidelines to follow.
Aurelia offers aurelia-skeletons. There are a couple of skeletons to choose from. The team behind Aurelia is actively supporting the skeletons, and they are always up-to-date with the newest version of the framework.
skeleton-es2016-webpack allows you to write ES2016 code and use npm for package management and webpack for bundling.
skeleton-es2016-webpack allows you to write ES2016 code and use npm for package management and webpack for bundling.
skeleton-es2016 allows you to write ES2016 code and use jspm for package management and SystemJS for loading and bundling.
skeleton-es2016 allows you to write ES2016 code and use jspm for package management and SystemJS for loading and bundling.
skeleton-typescript-webpack allows you to write TypeScript code and use npm for package management and webpack for bundling.
skeleton-typescript-webpack allows you to write TypeScript code and use npm for package management and webpack for bundling.
skeleton-typescript allows you to write TypeScript code and use jspm for package management and SystemJS for loading and bundling.
skeleton-typescript allows you to write TypeScript code and use jspm for package management and SystemJS for loading and bundling.
skeleton-typescript-asp.net5 allows you to write TypeScript code and use jspm for package management and SystemJS for loading and bundling. The ASP.NET backend is also integrated.
skeleton-typescript-asp.net5 allows you to write TypeScript code and use jspm for package management and SystemJS for loading and bundling. The ASP.NET backend is also integrated.
skeleton-es2016-asp.net5 allows you to write ES2016 code and use jspm for package management and SystemJS for loading and bundling. The ASP.NET backend is integrated.
skeleton-es2016-asp.net5 allows you to write ES2016 code and use jspm for package management and SystemJS for loading and bundling. The ASP.NET backend is integrated.
You can clone all skeletons from GitHub. The installation instructions can be found inside README.md files for each skeleton.
C:\Users\username\Desktop>git clone https://github.com/aurelia/skeleton-navigation.git
You are free to use any folder structure you want. If you are not sure where to start, you can use the following folder structure. The image represents files and folder in the src directory.
Aurelia is a framework oriented to web standards. This was one of the main goals of the team behind it. They will make sure that the framework always follows modern web. This is extremely good for the developers, since we can rely on the usability of the framework in the future. It also helps us be up-to-date with the browsers and the web.
This is a good practice not just for Aurelia but for any other JavaScript framework. ES6 offers new functionalities that can help in the development process. You can also use TypeScript, if you like strongly typed languages.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2242,
"s": 2165,
"text": "The best definition of the framework can be found in Aurelia official docs −"
},
{
"code": null,
"e": 2573,
"s": 2242,
"text": "Well, it's actually simple. Aurelia is just JavaScript. However, it's not yesterday's JavaScript, but the JavaScript of tomorrow. By using modern tooling we've been able to write Aurelia from the ground up in ECMAScript 2016. This means we have native modules, classes, decorators and more at our disposal...and you have them too."
},
{
"code": null,
"e": 3057,
"s": 2573,
"text": "Not only is Aurelia written in modern and future JavaScript, but it also takes a modern approach to architecture. In the past, frameworks have been monolithic beasts. Not Aurelia though. It's built as a series of collaborating libraries. Taken together, they form a powerful and robust framework for building Single Page Apps (SPAs). However, Aurelia's libraries can often be used individually, in traditional web sites or even on the server-side through technologies such as NodeJS."
},
{
"code": null,
"e": 3184,
"s": 3057,
"text": "Components − Components are building blocks of Aurelia framework. It is composed of HTML view and JavaScript view-model pairs."
},
{
"code": null,
"e": 3311,
"s": 3184,
"text": "Components − Components are building blocks of Aurelia framework. It is composed of HTML view and JavaScript view-model pairs."
},
{
"code": null,
"e": 3444,
"s": 3311,
"text": "Web Standards − This is one of the cleanest modern frameworks, completely focused on web standards without unnecessary abstractions."
},
{
"code": null,
"e": 3577,
"s": 3444,
"text": "Web Standards − This is one of the cleanest modern frameworks, completely focused on web standards without unnecessary abstractions."
},
{
"code": null,
"e": 3665,
"s": 3577,
"text": "Extensible − The framework offers an easy way to integrate with the other needed tools."
},
{
"code": null,
"e": 3753,
"s": 3665,
"text": "Extensible − The framework offers an easy way to integrate with the other needed tools."
},
{
"code": null,
"e": 3867,
"s": 3753,
"text": "Commercial Support − Aurelia offers commercial and enterprise support. It is an official product of Durandal Inc."
},
{
"code": null,
"e": 3981,
"s": 3867,
"text": "Commercial Support − Aurelia offers commercial and enterprise support. It is an official product of Durandal Inc."
},
{
"code": null,
"e": 4047,
"s": 3981,
"text": "License − Aurelia is open sourced and licensed under MIT license."
},
{
"code": null,
"e": 4113,
"s": 4047,
"text": "License − Aurelia is open sourced and licensed under MIT license."
},
{
"code": null,
"e": 4247,
"s": 4113,
"text": "Aurelia is very clean. If you follow the frameworks conventions, you can focus on your app without the framework getting in your way."
},
{
"code": null,
"e": 4381,
"s": 4247,
"text": "Aurelia is very clean. If you follow the frameworks conventions, you can focus on your app without the framework getting in your way."
},
{
"code": null,
"e": 4541,
"s": 4381,
"text": "It is also easily extensible. You can add or remove any tools that the framework offers and you can also add any other tools that aren't part of the framework."
},
{
"code": null,
"e": 4701,
"s": 4541,
"text": "It is also easily extensible. You can add or remove any tools that the framework offers and you can also add any other tools that aren't part of the framework."
},
{
"code": null,
"e": 4810,
"s": 4701,
"text": "Aurelia is very easy to work with. It is directed towards developers’ experience. It saves you lots of time."
},
{
"code": null,
"e": 4919,
"s": 4810,
"text": "Aurelia is very easy to work with. It is directed towards developers’ experience. It saves you lots of time."
},
{
"code": null,
"e": 5031,
"s": 4919,
"text": "The framework itself is directed towards web standards so you will always stay up to date with modern concepts."
},
{
"code": null,
"e": 5143,
"s": 5031,
"text": "The framework itself is directed towards web standards so you will always stay up to date with modern concepts."
},
{
"code": null,
"e": 5274,
"s": 5143,
"text": "Aurelia doesn’t have the largest community out there, but it is very agile, knowledgeable and willing to help within short notice."
},
{
"code": null,
"e": 5405,
"s": 5274,
"text": "Aurelia doesn’t have the largest community out there, but it is very agile, knowledgeable and willing to help within short notice."
},
{
"code": null,
"e": 5486,
"s": 5405,
"text": "There are no major limitations. The Framework is powerful and easy to work with."
},
{
"code": null,
"e": 5567,
"s": 5486,
"text": "There are no major limitations. The Framework is powerful and easy to work with."
},
{
"code": null,
"e": 5709,
"s": 5567,
"text": "In this chapter, you will learn how to get started with Aurelia framework. Before you do that, you will need NodeJS installed on your system."
},
{
"code": null,
"e": 5724,
"s": 5709,
"text": "NodeJS and NPM"
},
{
"code": null,
"e": 5818,
"s": 5724,
"text": "NodeJS is the platform needed for Aurelia development. Checkout our NodeJS Environment Setup."
},
{
"code": null,
"e": 5917,
"s": 5818,
"text": "Before we download Aurelia package, let's create a folder on desktop where our app will be placed."
},
{
"code": null,
"e": 5961,
"s": 5917,
"text": "C:\\Users\\username\\Desktop>mkdir aureliaApp\n"
},
{
"code": null,
"e": 6024,
"s": 5961,
"text": "Now we can download the package from official Aurelia website."
},
{
"code": null,
"e": 6165,
"s": 6024,
"text": "Aurelia supports ES2016 and TypeScript. We will use ES2016. Extract the downloaded files inside the aureliaApp folder that we created above."
},
{
"code": null,
"e": 6233,
"s": 6165,
"text": "First we need to install the web server from command prompt window."
},
{
"code": null,
"e": 6298,
"s": 6233,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>npm install http-server -g\n"
},
{
"code": null,
"e": 6376,
"s": 6298,
"text": "To start the web server, we need to run the following code in command prompt."
},
{
"code": null,
"e": 6434,
"s": 6376,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>http-server -o -c-1\n"
},
{
"code": null,
"e": 6483,
"s": 6434,
"text": "We can see our first Aurelia app in the browser."
},
{
"code": null,
"e": 6680,
"s": 6483,
"text": "In this chapter, we will explain Aurelia starting app created in our last chapter. We will also guide you through the folder structure, so you can grasp the core concepts behind Aurelia framework."
},
{
"code": null,
"e": 6938,
"s": 6680,
"text": "package.json represents documentation about npm packages installed. It also shows the version of those packages and provides an easy way to add, delete, change version or automatically install all packages when the app needs to be shared between developers."
},
{
"code": null,
"e": 7196,
"s": 6938,
"text": "package.json represents documentation about npm packages installed. It also shows the version of those packages and provides an easy way to add, delete, change version or automatically install all packages when the app needs to be shared between developers."
},
{
"code": null,
"e": 7331,
"s": 7196,
"text": "index.html is the default page of the app like in most of the HTML based apps. It is a place where scripts and stylesheets are loaded."
},
{
"code": null,
"e": 7466,
"s": 7331,
"text": "index.html is the default page of the app like in most of the HTML based apps. It is a place where scripts and stylesheets are loaded."
},
{
"code": null,
"e": 7567,
"s": 7466,
"text": "config.js is Aurelia loader configuration file. You will not spend much time working with this file."
},
{
"code": null,
"e": 7668,
"s": 7567,
"text": "config.js is Aurelia loader configuration file. You will not spend much time working with this file."
},
{
"code": null,
"e": 7732,
"s": 7668,
"text": "jspm_packages is the directory for the SystemJS loaded modules."
},
{
"code": null,
"e": 7796,
"s": 7732,
"text": "jspm_packages is the directory for the SystemJS loaded modules."
},
{
"code": null,
"e": 7904,
"s": 7796,
"text": "styles is the default styling directory. You can always change the place where you keep your styling files."
},
{
"code": null,
"e": 8012,
"s": 7904,
"text": "styles is the default styling directory. You can always change the place where you keep your styling files."
},
{
"code": null,
"e": 8114,
"s": 8012,
"text": "src folder is a place where you will spend most of your development time. It keeps HTML and js files."
},
{
"code": null,
"e": 8216,
"s": 8114,
"text": "src folder is a place where you will spend most of your development time. It keeps HTML and js files."
},
{
"code": null,
"e": 8389,
"s": 8216,
"text": "As we already stated, the src directory is the place where your app logic will be held. If you look at the default app you can see that app.js and app.html are very simple."
},
{
"code": null,
"e": 8505,
"s": 8389,
"text": "Aurelia allows us to use JavaScript core language for class definitions. Following default example shows EC6 class."
},
{
"code": null,
"e": 8562,
"s": 8505,
"text": "export class App {\n message = 'Welcome to Aurelia!';\n}"
},
{
"code": null,
"e": 8735,
"s": 8562,
"text": "The message property is bound to the HTML template using ${message}syntax. This syntax represents one-way binding converted into string and showed inside the template view."
},
{
"code": null,
"e": 8781,
"s": 8735,
"text": "<template>\n <h1>${message}</h1>\n</template>"
},
{
"code": null,
"e": 8913,
"s": 8781,
"text": "As we already discussed in the last chapter, we can start the server by running the following command in the command prompt window."
},
{
"code": null,
"e": 8971,
"s": 8913,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>http-server -o -c-1\n"
},
{
"code": null,
"e": 9015,
"s": 8971,
"text": "Application will be rendered on the screen."
},
{
"code": null,
"e": 9142,
"s": 9015,
"text": "Components are the main building blocks of Aurelia framework. In this chapter, you will learn how to create simple components."
},
{
"code": null,
"e": 9384,
"s": 9142,
"text": "As already discussed in the previous chapter, each component contains view-model which is written in JavaScript, and view written in HTML. You can see the following view-model definition. It is an ES6 example but you can also use TypeScript."
},
{
"code": null,
"e": 9475,
"s": 9384,
"text": "export class MyComponent {\n header = \"This is Header\";\n content = \"This is content\";\n}"
},
{
"code": null,
"e": 9655,
"s": 9475,
"text": "We can bind our values to the view as shown in the following example. ${header}syntax will bind the defined header value from MyComponent. The same concept is applied for content."
},
{
"code": null,
"e": 9721,
"s": 9655,
"text": "<template>\n <h1>${header}</h1>\n <p>${content}</p>\n</template>"
},
{
"code": null,
"e": 9771,
"s": 9721,
"text": "The above code will produce the following output."
},
{
"code": null,
"e": 9957,
"s": 9771,
"text": "If you want to update the header and footer when the user clicks the button, you can use the following example. This time we are defining header and footer inside EC6 class constructor."
},
{
"code": null,
"e": 10198,
"s": 9957,
"text": "export class App{ \n constructor() {\n this.header = 'This is Header';\n this.content = 'This is content';\n }\n updateContent() {\n this.header = 'This is NEW header...'\n this.content = 'This is NEW content...';\n }\n}"
},
{
"code": null,
"e": 10327,
"s": 10198,
"text": "We can add click.delegate() to connect updateContent() function with the button. More on this in one of our subsequent chapters."
},
{
"code": null,
"e": 10463,
"s": 10327,
"text": "<template>\n <h1>${header}</h1>\n <p>${content}</p>\n <button click.delegate = \"updateContent()\">Update Content</button>\n</template>"
},
{
"code": null,
"e": 10531,
"s": 10463,
"text": "When the button is clicked, the header and content will be updated."
},
{
"code": null,
"e": 10696,
"s": 10531,
"text": "Aurelia uses component lifecycle methods to manipulate the component lifecycle. In this chapter, we will show you those methods and explain the component lifecycle."
},
{
"code": null,
"e": 10889,
"s": 10696,
"text": "constructor() − Constructor method is used for initializing an object created with a class. This method is called first. If you don't specify this method, the default constructor will be used."
},
{
"code": null,
"e": 11082,
"s": 10889,
"text": "constructor() − Constructor method is used for initializing an object created with a class. This method is called first. If you don't specify this method, the default constructor will be used."
},
{
"code": null,
"e": 11353,
"s": 11082,
"text": "created(owningView, myView) − This is called once the view and view-model are created and connected to the controller. This method takes two arguments. The first one is the view where the component is declared (owningView). The second one is the component view (myView)."
},
{
"code": null,
"e": 11624,
"s": 11353,
"text": "created(owningView, myView) − This is called once the view and view-model are created and connected to the controller. This method takes two arguments. The first one is the view where the component is declared (owningView). The second one is the component view (myView)."
},
{
"code": null,
"e": 11882,
"s": 11624,
"text": "bind(bindingContext, overrideContext) − At this point of time, the binding has started. The first argument represents the binding context of the component. The second one is overrideContext. This argument is used for adding additional contextual properties."
},
{
"code": null,
"e": 12140,
"s": 11882,
"text": "bind(bindingContext, overrideContext) − At this point of time, the binding has started. The first argument represents the binding context of the component. The second one is overrideContext. This argument is used for adding additional contextual properties."
},
{
"code": null,
"e": 12223,
"s": 12140,
"text": "attached() − Attached method is invoked once the component is attached to the DOM."
},
{
"code": null,
"e": 12306,
"s": 12223,
"text": "attached() − Attached method is invoked once the component is attached to the DOM."
},
{
"code": null,
"e": 12414,
"s": 12306,
"text": "detached() − This method is opposite to attached. It is invoked when the component is removed from the DOM."
},
{
"code": null,
"e": 12522,
"s": 12414,
"text": "detached() − This method is opposite to attached. It is invoked when the component is removed from the DOM."
},
{
"code": null,
"e": 12614,
"s": 12522,
"text": "unbind() − The last lifecycle method is unbind. It is called when the component is unbound."
},
{
"code": null,
"e": 12706,
"s": 12614,
"text": "unbind() − The last lifecycle method is unbind. It is called when the component is unbound."
},
{
"code": null,
"e": 12901,
"s": 12706,
"text": "The lifecycle methods are useful when you want to have higher control over your component. You can use them when you need to trigger some functionalities at certain point of component lifecycle."
},
{
"code": null,
"e": 12940,
"s": 12901,
"text": "All lifecycle methods are shown below."
},
{
"code": null,
"e": 13495,
"s": 12940,
"text": "export class App {\n constructor(argument) {\n // Create and initialize your class object here...\n }\n\n created(owningView, myView) {\n // Invoked once the component is created...\n }\n\n bind(bindingContext, overrideContext) {\n // Invoked once the databinding is activated...\n }\n\n attached(argument) {\n // Invoked once the component is attached to the DOM...\n }\n\n detached(argument) {\n // Invoked when component is detached from the dom\n }\n\n unbind(argument) {\n // Invoked when component is unbound...\n }\n}"
},
{
"code": null,
"e": 13713,
"s": 13495,
"text": "Aurelia offers a way to add components dynamically. You can reuse a single component on different parts of your app without the need to include HTML multiple times. In this chapter, you will learn how to achieve this."
},
{
"code": null,
"e": 13770,
"s": 13713,
"text": "Let's create new components directory inside src folder."
},
{
"code": null,
"e": 13829,
"s": 13770,
"text": "C:\\Users\\username\\Desktop\\aureliaApp\\src>mkdir components\n"
},
{
"code": null,
"e": 13946,
"s": 13829,
"text": "Inside this directory, we will create custom-component.html. This component will be inserted later in the HTML page."
},
{
"code": null,
"e": 14023,
"s": 13946,
"text": "<template>\n <p>This is some text from dynamic component...</p>\n</template>"
},
{
"code": null,
"e": 14126,
"s": 14023,
"text": "We will create simple component in app.js. It will be used to render header and footer text on screen."
},
{
"code": null,
"e": 14217,
"s": 14126,
"text": "export class MyComponent {\n header = \"This is Header\";\n content = \"This is content\";\n}"
},
{
"code": null,
"e": 14385,
"s": 14217,
"text": "Inside our app.html file, we need to require the custom-component.html to be able to insert it dynamically. Once we do that, we can add a new element custom-component."
},
{
"code": null,
"e": 14560,
"s": 14385,
"text": "<template>\n <require from = \"./components/custom-component.html\"></require>\n\n <h1>${header}</h1>\n <p>${content}</p>\n <custom-component></custom-component>\n</template>"
},
{
"code": null,
"e": 14714,
"s": 14560,
"text": "Following is the output. Header and Footer text is rendered from myComponent inside app.js. The additional text is rendered from the custom-component.js."
},
{
"code": null,
"e": 14795,
"s": 14714,
"text": "In this chapter, you will learn how to use Aurelia dependency injection library."
},
{
"code": null,
"e": 14978,
"s": 14795,
"text": "First, we need to create new file dependency-test.js inside src folder. In this file, we will create a simple class DependencyTest. This class will be later injected as a dependency."
},
{
"code": null,
"e": 15077,
"s": 14978,
"text": "export class DependencyTest {\n constructor() {\n this.test = \"Test is succesfull!!!\";\n }\n}"
},
{
"code": null,
"e": 15287,
"s": 15077,
"text": "In our app.js file, we are importing inject library and DependencyTest class that we created above. To inject the class we are using @inject() function. Our App class will just log it to the developer console."
},
{
"code": null,
"e": 15499,
"s": 15287,
"text": "import {inject} from 'aurelia-framework';\nimport {DependencyTest} from './dependency-test';\n\n@inject(DependencyTest)\n\nexport class App {\n constructor(DependencyTest) {\n console.log(DependencyTest);\n }\n}"
},
{
"code": null,
"e": 15574,
"s": 15499,
"text": "We can check the console to see that the DependencyTest class is injected."
},
{
"code": null,
"e": 15653,
"s": 15574,
"text": "There will more examples of Aurelia dependency injection in the next chapters."
},
{
"code": null,
"e": 15852,
"s": 15653,
"text": "In this chapter, we will show you how to configure Aurelia framework for your needs. Sometimes you will need to set an initial configuration or run some code before the app is rendered to the users."
},
{
"code": null,
"e": 15941,
"s": 15852,
"text": "Let's create main.js file inside src folder. Inside this file we will configure Aurelia."
},
{
"code": null,
"e": 16058,
"s": 15941,
"text": "You also need to tell Aurelia to load configuration module. You can see the commented part in the following example."
},
{
"code": null,
"e": 16566,
"s": 16058,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Aurelia</title>\n <link rel = \"stylesheet\" href = \"styles/styles.css\">\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n </head>\n\n <body aurelia-app = \"main\"> \n <!--Add \"main\" value to \"aurelia-app\" attribute... -->\n <script src = \"jspm_packages/system.js\"></script>\n <script src = \"config.js\"></script>\n\t\t\n <script>\n SystemJS.import('aurelia-bootstrapper');\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 16735,
"s": 16566,
"text": "The code below shows how to use default configuration. configure function allows to set the configuration manually. We are setting use property to specify what we need."
},
{
"code": null,
"e": 16894,
"s": 16735,
"text": "export function configure(aurelia) {\n aurelia.use\n .standardConfiguration()\n .developmentLogging();\n\n aurelia.start().then(() => aurelia.setRoot());\n}"
},
{
"code": null,
"e": 17266,
"s": 16894,
"text": "There are lots of configuration options we could use. It is out of the scope of this article to show you all of it so we will explain how the configuration works on the following example. We are basically telling Aurelia to use default data binding language, default resources, development logging, router, history and event aggregator. These are standard set of plugins."
},
{
"code": null,
"e": 17498,
"s": 17266,
"text": "export function configure(aurelia) {\n aurelia.use\n .defaultBindingLanguage()\n .defaultResources()\n .developmentLogging()\n .router()\n .history()\n .eventAggregator();\n\n aurelia.start().then(() => aurelia.setRoot());\n}"
},
{
"code": null,
"e": 17569,
"s": 17498,
"text": "Note − These settings will be explained in detail in the next chapter."
},
{
"code": null,
"e": 17739,
"s": 17569,
"text": "When you start building your app, most of the time you will want to use some additional plugins. In this chapter, you will learn how to use plugins in Aurelia framework."
},
{
"code": null,
"e": 17905,
"s": 17739,
"text": "In the last chapter, we saw how to use default configuration in Aurelia framework. If you are using default configuration, standard set of plugins will be available."
},
{
"code": null,
"e": 18173,
"s": 17905,
"text": "defaultBindingLanguage() − This plugin offers an easy way to connect view-model with view. You already saw one-way data-binding syntax (${someValue}). Even though you could use some other binding language, it is a recommended practice to use default binding language."
},
{
"code": null,
"e": 18441,
"s": 18173,
"text": "defaultBindingLanguage() − This plugin offers an easy way to connect view-model with view. You already saw one-way data-binding syntax (${someValue}). Even though you could use some other binding language, it is a recommended practice to use default binding language."
},
{
"code": null,
"e": 18682,
"s": 18441,
"text": "defaultResources() − Default resources give us some primitive constructs such as if, repeat, compose, etc. You can even build these constructs on your own, but since they are so commonly used, Aurelia already created it inside this library."
},
{
"code": null,
"e": 18923,
"s": 18682,
"text": "defaultResources() − Default resources give us some primitive constructs such as if, repeat, compose, etc. You can even build these constructs on your own, but since they are so commonly used, Aurelia already created it inside this library."
},
{
"code": null,
"e": 19092,
"s": 18923,
"text": "Router() − Most of the applications use some kind of routing. Hence, Router is a part of the standard plugins. You can check more about routing in a subsequent chapter."
},
{
"code": null,
"e": 19261,
"s": 19092,
"text": "Router() − Most of the applications use some kind of routing. Hence, Router is a part of the standard plugins. You can check more about routing in a subsequent chapter."
},
{
"code": null,
"e": 19326,
"s": 19261,
"text": "History() − History plugin is usually used together with router."
},
{
"code": null,
"e": 19391,
"s": 19326,
"text": "History() − History plugin is usually used together with router."
},
{
"code": null,
"e": 19545,
"s": 19391,
"text": "eventAggregator() − This plugin is used for cross-component communication. It handles publishing and subscribing to messages or channels inside your app."
},
{
"code": null,
"e": 19699,
"s": 19545,
"text": "eventAggregator() − This plugin is used for cross-component communication. It handles publishing and subscribing to messages or channels inside your app."
},
{
"code": null,
"e": 19779,
"s": 19699,
"text": "These plugins aren't part of the default configuration but are frequently used."
},
{
"code": null,
"e": 19887,
"s": 19779,
"text": "fetch() − Fetch plugin is used for handling HTTP requests. You can use some other AJAX library if you want."
},
{
"code": null,
"e": 19995,
"s": 19887,
"text": "fetch() − Fetch plugin is used for handling HTTP requests. You can use some other AJAX library if you want."
},
{
"code": null,
"e": 20064,
"s": 19995,
"text": "animatorCSS() − This plugin offers a way of handling CSS animations."
},
{
"code": null,
"e": 20133,
"s": 20064,
"text": "animatorCSS() − This plugin offers a way of handling CSS animations."
},
{
"code": null,
"e": 20283,
"s": 20133,
"text": "animator-velocity() − Instead of CSS animations, you can use Velocity animation library. These plugins enable us to use Velocity inside Aurelia apps."
},
{
"code": null,
"e": 20433,
"s": 20283,
"text": "animator-velocity() − Instead of CSS animations, you can use Velocity animation library. These plugins enable us to use Velocity inside Aurelia apps."
},
{
"code": null,
"e": 20501,
"s": 20433,
"text": "dialog() − Dialog plugin offers a highly customizable modal window."
},
{
"code": null,
"e": 20569,
"s": 20501,
"text": "dialog() − Dialog plugin offers a highly customizable modal window."
},
{
"code": null,
"e": 20635,
"s": 20569,
"text": "i18n() − This is the plugin for internalization and localization."
},
{
"code": null,
"e": 20701,
"s": 20635,
"text": "i18n() − This is the plugin for internalization and localization."
},
{
"code": null,
"e": 20805,
"s": 20701,
"text": "ui-virtualization() − Virtualization is a useful library for handling large performance heavy UI tasks."
},
{
"code": null,
"e": 20909,
"s": 20805,
"text": "ui-virtualization() − Virtualization is a useful library for handling large performance heavy UI tasks."
},
{
"code": null,
"e": 20977,
"s": 20909,
"text": "validation() − Use this plugin when you need to validate your data."
},
{
"code": null,
"e": 21045,
"s": 20977,
"text": "validation() − Use this plugin when you need to validate your data."
},
{
"code": null,
"e": 21287,
"s": 21045,
"text": "All plugins explained above are officially maintained by the Aurelia Core Team at the moment of writing this tutorial. There will be some other useful plugins added in future. Following example shows how to configure your app to use plugins."
},
{
"code": null,
"e": 21384,
"s": 21287,
"text": "If, for example, we want to use animator-css and animator-velocity, we need to install it first."
},
{
"code": null,
"e": 21532,
"s": 21384,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>jspm install aurelia-animator-css\nC:\\Users\\username\\Desktop\\aureliaApp>jspm install aurelia-animator-velocity\n"
},
{
"code": null,
"e": 21637,
"s": 21532,
"text": "In the last chapter, you learnt how to use manual configuration. We can add our plugins in main.js file."
},
{
"code": null,
"e": 21942,
"s": 21637,
"text": "export function configure(aurelia) {\n aurelia.use\n .defaultBindingLanguage()\n .defaultResources()\n .developmentLogging()\n .router()\n .history()\n .eventAggregator()\n .plugin('aurelia-animatorCSS')\n .plugin('aurelia-animator-velocity')\n\n aurelia.start().then(() => aurelia.setRoot());\n}"
},
{
"code": null,
"e": 22096,
"s": 21942,
"text": "Aurelia has its own data-binding system. In this chapter, you will learn how to bind data with Aurelia, and also explain the different binding mechanics."
},
{
"code": null,
"e": 22211,
"s": 22096,
"text": "You already saw simple binding in some of our previous chapters. ${...}syntax is used to link veiw-model and view."
},
{
"code": null,
"e": 22305,
"s": 22211,
"text": "export class App { \n constructor() {\n this.myData = 'Welcome to Aurelia app!';\n }\n}"
},
{
"code": null,
"e": 22350,
"s": 22305,
"text": "<template>\n <h3>${myData}</h3>\n</template>"
},
{
"code": null,
"e": 22470,
"s": 22350,
"text": "The beauty of Aurelia is in its simplicity. The two-way data binding is automatically set, when we bind to input fields"
},
{
"code": null,
"e": 22557,
"s": 22470,
"text": "export class App { \n constructor() {\n this.myData = 'Enter some text!';\n }\n}"
},
{
"code": null,
"e": 22663,
"s": 22557,
"text": "<template>\n <input id = \"name\" type = \"text\" value.bind = \"myData\" />\n <h3>${myData}</h3>\n</template>"
},
{
"code": null,
"e": 22786,
"s": 22663,
"text": "Now, we have our view-model and view linked. Whenever we enter some text inside the input field, the view will be updated."
},
{
"code": null,
"e": 22957,
"s": 22786,
"text": "In this chapter, you will learn how to use behaviors. You can think of binding behavior as a filter that can change the binding data and display it in a different format."
},
{
"code": null,
"e": 23247,
"s": 22957,
"text": "This behavior is used to set how often should some binding update take place. We can use throttle to slow down the rate of updating input view-model. Consider the example from the last chapter. The default rate is 200 ms. We can change that to 2 sec by adding & throttle:2000 to our input."
},
{
"code": null,
"e": 23334,
"s": 23247,
"text": "export class App { \n constructor() {\n this.myData = 'Enter some text!';\n }\n}"
},
{
"code": null,
"e": 23456,
"s": 23334,
"text": "<template>\n <input id = \"name\" type = \"text\" value.bind = \"myData & throttle:2000\" />\n <h3>${myData}</h3>\n</template>"
},
{
"code": null,
"e": 23675,
"s": 23456,
"text": "debounce is almost the same as throttle. The difference being, debounce will update the binding after the user has stopped typing. The following example will update the binding if the user stops typing for two seconds."
},
{
"code": null,
"e": 23762,
"s": 23675,
"text": "export class App { \n constructor() {\n this.myData = 'Enter some text!';\n }\n}"
},
{
"code": null,
"e": 23884,
"s": 23762,
"text": "<template>\n <input id = \"name\" type = \"text\" value.bind = \"myData & debounce:2000\" />\n <h3>${myData}</h3>\n</template>"
},
{
"code": null,
"e": 24017,
"s": 23884,
"text": "oneTime is the most efficient behavior performance wise. You should always use it when you know that data should be bound only once."
},
{
"code": null,
"e": 24104,
"s": 24017,
"text": "export class App { \n constructor() {\n this.myData = 'Enter some text!';\n }\n}"
},
{
"code": null,
"e": 24220,
"s": 24104,
"text": "<template>\n <input id = \"name\" type = \"text\" value.bind = \"myData & oneTime\" />\n <h3>${myData}</h3>\n</template>"
},
{
"code": null,
"e": 24359,
"s": 24220,
"text": "The above example will bind the text to the view. However, if we change the default text, nothing will happen since it is bound only once."
},
{
"code": null,
"e": 24492,
"s": 24359,
"text": "If you need to convert some values in Aurelia app, you can use converters instead of manually converting values to a desired format."
},
{
"code": null,
"e": 24646,
"s": 24492,
"text": "When we want to convert the default date value to some specific format, we can use momentJS library. This is a small library used for manipulating dates."
},
{
"code": null,
"e": 24704,
"s": 24646,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>jspm install moment\n"
},
{
"code": null,
"e": 24852,
"s": 24704,
"text": "Let's create a new file converters.js. We will use this file to add converter specific code. Use the following command or create the file manually."
},
{
"code": null,
"e": 24910,
"s": 24852,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>touch converters.js\n"
},
{
"code": null,
"e": 25290,
"s": 24910,
"text": "Inside this file, we will import moment library and set DateFormatValueConverter to return only month, day and year values without additional data. Important thing to note is that Aurelia can recognize any class that ends with ValueConverter. This is why our class name is DateFormatValueConverter. This class will be registered as dateFormat and we can later use it inside view."
},
{
"code": null,
"e": 25433,
"s": 25290,
"text": "import moment from 'moment';\n\nexport class DateFormatValueConverter {\n toView(value) {\n return moment(value).format('M/D/YYYY');\n }\n}"
},
{
"code": null,
"e": 25508,
"s": 25433,
"text": "In app.js, we will just use the current date. This will be our view-model."
},
{
"code": null,
"e": 25590,
"s": 25508,
"text": "export class App {\n constructor() {\n this.currentDate = new Date();\n }\n}"
},
{
"code": null,
"e": 25793,
"s": 25590,
"text": "We already discussed require in custom-elements chapter. The pipe symbol | is used to apply the converter. We are only using dateFormat since this is how Aurelia is registering DateFormatValueConverter."
},
{
"code": null,
"e": 25902,
"s": 25793,
"text": "<template>\n <require from = \"./converters\"></require>\n\n <h3>${currentDate | dateFormat}</h3>\n</template>"
},
{
"code": null,
"e": 26082,
"s": 25902,
"text": "This is an example of currency formatting. You will notice that the concept is the same as in the above example. First, we need to install numeral library from the command prompt."
},
{
"code": null,
"e": 26141,
"s": 26082,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>jspm install numeral\n"
},
{
"code": null,
"e": 26185,
"s": 26141,
"text": "The Converter will set the currency format."
},
{
"code": null,
"e": 26336,
"s": 26185,
"text": "import numeral from 'numeral';\n\nexport class CurrencyFormatValueConverter {\n toView(value) {\n return numeral(value).format('($0,0.00)');\n }\n}"
},
{
"code": null,
"e": 26446,
"s": 26336,
"text": "View-model will just generate a random number. We will use this as currency value and update it every second."
},
{
"code": null,
"e": 26623,
"s": 26446,
"text": "export class App {\n constructor() {\n this.update();\n setInterval(() => this.update(), 1000);\n }\n update() {\n this.myCurrency = Math.random() * 1000;\n }\n}"
},
{
"code": null,
"e": 26699,
"s": 26623,
"text": "Our view will show the randomly generated number transformed as a currency."
},
{
"code": null,
"e": 26811,
"s": 26699,
"text": "<template>\n <require from = \"./converters\"></require>\n\n <h3>${myCurrency | currencyFormat}</h3>\n</template>"
},
{
"code": null,
"e": 26865,
"s": 26811,
"text": "In this chapter, you will learn about Aurelia events."
},
{
"code": null,
"e": 27093,
"s": 26865,
"text": "Even delegation is a useful concept where the event handler is attached to one top level element instead of multiple elements on the DOM. This will improve the application memory efficiency and should be used whenever possible."
},
{
"code": null,
"e": 27232,
"s": 27093,
"text": "This is a simple example of using event delegation with Aurelia framework. Our view will have a button with click.delegate event attached."
},
{
"code": null,
"e": 27316,
"s": 27232,
"text": "<template>\n <button click.delegate = \"myFunction()\">CLICK ME</button>\n</template>"
},
{
"code": null,
"e": 27373,
"s": 27316,
"text": "Once the button is clicked, myFunction() will be called."
},
{
"code": null,
"e": 27468,
"s": 27373,
"text": "export class App {\n myFunction() {\n console.log('The function is triggered...');\n }\n}"
},
{
"code": null,
"e": 27502,
"s": 27468,
"text": "We will get the following output."
},
{
"code": null,
"e": 27783,
"s": 27502,
"text": "There are some cases when you can't use delegation. Some JavaScript events don’t support delegation; IOS supports it for some elements. To find out which events allow delegation, you can search for a bubble property of any event here. In these cases, you can use trigger() method."
},
{
"code": null,
"e": 27864,
"s": 27783,
"text": "The same functionality from the above example can be created with click.trigger."
},
{
"code": null,
"e": 27947,
"s": 27864,
"text": "<template>\n <button click.trigger = \"myFunction()\">CLICK ME</button>\n</template>"
},
{
"code": null,
"e": 28042,
"s": 27947,
"text": "export class App {\n myFunction() {\n console.log('The function is triggered...');\n }\n}"
},
{
"code": null,
"e": 28218,
"s": 28042,
"text": "Event aggregator should be used when your events need to be attached to more listeners or when you need to observe some functionality of your app and wait for the data update."
},
{
"code": null,
"e": 28516,
"s": 28218,
"text": "Aurelia event aggregator has three methods. The publish method will fire off events and can be used by multiple subscribers. For subscribing to an event, we can use the subscribe method. And finally, we can use the dispose method to detach the subscribers. The following example demonstrates this."
},
{
"code": null,
"e": 28593,
"s": 28516,
"text": "Our view will just have three buttons for each of the three functionalities."
},
{
"code": null,
"e": 28801,
"s": 28593,
"text": "<template>\n <button click.delegate = \"publish()\">PUBLISH</button><br/>\n <button click.delegate = \"subscribe()\">SUBSCRIBE</button><br/>\n <button click.delegate = \"dispose()\">DISPOSE</button>\n</template>"
},
{
"code": null,
"e": 28879,
"s": 28801,
"text": "We need to import eventAggregator and inject it before we are able to use it."
},
{
"code": null,
"e": 29468,
"s": 28879,
"text": "import {inject} from 'aurelia-framework';\nimport {EventAggregator} from 'aurelia-event-aggregator';\n\n@inject(EventAggregator)\nexport class App {\n constructor(eventAggregator) {\n this.eventAggregator = eventAggregator;\n }\n publish() {\n var payload = 'This is some data...';\n this.eventAggregator.publish('myEventName', payload);\n }\n subscribe() {\n this.subscriber = this.eventAggregator.subscribe('myEventName', payload => {\n console.log(payload);\n });\n }\n dispose() {\n this.subscriber.dispose();\n console.log('Disposed!!!');\n }\n}"
},
{
"code": null,
"e": 29729,
"s": 29468,
"text": "We need to click the SUBSCRIBE button to listen for data that will be published in future. Once the subscriber is attached, whenever new data is sent, the console will log it. If we click the PUBLISH button five times, we will see that it is logged every time."
},
{
"code": null,
"e": 29795,
"s": 29729,
"text": "We can also detach our subscriber by clicking the DISPOSE button."
},
{
"code": null,
"e": 29866,
"s": 29795,
"text": "In this chapter, you will learn how to use forms in Aurelia framework."
},
{
"code": null,
"e": 30017,
"s": 29866,
"text": "First, we will see how to submit an input form. The view will have two input forms for username and password. We will use value.bind for data binding."
},
{
"code": null,
"e": 30401,
"s": 30017,
"text": "<template> \n <form role = \"form\" submit.delegate = \"signup()\">\n \n <label for = \"email\">Email</label>\n <input type = \"text\" value.bind = \"email\" placeholder = \"Email\">\n\n <label for = \"password\">Password</label>\n <input type = \"password\" value.bind = \"password\" placeholder = \"Password\">\n\n <button type = \"submit\">Signup</button>\n </form>\n</template>"
},
{
"code": null,
"e": 30524,
"s": 30401,
"text": "The signup function will just take the username and password values from the inputs and log it in the developer’s console."
},
{
"code": null,
"e": 30692,
"s": 30524,
"text": "export class App {\n email = '';\n password = '';\n\n signup() {\n var myUser = { email: this.email, password: this.password }\n console.log(myUser);\n };\n}"
},
{
"code": null,
"e": 30854,
"s": 30692,
"text": "The following example will demonstrate how to submit a checkbox with Aurelia framework. We will create one checkbox and bind the checked value to our view-model."
},
{
"code": null,
"e": 31125,
"s": 30854,
"text": "<template>\n <form role = \"form\" submit.delegate = \"submit()\">\n \n <label for = \"checkbox\">Checkbox</label>\n <input type = \"checkbox\" id = \"checkbox\" checked.bind = \"isChecked\"><br/>\n <button type = \"submit\">SUBMIT</button>\n \n </form>\n</template>"
},
{
"code": null,
"e": 31189,
"s": 31125,
"text": "Form submitting will just log the checked value in the console."
},
{
"code": null,
"e": 31335,
"s": 31189,
"text": "export class App {\n constructor() {\n this.isChecked = false;\n }\n submit() {\n console.log(\"isChecked: \" + this.isChecked);\n }\n}"
},
{
"code": null,
"e": 31699,
"s": 31335,
"text": "The following example will demonstrate how to submit radio buttons. The syntax repeat.for = \"option of options\" will repeat through an array of objects and create a radio button for each object. This is a neat way of dynamically creating elements in Aurelia framework. Rest is the same as in the previous examples. We are binding the model and the checked values."
},
{
"code": null,
"e": 32065,
"s": 31699,
"text": "<template>\n <form role = \"form\" submit.delegate = \"submit()\">\n\t\n <label repeat.for = \"option of options\">\n <input type = \"radio\" name = \"myOptions\" \n model.bind = \"option\" checked.bind = \"$parent.selectedOption\"/>\n ${option.text}\n </label>\n <br/>\n\t\t\n <button type = \"submit\">SUBMIT</button>\n </form>\n</template>"
},
{
"code": null,
"e": 32269,
"s": 32065,
"text": "In our view-model, we will create an array of objects this.options and specify that the first radio button is checked. Again, the SUBMIT button will just log in the console which radio button is checked."
},
{
"code": null,
"e": 32613,
"s": 32269,
"text": "export class PeriodPanel {\n options = [];\n selectedOption = {};\n\n constructor() {\n this.options = [\n {id:1, text:'First'}, \n {id:2, text:'Second'}, \n {id:3, text:'Third'}\n ]; \n this.selectedOption = this.options[0];\n }\n submit() {\n console.log('checked: ' + this.selectedOption.id);\n }\n}"
},
{
"code": null,
"e": 32695,
"s": 32613,
"text": "If we check the third radio button and submit our form, the console will show it."
},
{
"code": null,
"e": 32780,
"s": 32695,
"text": "In this chapter, you will learn how to work with HTTP requests in Aurelia framework."
},
{
"code": null,
"e": 32857,
"s": 32780,
"text": "Let's create four buttons that will be used for sending requests to our API."
},
{
"code": null,
"e": 33100,
"s": 32857,
"text": "<template>\n <button click.delegate = \"getData()\">GET</button>\n <button click.delegate = \"postData()\">POST</button>\n <button click.delegate = \"updateData()\">PUT</button>\n <button click.delegate = \"deleteData()\">DEL</button>\n</template>"
},
{
"code": null,
"e": 33251,
"s": 33100,
"text": "For sending requests to the server, Aurelia recommends fetch client. We are creating functions for every requests we need (GET, POST, PUT and DELETE)."
},
{
"code": null,
"e": 34442,
"s": 33251,
"text": "import 'fetch';\nimport {HttpClient, json} from 'aurelia-fetch-client';\n\nlet httpClient = new HttpClient();\n\nexport class App {\n getData() {\n httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1')\n .then(response => response.json())\n .then(data => {\n console.log(data);\n });\n }\n myPostData = { \n id: 101\n }\n\tpostData(myPostData) {\n httpClient.fetch('http://jsonplaceholder.typicode.com/posts', {\n method: \"POST\",\n body: JSON.stringify(myPostData)\n })\n\t\t\n .then(response => response.json())\n .then(data => {\n console.log(data);\n });\n }\n myUpdateData = {\n id: 1\n }\n\tupdateData(myUpdateData) {\n httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1', {\n method: \"PUT\",\n body: JSON.stringify(myUpdateData)\n })\n\t\t\n .then(response => response.json())\n .then(data => {\n console.log(data);\n });\n }\n deleteData() {\n httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1', {\n method: \"DELETE\"\n })\n .then(response => response.json())\n .then(data => {\n console.log(data);\n });\n }\n}"
},
{
"code": null,
"e": 34603,
"s": 34442,
"text": "We can run the app and click GET, POST, PUT and DEL buttons, respectively. We can see in the console that every request is successful, and the result is logged."
},
{
"code": null,
"e": 34818,
"s": 34603,
"text": "In this chapter, you will see some simple examples of Aurelia refs. You can use it to create a reference to a particular object. You can create a reference to elements or attributes, as seen in the following table."
},
{
"code": null,
"e": 34832,
"s": 34818,
"text": "ref = \"myRef\""
},
{
"code": null,
"e": 34878,
"s": 34832,
"text": "Used for creating a reference to DOM element."
},
{
"code": null,
"e": 34907,
"s": 34878,
"text": "attribute-name.ref = \"myRef\""
},
{
"code": null,
"e": 34971,
"s": 34907,
"text": "Used for creating a reference to custom attribute's view-model."
},
{
"code": null,
"e": 34995,
"s": 34971,
"text": "view-model.ref = \"myRef"
},
{
"code": null,
"e": 35057,
"s": 34995,
"text": "Used for creating a reference to custom element's view-model."
},
{
"code": null,
"e": 35076,
"s": 35057,
"text": "view.ref = \"myRef\""
},
{
"code": null,
"e": 35140,
"s": 35076,
"text": "Used for creating a reference to custom elements view instance."
},
{
"code": null,
"e": 35166,
"s": 35140,
"text": "rcontroller.ref = \"myRef\""
},
{
"code": null,
"e": 35237,
"s": 35166,
"text": "Used for creating a reference to custom element's controller instance."
},
{
"code": null,
"e": 35366,
"s": 35237,
"text": "In the following example, we will create a reference to the input element. We will use the default class syntax as a view-model."
},
{
"code": null,
"e": 35391,
"s": 35366,
"text": "export class App { } "
},
{
"code": null,
"e": 35478,
"s": 35391,
"text": "We are creating a reference to the input element by adding the ref = \"name\" attribute."
},
{
"code": null,
"e": 35574,
"s": 35478,
"text": "<template>\n <input type = \"text\" ref = \"name\"><br/>\n <h3>${name.value}</h3>\n</template> "
},
{
"code": null,
"e": 35677,
"s": 35574,
"text": "When we run the app, we will see that the text entered into the input field is rendered on the screen."
},
{
"code": null,
"e": 35804,
"s": 35677,
"text": "Routing is an important part of every application. In this chapter, you will learn how to use the router in Aurelia framework."
},
{
"code": null,
"e": 35960,
"s": 35804,
"text": "We have already created a components folder in one of the former chapters. If you don't have it created already, you should place it inside the src folder."
},
{
"code": null,
"e": 36019,
"s": 35960,
"text": "C:\\Users\\username\\Desktop\\aureliaApp\\src>mkdir components\n"
},
{
"code": null,
"e": 36082,
"s": 36019,
"text": "Inside this folder, we will create home and about directories."
},
{
"code": null,
"e": 36210,
"s": 36082,
"text": "C:\\Users\\username\\Desktop\\aureliaApp\\src\\components>mkdir home\nC:\\Users\\username\\Desktop\\aureliaApp\\src\\components>mkdir about\n"
},
{
"code": null,
"e": 36279,
"s": 36210,
"text": "Inside the home folder, we need to create view and view-model files."
},
{
"code": null,
"e": 36424,
"s": 36279,
"text": "C:\\Users\\username\\Desktop\\aureliaApp\\src\\components\\home>touch home.js\nC:\\Users\\username\\Desktop\\aureliaApp\\src\\components\\home>touch home.html\n"
},
{
"code": null,
"e": 36473,
"s": 36424,
"text": "We also need view and view-model for about page."
},
{
"code": null,
"e": 36622,
"s": 36473,
"text": "C:\\Users\\username\\Desktop\\aureliaApp\\src\\components\\about>touch about.js\nC:\\Users\\username\\Desktop\\aureliaApp\\src\\components\\about>touch about.html\n"
},
{
"code": null,
"e": 36681,
"s": 36622,
"text": "Note − You can also create all the above folders manually."
},
{
"code": null,
"e": 36745,
"s": 36681,
"text": "Next, we need to add some default code to the files we created."
},
{
"code": null,
"e": 36785,
"s": 36745,
"text": "<template>\n <h1>HOME</h1>\n</template>"
},
{
"code": null,
"e": 36806,
"s": 36785,
"text": "export class Home {}"
},
{
"code": null,
"e": 36847,
"s": 36806,
"text": "<template>\n <h1>ABOUT</h1>\n</template>"
},
{
"code": null,
"e": 36869,
"s": 36847,
"text": "export class About {}"
},
{
"code": null,
"e": 36926,
"s": 36869,
"text": "We will create view-model for router inside app.js file."
},
{
"code": null,
"e": 37329,
"s": 36926,
"text": "export class App {\n configureRouter(config, router) {\n config.title = 'Aurelia';\n\t\t\n config.map([\n { route: ['','home'], name: 'home', \n moduleId: './components/home/home', nav: true, title:'Home' },\n { route: 'about', name: 'about',\n moduleId: './components/about/about', nav: true, title:'About' }\n ]);\n\n this.router = router;\n }\n}"
},
{
"code": null,
"e": 37373,
"s": 37329,
"text": "Our router view will be placed in app.html."
},
{
"code": null,
"e": 37594,
"s": 37373,
"text": "<template>\n <nav>\n <ul>\n <li repeat.for = \"row of router.navigation\">\n <a href.bind = \"row.href\">${row.title}</a>\n </li>\n </ul>\n </nav>\t\n <router-view></router-view>\n</template>"
},
{
"code": null,
"e": 37678,
"s": 37594,
"text": "When we run the app, we will can change the routes by clicking home or about links."
},
{
"code": null,
"e": 37745,
"s": 37678,
"text": "In this chapter, you will learn how to use aurelia-history plugin."
},
{
"code": null,
"e": 37929,
"s": 37745,
"text": "This plugin is already available as a part of the standard configuration. If you have set aurelia.use.standardConfiguration() as a part of a manual configuration, you are ready to go."
},
{
"code": null,
"e": 38088,
"s": 37929,
"text": "export function configure(aurelia) {\n aurelia.use\n .standardConfiguration()\n .developmentLogging();\n\n aurelia.start().then(() => aurelia.setRoot());\n}"
},
{
"code": null,
"e": 38334,
"s": 38088,
"text": "We will use an example from the last chapter (Aurelia - Routing). If we want to set the functionality for navigating back or forward, we can use the history object with back() and forward() methods. We will add this after a router configuration."
},
{
"code": null,
"e": 38813,
"s": 38334,
"text": "export class App {\n configureRouter(config, router) {\n config.title = 'Aurelia';\n config.map([\n { route: ['','home'], name: 'home', \n moduleId: './pages/home/home', nav: true, title:'Home' },\n { route: 'about', name: 'about', \n moduleId: './pages/about/about', nav: true, title:'About' }\n ]);\n this.router = router;\n }\n goBack() {\n history.back();\n }\n\tgoForward() {\n history.forward();\n }\n}"
},
{
"code": null,
"e": 38853,
"s": 38813,
"text": "Now, let's add two buttons to our view."
},
{
"code": null,
"e": 39281,
"s": 38853,
"text": "<template>\n <nav>\n <ul>\n <li repeat.for = \"row of router.navigation\"> \n <a href.bind = \"row.href\">${row.title}</a>\n </li>\n </ul>\n </nav>\n\t\n <button click.delegate = \"goBack()\"></button> \n //The button used for navigationg back...\n\t\n <button click.delegate = \"goForward()\"></button> \n //The button used for navigationg forward...\n\t\n <router-view></router-view>\n</template>"
},
{
"code": null,
"e": 39356,
"s": 39281,
"text": "The users can navigate back and forward by clicking the buttons we added. "
},
{
"code": null,
"e": 39436,
"s": 39356,
"text": "In this chapter, you will learn how to use CSS animations in Aurelia framework."
},
{
"code": null,
"e": 39544,
"s": 39436,
"text": "Our view will have one element that will be animated and a button to trigger the animateElement() function."
},
{
"code": null,
"e": 39666,
"s": 39544,
"text": "<template>\n <div class = \"myElement\"></div>\n <button click.delegate = \"animateElement()\">ANIMATE</button>\n</template>"
},
{
"code": null,
"e": 39878,
"s": 39666,
"text": "Inside our JavaScript file, we will import CssAnimator plugin and inject it as a dependency. The animateElement function will call the animator to start animation. The animation will be created in the next step."
},
{
"code": null,
"e": 40272,
"s": 39878,
"text": "import {CssAnimator} from 'aurelia-animator-css';\nimport {inject} from 'aurelia-framework';\n\n@inject(CssAnimator, Element)\nexport class App {\n constructor(animator, element) {\n this.animator = animator;\n this.element = element;\n }\n\n animateElement() {\n var myElement = this.element.querySelector('.myElement');\n this.animator.animate(myElement, 'myAnimation');\n }\n}"
},
{
"code": null,
"e": 40444,
"s": 40272,
"text": "We will write CSS inside styles/styles.css file. .myAnimation-add is the starting point of an animation while .myAnimation-remove is called when the animation is complete."
},
{
"code": null,
"e": 41132,
"s": 40444,
"text": ".myElement {\n width:100px;\n height: 100px;\n border:1px solid blue;\n}\n\n.myAnimation-add {\n -webkit-animation: changeBack 3s;\n animation: changeBack 3s;\n}\n\n.myAnimation-remove {\n -webkit-animation: fadeIn 3s;\n animation: fadeIn 3s;\n}\n\n@-webkit-keyframes changeBack {\n 0% { background-color: #e6efff; }\n 25% { background-color: #4d91ff; }\n 50% { background-color: #0058e6; }\n 75% { background-color: #003180; }\n 100% { background-color: #000a1a; }\n}\n\n@keyframes changeBack {\n 0% { background-color: #000a1a; }\n 25% { background-color: #003180; }\n 50% { background-color: #0058e6; }\n 75% { background-color: #4d91ff; }\n 100% { background-color: #e6efff; }\n}"
},
{
"code": null,
"e": 41336,
"s": 41132,
"text": "Once the ANIMATE button is clicked, the background color will be changed from light blue to a dark shade. When this animation is complete after three seconds, the element will fade to its starting state."
},
{
"code": null,
"e": 41442,
"s": 41336,
"text": "Aurelia offers a way to implement dialog (modal) window. In this chapter, we will show you how to use it."
},
{
"code": null,
"e": 41505,
"s": 41442,
"text": "Dialog plugin can be installed from the command prompt window."
},
{
"code": null,
"e": 41571,
"s": 41505,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>jspm install aurelia-dialog\n"
},
{
"code": null,
"e": 41742,
"s": 41571,
"text": "For this plugin to work, we need to use manual bootstrapping. We covered this in the Configuration chapter. Inside main.js file, we need to add the aurelia-dialog plugin."
},
{
"code": null,
"e": 41931,
"s": 41742,
"text": "export function configure(aurelia) {\n aurelia.use\n .standardConfiguration()\n .developmentLogging()\n .plugin('aurelia-dialog'); \n\n aurelia.start().then(() => aurelia.setRoot());\n}"
},
{
"code": null,
"e": 42078,
"s": 41931,
"text": "First, we will make a new directory called modal. Let's place it inside the components folder. Open the command prompt and run the following code."
},
{
"code": null,
"e": 42143,
"s": 42078,
"text": "C:\\Users\\username\\Desktop\\aureliaApp\\src\\components>mkdir modal\n"
},
{
"code": null,
"e": 42251,
"s": 42143,
"text": "In this folder, we will create two new files. These files will represent view and view-model for our modal."
},
{
"code": null,
"e": 42406,
"s": 42251,
"text": "C:\\Users\\username\\Desktop\\aureliaApp\\src\\components\\modal>touch my-modal.html\nC:\\Users\\username\\Desktop\\aureliaApp\\src\\components\\modal>touch my-modal.js\n"
},
{
"code": null,
"e": 42635,
"s": 42406,
"text": "First, let's add view-model code. We need to import and inject dialog-controller. This controller is used for handling modal specific functionalities. In the following example, we are using it to centralize a modal horizontally."
},
{
"code": null,
"e": 42988,
"s": 42635,
"text": "import {inject} from 'aurelia-framework';\nimport {DialogController} from 'aurelia-dialog';\n\n@inject(DialogController)\n\nexport class Prompt {\n constructor(controller) {\n this.controller = controller;\n this.answer = null;\n\n controller.settings.centerHorizontalOnly = true;\n }\n activate(message) {\n this.message = message;\n }\n}"
},
{
"code": null,
"e": 43078,
"s": 42988,
"text": "The view code will look like this. The buttons when clicked will open or close the modal."
},
{
"code": null,
"e": 43403,
"s": 43078,
"text": "<template>\n <ai-dialog>\n <ai-dialog-body>\n <h2>${message}</h2>\n </ai-dialog-body>\n\n <ai-dialog-footer>\n <button click.trigger = \"controller.cancel()\">Cancel</button>\n <button click.trigger = \"controller.ok(message)\">Ok</button>\n </ai-dialog-footer>\t\n </ai-dialog>\t\n</template>"
},
{
"code": null,
"e": 43627,
"s": 43403,
"text": "The last step is a function for triggering our modal. We need to import and inject DialogService. This service has method open, where we can pass view-model from my-modal file and model, so we can dynamically bind the data."
},
{
"code": null,
"e": 44233,
"s": 43627,
"text": "import {DialogService} from 'aurelia-dialog';\nimport {inject} from 'aurelia-framework';\nimport {Prompt} from './components/modal/my-modal';\n\n@inject(DialogService)\n\nexport class App {\n constructor(dialogService) {\n this.dialogService = dialogService;\n }\n openModal() {\n this.dialogService.open( {viewModel: Prompt, model: 'Are you sure?' }).then(response => {\n console.log(response);\n\t\t\t\n if (!response.wasCancelled) {\n console.log('OK');\n } else {\n console.log('cancelled');\n }\n console.log(response.output);\n });\n }\n};"
},
{
"code": null,
"e": 44301,
"s": 44233,
"text": "Finally, we will create a button so we can call openModal function."
},
{
"code": null,
"e": 44384,
"s": 44301,
"text": "<template>\n <button click.trigger = \"openModal()\">OPEN MODAL</button>\n<template>"
},
{
"code": null,
"e": 44469,
"s": 44384,
"text": "If we run the app, we can click the OPEN MODAL button to trigger a new modal window."
},
{
"code": null,
"e": 44573,
"s": 44469,
"text": "Aurelia offers i18n plugin. In this chapter, you will learn how to localize your app using this plugin."
},
{
"code": null,
"e": 44655,
"s": 44573,
"text": "Open the command prompt window and run the following code to install i18n plugin."
},
{
"code": null,
"e": 44719,
"s": 44655,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>jspm install aurelia-i18n\n"
},
{
"code": null,
"e": 44759,
"s": 44719,
"text": "We also need to install backend plugin."
},
{
"code": null,
"e": 44834,
"s": 44759,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>jspm install npm:i18next-xhr-backend\n"
},
{
"code": null,
"e": 44900,
"s": 44834,
"text": "In the project root folder, we need to create a locale directory."
},
{
"code": null,
"e": 44951,
"s": 44900,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>mkdir locale\n"
},
{
"code": null,
"e": 45073,
"s": 44951,
"text": "In this folder, you need to add new folders for any language you want. We will create en with translation.js file inside."
},
{
"code": null,
"e": 45201,
"s": 45073,
"text": "C:\\Users\\username\\Desktop\\aureliaApp\\locale>mkdir en\nC:\\Users\\username\\Desktop\\aureliaApp\\locale\\en>touch translation.json \n"
},
{
"code": null,
"e": 45371,
"s": 45201,
"text": "You need to use manual bootstrapping to be able to use this plugin. Check the Configuration chapter for more information. We need to add i18n plugin to the main.js file."
},
{
"code": null,
"e": 46059,
"s": 45371,
"text": "import {I18N} from 'aurelia-i18n';\nimport XHR from 'i18next-xhr-backend';\n\nexport function configure(aurelia) {\n aurelia.use\n .standardConfiguration()\n .developmentLogging()\n\t\n .plugin('aurelia-i18n', (instance) => {\n // register backend plugin\n instance.i18next.use(XHR);\n\n // adapt options to your needs (see http://i18next.com/docs/options/)\n instance.setup({\n backend: { \n loadPath: '/locales/{{lng}}/{{ns}}.json',\n },\n\t\t\t\t\n lng : 'de',\n attributes : ['t','i18n'],\n fallbackLng : 'en',\n debug : false\n });\n });\n\n aurelia.start().then(a => a.setRoot());\n}"
},
{
"code": null,
"e": 46317,
"s": 46059,
"text": "This is the file where you can set translation values. We will use an example from an official documentation. The de-DE folder should actually be used for translating to German language, however we will use English phrases instead, for easier understanding."
},
{
"code": null,
"e": 46631,
"s": 46317,
"text": "{\n \"score\": \"Score: {{score}}\",\n \"lives\": \"{{count}} life remaining\",\n \"lives_plural\": \"{{count}} lives remaining\",\n \"lives_indefinite\": \"a life remaining\",\n \"lives_plural_indefinite\": \"some lives remaining\",\n \"friend\": \"A friend\",\n \"friend_male\": \"A boyfriend\",\n \"friend_female\": \"A girlfriend\"\n}"
},
{
"code": null,
"e": 46713,
"s": 46631,
"text": "We just need to import i18n plugin and set it to use JSON code from de-DE folder."
},
{
"code": null,
"e": 46969,
"s": 46713,
"text": "import {I18N} from 'aurelia-i18n';\n\nexport class App {\n static inject = [I18N];\n\t\n constructor(i18n) {\n this.i18n = i18n;\n this.i18n\n .setLocale('de-DE')\n\t\t\n .then( () => {\n console.log('Locale is ready!');\n });\n }\n}"
},
{
"code": null,
"e": 47226,
"s": 46969,
"text": "There are couple of ways to translate data. We will use a custom ValueConverter named t. You can see in the following example various ways of formatting data. Compare this with the translation.json file and you will notice the patterns used for formatting."
},
{
"code": null,
"e": 47970,
"s": 47226,
"text": "<template>\n <p>\n Translation with Variables: <br />\n ${ 'score' | t: {'score': 13}}\n </p>\n\n <p>\n Translation singular: <br />\n ${ 'lives' | t: { 'count': 1 } }\n </p>\n\n <p>\n Translation plural: <br />\n ${ 'lives' | t: { 'count': 2 } }\n </p>\n\n <p> \n Translation singular indefinite: <br />\n ${ 'lives' | t: { 'count': 1, indefinite_article: true } }\n </p>\n\n <p>\n Translation plural indefinite: <br />\n ${ 'lives' | t: { 'count': 2, indefinite_article: true } }\n </p>\n\n <p>\n Translation without/with context: <br />\n ${ 'friend' | t } <br />\n ${ 'friend' | t: { context: 'male' } } <br />\n ${ 'friend' | t: { context: 'female' } }\n </p>\n\t\n</template>"
},
{
"code": null,
"e": 48025,
"s": 47970,
"text": "When we run the app, we will get the following output."
},
{
"code": null,
"e": 48094,
"s": 48025,
"text": "In this chapter, you will learn how to set up and use aurelia-tools."
},
{
"code": null,
"e": 48158,
"s": 48094,
"text": "Let's create a root folder where we will keep all Aurelia apps."
},
{
"code": null,
"e": 48208,
"s": 48158,
"text": "C:\\Users\\username\\Desktop>mkdir aurelia-projects\n"
},
{
"code": null,
"e": 48292,
"s": 48208,
"text": "Inside aurelia-projects folder, we will clone aurelia-tools repository from github."
},
{
"code": null,
"e": 48383,
"s": 48292,
"text": "C:\\Users\\username\\Desktop\\aurelia-projects>git clone https://github.com/aurelia/tools.git\n"
},
{
"code": null,
"e": 48515,
"s": 48383,
"text": "To start a new Aurelia project, the recommended way is to use one of the aurelia-skeletons. Let's clone Aurelia skeletons from git."
},
{
"code": null,
"e": 48620,
"s": 48515,
"text": "C:\\Users\\username\\Desktop\\aurelia-projects>git clone https://github.com/aurelia/skeleton-navigation.git\n"
},
{
"code": null,
"e": 48756,
"s": 48620,
"text": "We also need to install packages, modules, and dependencies. You can choose between various skeleton apps. We will use skeleton-es2016."
},
{
"code": null,
"e": 48940,
"s": 48756,
"text": "C:\\Users\\username\\Desktop\\aurelia-projects\\skeleton-navigation\\skeleton-es2016>npm install\nC:\\Users\\username\\Desktop\\aurelia-projects\\skeleton-navigation\\skeleton-es2016>jspm install\n"
},
{
"code": null,
"e": 49021,
"s": 48940,
"text": "Finally, we need to run the following code to build the development environment."
},
{
"code": null,
"e": 49120,
"s": 49021,
"text": "C:\\Users\\username\\Desktop\\aurelia-projects\\skeleton-navigation\\skeleton-es2016>gulp build-dev-env\n"
},
{
"code": null,
"e": 49175,
"s": 49120,
"text": "Update local repositories using the following command."
},
{
"code": null,
"e": 49276,
"s": 49175,
"text": "C:\\Users\\username\\Desktop\\aurelia-projects\\skeleton-navigation\\skeleton-es2016>gulp update-own-deps\n"
},
{
"code": null,
"e": 49330,
"s": 49276,
"text": "We can also pull Aurelia dependency without building."
},
{
"code": null,
"e": 49428,
"s": 49330,
"text": "C:\\Users\\username\\Desktop\\aurelia-projects\\skeleton-navigation\\skeleton-es2016>gulp pull-dev-env\n"
},
{
"code": null,
"e": 49502,
"s": 49428,
"text": "In this chapter, you will learn how to use bundling in Aurelia framework."
},
{
"code": null,
"e": 49590,
"s": 49502,
"text": "You can install aurelia-bundler by running the following command in the command prompt."
},
{
"code": null,
"e": 49667,
"s": 49590,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>npm install aurelia-bundler --save-dev\n"
},
{
"code": null,
"e": 49742,
"s": 49667,
"text": "If you don't have gulp installed, you can install it by running this code."
},
{
"code": null,
"e": 49797,
"s": 49742,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>npm install gulp\n"
},
{
"code": null,
"e": 49848,
"s": 49797,
"text": "You can also install require-dir package from npm."
},
{
"code": null,
"e": 49910,
"s": 49848,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>npm install require-dir\n"
},
{
"code": null,
"e": 49965,
"s": 49910,
"text": "First, create gulpfile.js file in apps root directory."
},
{
"code": null,
"e": 50021,
"s": 49965,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>touch gulpfile.js\n"
},
{
"code": null,
"e": 50104,
"s": 50021,
"text": "You will need the build folder. In this directory, add another folder named tasks."
},
{
"code": null,
"e": 50209,
"s": 50104,
"text": "C:\\Users\\username\\Desktop\\aureliaApp>mkdir build\nC:\\Users\\username\\Desktop\\aureliaApp\\build>mkdir tasks\n"
},
{
"code": null,
"e": 50264,
"s": 50209,
"text": "You need to create bundle.js file inside tasks folder."
},
{
"code": null,
"e": 50330,
"s": 50264,
"text": "C:\\Users\\username\\Desktop\\aureliaApp\\build\\tasks>touch bundle.js\n"
},
{
"code": null,
"e": 50423,
"s": 50330,
"text": "Use gulp as the task runner. You need to tell it to run the code from build\\tasks\\bundle.js."
},
{
"code": null,
"e": 50463,
"s": 50423,
"text": "require('require-dir')('build/tasks');\n"
},
{
"code": null,
"e": 50734,
"s": 50463,
"text": "Now, create the task that you need. This task will take the app, create dist/appbuild.js and dist/vendor-build.js files. After the bundling process is complete, the config.js file will also be updated. You can include all files and plugins you want to inject and minify."
},
{
"code": null,
"e": 51490,
"s": 50734,
"text": "var gulp = require('gulp');\nvar bundle = require('aurelia-bundler').bundle;\n\nvar config = {\n force: true,\n baseURL: '.',\n configPath: './config.js',\n\t\n bundles: {\n \"dist/app-build\": {\n includes: [\n '[*.js]',\n '*.html!text',\n '*.css!text',\n ],\n options: {\n inject: true,\n minify: true\n }\n },\n\t\t\"dist/vendor-build\": {\n includes: [\n 'aurelia-bootstrapper',\n 'aurelia-fetch-client',\n 'aurelia-router',\n 'aurelia-animator-css',\n ],\n options: {\n inject: true,\n minify: true\n }\n }\n }\n};\n\ngulp.task('bundle', function() {\n return bundle(config);\n}); "
},
{
"code": null,
"e": 51551,
"s": 51490,
"text": "The command prompt will inform us when bundling is complete."
},
{
"code": null,
"e": 51642,
"s": 51551,
"text": "In this chapter, you will learn how to add Aurelia context debugger as a chrome extension."
},
{
"code": null,
"e": 51767,
"s": 51642,
"text": "Note − Before adding the extension, you need to have aurelia-tools files. If you don't have it, you can check Tools chapter."
},
{
"code": null,
"e": 51860,
"s": 51767,
"text": "The easiest way to open chrome extensions is to run the following code in browser’s URL bar."
},
{
"code": null,
"e": 51881,
"s": 51860,
"text": "chrome://extensions\n"
},
{
"code": null,
"e": 52079,
"s": 51881,
"text": "Since this extension isn't yet available from Chrome store, check developermode checkbox and click Load Unpacked Extensions. This will open a small window where you can choose the extension to add."
},
{
"code": null,
"e": 52179,
"s": 52079,
"text": "For this example, let us choose Desktop/aurelia-projects/tools/context-debugger folder and open it."
},
{
"code": null,
"e": 52240,
"s": 52179,
"text": "Now, we can see that the extension is loaded in the browser."
},
{
"code": null,
"e": 52369,
"s": 52240,
"text": "We can also check the developers console. When we click elements tab, we will see aurelia-properties at the bottom right corner."
},
{
"code": null,
"e": 52580,
"s": 52369,
"text": "Community is one of the most important factors to consider when choosing a framework. Aurelia offers fantastic support for its customers. In this chapter, you will learn how you can get help when you are stuck."
},
{
"code": null,
"e": 52650,
"s": 52580,
"text": "You can find Aurelia docs on this link − https://aurelia.io/docs.html"
},
{
"code": null,
"e": 52821,
"s": 52650,
"text": "If you need a fast answer, you can always submit a question to aurelia gitter channel. This channel can be found on the following link − https://gitter.im/Aurelia/Discuss"
},
{
"code": null,
"e": 52915,
"s": 52821,
"text": "You can also submit an issue to official Aurelia github repository https://github.com/aurelia"
},
{
"code": null,
"e": 53045,
"s": 52915,
"text": "If you want to keep track of any updates and changes of Aurelia, you can follow Durandal's official blog http://blog.durandal.io/"
},
{
"code": null,
"e": 53168,
"s": 53045,
"text": "You can also follow the official blog of Rob Eisenberg, creator of Aurelia framework http://eisenbergeffect.bluespire.com/"
},
{
"code": null,
"e": 53293,
"s": 53168,
"text": "Aurelia offers enterprise support for teams and individuals. If you are interested, send an email to the following address −"
},
{
"code": null,
"e": 53314,
"s": 53293,
"text": "[email protected]\n"
},
{
"code": null,
"e": 53390,
"s": 53314,
"text": "You can hire Aurelia Expert Developers by sending an email to this address."
},
{
"code": null,
"e": 53414,
"s": 53390,
"text": "[email protected]\n"
},
{
"code": null,
"e": 53506,
"s": 53414,
"text": "If you want Aurelia official training for your team, you can send an email to this address."
},
{
"code": null,
"e": 53528,
"s": 53506,
"text": "[email protected]\n"
},
{
"code": null,
"e": 53673,
"s": 53528,
"text": "Aurelia is a new framework hence, the best practices are yet to be established. In this chapter, you will find some useful guidelines to follow."
},
{
"code": null,
"e": 53890,
"s": 53673,
"text": "Aurelia offers aurelia-skeletons. There are a couple of skeletons to choose from. The team behind Aurelia is actively supporting the skeletons, and they are always up-to-date with the newest version of the framework."
},
{
"code": null,
"e": 54007,
"s": 53890,
"text": "skeleton-es2016-webpack allows you to write ES2016 code and use npm for package management and webpack for bundling."
},
{
"code": null,
"e": 54124,
"s": 54007,
"text": "skeleton-es2016-webpack allows you to write ES2016 code and use npm for package management and webpack for bundling."
},
{
"code": null,
"e": 54247,
"s": 54124,
"text": "skeleton-es2016 allows you to write ES2016 code and use jspm for package management and SystemJS for loading and bundling."
},
{
"code": null,
"e": 54370,
"s": 54247,
"text": "skeleton-es2016 allows you to write ES2016 code and use jspm for package management and SystemJS for loading and bundling."
},
{
"code": null,
"e": 54495,
"s": 54370,
"text": "skeleton-typescript-webpack allows you to write TypeScript code and use npm for package management and webpack for bundling."
},
{
"code": null,
"e": 54620,
"s": 54495,
"text": "skeleton-typescript-webpack allows you to write TypeScript code and use npm for package management and webpack for bundling."
},
{
"code": null,
"e": 54751,
"s": 54620,
"text": "skeleton-typescript allows you to write TypeScript code and use jspm for package management and SystemJS for loading and bundling."
},
{
"code": null,
"e": 54882,
"s": 54751,
"text": "skeleton-typescript allows you to write TypeScript code and use jspm for package management and SystemJS for loading and bundling."
},
{
"code": null,
"e": 55062,
"s": 54882,
"text": "skeleton-typescript-asp.net5 allows you to write TypeScript code and use jspm for package management and SystemJS for loading and bundling. The ASP.NET backend is also integrated."
},
{
"code": null,
"e": 55242,
"s": 55062,
"text": "skeleton-typescript-asp.net5 allows you to write TypeScript code and use jspm for package management and SystemJS for loading and bundling. The ASP.NET backend is also integrated."
},
{
"code": null,
"e": 55409,
"s": 55242,
"text": "skeleton-es2016-asp.net5 allows you to write ES2016 code and use jspm for package management and SystemJS for loading and bundling. The ASP.NET backend is integrated."
},
{
"code": null,
"e": 55576,
"s": 55409,
"text": "skeleton-es2016-asp.net5 allows you to write ES2016 code and use jspm for package management and SystemJS for loading and bundling. The ASP.NET backend is integrated."
},
{
"code": null,
"e": 55702,
"s": 55576,
"text": "You can clone all skeletons from GitHub. The installation instructions can be found inside README.md files for each skeleton."
},
{
"code": null,
"e": 55790,
"s": 55702,
"text": "C:\\Users\\username\\Desktop>git clone https://github.com/aurelia/skeleton-navigation.git\n"
},
{
"code": null,
"e": 55981,
"s": 55790,
"text": "You are free to use any folder structure you want. If you are not sure where to start, you can use the following folder structure. The image represents files and folder in the src directory."
},
{
"code": null,
"e": 56323,
"s": 55981,
"text": "Aurelia is a framework oriented to web standards. This was one of the main goals of the team behind it. They will make sure that the framework always follows modern web. This is extremely good for the developers, since we can rely on the usability of the framework in the future. It also helps us be up-to-date with the browsers and the web."
},
{
"code": null,
"e": 56548,
"s": 56323,
"text": "This is a good practice not just for Aurelia but for any other JavaScript framework. ES6 offers new functionalities that can help in the development process. You can also use TypeScript, if you like strongly typed languages."
},
{
"code": null,
"e": 56555,
"s": 56548,
"text": " Print"
},
{
"code": null,
"e": 56566,
"s": 56555,
"text": " Add Notes"
}
] |
Bootstrap - Navigation Elements | Bootstrap provides a few different options for styling navigation elements. All of them share the same markup and base class, .nav. Bootstrap also provides a helper class, to share markup and states. Swap modifier classes to switch between each style.
To create a tabbed navigation menu −
Start with a basic unordered list with the base class of .nav
Start with a basic unordered list with the base class of .nav
Add class .nav-tabs.
Add class .nav-tabs.
The following example demonstrates this −
<p>Tabs Example</p>
<ul class = "nav nav-tabs">
<li class = "active"><a href = "#">Home</a></li>
<li><a href = "#">SVN</a></li>
<li><a href = "#">iOS</a></li>
<li><a href = "#">VB.Net</a></li>
<li><a href = "#">Java</a></li>
<li><a href = "#">PHP</a></li>
</ul>
Tabs Example
Home
SVN
iOS
VB.Net
Java
PHP
To turn the tabs into pills, follow the same steps as above, use the class .nav-pills instead of .nav-tabs.
The following example demonstrates this −
<p>Pills Example</p>
<ul class = "nav nav-pills">
<li class = "active"><a href = "#">Home</a></li>
<li><a href = "#">SVN</a></li>
<li><a href = "#">iOS</a></li>
<li><a href = "#">VB.Net</a></li>
<li><a href = "#">Java</a></li>
<li><a href = "#">PHP</a></li>
</ul>
Pills Example
Home
SVN
iOS
VB.Net
Java
PHP
You can stack the pills vertically using the class .nav-stacked along with the classes − .nav, .nav-pills.
The following example demonstrates this −
<p>Vertical Pills Example</p>
<ul class = "nav nav-pills nav-stacked">
<li class = "active"><a href = "#">Home</a></li>
<li><a href = "#">SVN</a></li>
<li><a href = "#">iOS</a></li>
<li><a href = "#">VB.Net</a></li>
<li><a href = "#">Java</a></li>
<li><a href = "#">PHP</a></li>
</ul>
Vertical Pills Example
Home
SVN
iOS
VB.Net
Java
PHP
You can make tabs or pills of equal widths as of their parent at screens wider than 768px using class .nav-justified along with .nav, .nav-tabs or .nav, .nav-pills respectively. On smaller screens, the nav links are stacked.
The following example demonstrates this −
<p>Justified Nav Elements Example</p>
<ul class = "nav nav-pills nav-justified">
<li class = "active"><a href = "#">Home</a></li>
<li><a href = "#">SVN</a></li>
<li><a href = "#">iOS</a></li>
<li><a href = "#">VB.Net</a></li>
<li><a href = "#">Java</a></li>
<li><a href = "#">PHP</a></li>
</ul>
<br>
<br>
<br>
<ul class = "nav nav-tabs nav-justified">
<li class = "active"><a href = "#">Home</a></li>
<li><a href = "#">SVN</a></li>
<li><a href = "#">iOS</a></li>
<li><a href = "#">VB.Net</a></li>
<li><a href = "#">Java</a></li>
<li><a href = "#">PHP</a></li>
</ul>
Justified Nav Elements Example
Home
SVN
iOS
VB.Net
Java
PHP
Home
SVN
iOS
VB.Net
Java
PHP
For each of the .nav classes, if you add the .disabled class, it will create a gray link that also disables the :hover state as shown in the following example −
<p>Disabled Link Example</p>
<ul class = "nav nav-pills">
<li class = "active"><a href = "#">Home</a></li>
<li><a href = "#">SVN</a></li>
<li class = "disabled"><a href = "#">iOS(disabled link)</a></li>
<li><a href = "#">VB.Net</a></li>
<li><a href = "#">Java</a></li>
<li><a href = "#">PHP</a></li>
</ul>
<br>
<br>
<ul class = "nav nav-tabs">
<li class = "active"><a href = "#">Home</a></li>
<li><a href = "#">SVN</a></li>
<li><a href = "#">iOS</a></li>
<li class = "disabled"><a href = "#">VB.Net(disabled link)</a></li>
<li><a href = "#">Java</a></li>
<li><a href = "#">PHP</a></li>
</ul>
Disabled Link Example
Home
SVN
iOS(disabled link)
VB.Net
Java
PHP
Home
SVN
iOS
VB.Net(disabled link)
Java
PHP
Navigation menus share a similar syntax with dropdown menus. By default, you have a list item that has an anchor working in conjunction with some data-attributes to trigger an unordered list with a .dropdown-menu class.
To add dropdowns to tab −
Start with a basic unordered list with the base class of .nav
Start with a basic unordered list with the base class of .nav
Add the class .nav-tabs.
Add the class .nav-tabs.
Now add an unordered list with a .dropdown-menu class.
Now add an unordered list with a .dropdown-menu class.
<p>Tabs With Dropdown Example</p>
<ul class = "nav nav-tabs">
<li class = "active"><a href = "#">Home</a></li>
<li><a href = "#">SVN</a></li>
<li><a href = "#">iOS</a></li>
<li><a href = "#">VB.Net</a></li>
<li class = "dropdown">
<a class = "dropdown-toggle" data-toggle = "dropdown" href = "#">
Java
<span class = "caret"></span>
</a>
<ul class = "dropdown-menu">
<li><a href = "#">Swing</a></li>
<li><a href = "#">jMeter</a></li>
<li><a href = "#">EJB</a></li>
<li class = "divider"></li>
<li><a href = "#">Separated link</a></li>
</ul>
</li>
<li><a href = "#">PHP</a></li>
</ul>
Tabs With Dropdown Example
Home
SVN
iOS
VB.Net
Java
Swing
jMeter
EJB
Separated link
Swing
jMeter
EJB
Separated link
PHP
To do the same thing with pills, simply swap the .nav-tabs class with .nav-pills as shown in the following example.
<p>Pills With Dropdown Example</p>
<ul class = "nav nav-pills">
<li class = "active"><a href = "#">Home</a></li>
<li><a href = "#">SVN</a></li>
<li><a href = "#">iOS</a></li>
<li><a href = "#">VB.Net</a></li>
<li class = "dropdown">
<a class = "dropdown-toggle" data-toggle = "dropdown" href = "#">
Java <span class = "caret"></span>
</a>
<ul class = "dropdown-menu">
<li><a href = "#">Swing</a></li>
<li><a href = "#">jMeter</a></li>
<li><a href = "#">EJB</a></li>
<li class = "divider"></li>
<li><a href = "#">Separated link</a></li>
</ul>
</li>
<li><a href = "#">PHP</a></li>
</ul>
Pills With Dropdown Example
Home
SVN
iOS
VB.Net
Java
Swing
jMeter
EJB
Separated link
Swing
jMeter
EJB
Separated link
PHP
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3583,
"s": 3331,
"text": "Bootstrap provides a few different options for styling navigation elements. All of them share the same markup and base class, .nav. Bootstrap also provides a helper class, to share markup and states. Swap modifier classes to switch between each style."
},
{
"code": null,
"e": 3620,
"s": 3583,
"text": "To create a tabbed navigation menu −"
},
{
"code": null,
"e": 3682,
"s": 3620,
"text": "Start with a basic unordered list with the base class of .nav"
},
{
"code": null,
"e": 3744,
"s": 3682,
"text": "Start with a basic unordered list with the base class of .nav"
},
{
"code": null,
"e": 3765,
"s": 3744,
"text": "Add class .nav-tabs."
},
{
"code": null,
"e": 3786,
"s": 3765,
"text": "Add class .nav-tabs."
},
{
"code": null,
"e": 3828,
"s": 3786,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 4109,
"s": 3828,
"text": "<p>Tabs Example</p>\n\n<ul class = \"nav nav-tabs\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">SVN</a></li>\n <li><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">VB.Net</a></li>\n <li><a href = \"#\">Java</a></li>\n <li><a href = \"#\">PHP</a></li>\n</ul>"
},
{
"code": null,
"e": 4122,
"s": 4109,
"text": "Tabs Example"
},
{
"code": null,
"e": 4127,
"s": 4122,
"text": "Home"
},
{
"code": null,
"e": 4131,
"s": 4127,
"text": "SVN"
},
{
"code": null,
"e": 4135,
"s": 4131,
"text": "iOS"
},
{
"code": null,
"e": 4142,
"s": 4135,
"text": "VB.Net"
},
{
"code": null,
"e": 4147,
"s": 4142,
"text": "Java"
},
{
"code": null,
"e": 4151,
"s": 4147,
"text": "PHP"
},
{
"code": null,
"e": 4259,
"s": 4151,
"text": "To turn the tabs into pills, follow the same steps as above, use the class .nav-pills instead of .nav-tabs."
},
{
"code": null,
"e": 4301,
"s": 4259,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 4584,
"s": 4301,
"text": "<p>Pills Example</p>\n\n<ul class = \"nav nav-pills\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">SVN</a></li>\n <li><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">VB.Net</a></li>\n <li><a href = \"#\">Java</a></li>\n <li><a href = \"#\">PHP</a></li>\n</ul>"
},
{
"code": null,
"e": 4598,
"s": 4584,
"text": "Pills Example"
},
{
"code": null,
"e": 4603,
"s": 4598,
"text": "Home"
},
{
"code": null,
"e": 4607,
"s": 4603,
"text": "SVN"
},
{
"code": null,
"e": 4611,
"s": 4607,
"text": "iOS"
},
{
"code": null,
"e": 4618,
"s": 4611,
"text": "VB.Net"
},
{
"code": null,
"e": 4623,
"s": 4618,
"text": "Java"
},
{
"code": null,
"e": 4627,
"s": 4623,
"text": "PHP"
},
{
"code": null,
"e": 4734,
"s": 4627,
"text": "You can stack the pills vertically using the class .nav-stacked along with the classes − .nav, .nav-pills."
},
{
"code": null,
"e": 4776,
"s": 4734,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 5080,
"s": 4776,
"text": "<p>Vertical Pills Example</p>\n\n<ul class = \"nav nav-pills nav-stacked\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">SVN</a></li>\n <li><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">VB.Net</a></li>\n <li><a href = \"#\">Java</a></li>\n <li><a href = \"#\">PHP</a></li>\n</ul>"
},
{
"code": null,
"e": 5103,
"s": 5080,
"text": "Vertical Pills Example"
},
{
"code": null,
"e": 5108,
"s": 5103,
"text": "Home"
},
{
"code": null,
"e": 5112,
"s": 5108,
"text": "SVN"
},
{
"code": null,
"e": 5116,
"s": 5112,
"text": "iOS"
},
{
"code": null,
"e": 5123,
"s": 5116,
"text": "VB.Net"
},
{
"code": null,
"e": 5128,
"s": 5123,
"text": "Java"
},
{
"code": null,
"e": 5132,
"s": 5128,
"text": "PHP"
},
{
"code": null,
"e": 5357,
"s": 5132,
"text": "You can make tabs or pills of equal widths as of their parent at screens wider than 768px using class .nav-justified along with .nav, .nav-tabs or .nav, .nav-pills respectively. On smaller screens, the nav links are stacked."
},
{
"code": null,
"e": 5399,
"s": 5357,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 6004,
"s": 5399,
"text": "<p>Justified Nav Elements Example</p>\n\n<ul class = \"nav nav-pills nav-justified\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">SVN</a></li>\n <li><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">VB.Net</a></li>\n <li><a href = \"#\">Java</a></li>\n <li><a href = \"#\">PHP</a></li>\n</ul>\n\n<br>\n<br>\n<br>\n\n<ul class = \"nav nav-tabs nav-justified\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">SVN</a></li>\n <li><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">VB.Net</a></li>\n <li><a href = \"#\">Java</a></li>\n <li><a href = \"#\">PHP</a></li>\n</ul>"
},
{
"code": null,
"e": 6035,
"s": 6004,
"text": "Justified Nav Elements Example"
},
{
"code": null,
"e": 6040,
"s": 6035,
"text": "Home"
},
{
"code": null,
"e": 6044,
"s": 6040,
"text": "SVN"
},
{
"code": null,
"e": 6048,
"s": 6044,
"text": "iOS"
},
{
"code": null,
"e": 6055,
"s": 6048,
"text": "VB.Net"
},
{
"code": null,
"e": 6060,
"s": 6055,
"text": "Java"
},
{
"code": null,
"e": 6064,
"s": 6060,
"text": "PHP"
},
{
"code": null,
"e": 6069,
"s": 6064,
"text": "Home"
},
{
"code": null,
"e": 6073,
"s": 6069,
"text": "SVN"
},
{
"code": null,
"e": 6077,
"s": 6073,
"text": "iOS"
},
{
"code": null,
"e": 6084,
"s": 6077,
"text": "VB.Net"
},
{
"code": null,
"e": 6089,
"s": 6084,
"text": "Java"
},
{
"code": null,
"e": 6093,
"s": 6089,
"text": "PHP"
},
{
"code": null,
"e": 6254,
"s": 6093,
"text": "For each of the .nav classes, if you add the .disabled class, it will create a gray link that also disables the :hover state as shown in the following example −"
},
{
"code": null,
"e": 6894,
"s": 6254,
"text": "<p>Disabled Link Example</p>\n\n<ul class = \"nav nav-pills\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">SVN</a></li>\n \n <li class = \"disabled\"><a href = \"#\">iOS(disabled link)</a></li>\n <li><a href = \"#\">VB.Net</a></li>\n <li><a href = \"#\">Java</a></li>\n <li><a href = \"#\">PHP</a></li>\n</ul>\n\n<br>\n<br>\n\n<ul class = \"nav nav-tabs\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">SVN</a></li>\n <li><a href = \"#\">iOS</a></li>\n \n <li class = \"disabled\"><a href = \"#\">VB.Net(disabled link)</a></li>\n <li><a href = \"#\">Java</a></li>\n <li><a href = \"#\">PHP</a></li>\n</ul>\t"
},
{
"code": null,
"e": 6916,
"s": 6894,
"text": "Disabled Link Example"
},
{
"code": null,
"e": 6921,
"s": 6916,
"text": "Home"
},
{
"code": null,
"e": 6925,
"s": 6921,
"text": "SVN"
},
{
"code": null,
"e": 6944,
"s": 6925,
"text": "iOS(disabled link)"
},
{
"code": null,
"e": 6951,
"s": 6944,
"text": "VB.Net"
},
{
"code": null,
"e": 6956,
"s": 6951,
"text": "Java"
},
{
"code": null,
"e": 6960,
"s": 6956,
"text": "PHP"
},
{
"code": null,
"e": 6965,
"s": 6960,
"text": "Home"
},
{
"code": null,
"e": 6969,
"s": 6965,
"text": "SVN"
},
{
"code": null,
"e": 6973,
"s": 6969,
"text": "iOS"
},
{
"code": null,
"e": 6995,
"s": 6973,
"text": "VB.Net(disabled link)"
},
{
"code": null,
"e": 7000,
"s": 6995,
"text": "Java"
},
{
"code": null,
"e": 7004,
"s": 7000,
"text": "PHP"
},
{
"code": null,
"e": 7224,
"s": 7004,
"text": "Navigation menus share a similar syntax with dropdown menus. By default, you have a list item that has an anchor working in conjunction with some data-attributes to trigger an unordered list with a .dropdown-menu class."
},
{
"code": null,
"e": 7250,
"s": 7224,
"text": "To add dropdowns to tab −"
},
{
"code": null,
"e": 7312,
"s": 7250,
"text": "Start with a basic unordered list with the base class of .nav"
},
{
"code": null,
"e": 7374,
"s": 7312,
"text": "Start with a basic unordered list with the base class of .nav"
},
{
"code": null,
"e": 7399,
"s": 7374,
"text": "Add the class .nav-tabs."
},
{
"code": null,
"e": 7424,
"s": 7399,
"text": "Add the class .nav-tabs."
},
{
"code": null,
"e": 7479,
"s": 7424,
"text": "Now add an unordered list with a .dropdown-menu class."
},
{
"code": null,
"e": 7534,
"s": 7479,
"text": "Now add an unordered list with a .dropdown-menu class."
},
{
"code": null,
"e": 8247,
"s": 7534,
"text": "<p>Tabs With Dropdown Example</p>\n\n<ul class = \"nav nav-tabs\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">SVN</a></li>\n <li><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">VB.Net</a></li>\n \n <li class = \"dropdown\">\n <a class = \"dropdown-toggle\" data-toggle = \"dropdown\" href = \"#\">\n Java \n <span class = \"caret\"></span>\n </a>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">Swing</a></li>\n <li><a href = \"#\">jMeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n \n </li>\n\t\n <li><a href = \"#\">PHP</a></li>\n</ul>"
},
{
"code": null,
"e": 8274,
"s": 8247,
"text": "Tabs With Dropdown Example"
},
{
"code": null,
"e": 8279,
"s": 8274,
"text": "Home"
},
{
"code": null,
"e": 8283,
"s": 8279,
"text": "SVN"
},
{
"code": null,
"e": 8287,
"s": 8283,
"text": "iOS"
},
{
"code": null,
"e": 8294,
"s": 8287,
"text": "VB.Net"
},
{
"code": null,
"e": 8354,
"s": 8294,
"text": "\n\n Java \n\n\nSwing\njMeter\nEJB\n\nSeparated link\n\n"
},
{
"code": null,
"e": 8360,
"s": 8354,
"text": "Swing"
},
{
"code": null,
"e": 8367,
"s": 8360,
"text": "jMeter"
},
{
"code": null,
"e": 8371,
"s": 8367,
"text": "EJB"
},
{
"code": null,
"e": 8386,
"s": 8371,
"text": "Separated link"
},
{
"code": null,
"e": 8390,
"s": 8386,
"text": "PHP"
},
{
"code": null,
"e": 8506,
"s": 8390,
"text": "To do the same thing with pills, simply swap the .nav-tabs class with .nav-pills as shown in the following example."
},
{
"code": null,
"e": 9221,
"s": 8506,
"text": "<p>Pills With Dropdown Example</p>\n\n<ul class = \"nav nav-pills\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">SVN</a></li>\n <li><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">VB.Net</a></li>\n \n <li class = \"dropdown\">\n <a class = \"dropdown-toggle\" data-toggle = \"dropdown\" href = \"#\">\n Java <span class = \"caret\"></span>\n </a>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">Swing</a></li>\n <li><a href = \"#\">jMeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n \n </li>\n\t\n <li><a href = \"#\">PHP</a></li>\n</ul>"
},
{
"code": null,
"e": 9249,
"s": 9221,
"text": "Pills With Dropdown Example"
},
{
"code": null,
"e": 9254,
"s": 9249,
"text": "Home"
},
{
"code": null,
"e": 9258,
"s": 9254,
"text": "SVN"
},
{
"code": null,
"e": 9262,
"s": 9258,
"text": "iOS"
},
{
"code": null,
"e": 9269,
"s": 9262,
"text": "VB.Net"
},
{
"code": null,
"e": 9329,
"s": 9269,
"text": "\n\n Java \n\n\nSwing\njMeter\nEJB\n\nSeparated link\n\n"
},
{
"code": null,
"e": 9335,
"s": 9329,
"text": "Swing"
},
{
"code": null,
"e": 9342,
"s": 9335,
"text": "jMeter"
},
{
"code": null,
"e": 9346,
"s": 9342,
"text": "EJB"
},
{
"code": null,
"e": 9361,
"s": 9346,
"text": "Separated link"
},
{
"code": null,
"e": 9365,
"s": 9361,
"text": "PHP"
},
{
"code": null,
"e": 9398,
"s": 9365,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9412,
"s": 9398,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9447,
"s": 9412,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9464,
"s": 9447,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9501,
"s": 9464,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 9529,
"s": 9501,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9562,
"s": 9529,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 9574,
"s": 9562,
"text": " Azaz Patel"
},
{
"code": null,
"e": 9609,
"s": 9574,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9626,
"s": 9609,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 9659,
"s": 9626,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 9679,
"s": 9659,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 9686,
"s": 9679,
"text": " Print"
},
{
"code": null,
"e": 9697,
"s": 9686,
"text": " Add Notes"
}
] |
Search an element in an array where difference between adjacent elements is 1 | 28 Jun, 2022
Given an array where difference between adjacent elements is 1, write an algorithm to search for an element in the array and return the position of the element (return the first occurrence).Examples :
Let element to be searched be x
Input: arr[] = {8, 7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3}
x = 3
Output: Element 3 found at index 7
Input: arr[] = {1, 2, 3, 4, 5, 4}
x = 5
Output: Element 5 found at index 4
A Simple Approach is to traverse the given array one by one and compare every element with given element ‘x’. If matches, then return index.
The above solution can be Optimized using the fact that difference between all adjacent elements is 1. The idea is to start comparing from the leftmost element and find the difference between current array element and x. Let this difference be ‘diff’. From the given property of array, we always know that x must be at-least ‘diff’ away, so instead of searching one by one, we jump ‘diff’.
Below is the implementation of above idea.
C++
C
Java
Python 3
C#
PHP
Javascript
// C++ program to search an element in an array where// difference between all elements is 1#include <bits/stdc++.h>using namespace std; // x is the element to be searched in arr[0..n-1]int search(int arr[], int n, int x){ // Traverse the given array starting from // leftmost element int i = 0; while (i < n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between current // array element and x i = i + abs(arr[i] - x); } cout << "number is not present!"; return -1;} // Driver program to test above functionint main(){ int arr[] = { 8, 7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; cout << "Element " << x << " is present at index " << search(arr, n, 3); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to search an element in an array where// difference between all elements is 1#include <stdio.h>#include <stdlib.h> // x is the element to be searched in arr[0..n-1]int search(int arr[], int n, int x){ // Traverse the given array starting from // leftmost element int i = 0; while (i < n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between current // array element and x i = i + abs(arr[i] - x); } printf("number is not present!"); return -1;} // Driver program to test above functionint main(){ int arr[] = { 8, 7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; printf("Element %d is present at index ", search(arr, n, 3)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to search an element in an// array where difference between all// elements is 1 import java.io.*; class GFG { // x is the element to be searched // in arr[0..n-1] static int search(int arr[], int n, int x) { // Traverse the given array starting // from leftmost element int i = 0; while (i < n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between current // array element and x i = i + Math.abs(arr[i]-x); } System.out.println ("number is not" + " present!"); return -1; } // Driver program to test above function public static void main (String[] args) { int arr[] = {8 ,7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 }; int n = arr.length; int x = 3; System.out.println("Element " + x + " is present at index " + search(arr,n,3)); }} //This code is contributed by vt_m.
# Python 3 program to search an element# in an array where difference between# all elements is 1 # x is the element to be searched in# arr[0..n-1]def search(arr, n, x): # Traverse the given array starting # from leftmost element i = 0 while (i < n): # If x is found at index i if (arr[i] == x): return i # Jump the difference between # current array element and x i = i + abs(arr[i] - x) print("number is not present!") return -1 # Driver program to test above functionarr = [8 ,7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 ]n = len(arr)x = 3print("Element" , x , " is present at index ", search(arr,n,3)) # This code is contributed by Smitha
// C# program to search an element// in an array where difference// between all elements is 1using System; public class GFG{ // in arr[0..n-1] static int search(int []arr, int n, int x) { // Traverse the given array starting // from leftmost element int i = 0; while (i < n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between // current array element and x i = i + Math.Abs(arr[i] - x); } Console.WriteLine ("number is not" + " present!"); return -1; } // Driver code public static void Main() { int []arr = {8 ,7, 6, 7, 6, 5, 4,3, 2, 3, 4, 3 }; int n = arr.Length; int x = 3; Console.WriteLine("Element " + x + " is present at index " + search(arr, n, 3)); }} // This code is contributed by Sam007
<?php// PHP program to search an// element in an array where// difference between all// elements is 1 // x is the element to be// searched in arr[0..n-1]function search($arr, $n, $x){ // Traverse the given array // starting from leftmost // element $i = 0; while ($i < $n) { // If x is found at index i if ($arr[$i] == $x) return $i; // Jump the difference // between current // array element and x $i = $i + abs($arr[$i] - $x); } echo "number is not present!"; return -1;} // Driver Code$arr = array(8 ,7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3);$n = sizeof($arr);$x = 3;echo "Element " , $x , " is present " , "at index ", search($arr, $n, 3); // This code is contributed// by nitin mittal.?>
<script> // Javascript program to search an element in an array where// difference between all elements is 1 // x is the element to be searched in arr[0..n-1]function search(arr, n, x){ // Traverse the given array starting from // leftmost element let i = 0; while (i<n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between current // array element and x i = i + Math.abs(arr[i]-x); } document.write("number is not present!"); return -1;} // Driver program let arr = [8 ,7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 ]; let n = arr.length; let x = 3; document.write( "Element " + x + " is present at index " + search(arr,n,3)); // This code is contributed by jana_sayantan.</script>
Element 3 is present at index 7
Time Complexity: O(n)Auxiliary Space: O(1)
Searching in an array where adjacent differ by at most kThis article is contributed by Rishabh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Sam007
nitin mittal
Smitha Dinesh Semwal
shubham_singh
subhammahato348
jana_sayantan
adityakumar129
hardikkoriintern
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 256,
"s": 54,
"text": "Given an array where difference between adjacent elements is 1, write an algorithm to search for an element in the array and return the position of the element (return the first occurrence).Examples : "
},
{
"code": null,
"e": 479,
"s": 256,
"text": "Let element to be searched be x\n\nInput: arr[] = {8, 7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3} \n x = 3\nOutput: Element 3 found at index 7\n\nInput: arr[] = {1, 2, 3, 4, 5, 4}\n x = 5\nOutput: Element 5 found at index 4 "
},
{
"code": null,
"e": 620,
"s": 479,
"text": "A Simple Approach is to traverse the given array one by one and compare every element with given element ‘x’. If matches, then return index."
},
{
"code": null,
"e": 1011,
"s": 620,
"text": "The above solution can be Optimized using the fact that difference between all adjacent elements is 1. The idea is to start comparing from the leftmost element and find the difference between current array element and x. Let this difference be ‘diff’. From the given property of array, we always know that x must be at-least ‘diff’ away, so instead of searching one by one, we jump ‘diff’. "
},
{
"code": null,
"e": 1054,
"s": 1011,
"text": "Below is the implementation of above idea."
},
{
"code": null,
"e": 1058,
"s": 1054,
"text": "C++"
},
{
"code": null,
"e": 1060,
"s": 1058,
"text": "C"
},
{
"code": null,
"e": 1065,
"s": 1060,
"text": "Java"
},
{
"code": null,
"e": 1074,
"s": 1065,
"text": "Python 3"
},
{
"code": null,
"e": 1077,
"s": 1074,
"text": "C#"
},
{
"code": null,
"e": 1081,
"s": 1077,
"text": "PHP"
},
{
"code": null,
"e": 1092,
"s": 1081,
"text": "Javascript"
},
{
"code": "// C++ program to search an element in an array where// difference between all elements is 1#include <bits/stdc++.h>using namespace std; // x is the element to be searched in arr[0..n-1]int search(int arr[], int n, int x){ // Traverse the given array starting from // leftmost element int i = 0; while (i < n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between current // array element and x i = i + abs(arr[i] - x); } cout << \"number is not present!\"; return -1;} // Driver program to test above functionint main(){ int arr[] = { 8, 7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; cout << \"Element \" << x << \" is present at index \" << search(arr, n, 3); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 1984,
"s": 1092,
"text": null
},
{
"code": "// C program to search an element in an array where// difference between all elements is 1#include <stdio.h>#include <stdlib.h> // x is the element to be searched in arr[0..n-1]int search(int arr[], int n, int x){ // Traverse the given array starting from // leftmost element int i = 0; while (i < n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between current // array element and x i = i + abs(arr[i] - x); } printf(\"number is not present!\"); return -1;} // Driver program to test above functionint main(){ int arr[] = { 8, 7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; printf(\"Element %d is present at index \", search(arr, n, 3)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 2858,
"s": 1984,
"text": null
},
{
"code": "// Java program to search an element in an// array where difference between all// elements is 1 import java.io.*; class GFG { // x is the element to be searched // in arr[0..n-1] static int search(int arr[], int n, int x) { // Traverse the given array starting // from leftmost element int i = 0; while (i < n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between current // array element and x i = i + Math.abs(arr[i]-x); } System.out.println (\"number is not\" + \" present!\"); return -1; } // Driver program to test above function public static void main (String[] args) { int arr[] = {8 ,7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 }; int n = arr.length; int x = 3; System.out.println(\"Element \" + x + \" is present at index \" + search(arr,n,3)); }} //This code is contributed by vt_m.",
"e": 4013,
"s": 2858,
"text": null
},
{
"code": "# Python 3 program to search an element# in an array where difference between# all elements is 1 # x is the element to be searched in# arr[0..n-1]def search(arr, n, x): # Traverse the given array starting # from leftmost element i = 0 while (i < n): # If x is found at index i if (arr[i] == x): return i # Jump the difference between # current array element and x i = i + abs(arr[i] - x) print(\"number is not present!\") return -1 # Driver program to test above functionarr = [8 ,7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 ]n = len(arr)x = 3print(\"Element\" , x , \" is present at index \", search(arr,n,3)) # This code is contributed by Smitha",
"e": 4776,
"s": 4013,
"text": null
},
{
"code": "// C# program to search an element// in an array where difference// between all elements is 1using System; public class GFG{ // in arr[0..n-1] static int search(int []arr, int n, int x) { // Traverse the given array starting // from leftmost element int i = 0; while (i < n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between // current array element and x i = i + Math.Abs(arr[i] - x); } Console.WriteLine (\"number is not\" + \" present!\"); return -1; } // Driver code public static void Main() { int []arr = {8 ,7, 6, 7, 6, 5, 4,3, 2, 3, 4, 3 }; int n = arr.Length; int x = 3; Console.WriteLine(\"Element \" + x + \" is present at index \" + search(arr, n, 3)); }} // This code is contributed by Sam007",
"e": 5851,
"s": 4776,
"text": null
},
{
"code": "<?php// PHP program to search an// element in an array where// difference between all// elements is 1 // x is the element to be// searched in arr[0..n-1]function search($arr, $n, $x){ // Traverse the given array // starting from leftmost // element $i = 0; while ($i < $n) { // If x is found at index i if ($arr[$i] == $x) return $i; // Jump the difference // between current // array element and x $i = $i + abs($arr[$i] - $x); } echo \"number is not present!\"; return -1;} // Driver Code$arr = array(8 ,7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3);$n = sizeof($arr);$x = 3;echo \"Element \" , $x , \" is present \" , \"at index \", search($arr, $n, 3); // This code is contributed// by nitin mittal.?>",
"e": 6635,
"s": 5851,
"text": null
},
{
"code": "<script> // Javascript program to search an element in an array where// difference between all elements is 1 // x is the element to be searched in arr[0..n-1]function search(arr, n, x){ // Traverse the given array starting from // leftmost element let i = 0; while (i<n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between current // array element and x i = i + Math.abs(arr[i]-x); } document.write(\"number is not present!\"); return -1;} // Driver program let arr = [8 ,7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 ]; let n = arr.length; let x = 3; document.write( \"Element \" + x + \" is present at index \" + search(arr,n,3)); // This code is contributed by jana_sayantan.</script>",
"e": 7446,
"s": 6635,
"text": null
},
{
"code": null,
"e": 7478,
"s": 7446,
"text": "Element 3 is present at index 7"
},
{
"code": null,
"e": 7521,
"s": 7478,
"text": "Time Complexity: O(n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7742,
"s": 7521,
"text": "Searching in an array where adjacent differ by at most kThis article is contributed by Rishabh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 7749,
"s": 7742,
"text": "Sam007"
},
{
"code": null,
"e": 7762,
"s": 7749,
"text": "nitin mittal"
},
{
"code": null,
"e": 7783,
"s": 7762,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 7797,
"s": 7783,
"text": "shubham_singh"
},
{
"code": null,
"e": 7813,
"s": 7797,
"text": "subhammahato348"
},
{
"code": null,
"e": 7827,
"s": 7813,
"text": "jana_sayantan"
},
{
"code": null,
"e": 7842,
"s": 7827,
"text": "adityakumar129"
},
{
"code": null,
"e": 7859,
"s": 7842,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 7866,
"s": 7859,
"text": "Arrays"
},
{
"code": null,
"e": 7876,
"s": 7866,
"text": "Searching"
},
{
"code": null,
"e": 7883,
"s": 7876,
"text": "Arrays"
},
{
"code": null,
"e": 7893,
"s": 7883,
"text": "Searching"
}
] |
TCP Congestion Control | 05 Nov, 2021
Prerequisites – Basic Congestion control knowledge
TCP uses a congestion window and a congestion policy that avoid congestion. Previously, we assumed that only the receiver can dictate the sender’s window size. We ignored another entity here, the network. If the network cannot deliver the data as fast as it is created by the sender, it must tell the sender to slow down. In other words, in addition to the receiver, the network is a second entity that determines the size of the sender’s window.
Congestion policy in TCP –
Slow Start Phase: starts slowly increment is exponential to thresholdCongestion Avoidance Phase: After reaching the threshold increment is by 1Congestion Detection Phase: Sender goes back to Slow start phase or Congestion avoidance phase.
Slow Start Phase: starts slowly increment is exponential to threshold
Congestion Avoidance Phase: After reaching the threshold increment is by 1
Congestion Detection Phase: Sender goes back to Slow start phase or Congestion avoidance phase.
Slow Start Phase : exponential increment – In this phase after every RTT the congestion window size increments exponentially.
Initially cwnd = 1
After 1 RTT, cwnd = 2^(1) = 2
2 RTT, cwnd = 2^(2) = 4
3 RTT, cwnd = 2^(3) = 8
Congestion Avoidance Phase : additive increment – This phase starts after the threshold value also denoted as ssthresh. The size of cwnd(congestion window) increases additive. After each RTT cwnd = cwnd + 1.
Initially cwnd = i
After 1 RTT, cwnd = i+1
2 RTT, cwnd = i+2
3 RTT, cwnd = i+3
Congestion Detection Phase : multiplicative decrement – If congestion occurs, the congestion window size is decreased. The only way a sender can guess that congestion has occurred is the need to retransmit a segment. Retransmission is needed to recover a missing packet that is assumed to have been dropped by a router due to congestion. Retransmission can occur in one of two cases: when the RTO timer times out or when three duplicate ACKs are received.
Case 1 : Retransmission due to Timeout – In this case congestion possibility is high.(a) ssthresh is reduced to half of the current window size.(b) set cwnd = 1(c) start with slow start phase again.
(a) ssthresh is reduced to half of the current window size.(b) set cwnd = 1(c) start with slow start phase again.
Case 2 : Retransmission due to 3 Acknowledgement Duplicates – In this case congestion possibility is less.(a) ssthresh value reduces to half of the current window size.(b) set cwnd= ssthresh(c) start with congestion avoidance phase
(a) ssthresh value reduces to half of the current window size.(b) set cwnd= ssthresh(c) start with congestion avoidance phase
Example – Assume a TCP protocol experiencing the behavior of slow start. At 5th transmission round with a threshold (ssthresh) value of 32 goes into congestion avoidance phase and continues till 10th transmission. At 10th transmission round, 3 duplicate ACKs are received by the receiver and enter into additive increase mode. Timeout occurs at 16th transmission round. Plot the transmission round (time) vs congestion window size of TCP segments.
GATE CS Corner Questions –
Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.
GATE CS 2008, Question 56GATE CS 2012, Question 65GATE CS 2014 (Set 1), Question 65GATE IT 2005, Question 73
GATE CS 2008, Question 56
GATE CS 2012, Question 65
GATE CS 2014 (Set 1), Question 65
GATE IT 2005, Question 73
This article is contributed by SHAURYA UPPAL. 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.
vaibhavsinghtanwar
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 105,
"s": 54,
"text": "Prerequisites – Basic Congestion control knowledge"
},
{
"code": null,
"e": 552,
"s": 105,
"text": "TCP uses a congestion window and a congestion policy that avoid congestion. Previously, we assumed that only the receiver can dictate the sender’s window size. We ignored another entity here, the network. If the network cannot deliver the data as fast as it is created by the sender, it must tell the sender to slow down. In other words, in addition to the receiver, the network is a second entity that determines the size of the sender’s window."
},
{
"code": null,
"e": 579,
"s": 552,
"text": "Congestion policy in TCP –"
},
{
"code": null,
"e": 818,
"s": 579,
"text": "Slow Start Phase: starts slowly increment is exponential to thresholdCongestion Avoidance Phase: After reaching the threshold increment is by 1Congestion Detection Phase: Sender goes back to Slow start phase or Congestion avoidance phase."
},
{
"code": null,
"e": 888,
"s": 818,
"text": "Slow Start Phase: starts slowly increment is exponential to threshold"
},
{
"code": null,
"e": 963,
"s": 888,
"text": "Congestion Avoidance Phase: After reaching the threshold increment is by 1"
},
{
"code": null,
"e": 1059,
"s": 963,
"text": "Congestion Detection Phase: Sender goes back to Slow start phase or Congestion avoidance phase."
},
{
"code": null,
"e": 1185,
"s": 1059,
"text": "Slow Start Phase : exponential increment – In this phase after every RTT the congestion window size increments exponentially."
},
{
"code": null,
"e": 1283,
"s": 1185,
"text": "Initially cwnd = 1\nAfter 1 RTT, cwnd = 2^(1) = 2\n2 RTT, cwnd = 2^(2) = 4\n3 RTT, cwnd = 2^(3) = 8\n"
},
{
"code": null,
"e": 1491,
"s": 1283,
"text": "Congestion Avoidance Phase : additive increment – This phase starts after the threshold value also denoted as ssthresh. The size of cwnd(congestion window) increases additive. After each RTT cwnd = cwnd + 1."
},
{
"code": null,
"e": 1571,
"s": 1491,
"text": "Initially cwnd = i\nAfter 1 RTT, cwnd = i+1\n2 RTT, cwnd = i+2\n3 RTT, cwnd = i+3\n"
},
{
"code": null,
"e": 2027,
"s": 1571,
"text": "Congestion Detection Phase : multiplicative decrement – If congestion occurs, the congestion window size is decreased. The only way a sender can guess that congestion has occurred is the need to retransmit a segment. Retransmission is needed to recover a missing packet that is assumed to have been dropped by a router due to congestion. Retransmission can occur in one of two cases: when the RTO timer times out or when three duplicate ACKs are received."
},
{
"code": null,
"e": 2226,
"s": 2027,
"text": "Case 1 : Retransmission due to Timeout – In this case congestion possibility is high.(a) ssthresh is reduced to half of the current window size.(b) set cwnd = 1(c) start with slow start phase again."
},
{
"code": null,
"e": 2340,
"s": 2226,
"text": "(a) ssthresh is reduced to half of the current window size.(b) set cwnd = 1(c) start with slow start phase again."
},
{
"code": null,
"e": 2572,
"s": 2340,
"text": "Case 2 : Retransmission due to 3 Acknowledgement Duplicates – In this case congestion possibility is less.(a) ssthresh value reduces to half of the current window size.(b) set cwnd= ssthresh(c) start with congestion avoidance phase"
},
{
"code": null,
"e": 2698,
"s": 2572,
"text": "(a) ssthresh value reduces to half of the current window size.(b) set cwnd= ssthresh(c) start with congestion avoidance phase"
},
{
"code": null,
"e": 3146,
"s": 2698,
"text": "Example – Assume a TCP protocol experiencing the behavior of slow start. At 5th transmission round with a threshold (ssthresh) value of 32 goes into congestion avoidance phase and continues till 10th transmission. At 10th transmission round, 3 duplicate ACKs are received by the receiver and enter into additive increase mode. Timeout occurs at 16th transmission round. Plot the transmission round (time) vs congestion window size of TCP segments."
},
{
"code": null,
"e": 3173,
"s": 3146,
"text": "GATE CS Corner Questions –"
},
{
"code": null,
"e": 3371,
"s": 3173,
"text": "Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them."
},
{
"code": null,
"e": 3480,
"s": 3371,
"text": "GATE CS 2008, Question 56GATE CS 2012, Question 65GATE CS 2014 (Set 1), Question 65GATE IT 2005, Question 73"
},
{
"code": null,
"e": 3506,
"s": 3480,
"text": "GATE CS 2008, Question 56"
},
{
"code": null,
"e": 3532,
"s": 3506,
"text": "GATE CS 2012, Question 65"
},
{
"code": null,
"e": 3566,
"s": 3532,
"text": "GATE CS 2014 (Set 1), Question 65"
},
{
"code": null,
"e": 3592,
"s": 3566,
"text": "GATE IT 2005, Question 73"
},
{
"code": null,
"e": 3889,
"s": 3592,
"text": "This article is contributed by SHAURYA UPPAL. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4014,
"s": 3889,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4033,
"s": 4014,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 4051,
"s": 4033,
"text": "Computer Networks"
},
{
"code": null,
"e": 4059,
"s": 4051,
"text": "GATE CS"
},
{
"code": null,
"e": 4077,
"s": 4059,
"text": "Computer Networks"
}
] |
PEP 8 : Coding Style guide in Python | 24 Nov, 2020
Indeed coding and applying logic is the foundation of any programming language but there’s also another factor that every coder must keep in mind while coding and that is the coding style. Keeping this in mind, Python maintains a strict way of order and format of scripting.Following this sometimes mandatory and is a great help on the user’s end, to understand. Making it easy for others to read code is always a good idea, and adopting a nice coding style helps tremendously for that.
For Python, PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you:
1. Use 4-space indentation and no tabs.Examples:
# Aligned with opening delimiter.
grow = function_name(variable_one, variable_two,
variable_three, variable_four)
# First line contains no argument. Second line onwards
# more indentation included to distinguish this from
# the rest.
def function_name(
variable_one, variable_two, variable_three,
variable_four):
print(variable_one)
The 4 space rule is not always mandatory and can be overruled for continuation line.
2. Use docstrings : There are both single and multi-line docstrings that can be used in Python. However, the single line comment fits in one line, triple quotes are used in both cases. These are used to define a particular program or define a particular function.Example:
def exam():
"""This is single line docstring"""
"""This is
a
multiline comment"""
3. Wrap lines so that they don’t exceed 79 characters : The Python standard library is conservative and requires limiting lines to 79 characters. The lines can be wrapped using parenthesis, brackets, and braces. They should be used in preference to backslashes.Example:
with open('/path/from/where/you/want/to/read/file') as file_one, \
open('/path/where/you/want/the/file/to/be/written', 'w') as file_two:
file_two.write(file_one.read())
4. Use of regular and updated comments are valuable to both the coders and users : There are also various types and conditions that if followed can be of great help from programs and users point of view. Comments should form complete sentences. If a comment is a full sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter. In short comments, the period at the end can be omitted. In block comments, there are more than one paragraphs and each sentence must end with a period. Block comments and inline comments can be written followed by a single ‘#’.Example of inline comments:
geek = geek + 1 # Increment
5. Use of trailing commas : This is not mandatory except while making a tuple.Example:
tup = ("geek",)
5. Use Python’s default UTF-8 or ASCII encodings and not any fancy encodings, if it is meant for international environment.
6. Use spaces around operators and after commas, but not directly inside bracketing constructs:
a = f(1, 2) + g(3, 4)
7. Naming Conventions : There are few naming conventions that should be followed in order to make the program less complex and more readable. At the same time, the naming conventions in Python is a bit of mess, but here are few conventions that can be followed easily.There is an overriding principle that follows that the names that are visible to the user as public parts of API should follow conventions that reflect usage rather than implementation.Here are few other naming conventions:
b (single lowercase letter)
B (single upper case letter)
lowercase
lower_case_with_underscores
UPPERCASE
UPPER_CASE_WITH_UNDERSCORES
CapitalizedWords (or CamelCase). This is also sometimes known as StudlyCaps.
Note: While using abbreviations in CapWords, capitalize all the letters
of the abbreviation. Thus HTTPServerError is better than HttpServerError.
mixedCase (differs from CapitalizedWords by initial lowercase character!)
Capitalized_Words_With_Underscores
In addition to these few leading or trailing underscores are also considered.Examples:single_leading_underscore: weak “internal use” indicator. E.g. from M import * does not import objects whose name starts with an underscore.
single_trailing_underscore_: used to avoid conflicts with Python keyword.Example:
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore: when naming a class attribute, invokes name mangling.(inside class FooBar, __boo becomes _FooBar__boo;).
__double_leading_and_trailing_underscore__: “magic” objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Only use them as documented.
8. Characters that should not be used for identifiers : ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names as these are similar to the numerals one and zero.
9. Don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code.10. Name your classes and functions consistently : The convention is to use CamelCase for classes and lower_case_with_underscores for functions and methods. Always use self as the name for the first method argument.
11. While naming of function of methods always use self for the first argument to instance methods and cls for the first argument to class methods.If a functions argument name matches with reserved words then it can be written with a trailing comma. For e.g., class_
You can refer to this simple program to know how to write an understandable code:
# Python program to find the# factorial of a number provided by the user. # change the value for a different result num = 7 # uncomment to take input from the user #num = int(input("Enter a number: ")) factorial = 1 # check if the number is negative, positive or zero if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial)
Output:
The factorial of 7 is 5040
This article is contributed by Chinmoy Lenka. 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.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 541,
"s": 54,
"text": "Indeed coding and applying logic is the foundation of any programming language but there’s also another factor that every coder must keep in mind while coding and that is the coding style. Keeping this in mind, Python maintains a strict way of order and format of scripting.Following this sometimes mandatory and is a great help on the user’s end, to understand. Making it easy for others to read code is always a good idea, and adopting a nice coding style helps tremendously for that."
},
{
"code": null,
"e": 786,
"s": 541,
"text": "For Python, PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you:"
},
{
"code": null,
"e": 835,
"s": 786,
"text": "1. Use 4-space indentation and no tabs.Examples:"
},
{
"code": null,
"e": 971,
"s": 835,
"text": "# Aligned with opening delimiter.\ngrow = function_name(variable_one, variable_two,\n variable_three, variable_four)\n"
},
{
"code": null,
"e": 1212,
"s": 971,
"text": "# First line contains no argument. Second line onwards\n# more indentation included to distinguish this from \n# the rest.\ndef function_name(\n variable_one, variable_two, variable_three,\n variable_four):\n print(variable_one)\n"
},
{
"code": null,
"e": 1297,
"s": 1212,
"text": "The 4 space rule is not always mandatory and can be overruled for continuation line."
},
{
"code": null,
"e": 1569,
"s": 1297,
"text": "2. Use docstrings : There are both single and multi-line docstrings that can be used in Python. However, the single line comment fits in one line, triple quotes are used in both cases. These are used to define a particular program or define a particular function.Example:"
},
{
"code": null,
"e": 1669,
"s": 1569,
"text": "def exam():\n \"\"\"This is single line docstring\"\"\"\n\n \"\"\"This is\n a\n multiline comment\"\"\"\n"
},
{
"code": null,
"e": 1939,
"s": 1669,
"text": "3. Wrap lines so that they don’t exceed 79 characters : The Python standard library is conservative and requires limiting lines to 79 characters. The lines can be wrapped using parenthesis, brackets, and braces. They should be used in preference to backslashes.Example:"
},
{
"code": null,
"e": 2118,
"s": 1939,
"text": "with open('/path/from/where/you/want/to/read/file') as file_one, \\\n open('/path/where/you/want/the/file/to/be/written', 'w') as file_two:\n file_two.write(file_one.read())\n"
},
{
"code": null,
"e": 2755,
"s": 2118,
"text": "4. Use of regular and updated comments are valuable to both the coders and users : There are also various types and conditions that if followed can be of great help from programs and users point of view. Comments should form complete sentences. If a comment is a full sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter. In short comments, the period at the end can be omitted. In block comments, there are more than one paragraphs and each sentence must end with a period. Block comments and inline comments can be written followed by a single ‘#’.Example of inline comments:"
},
{
"code": null,
"e": 2800,
"s": 2755,
"text": "geek = geek + 1 # Increment\n"
},
{
"code": null,
"e": 2887,
"s": 2800,
"text": "5. Use of trailing commas : This is not mandatory except while making a tuple.Example:"
},
{
"code": null,
"e": 2904,
"s": 2887,
"text": "tup = (\"geek\",)\n"
},
{
"code": null,
"e": 3028,
"s": 2904,
"text": "5. Use Python’s default UTF-8 or ASCII encodings and not any fancy encodings, if it is meant for international environment."
},
{
"code": null,
"e": 3124,
"s": 3028,
"text": "6. Use spaces around operators and after commas, but not directly inside bracketing constructs:"
},
{
"code": null,
"e": 3146,
"s": 3124,
"text": "a = f(1, 2) + g(3, 4)"
},
{
"code": null,
"e": 3638,
"s": 3146,
"text": "7. Naming Conventions : There are few naming conventions that should be followed in order to make the program less complex and more readable. At the same time, the naming conventions in Python is a bit of mess, but here are few conventions that can be followed easily.There is an overriding principle that follows that the names that are visible to the user as public parts of API should follow conventions that reflect usage rather than implementation.Here are few other naming conventions:"
},
{
"code": null,
"e": 4112,
"s": 3638,
"text": "b (single lowercase letter)\n\nB (single upper case letter)\n\nlowercase\n\nlower_case_with_underscores\n\nUPPERCASE\n\nUPPER_CASE_WITH_UNDERSCORES\n\nCapitalizedWords (or CamelCase). This is also sometimes known as StudlyCaps.\nNote: While using abbreviations in CapWords, capitalize all the letters \nof the abbreviation. Thus HTTPServerError is better than HttpServerError.\n\nmixedCase (differs from CapitalizedWords by initial lowercase character!)\n\nCapitalized_Words_With_Underscores"
},
{
"code": null,
"e": 4339,
"s": 4112,
"text": "In addition to these few leading or trailing underscores are also considered.Examples:single_leading_underscore: weak “internal use” indicator. E.g. from M import * does not import objects whose name starts with an underscore."
},
{
"code": null,
"e": 4421,
"s": 4339,
"text": "single_trailing_underscore_: used to avoid conflicts with Python keyword.Example:"
},
{
"code": null,
"e": 4466,
"s": 4421,
"text": "Tkinter.Toplevel(master, class_='ClassName')"
},
{
"code": null,
"e": 4600,
"s": 4466,
"text": "__double_leading_underscore: when naming a class attribute, invokes name mangling.(inside class FooBar, __boo becomes _FooBar__boo;)."
},
{
"code": null,
"e": 4783,
"s": 4600,
"text": "__double_leading_and_trailing_underscore__: “magic” objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Only use them as documented."
},
{
"code": null,
"e": 5009,
"s": 4783,
"text": "8. Characters that should not be used for identifiers : ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names as these are similar to the numerals one and zero."
},
{
"code": null,
"e": 5380,
"s": 5009,
"text": "9. Don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code.10. Name your classes and functions consistently : The convention is to use CamelCase for classes and lower_case_with_underscores for functions and methods. Always use self as the name for the first method argument."
},
{
"code": null,
"e": 5647,
"s": 5380,
"text": "11. While naming of function of methods always use self for the first argument to instance methods and cls for the first argument to class methods.If a functions argument name matches with reserved words then it can be written with a trailing comma. For e.g., class_"
},
{
"code": null,
"e": 5729,
"s": 5647,
"text": "You can refer to this simple program to know how to write an understandable code:"
},
{
"code": "# Python program to find the# factorial of a number provided by the user. # change the value for a different result num = 7 # uncomment to take input from the user #num = int(input(\"Enter a number: \")) factorial = 1 # check if the number is negative, positive or zero if num < 0: print(\"Sorry, factorial does not exist for negative numbers\") elif num == 0: print(\"The factorial of 0 is 1\") else: for i in range(1,num + 1): factorial = factorial*i print(\"The factorial of\",num,\"is\",factorial) ",
"e": 6258,
"s": 5729,
"text": null
},
{
"code": null,
"e": 6266,
"s": 6258,
"text": "Output:"
},
{
"code": null,
"e": 6294,
"s": 6266,
"text": "The factorial of 7 is 5040\n"
},
{
"code": null,
"e": 6595,
"s": 6294,
"text": "This article is contributed by Chinmoy Lenka. 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": 6720,
"s": 6595,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6727,
"s": 6720,
"text": "Python"
}
] |
Matplotlib.pyplot.hist2d() in Python | 21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The hist2d() function in pyplot module of matplotlib library is used to make a 2D histogram plot.
Syntax:matplotlib.pyplot.hist2d(x, y, bins=10, range=None, density=False, weights=None, cmin=None, cmax=None, \*, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
x, y : These parameter are the sequence of data.
bins : This parameter is an optional parameter and it contains the integer or sequence or string.
range : This parameter is an optional parameter and it the lower and upper range of the bins.
density : This parameter is an optional parameter and it contains the boolean values.
weights : This parameter is an optional parameter and it is an array of weights, of the same shape as x.
cmin : This parameter has all bins that has count less than cmin will not be displayed.
cmax : This parameter has all bins that has count more than cmax will not be displayed.
Returns: This returns the following:
h :This returns the bi-dimensional histogram of samples x and y.
xedges :This returns the bin edges along the x axis.
yedges :This returns the bin edges along the y axis.
image :This returns the QuadMesh.
Below examples illustrate the matplotlib.pyplot.hist2d() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatterimport numpy as npimport matplotlib.pyplot as plt N_points = 100000x = np.random.randn(N_points)y = 4 * x + np.random.randn(100000) + 50 plt.hist2d(x, y, bins = 100, norm = colors.LogNorm(), cmap ="gray") plt.title('matplotlib.pyplot.hist2d() function \Example\n\n', fontweight ="bold") plt.show()
Output:
Example #2:
#Implementation of matplotlib functionfrom matplotlib import colorsimport numpy as npfrom numpy.random import multivariate_normalimport matplotlib.pyplot as plt result = np.vstack([ multivariate_normal([10, 10], [[3, 2], [2, 3]], size=1000000), multivariate_normal([30, 20], [[2, 3], [1, 3]], size=100000)]) plt.hist2d(result[:, 0], result[:, 1], bins = 100, cmap = "Greens", norm = colors.LogNorm())plt.title('matplotlib.pyplot.hist2d function \Example')plt.show() plt.hist2d(result[:, 0], result[:, 1], bins = 100, cmap = "RdYlGn_r", norm = colors.LogNorm())plt.show()
Output:
Python-matplotlib
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 321,
"s": 223,
"text": "The hist2d() function in pyplot module of matplotlib library is used to make a 2D histogram plot."
},
{
"code": null,
"e": 458,
"s": 321,
"text": "Syntax:matplotlib.pyplot.hist2d(x, y, bins=10, range=None, density=False, weights=None, cmin=None, cmax=None, \\*, data=None, \\*\\*kwargs)"
},
{
"code": null,
"e": 540,
"s": 458,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 589,
"s": 540,
"text": "x, y : These parameter are the sequence of data."
},
{
"code": null,
"e": 687,
"s": 589,
"text": "bins : This parameter is an optional parameter and it contains the integer or sequence or string."
},
{
"code": null,
"e": 781,
"s": 687,
"text": "range : This parameter is an optional parameter and it the lower and upper range of the bins."
},
{
"code": null,
"e": 867,
"s": 781,
"text": "density : This parameter is an optional parameter and it contains the boolean values."
},
{
"code": null,
"e": 972,
"s": 867,
"text": "weights : This parameter is an optional parameter and it is an array of weights, of the same shape as x."
},
{
"code": null,
"e": 1060,
"s": 972,
"text": "cmin : This parameter has all bins that has count less than cmin will not be displayed."
},
{
"code": null,
"e": 1148,
"s": 1060,
"text": "cmax : This parameter has all bins that has count more than cmax will not be displayed."
},
{
"code": null,
"e": 1185,
"s": 1148,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 1250,
"s": 1185,
"text": "h :This returns the bi-dimensional histogram of samples x and y."
},
{
"code": null,
"e": 1303,
"s": 1250,
"text": "xedges :This returns the bin edges along the x axis."
},
{
"code": null,
"e": 1356,
"s": 1303,
"text": "yedges :This returns the bin edges along the y axis."
},
{
"code": null,
"e": 1390,
"s": 1356,
"text": "image :This returns the QuadMesh."
},
{
"code": null,
"e": 1478,
"s": 1390,
"text": "Below examples illustrate the matplotlib.pyplot.hist2d() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 1490,
"s": 1478,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib functionfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatterimport numpy as npimport matplotlib.pyplot as plt N_points = 100000x = np.random.randn(N_points)y = 4 * x + np.random.randn(100000) + 50 plt.hist2d(x, y, bins = 100, norm = colors.LogNorm(), cmap =\"gray\") plt.title('matplotlib.pyplot.hist2d() function \\Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 1942,
"s": 1490,
"text": null
},
{
"code": null,
"e": 1950,
"s": 1942,
"text": "Output:"
},
{
"code": null,
"e": 1962,
"s": 1950,
"text": "Example #2:"
},
{
"code": "#Implementation of matplotlib functionfrom matplotlib import colorsimport numpy as npfrom numpy.random import multivariate_normalimport matplotlib.pyplot as plt result = np.vstack([ multivariate_normal([10, 10], [[3, 2], [2, 3]], size=1000000), multivariate_normal([30, 20], [[2, 3], [1, 3]], size=100000)]) plt.hist2d(result[:, 0], result[:, 1], bins = 100, cmap = \"Greens\", norm = colors.LogNorm())plt.title('matplotlib.pyplot.hist2d function \\Example')plt.show() plt.hist2d(result[:, 0], result[:, 1], bins = 100, cmap = \"RdYlGn_r\", norm = colors.LogNorm())plt.show()",
"e": 2651,
"s": 1962,
"text": null
},
{
"code": null,
"e": 2659,
"s": 2651,
"text": "Output:"
},
{
"code": null,
"e": 2677,
"s": 2659,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2684,
"s": 2677,
"text": "Python"
},
{
"code": null,
"e": 2782,
"s": 2684,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2800,
"s": 2782,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2842,
"s": 2800,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2864,
"s": 2842,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2899,
"s": 2864,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2925,
"s": 2899,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2957,
"s": 2925,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2986,
"s": 2957,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3016,
"s": 2986,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3043,
"s": 3016,
"text": "Python Classes and Objects"
}
] |
How to Rename Multiple PySpark DataFrame Columns | 29 Jun, 2021
In this article, we will discuss how to rename the multiple columns in PySpark Dataframe. For this we will use withColumnRenamed() and toDF() functions.
Creating Dataframe for demonstration:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data with null values# we can define null values with nonedata = [[None, "sravan", "vignan"], ["2", None, "vvit"], ["3", "rohith", None], ["4", "sridevi", "vignan"], ["1", None, None], ["5", "gnanesh", "iit"]] # specify column namescolumns = ['ID', 'NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # show columnsprint(dataframe.columns) # display dataframedataframe.show()
Output:
Method 1: Using withColumnRenamed()
This method is used to rename a column in the dataframe
Syntax: dataframe.withColumnRenamed(“old_column_name”, “new_column_name”)
where
dataframe is the pyspark dataframe
old_column_name is the existing column name
new_column_name is the new column name
To change multiple columns, we can specify the functions for n times, separated by “.” operator
Syntax: dataframe.withColumnRenamed(“old_column_name”, “new_column_name”).
withColumnRenamed”old_column_name”, “new_column_name”)
Example 1: Python program to change the column name for two columns
Python3
# display actual columnsprint("Actual columns: ", dataframe.columns) # change the college column name to university # and ID to student_iddataframe = dataframe.withColumnRenamed( "college", "university").withColumnRenamed("ID", "student_id") # display modified columnsprint("modified columns: ", dataframe.columns) # final dataframedataframe.show()
Output:
Example 2: Rename all columns
Python3
# display actual columnsprint("Actual columns: ", dataframe.columns) # change the college column name to university # and ID to student_iddataframe = dataframe.withColumnRenamed( "college", "university").withColumnRenamed( "ID", "student_id").withColumnRenamed("NAME", "student_name") # display modified columnsprint("modified columns: ", dataframe.columns) # final dataframedataframe.show()
Output:
Method 2: Using toDF()
This method is used to change the names of all the columns of the dataframe
Syntax: dataframe.toDF(*(“column 1′′,”column 2”,”column n))
where, columns are the columns in the dataframe
Example: Python program to change the column names
Python3
# display actualprint("Actual columns: ", dataframe.columns) # change column names to A,B,Cdataframe = dataframe.toDF(*("A", "B", "C")) # display new columnsprint("New columns: ", dataframe.columns) # display dataframedataframe.show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 181,
"s": 28,
"text": "In this article, we will discuss how to rename the multiple columns in PySpark Dataframe. For this we will use withColumnRenamed() and toDF() functions."
},
{
"code": null,
"e": 219,
"s": 181,
"text": "Creating Dataframe for demonstration:"
},
{
"code": null,
"e": 227,
"s": 219,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data with null values# we can define null values with nonedata = [[None, \"sravan\", \"vignan\"], [\"2\", None, \"vvit\"], [\"3\", \"rohith\", None], [\"4\", \"sridevi\", \"vignan\"], [\"1\", None, None], [\"5\", \"gnanesh\", \"iit\"]] # specify column namescolumns = ['ID', 'NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # show columnsprint(dataframe.columns) # display dataframedataframe.show()",
"e": 954,
"s": 227,
"text": null
},
{
"code": null,
"e": 962,
"s": 954,
"text": "Output:"
},
{
"code": null,
"e": 998,
"s": 962,
"text": "Method 1: Using withColumnRenamed()"
},
{
"code": null,
"e": 1054,
"s": 998,
"text": "This method is used to rename a column in the dataframe"
},
{
"code": null,
"e": 1128,
"s": 1054,
"text": "Syntax: dataframe.withColumnRenamed(“old_column_name”, “new_column_name”)"
},
{
"code": null,
"e": 1134,
"s": 1128,
"text": "where"
},
{
"code": null,
"e": 1169,
"s": 1134,
"text": "dataframe is the pyspark dataframe"
},
{
"code": null,
"e": 1213,
"s": 1169,
"text": "old_column_name is the existing column name"
},
{
"code": null,
"e": 1252,
"s": 1213,
"text": "new_column_name is the new column name"
},
{
"code": null,
"e": 1348,
"s": 1252,
"text": "To change multiple columns, we can specify the functions for n times, separated by “.” operator"
},
{
"code": null,
"e": 1423,
"s": 1348,
"text": "Syntax: dataframe.withColumnRenamed(“old_column_name”, “new_column_name”)."
},
{
"code": null,
"e": 1478,
"s": 1423,
"text": "withColumnRenamed”old_column_name”, “new_column_name”)"
},
{
"code": null,
"e": 1546,
"s": 1478,
"text": "Example 1: Python program to change the column name for two columns"
},
{
"code": null,
"e": 1554,
"s": 1546,
"text": "Python3"
},
{
"code": "# display actual columnsprint(\"Actual columns: \", dataframe.columns) # change the college column name to university # and ID to student_iddataframe = dataframe.withColumnRenamed( \"college\", \"university\").withColumnRenamed(\"ID\", \"student_id\") # display modified columnsprint(\"modified columns: \", dataframe.columns) # final dataframedataframe.show()",
"e": 1907,
"s": 1554,
"text": null
},
{
"code": null,
"e": 1915,
"s": 1907,
"text": "Output:"
},
{
"code": null,
"e": 1945,
"s": 1915,
"text": "Example 2: Rename all columns"
},
{
"code": null,
"e": 1953,
"s": 1945,
"text": "Python3"
},
{
"code": "# display actual columnsprint(\"Actual columns: \", dataframe.columns) # change the college column name to university # and ID to student_iddataframe = dataframe.withColumnRenamed( \"college\", \"university\").withColumnRenamed( \"ID\", \"student_id\").withColumnRenamed(\"NAME\", \"student_name\") # display modified columnsprint(\"modified columns: \", dataframe.columns) # final dataframedataframe.show()",
"e": 2350,
"s": 1953,
"text": null
},
{
"code": null,
"e": 2358,
"s": 2350,
"text": "Output:"
},
{
"code": null,
"e": 2381,
"s": 2358,
"text": "Method 2: Using toDF()"
},
{
"code": null,
"e": 2457,
"s": 2381,
"text": "This method is used to change the names of all the columns of the dataframe"
},
{
"code": null,
"e": 2517,
"s": 2457,
"text": "Syntax: dataframe.toDF(*(“column 1′′,”column 2”,”column n))"
},
{
"code": null,
"e": 2565,
"s": 2517,
"text": "where, columns are the columns in the dataframe"
},
{
"code": null,
"e": 2616,
"s": 2565,
"text": "Example: Python program to change the column names"
},
{
"code": null,
"e": 2624,
"s": 2616,
"text": "Python3"
},
{
"code": "# display actualprint(\"Actual columns: \", dataframe.columns) # change column names to A,B,Cdataframe = dataframe.toDF(*(\"A\", \"B\", \"C\")) # display new columnsprint(\"New columns: \", dataframe.columns) # display dataframedataframe.show()",
"e": 2862,
"s": 2624,
"text": null
},
{
"code": null,
"e": 2870,
"s": 2862,
"text": "Output:"
},
{
"code": null,
"e": 2877,
"s": 2870,
"text": "Picked"
},
{
"code": null,
"e": 2892,
"s": 2877,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 2899,
"s": 2892,
"text": "Python"
}
] |
R – if statement | 18 Oct, 2021
If statement is one of the Decision-making statements in the R programming language. It is one of the easiest decision-making statements. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax:
if (expression) {
#statement to execute if condition is true
}
If the expression is true, the statement gets executed. But if the expression is FALSE, nothing happens. The expression can be a logical/numerical vector, but only the first element is taken into consideration. In the case of numeric vector, zero is taken as FALSE, rest as TRUE.
Control falls into the if block.
The flow jumps to Condition.
Condition is tested. If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.
If Condition yields true, goto Step 4.
If Condition yields false, goto Step 5.
The if-block or the body inside the if is executed.
Flow steps out of the if block.
python
# R program to illustrate if statement # assigning value to variable aa <- 5 # conditionif(a > 0){ print("Positive Number") # Statement}
Output:
Positive Number
In this example, variable a is assigned a value of 2. The given expression will check if the value of variable a is greater than 0. If the value of a is greater than zero, the print statement will be executed and the output will be “Positive Number”. If the value of a is less than 0, nothing will happen.
Python
# Assigning value to variable xx <- 12 # Conditionif (x > 20){ print("12 is less than 20") # Statement}print("Hello World")
Output:
12 is less than 20
Hello World
In this example, variable x is assigned a value. The given expression will check if the value of variable x is greater than 20.
If the value of x is greater than 20, the statement given in the curly braces will be executed and the output will be “12 is less than 20”. Here, we have one more statement outside the curly braces. This statement will be executed whenever we run the program as it’s not a part of the given condition.
R
# R program to illustrate if statement# assigning value to variable aa <- -5 # conditionif(a > 0){ print("Positive Number") # Statement}else{ print("-ve number")}
Output:
"-ve number"
kumar_satyam
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Creating a Data Frame from Vectors in R Programming | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 376,
"s": 54,
"text": "If statement is one of the Decision-making statements in the R programming language. It is one of the easiest decision-making statements. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not."
},
{
"code": null,
"e": 385,
"s": 376,
"text": "Syntax: "
},
{
"code": null,
"e": 451,
"s": 385,
"text": "if (expression) {\n #statement to execute if condition is true\n}"
},
{
"code": null,
"e": 731,
"s": 451,
"text": "If the expression is true, the statement gets executed. But if the expression is FALSE, nothing happens. The expression can be a logical/numerical vector, but only the first element is taken into consideration. In the case of numeric vector, zero is taken as FALSE, rest as TRUE."
},
{
"code": null,
"e": 764,
"s": 731,
"text": "Control falls into the if block."
},
{
"code": null,
"e": 793,
"s": 764,
"text": "The flow jumps to Condition."
},
{
"code": null,
"e": 892,
"s": 793,
"text": "Condition is tested. If Condition yields true, goto Step 4.If Condition yields false, goto Step 5."
},
{
"code": null,
"e": 931,
"s": 892,
"text": "If Condition yields true, goto Step 4."
},
{
"code": null,
"e": 971,
"s": 931,
"text": "If Condition yields false, goto Step 5."
},
{
"code": null,
"e": 1023,
"s": 971,
"text": "The if-block or the body inside the if is executed."
},
{
"code": null,
"e": 1055,
"s": 1023,
"text": "Flow steps out of the if block."
},
{
"code": null,
"e": 1062,
"s": 1055,
"text": "python"
},
{
"code": "# R program to illustrate if statement # assigning value to variable aa <- 5 # conditionif(a > 0){ print(\"Positive Number\") # Statement}",
"e": 1203,
"s": 1062,
"text": null
},
{
"code": null,
"e": 1212,
"s": 1203,
"text": "Output: "
},
{
"code": null,
"e": 1228,
"s": 1212,
"text": "Positive Number"
},
{
"code": null,
"e": 1535,
"s": 1228,
"text": "In this example, variable a is assigned a value of 2. The given expression will check if the value of variable a is greater than 0. If the value of a is greater than zero, the print statement will be executed and the output will be “Positive Number”. If the value of a is less than 0, nothing will happen. "
},
{
"code": null,
"e": 1542,
"s": 1535,
"text": "Python"
},
{
"code": "# Assigning value to variable xx <- 12 # Conditionif (x > 20){ print(\"12 is less than 20\") # Statement}print(\"Hello World\")",
"e": 1670,
"s": 1542,
"text": null
},
{
"code": null,
"e": 1679,
"s": 1670,
"text": "Output: "
},
{
"code": null,
"e": 1710,
"s": 1679,
"text": "12 is less than 20\nHello World"
},
{
"code": null,
"e": 1839,
"s": 1710,
"text": "In this example, variable x is assigned a value. The given expression will check if the value of variable x is greater than 20. "
},
{
"code": null,
"e": 2141,
"s": 1839,
"text": "If the value of x is greater than 20, the statement given in the curly braces will be executed and the output will be “12 is less than 20”. Here, we have one more statement outside the curly braces. This statement will be executed whenever we run the program as it’s not a part of the given condition."
},
{
"code": null,
"e": 2143,
"s": 2141,
"text": "R"
},
{
"code": "# R program to illustrate if statement# assigning value to variable aa <- -5 # conditionif(a > 0){ print(\"Positive Number\") # Statement}else{ print(\"-ve number\")}",
"e": 2313,
"s": 2143,
"text": null
},
{
"code": null,
"e": 2321,
"s": 2313,
"text": "Output:"
},
{
"code": null,
"e": 2334,
"s": 2321,
"text": "\"-ve number\""
},
{
"code": null,
"e": 2347,
"s": 2334,
"text": "kumar_satyam"
},
{
"code": null,
"e": 2354,
"s": 2347,
"text": "Picked"
},
{
"code": null,
"e": 2365,
"s": 2354,
"text": "R Language"
},
{
"code": null,
"e": 2463,
"s": 2365,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2515,
"s": 2463,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 2573,
"s": 2515,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2625,
"s": 2573,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2657,
"s": 2625,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 2692,
"s": 2657,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2736,
"s": 2692,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 2774,
"s": 2736,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2823,
"s": 2774,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2860,
"s": 2823,
"text": "How to import an Excel File into R ?"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.